text
stringlengths 180
608k
|
---|
[Question]
[
The set of all polynomials with **integer** coefficients is countable.
This means that there is a sequence that contains each polynomial with integer coefficients exactly once.
Your goal is it to write a function or program that outputs such a sequence.
Example (you may use another sequence):
```
// list of integers [i -> Z(i)] : 0,1,-1,2,-2,...
// integer -> polynomial
// 1. factor index n=product_i p_i^k_i
// 2. return polynomial sum_i Z(k_i)*x^(i-1)
1 -> 0 // all powers 0 -> all summands 0
2 -> 1 // 2^1 -> 1*x^0
3 -> x // 3^1 -> 1*x^1
4 -> -1 // 2^2 -> -1*x^0
5 -> x² // 5^1 -> 1*x^2
6 -> x+1 // 2^1*3^1 -> 1*x^0+1*x^1
7 -> x³ // 7^1 -> 1*x^3
8 -> 2 // 2^3 -> 2*x^0
9 -> -x // 3^2 -> -1*x^1
...
```
For ideas how to compute the sequence of all integers see [here](https://codegolf.stackexchange.com/questions/93441/print-all-integers)
Rules:
* Each integer polynomial has to (eventually) appear in the sequence generated by your program
* Polynomials are **not** allowed to appear more than once
* The standard sequence [IO-rules](https://codegolf.stackexchange.com/tags/sequence/info) apply
* You may output polynomials as lists of coefficients
* Using the empty string/list to represent zero is allowed
* You are allowed to output the coefficients in reverse order (constant coefficient on the left)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") the shortest program (per language) wins.
[Answer]
# [Python](https://docs.python.org/3.8/), 56 bytes
```
P=[[0]]
for*t,h in P:print(P[-1]);P+=t+[h,0],t+[(h<1)-h]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P8A2OtogNpYrLb9Iq0QnQyEzTyHAqqAoM69EIyBa1zBW0zpA27ZEOzpDxyBWB0hrZNgYaupmxP7/DwA "Python 3.8 (pre-release) – Try It Online")
Prints lists indefinitely as polynomials reversed. The idea is that every nonempty list of integers is generated uniquely by repeatedly applying one of two operations starting from the singleton `[0]`:
1. Append a `[0]`
2. Advance the last element `h` via the map `h -> (h<=0)-h`, which walks through the integers as `0, 1, -1, 2, -2, 3, -3, ...`.
We do a breadth-first walk on this infinite binary tree to generate all these lists. To do this, we keep a list `P` of nodes to explore starting with just the root `[0]`, iterate over it, and when we explore a node `l`, we append to `P` the two children of `l`.
Note that branch (1) creates the lists with a trailing 0 and branch (2) creates all those starting with any other value. So, outputting just the branch (2) nodes gives all nonzero polynomials represented without extra trailing zeroes. We do this by repeatedly printing the last element of `P` after doing the append which puts the branch (2) result last. By also doing this print at the start, we also output the zero polynomial at the root of `P`, which we'd otherwise miss.
*Thanks to loopy walt for -1 byte by flipping the order and Jonathan Allan
for -1 from not using `<=`.*
[Answer]
# [Python](https://www.python.org), 75 bytes
```
f=lambda s:s*[0]and[s%-2^r(s//4)]+f(r(s//2))
r=lambda s:s and s%2^2*r(s//4)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3vdNscxJzk1ISFYqtirWiDWIT81Kii1V1jeKKNIr19U00Y7XTNMBMI01NriIkxQpAlQrFqkZxRlpQpVAjfdPyixQU8hQy8xSKEvPSUzVMDDStCooy80o00jTygKZA2DmpeRrVWrmJBRolpQU5qTogVpoORIehARBoamrWakINhbkXAA)
^^^
Version without string intermediates.
# [Python](https://www.python.org), 48 bytes
```
f=lambda n,i:n and(n>>2**i-1&1)-2*f(n>>2*2**i,i)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RY9BCoMwEEX3OcWsSkZUtHRRBF16CZGSYqIBnYQQKaX0JN100257nt6mEVs6q8_M_Pdnbk979oOh-_0xe5Xs35kqRzEdOwEU64JAUMepqrZRpJN8k2OyjdTaWFqxxq_v1UkFNScsGBgooQlbYQrKONCgCZygXnJKj9ofRkm9Hzhiy-A06FEGSwgC0yR5W5ZZYIBJrbEcGTjpZ0dgGFtY9GftMiys0-T5kots1YHNL9EkLPezHWW8qDpeHXkWChGv-D379_YH)
^^^
This one may be illegal: It takes enumeration index and coefficient index and returns only that coefficient.
Uses @Bubbler's negabinaries instead of my previous method.
# [Python](https://www.python.org), 107 bytes
```
lambda n:g(f"{n:b}"[::-1])or[0]
g=lambda s:"1"in s and[-(s[0]>"0")^int("0"+s[2::2][::-1],2)]+g(s[1::2])or[]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCoMwEEX3PUXIKlMVjKsSsDfoCWwKEU0q1VGMLop4km6E0t6pt2lCnM18_vz_5vUdntO9x-2t8-tnnnRy-j1a1ZWVIigM03RBUa60ECLhEvqxSOXB5HvCCsppg8QShVWRMOuuZ5pSuDU4MSciW2RCZDLU4wxkZFyKe8_D5P7yovuRECSONSo0NctSEMPoKZohwCHotka2HDs1sGke2jr2SsehwVM3ALACBOi2hf0H)
If representing the 0 polynomial by the empty list is acceptable, we can save 5 as @JonathanAllan points out.
# [Python](https://www.python.org), 102 bytes
```
lambda n:g(f"{n:b}"[::-1])
g=lambda s:"1"in s and[-(s[0]>"0")^int("0"+s[2::2][::-1],2)]+g(s[1::2])or[]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY1BCoMwEEX3niJklakK6qoE7A16gjSFiCYVdAxRF0U8STdCae_U2zQSZzOPmflvXl_7nB4Dbm9d3j7zpNPzT3eqr2pFkBum6YK8WqngPM0lRKY8liOnOW2RjERhLVI2ikxeaEbh3uLEPMSjKDgvZEgmBcjY-Kt8n8HghDy-XfXgCEHiXU6haViRAbdut2iGAFHgrkG2nHpl2TTbrkl20klI5JkvAFgBgnTbQv8D)
Does not use prime factors. Expects a nonnegative integer and returns the coefficients lowest (constant) to highest.
## How?
Uses binary representation. Coefficient 0 encoded in bits (least significant to most) 1,3,5,7,9,... coefficient 1 encoded in bits 2,6,10,14,..., coefficient 2 encoded in bits 4,12,20,28,..., etc. The bits are simply read as a binary number except that the lsb encodes the sign (more precisely, the presence or absence of a tilde operator i.e. 0 <-> -1, 1 <-> -2, etc. Advantage over "naive" `-`: no redundancy at 0.)
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 10 bytes
```
Ňƒ$ƥ←2EƂ∙ŋ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHHBgqWlJWm6FpuPth-bpHJs6aO2CUauRk6POmYe7V5SnJRcDJWHqQMA)
The zero polynomial is represented by `0`, and other polynomials are represented by an ascending list of coefficients. For example, `x^2 + 2x + 3` is represented by `[3, 2, 1]`.
```
Ňƒ$ƥ←2EƂ∙ŋ
Ň Choose a natural number n
ƒ$ƥ←2EƂ∙ Compute the array of exponents of n's prime factorization.
This is basically Jelly's ÆE operator
ŋ Optionally negate each nonzero element
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 10 ~~ 8 [bytes](https://github.com/DennisMitchell/jelly)
```
ÆENḂ¡€:2
```
A monadic Link that accepts a positive integer, \$n\$, and yields the \$n^{\text{th}}\$ integer polynomial as a list of coefficients for increasing powers of \$x\$ with no trailing zeros (i.e. `[0, 0, 2, 0, -5]` represents \$-5x^4+2x^2\$, and `[]` represents \$0\$)
**[Try it online!](https://tio.run/##ASQA2/9qZWxsef//w4ZFTuG4gsKh4oKsOjL/w4fFkuG5mClZ//8xMDA "Jelly – Try It Online")**
### How?
```
ÆENḂ¡€:2 - Link: n
ÆE - prime factor exponents e.g. n=3*3*7*7*7 -> [0,2,0,3]
€ - for each {exponent value, e}:
¬° - repeat...
Ḃ - ...number of times: modulo 2 {e} -> 1 if e is odd else 0
N - ...action: negate
:2 - integer divide by two (vectorises)
```
This gives the same order as the example sequence, just with negated coefficients.
[Answer]
# [J](https://www.jsoftware.com), 11 bytes
```
_2#._#:@q:]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxOt5IWS9e2cqh0CoWIrJRkys1OSPfIU3NTsFQO1PP2AAivmABhAYA)
The first half (using prime factorization exponents) is stolen from existing solutions, but the second half is new I guess. To convert "all integers >= 0" to "all integers", I use the [negabinary](https://mathworld.wolfram.com/Negabinary.html) system. That is, convert each nonnegative integer to base 2 and then interpret the binary sequence as base -2. This is shorter in J than doing a "divmod 2".
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
ÆEBḅ-2
```
[Try it online!](https://tio.run/##y0rNyan8//9wm6vTwx2tukb/D7cfnfRw5wzNyP//DQ0MAA "Jelly – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 9 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ḟıDu@×;2÷
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVFMSVCOCU5RiVDNCVCMUR1JTQwJUMzJTk3JTNCMiVDMyVCNyZmb290ZXI9JmlucHV0PTUmZmxhZ3M9)
or [verify a few more cases](https://Not-Thonnu.github.io/run#aGVhZGVyPSVDNCVCMSZjb2RlPSVFMSVCOCU5RiVDNCVCMUR1JTQwJUMzJTk3JTNCMiVDMyVCNyZmb290ZXI9JTNCJUMyJUI2aiZpbnB1dD0xMCZmbGFncz0=)
Port of Jonathan Allan's Jelly answer.
*-1 thanks to @Neil*
#### Explanation
```
ḟıDu@×;2÷ # Implicit input
ḟ # Prime factor exponents
ı ; # Map over this list:
D # Duplicate current number
u@ # -1 ** that
√ó # Multiply by the number
2√∑ # Floor divide each by 2
# Implicit output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~56~~ ~~53~~ ~~51~~ 31 bytes
```
≔IE⮌⍘N²ιθWθ«≔Φι﹪λ²θ⟦I↨⮌Φι¬﹪λ²±²
```
[Try it online!](https://tio.run/##TY9La9xAEITP9q/Y4yw40I@ZfpBTYjDk4MUkx5CD4oi1QNm1V1rnEPLb5ZIxSWBmpJ7pr6rr/qE73R@7cVk@TNOwP5TrbprLbfdYPvfP/Wnqy8du6r/Mp@GwL58Oj@d5d/75vT@V7dVGtjgG7Kft@8tfD8PYb8rTdvP78uJN62YYZ7QOV5vb44/zeCzjG7QCF3fQnMvXV8PV5K/jP2x3xCz/oyu86/fd3Je1@gadP8sSGVGtmVdlbp5Nw1BLw1/WxqJmQa9dkdXRoxKm5tyoUvMIM1VPEsdFcEPZqkDFWEgdMFMzwk7NVHzMQAmqCtFKLhTwlmrAIKucrk4WkeLhyWyhriwpVRrDG@MQTIyZgvFOtdVwqmoIoU1UU9mlCUujphpwJ@XakuGH8QkaTGtmvAJ1RI6aaim69kTlUFpjCyUuK5azhxgCZS7vnscX "Charcoal – Try It Online") Link is to verbose version of code. Outputs the `0`-indexed `n`th polynomial (lowest degree first). Explanation:
```
≔IE⮌⍘N²ιθ
```
Input `n` and convert it to base `2`. (Note that if an empty output is acceptable for the zero polynomial, then `≔⮌↨N²θ` would suffice, saving 3 bytes.)
```
Wθ«
```
Repeat until there are no more terms of the polynomial.
```
≔Φι﹪λ²θ
```
Remove the current term from the value.
```
⟦I↨⮌Φι¬﹪λ²±²
```
Extract the current term from the previous value and convert it from negabinary for output.
~~114~~ ~~111~~ ~~109~~ 87 bytes to pretty-print the output:
```
≔⮌↨N²θWθ«⊞υ↨⮌Φθ¬﹪λ²±²≔Φθ﹪λ²θ»∨Φ⪫⮌Eυ⎇ι⁺⎇∨¬κ⊖↔ι﹪%+dι§ +-ι⎇κ⁺x⎇⊖κ⍘κ”y⁰¹²³⁴⁵⁶⁷⁸⁹”ωωωω∨κ⁻+ι0
```
[Try it online!](https://tio.run/##VVDbattAEH2Ov0IICiuswM7OXsmTSymkYDe0/QHFXmwRRYp1SVJKH/RHpfe8@lP0I@6sYuMUpJFm9txml5usXlZZsd/PmiZfl@yDv/d149nrjMplede1i@722tcsSSORUNkmF5OHTV74iG2T6Mvk7KprNqxLo5FxpL/Ni5ZI2zRaVC2bV6uuqFgxSgSRhV9nrWehu5icHaxPnP/wz5ZfJ1d1XrbsfX3EvavyU9x5dhcyfPJ1mdWfWZ5GV0XXsGNPrJDjhsTe@GXtb33Z@hWbXTdV0VGQfEx1sI1fTVdxGuU0mbWX5co/sjiano@j5ORxc/CIH@PT8KV6cAuX8rGl5OuAj4f@2@5p9333Y@h/Dv2vof899H@G/u/QP8WEfkhelLGmEUUn5jwvg9X0OQSNYx7T3e331lkrtdJGIoAyTqHV1AtFf04qEKi15SPKOmkIg8Jq1AYUl1wZa7VGNI4LQwMLilolBaloEBwNkYErzel16BzSR2tiCeokiUpuBLfkLaQmGskiOIOGa2udMNY4AG3RIAgnpFBA3hSHk4kG4BbonEslreESNS2BSiA6BCOUAKG4QrTkzhGkckB@FJ@TBvCwM50S1dDKVjrUTmDAWAkWeVhbcEdDSY8BY4WmhZzbn98X/wA "Charcoal – Try It Online") Link is to verbose version of code. Pretty-prints the `0`-indexed `n`th polynomial. Explanation:
```
≔⮌↨N²θ
```
Input `n` and convert it to base `2`. (Note that if an empty output is acceptable for the zero polynomial, then `≔⮌↨N²θ` would suffice, saving 3 bytes.)
```
Wθ«
```
Repeat until there are no more terms of the polynomial.
```
⊞υ↨⮌Φθ¬﹪λ²±²
```
Extract the current term from the previous value and convert it from negabinary.
```
≔Φθ﹪λ²θ
```
Remove the current term from the value.
```
»∨Φ⪫⮌Eυ⎇ι⁺⎇∨¬κ⊖↔ι﹪%+dι§ +-ι⎇κ⁺x⎇⊖κ⍘κ”y⁰¹²³⁴⁵⁶⁷⁸⁹”ωωωω∨κ⁻+ι0
```
Pretty-print the polynomial. (And I think this must be the first time I've used 4 `ω`s in a row!)
Edit: Now uses @loopywalt's encoding and @Bubbler's negabinary trick.
[Answer]
# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a`, 35 bytes
```
|-?[1-9][0-9]*(,(0|-?[1-9][0-9]*))*
```
Generates polynomials infinitely, given as lists of coefficients from highest to lowest degree. E.g. `1,-2,3` represents \$x^2-2x+3\$. The first result is the empty string, representing \$0\$.
[Attempt This Online!](https://ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdVm0km6iUuyCpaUlaboWN5VrdO2jDXUtY6MNgISWho6GAaqIpqYWRClUxwIoDQA)
### Explanation
Iterating over countable sets is basically Regenerate's whole thing, although since it's designed for generating strings, its number-handling is a bit primitive.
```
|-?[1-9][0-9]*(,(0|-?[1-9][0-9]*))*
| Either the result is empty, or:
-?[1-9][0-9]* Lead with a nonzero coefficient:
-? Possibly negative
[1-9] Starts with a nonzero digit
[0-9]* Continues with 0 or more additional digits
( )* Continue with zero or more further coefficients:
, Comma to separate from previous coefficient
(0| ) Either the coefficient is 0, or it's nonzero:
-? Possibly negative
[1-9] Starts with a nonzero digit
[0-9]* Continues with 0 or more additional digits
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 36 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 4.5 bytes
```
∆ǏÞnİ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyJyPSIsIiIsIuKIhsePw55uxLAiLCIiLCI3Il0=)
Ports jelly with a few vyxal specific things.
*-15 bits/-1.875 bytes from Bubbler pointing out that `√ûn` exists*
## Explained
```
∆ǏÞnİ­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌­
∆Ǐ # ‎⁡To each prime factor exponent from the input
İ # ‎⁢get the exponent-th item of
Þn # ‎⁣an infinite list of all the integers (positive and negative - 0, 1, -1, 2, -2, ...)
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Scala](https://www.scala-lang.org/), 260 bytes
Port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/263217/110802) in Scala.
---
Golfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=ZZDBTsJAEIZj4qlPMRfIjFJckIOptIkJFxPrhXgiYLali2vKQnYXE4U-iRcueNIH0qdx2wYJcQ6z_-z882V33j9MynN-uf1aJM9ZaiHmUsF6t7LCv_o5OZ1mAgbIg1tlW0mZKZQCkUes2UwiRpsN8n6p-4yIXySQ5SYDZ-GNJAzZ4coJv-OVuPgYh6WVzhNqJFVboKkawZ00duTUODQw5zZ9WqfcgVgY3cv8utKPYYQxmpbfpYnGgVM9IgoCgXXVdVVRUfWe6tI_HvujxdXQBLtnB1xRL-P7E6Akzd2CkOuZCeBGa_46Glot1WxMATwoaSGEtQcuxEKjgr4PDFbKyhx6jGDprDZXKFARVbYXnsPU_VSq1JY_Ng6A-5EOc0HtOV-ioLZdDDNbDe0xR4NtI9-yElp4hVe_ebutz18)
```
def D(a:Int,b:Int)=if((a>0&&b>0)||(a<0&&b<0))a/b else if(a%b==0)a/b else a/b-1
def M(a:Int,b:Int)=((a%b)+b)%b
def f(s:Int):List[Int]=s match{case 0=>Nil;case _=>(M(s,-2)^r(D(s,4)))::f(r(D(s,2)))}
def r(s:Int):Int=s match{case 0=>0;case _=>M(s,2)^(2*r(D(s,4)))}
```
Ungolfed version. [Attempt This Online!](https://ato.pxeger.com/run?1=dVLBTsJAEE088hXvItkVigU5GENJTLyYiBfiiaDZlhbWlC3pLiQo3P0HL170o_waZ7c0BSI9bGdn5s17MzufPzoSqbj6-vpemsS7_j37yMLXODIYCKnwXgMmcYLF2swydSdXTNzgXpkmQvfn7kTgEgGZgDGBPnzU6witwbHZgHy90kcG5xC4ROgwcapjBxQ4p3AQWMxR2F3hoU2ube1A0yCbnNLEipIcDXuQVSITpsvMB6nNiMwx5WvMhYlmu14iQcQ-gj4eZVp5XqzHoljFr5vwOhzPyFk1KHJ2OXXaaBDfUaBDgf1W8kpQIf2UFP9IyIEGJ4F1cPGfjn26OT0tE_mUSG_zXKxHQ5NLNR0T_ZOS1XMmWc4Ueh5xL5WRKbr0NAtKNaliCVOuKrASKSY0EakiYyej7exLSNunj7fmYsES3jLZMDYOVJY5ALa0fIsLqdtasZC7vSz38w8)
```
object Main {
def pythonDiv(a: Int, b: Int): Int = {
if ((a > 0 && b > 0) || (a < 0 && b < 0)) a / b
else if (a % b == 0) a / b
else a / b - 1
}
def pythonMod(a: Int, b: Int): Int = ((a % b) + b) % b
def f(s: Int): List[Int] = s match {
case 0 => Nil
case _ => List(pythonMod(s, -2) ^ r(pythonDiv(s, 4))) ++ f(r(pythonDiv(s, 2)))
}
def r(s: Int): Int = s match {
case 0 => 0
case _ => pythonMod(s, 2) ^ (2 * r(pythonDiv(s, 4)))
}
def main(args: Array[String]): Unit = {
for(n <- 0 until 40) println(f(n))
val distinctLists = (0 until 10000).map(f).toSet
println(distinctLists.size)
}
}
```
[Answer]
# Python3, 242 bytes:
```
def f(n):
d,D={},{}
while n>1:
k=0
for i in range(2,n+1):
if all(i%j for j in range(2,i)if i!=j):
k+=1;D[i]=k
if 0==n%i:d[i]=d.get(i,0)+1;n//=i
return'+'.join(f'{(abs(T:=d[j])//2+1*T%2)*[-1,1][T%2]}*x^{D[j]-1}'for j in d)
```
Returns a pretty-printed polynomial for \$n\$.
[Try it online!](https://tio.run/##XU9Na4QwED3XXzE9iInJrsZeyi7pyX8hFixJdifKKKmlLeJvt3EXSulleF8D703f83Wkp@cpbJuxDhwjfkrAyFovq1zWBD6vOFigFxVl6HUZrxsDICBB6OhiWSVJqP0LAB10w8Aw9beQ/xtCHl181P4ehV5oda4bbHV/49EttaYUT2YXzfFiZ4ay5EKdqSg0JhDs/BEoE9nRj0jMZQvr3t6ZaXzLi6ISKt9hWvG8OSip2uZO2zX/el3qiA9qzX6LGb79W6IkqDLWe5gC0swcQ863Hw)
[Answer]
# [Haskell](https://www.haskell.org), 96 bytes
```
import Data.List
f=nub$(dropWhile(==0))<$>concatMap(\n->(iterate(map(:)[-n..n]<*>)[[]])!!n)[0..]
```
`iterate(map(:)[-n..n]<*>)[[]]!!n` gets us {−*n*, …, *n*}*ⁿ*. Then we drop leading zeros and let `nub` do all the hard work.
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNxMycwvyi0oUXBJLEvV8MotLuNJs80qTVDRSivILwjMyc1I1bG0NNDVtVOyS8_OSE0t8Ews0YvJ07TQyS1KLEktSNXKBAlaa0bp5enp5sTZadprR0bGxmoqKeZrRBnp6sRB7duUmZuYp2CoUFGXmlSioKJQkZqcqmBoAWWkQBTAHAQA)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
f=(n,i=0)=>n?n&1?f(n/2,(i<1)-i):[i,...f(n>>1)]:[]
```
[Try it online!](https://tio.run/##DctBDkAwEADA38huVKkb1XqIOAitrMiulPh@uU4yx/Iu95roeiqWLeQcHbAi16DzPHJhxghctwpoMFgR9hMprfWP3huc@2nONkqCf1ga2tDZsiRchW85gz5lhwiEaPMH "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 52 bytes
```
f=(n,i=0)=>n?n&1?f(n/2,i+1):[n&2?~i:i,...f(n>>2)]:[]
```
[Try it online!](https://tio.run/##DctBCoAgEADA38QumpVHRX1IdIjK2IjdqOjY163rwGzjM17TScdds8xLKTkAawothsiJqy5l4MZqUh26niubXnKkjTG/x2hxcP1QfJYT/uS9UoST8CX7YnZZIQMh@vIB "JavaScript (Node.js) – Try It Online")
Write index into binary and convert `x011111` into one coefficient
zero is expressed as `00` so needn't extra check of remaining
[Answer]
# [BQN (CBQN)](https://mlochbaum.github.io/BQN/), 55 bytes
```
{ùï©‚Üë‚ç∑‚àæ{{‚äë(ùï©=0)‚äê0}‚ä∏‚Ü쬮‚àæ{‚•ä([‚•ä(‚Üïùï©)‚âç(-‚Üïùï©)])‚àæ‚åú‚çüùï©‚ãà‚ü®‚ü©}¬®‚Üïùï©}¬®‚Üïùï©+2}
```
This is a port of my Haskell answer. It's extremely slow.
[Attempt This Online!](https://ato.pxeger.com/run?1=m704qTBvwYKlpSVpuhY3Gx81LArOyC-v_jB36spHbRMf9W5_1LGvuvpR10QNkJCtgeajrgkGtY-6djxqm3xoBUjy0dIujWgQ8ahtKkiN5qPOXg1dGCdWE6jmUc-cR73zwWZ2dzyav-LR_JW1QM0QJQiWtlGtCcQhUPfA3AUA)
] |
[Question]
[
I just discovered this site and this is my first question, I hope I'm doing it correctly.
The challenge is the following, you must write a code that prints all the prime numbers of \$n\$ digits. Since this problem is computationally complicated, I think that one way to simplify it is to give a number \$m\$ that will be the first digits of the primes to be printed and let's take \$n\in[1,2,...,10]\$ (there are 45086079 10-digit primes [OEIS A006879](https://oeis.org/A006879)). To reduce problems that the primes of large digits (10,9,8) can generate, we can say that if \$n=10,9,8,7\$ then \$\#m\geq 3\$, where \$\#m\$ denotes the number of digits in \$m\$.
**EXAMPLE**
```
input:
n=4
m=22
output:
2203 2207 2213 2221 2237 2239 2243 2251 2267 2269 2273 2281 2287 2293 2297
```
**RULES**
* You can use built-in functions to generate prime numbers.
* The user must provide \$m\$ and \$n\$.
* Lowest number of bytes in each language wins.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + [bsdgames package](https://manpages.debian.org/testing/bsdgames/primes.6.en.html), 39
```
primes 1 $[10**$2]|grep ^$1|egrep .{$2}
```
[Try it online!](https://tio.run/##S0oszvj/v6AoMze1WMFQQSXa0EBLS8Uotia9KLVAIU7FsCYVzNKrVjGq/f//v5HRfxMA "Bash – Try It Online")
[Answer]
# [R](https://www.r-project.org), 65 bytes
```
\(n,m,k=10^(n-nchar(m)))for(i in 0:k+m*k)sum(!i%%2:i)<2&&print(i)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3HWM08nRydbJtDQ3iNPJ085IzEos0cjU1NdPyizQyFTLzFAyssrVztbI1i0tzNRQzVVWNrDI1bYzU1AqKMvNKNDI1IQZtS9Mw0TEy0uRK0zDUMQdRRjqGxlDJBQsgNAA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~12~~ 11 bytes
```
↵:₀/ṡ~æ'⁰øp
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLihrU64oKAL+G5oX7DpifigbDDuHAiLCIiLCI0XG4yMiJd)
Takes `n` then `m`. Prints the primes in order from largest to smallest.
## Explained
```
↵:₀/ṡ~æ'⁰øp
↵:₀/ # 10 ** n, 10 ** (n - 1)
ṡ # range(^, ^)
~æ # filtered to only include primes
'⁰øp # and filtered to only keep numbers which start with m
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
Lε↵~*~+ṡ~æ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJMzrXihrV+Kn4r4bmhfsOmIiwiIiwiMjJcbjQiXQ==)
```
↵ # 10 **
ε # Digit count minus
L # Length of starting digits
~* # Multiply by starting digits (without popping)
~+ # Add to starting digits (without popping)
ṡ # Range from ^^ to ^
~æ # Filter by isprime
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
≔Xχ⁻NLηθIΦ⁺…⁰θ×Nθ∧›ι¹⬤…²ι﹪ιλ
```
[Try it online!](https://tio.run/##ZYzLCsIwEEX3/YosJxChDe66KoIiWCniD8Q2tIHpxOahnx8Tcefs5tx77rgoN1qFKXXem5lgsG/toKkF6w1FD2d6xnCN6yNTLthF0xwWWDjPz8bbanCGAhyUD3A0GHJrwKzdFM0a6tIR7G5W/be0lYWOJjg5rYpnBGsKQvzZUjCTQW@niLbEyL/XprSvpEy7F34A "Charcoal – Try It Online") Link is to verbose version of code. Takes `n` as the first input and `m` as the second. Explanation:
```
≔Xχ⁻NLηθ
```
Subtract the number of digits in `m` from `n` and then take `10` to that power.
```
IΦ⁺…⁰θ×Nθ∧›ι¹⬤…²ι﹪ιλ
```
Take the range from `0` to that number, add on `m` multiplied by that number, then output only the prime numbers in that range.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 10 bytes
```
⟨{~l}a₀⟩ṗ≜
```
[Try it online!](https://tio.run/##ATMAzP9icmFjaHlsb2cy/@KGsOKCgeG2oP/in6h7fmx9YeKCgOKfqeG5l@KJnP//WzQsMjJd/1o "Brachylog – Try It Online")
A generator solution that generates all possible outputs (the TIO header converts the generator to a list for printing, but [consensus](https://codegolf.meta.stackexchange.com/a/10753) is that the generator on its own is sufficient to output a list). Input is a list `[*n*,*m*]`.
This should be 8 bytes, but I had to add grouping characters `{}` to work around a bug in Brachylog's parser.
## Explanation
```
⟨{~l}a₀⟩ṗ≜
~ Checking values whose
l length
⟨ is the first input, and
a₀ which have a prefix that is
⟩ the second input,
ṗ using only the values that are prime numbers,
≜ generate all specific values that meet these criteria.
```
The `{` and `}` don't do anything but are required to prevent the parser crashing.
One interesting quirk of Brachylog: the `l` doesn't imply anything about us looking for *numbers* here, and will also try 4-element lists, but a few of the later restrictions restrict the program to looking for numbers specifically and thus it'll discount 4-element lists as a possibility.
Brachylog's primality testing algorithm is slow but general – it'll work in theory for any number of digits and any size of prefix, but may take a long time on larger numbers.
[Answer]
# [Python](https://www.python.org), 83 80 75 bytes
```
lambda n,m:primerange(x:=m*(y:=10**(n-len(str(m)))),x+y)
from sympy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3vXMSc5NSEhXydHKtCooyc1OLEvPSUzUqrGxztTQqrWwNDbS0NPJ0c1LzNIpLijRyNYFAp0K7UpMrrSg_V6G4MregUiEztyC_qEQLYuT2PFsTrlxbIyMuoHl5JRpaaRpAwzU1IbILFkBoAA)
-3 bytes by changing list(x) to [\*x]
-5 bytes thanks to [@emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 117 bytes
```
.+$
$*#
((.)+)¶(?<-2>#)+
$1
+%1`#
0$'¶$`1$'¶$`2$'¶$`3$'¶$`4$'¶$`5$'¶$`6$'¶$`7$'¶$`8$'¶$`9
.+
$*
A`^1?$|^(11+)\1+$
%`1
```
[Try it online!](https://tio.run/##Jc09CoAwDEDhPddoxNZgMbX@gSjeQ6QODi4O4ui5PIAXq0Kmb3vv3K79WGO0hICZAq2tIfM@euxzNyhDgAyUcFBQYPo@GFhwQil4oRJqoRFaoQP7xzKYwsIj3otmJjPz/00Cx@gc@A8 "Retina 0.8.2 – Try It Online") Takes `m` as the first input and `n` as the second. Explanation:
```
.+$
$*#
```
Convert `n` to unary.
```
((.)+)¶(?<-2>#)+
$1
```
Decrement `n` for each digit of `m`.
```
+%1`#
0$'¶$`1$'¶$`2$'¶$`3$'¶$`4$'¶$`5$'¶$`6$'¶$`7$'¶$`8$'¶$`9
```
Extend `m` to be `n` digits long, a digit at a time.
```
.+
$*
```
Convert all the values to unary.
```
A`^1?$|^(11+)\1+$
```
Discard `0`, `1` and all composite numbers. (If `n` was always at least `2`, the `^1?$|` would not be needed for a saving of 5 bytes.)
```
%`1
```
Convert the remaining primes back to decimal.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
°DT÷Ÿʒp}ʒ²Å?
```
[Try it online!](https://tio.run/##ASEA3v9vc2FiaWX//8KwRFTDt8W4ypJwfcqSwrLDhT///zQKMjI "05AB1E – Try It Online")
Port of lyxal's Vyxal answer. It can probably be a bit shorter, but I can't get it to work with just 1 filter.
**Explanation:**
```
°DT÷Ÿʒp}ʒ²Å? # Implicit input, with n first then m
° # 10 ** n
DT÷ # 10 ** (n - 1)
Ÿ # Range between them
ʒp} # Primes only
ʒ # Keep only those
Å? # which start with
² # the second input, m
# Implicit output
```
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 17 \log\_{256}(96) \approx \$ 13.99 bytes
```
10@D10,s:gNkgz1ZV
```
(No ATO link since that's on an older version)
Port of lyxal's Vyxal answer.
#### Explanation
```
10@D10,s:gNkgz1ZV # Implicit input, with n first then m
10@ # 10 ** n
D10, # 10 ** (n - 1)
s: # Range between them
gNk # Primes only
g # Keep only those
ZV # which start with
z1 # the second input, m
# Implicit output
```
#### Screenshot
[](https://i.stack.imgur.com/YHrC0.png)
[Answer]
# [C (gcc)](https://gcc.gnu.org/) with `-lgmp`, ~~159~~ 147 bytes
* -2 thanks to ceilingcat
* -10 by removing the `#import`
Takes a number length and prefix (as a string).
Luckily GMP has a "next prime number" function, so I just had to turn the prime numbers into strings and compare the prefix to the stringified values.
```
*t,p[9];f(m,w,u,v)int*w;{u=strlen(w);__gmpz_init(p);for(v=0;v<=m;(v=__gmp_asprintf(&t,"%Zd",p))==m&!strncmp(w,t,u)&&puts(t))__gmpz_nextprime(p,p);}
```
[Try it online!](https://tio.run/##LczRCoIwFMbx@57ChOQcOUJIN7H2IkWITCcDN4ceNRJfvTWiuw8@fn9VdEqFkDP5x/UpNFhaaaYFjeN8FdssJx771sGKoqo669@VcYbBo9DDCIs8i@UmrYjrd1f15MdoNWRM6enepOQRpbTZMYacsh5WYpoxy/zMEzDiP@vaF0dqW/CRiD3ESmJr42AZTIPJdkgSDRdKyzJFcdjDR@m@7qZQ9NF/AQ "C (gcc) – Try It Online")
[Answer]
# [JavaScript (V8)](https://v8.dev/), 78 bytes
Expects `(n)(m)`, with `m` passed as a string.
```
n=>m=>{for(q=1;!m[n-1];q*=10)m+=0;for(;q--;m++)for(x=m;x-2||print(m),m%--x;);}
```
[Try it online!](https://tio.run/##XcpBCsIwEIXhvafQgpAxDjRpF8IwvYi4KEKhwtQmlhKwnj0mdJfl@97/6tf@8/TjvOB6iwPHiTvh7ju8vXJs6CT3Cc2D3IVNDaK5pnyRQyTRGvIILBTQbtvsx2lRAlc5IwYC@sVBGVBVUwEd9xfosFtBNpEtrElmCmtzl8L4Bw "JavaScript (V8) – Try It Online")
### Commented
```
n => // outer function taking n
m => { // inner function taking m
for( // initialization loop:
q = 1; // q = size of range, initialized to 1
!m[n - 1]; // stop when m is large enough
q *= 10 // at each iteration, multiply q by 10
) m += 0; // and append a trailing 0 to m
for( // main outer loop:
; //
q--; // stop when q = 0 / decrement it afterwards
m++ // increment m after each iteration
) //
for( // main inner loop:
x = m; // stat with x = m
x - 2 || // if we've reached x = 2 without breaking:
print(m), // m is prime --> print it
m % --x; // decrement x and stop if it's a divisor of m
); //
} //
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
°ÅP¹ùʒIÅ?
```
[Try it online.](https://tio.run/##yy9OTMpM/f//0IbDrQGHdh7eeWqS5@FW@///TbiMjAA)
**Explanation:**
```
° # Push 10 to the power of the first (implicit) input-integer `n`
ÅP # Pop and push a list of all primes lower than (or equal to) that 10**n
¹ù # Only keep the primes with a length equal to the first input `n`
ʒ # Filter it further by keeping those:
IÅ? # That start with the second input-integer `m`
# (after which the filtered list of primes is output implicitly as result)
```
---
If we could assume that \$n>L\_m\$, where \$L\_m\$ is the length of \$m\$, it could be 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) instead:
```
°Ý«¹ùʒp
```
[Try it online.](https://tio.run/##ARsA5P9vc2FiaWX//8Kww53Cq8K5w7nKknD//zQKMjI)
Without that assumption, it would still be 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) with this approach:
```
°Ý«Iš¹ùʒp
```
[Try it online.](https://tio.run/##AR4A4f9vc2FiaWX//8Kww53Cq0nFocK5w7nKknD//zIKMTM)
**Explanation:**
```
° # Push 10 to the power of the first (implicit) input-integer `n`
Ý # Pop and push a list in the range [0,10**n]
« # Append each to the second (implicit) input-integer `m`
¹ù # Only keep the integers with a length equal to the first input `n`
ʒ # Filter it further by keeping those:
p # That are primes
# (after which the filtered list is output implicitly as result)
Iš # (prepend the second input-integer `m` to the list; if the length of `m` is
# equal to `n`, the final result will be `[m]` iff `m` is a prime, or an
# empty list otherwise)
```
[Answer]
# [Python](https://www.python.org), 105 bytes
```
lambda n,m:[p for p in primerange(10**n+1)if n==len(d:=str(p))and(s:=str(m))<=d<s+'~']
from sympy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Jc2xDcIwEAXQPlNcF18SJBJRoCieBCiMHIOl3NmynSINi9BEQjACu7ANkVx9_f-L9_z4Jd0dry8jz-85md3xZydFV62AG-pPHowL4MEy-GBpDIpvo2j3VcV1i9YASzmNLHQvYwrCIyrWIuZGiIPUQ6zLR3kpTHAEcSG_gCXvQqoy-N0geWi6rtgETsKIbUDM57rm_AM)
] |
[Question]
[
## Input:
A non-empty list / vector where each element holds a value/character, indicating if you'll count **up** or **down**. I'll use `1` and `-1`, but you may choose whatever you like. You can only use two values, you can't use `1,2,3...` and `-1,-2,-3...`, for up and down respectively.
## Challenge:
You'll use the numbers in the geometric series **1, 2, 4, 8, 16, 32...**. Every time you start counting up or down, you'll count in increments of **1**, then **2**, then **4** and so on. If you change and start counting the other way then you'll subtract **1**, then **2**, then **4** and so on. The output shall be the number you get to in the end.
### Examples:
In the example below, the first line is the input, the second line is the numbers you're counting up/down, the third line is the cumulative sum, and the last line is the output.
**Example 1:**
```
1 1 1 1 1 1 1 1 1 1
1 2 4 8 16 32 64 128 256 512
1 3 7 15 31 63 127 255 511 1023
1023
```
**Example 2:**
```
1 1 1 1 1 1 -1 -1 -1 -1 1 1 1
1 2 4 8 16 32 -1 -2 -4 -8 1 2 4
1 3 7 15 31 63 62 60 56 48 49 51 55
55
```
As you can see, the first `1` or `-1` "resets" the value we're counting, and consecutive sequences of `1` or `-1` means doubling the value.
**Example 3:**
```
-1 -1 1 1 -1 -1 -1
-1 -2 1 2 -1 -2 -4
-1 -3 -2 0 -1 -3 -7
-7
```
---
Some additional test cases to account for some potential corner cases.
The input is on the first line. The output is on the second.
```
1
1
-------
-1
-1
-------
-1 1 -1 1 -1 1 -1 1 -1 1 -1 1
0
```
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest submission in each language wins.
[Answer]
## [Husk](https://github.com/barbuz/Husk), 3 bytes
```
ṁḋg
```
[Try it online!](https://tio.run/##yygtzv6vkJv/qKmx6NC2/w93Nj7c0Z3@////aMNYrmhdCKEDRCCoC0VAQYgACoQohSrGQqDp0kVCEP0A "Husk – Try It Online")
## Explanation
```
ṁḋg
g Group equal adjacent elements,
ṁ take sum of
ḋ base-2 decoding of each group.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
Y'Wq*s
```
[Try it online!](https://tio.run/##y00syfn/P1I9vFCr@P//aEMFBNRFQmAYCwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8D9SPbxQq/i/S8j/aEMFDBjLhSKqi4Rg8ggeTAqkCSwBkYXKYyFiAQ).
### Explanation
Consider input `[1 1 1 1 1 1 -1 -1 -1 -1 1 1 1]`.
```
% Implicit input
% STACK: [1 1 1 1 1 1 -1 -1 -1 -1 1 1 1]
Y' % Run-length encoding
% STACK: [1 -1 1], [6 4 3]
W % Exponentiation with base 2, element-wise
% STACK: [1 -1 1], [64 16 8]
q % Subtract 1
% STACK: [1 -1 1], [63 15 7]
* % Multiply, element-wise
% STACK: [63 -15 7]
s % sum of array
% STACK: 55
% Implicit display
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~8~~ 6 bytes
*-2 bytes thanks to @ETHproductions*
```
ò¦ xì2
```
[Try it online!](https://codepen.io/justinm53/full/NvKjZr?code=8qYgeOwy&inputs=WzEsMSwxLDEsMSwxLDEsMSwxLDFd,WzEsMSwxLDEsMSwxLC0xLC0xLC0xLC0xLDEsMSwxXQ==,Wy0xLC0xLDEsMSwtMSwtMSwtMV0=,WzFd,Wy0xXQ==,Wy0xLDEsLTEsMSwtMSwxLC0xLDEsLTEsMSwtMSwxXQ==)
## Explanation
Implicit input: `[1, 1, 1, -1, -1, -1, -1, 1, 1]`
```
ò¦
```
Partition input array (`ò`) between different (`¦`) elements:
`[[1, 1, 1], [-1, -1, -1, -1], [1, 1]]`
```
ì2
```
Map each partition to itself parsed as an array of base-`2` digits (`ì`): `[7, -15, 3]`
```
x
```
Get the sum (`x`) of the resulting array: `-5`
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 65 bytes
```
W(?\q.p)w.;0.w;/0>I!U-unP(nwUs;q\^q:;^!u?P(w!u+w.;;>2p!u/@Os..sr\
```
[Try it online!](https://tio.run/##Sy5Nyqz4/z9cwz6mUK9As1zP2kCv3FrfwM5TMVS3NC9AI688tNi6MCau0Mo6TrHUPkCjXLFUG6jM2s6oQLFU38G/WE@vuCjm/39DBQTURUJgCAA "Cubix – Try It Online")
```
W ( ? \
q . p )
w . ; 0
. w ; /
0 > I ! U - u n P ( n w U s ; q
\ ^ q : ; ^ ! u ? P ( w ! u + w
. ; ; > 2 p ! u / @ O s . . s r
\ . . . . . . . . . . . . . . .
. . . .
. . . .
. . . .
. . . .
```
[Watch it run](https://ethproductions.github.io/cubix/?code=ICAgICAgICBXICggPyBcCiAgICAgICAgcSAuIHAgKQogICAgICAgIHcgLiA7IDAKICAgICAgICAuIHcgOyAvCjAgPiBJICEgVSAtIHUgbiBQICggbiB3IFUgcyA7IHEKXCBeIHEgOiA7IF4gISB1ID8gUCAoIHcgISB1ICsgdwouIDsgOyA+IDIgcCAhIHUgLyBAIE8gcyAuIC4gcyByClwgLiAuIC4gLiAuIC4gLiAuIC4gLiAuIC4gLiAuIC4KICAgICAgICAuIC4gLiAuCiAgICAgICAgLiAuIC4gLgogICAgICAgIC4gLiAuIC4KICAgICAgICAuIC4gLiAuCg==&input=MSAgIDEgICAxICAgMSAgIDEgICAxICAgLTEgIC0xICAtMSAgLTEgIDEgICAxICAgMQ==&speed=15)
As a brief explanation of this:
* Read in each integer (1 or -1) and compare it to previous. If:
+ the same push it to the bottom as the start of a counter
+ else bring counter to top and increment/decrement it as appropriate.
* Once input is finished bring each counter to the top and handling negatives do 2 ^ counter - 1
* Sum the results and output
[Answer]
## JavaScript (ES6), 38 bytes
```
a=>a.map(e=>r+=d=d*e>0?d+d:e,r=d=0)&&r
```
[Answer]
# [R](https://www.r-project.org/), 32 bytes
```
sum((2^(R=rle(scan()))$l-1)*R$v)
```
[Try it online!](https://tio.run/##K/r/v7g0V0PDKE4jyLYoJ1WjODkxT0NTU1MlR9dQUytIpUzzv66hggIIAxEYw/i6hv8B "R – Try It Online")
This is the same method as a few others here.
With the input of `-1 -1 1 1 -1 -1 -1`
* Do a Run Length Encoding on the input. Results with lengths of `2, 2, 3` and values `-1, 1, -1`
* Do 2 to power of lengths - 1. Results in `3, 3, 7`
* Multiply by the RLE values giving `-3, 3, -7`
* Return the sum `-7`
[Answer]
# [Python 3](https://docs.python.org/3/), ~~57~~ 56 bytes
*-1 byte thanks to @notjagan*
```
f=lambda a,*s,m=1:m*a+(s>()and f(*s,m=(m*2)**(a==s[0])))
```
[Try it online!](https://tio.run/##dY/BCoMwEETvfsXe3KRp0ZZexPRHbA5bJFRoopgcLOK321hagqXCLguzbwame/p7a0@zBgnXWcsHmVtNQII7YWReGE47dBdkZGvQ@FbR8CPjHElKV2WKMTZTsFcJQJUL2Bwl/hP7n13hazFin7AvFOHIb59AqyTRbQ8DNBaoCOaub6zHdCzKczbBOKWH8Dfk0fkeByaW9sPS9QU "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ŒgḄS
```
[Try it online!](https://tio.run/##y0rNyan8///opPSHO1qC////H22og4C6SAgMYwE "Jelly – Try It Online")
[Answer]
# C++14, 58 bytes
```
[](auto v,int&s){int p=s=0;for(auto x:v)s+=p=x*p<1?x:2*p;}
```
Takes input via the `v` argument (`std::vector`, or any iterable container), outputs to the `s` argument (by reference). Each element of `v` must be either `1` or `-1`.
[Example usage and test cases.](http://coliru.stacked-crooked.com/a/ccb1ed581386c8fb)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
ḅ⟨{ȧᵐ~ḃ}×h⟩ᵐ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO1kfzV1SfWP5w64S6hzuaaw9Pz3g0fyWQp/3/f7ShDgLGIyEwjP0fBQA "Brachylog – Try It Online")
Brachylog uses `_` instead of `-`.
Explanation:
```
?ḅ⟨{ȧᵐ~ḃ}×h⟩ᵐ+. Predicate (implicit ?.)
? The input
ḅ A list where its elements' elements are equal, and when concatenated is ?
ᵐ The result of mapping this predicate over ?
⟨ ⟩ The result of forking two predicates over ? with a third
{ } The result of this predicate on ?
ᵐ The result of mapping this predicate over ?
ȧ The absolute value of ?
~ An input where the result of this predicate over it is ?
ḃ A list that represents the digits of ? in base I (default 2)
h An object that is the first element of ?
× A number that is the product of ?
+ A number that is the sum of ?
. The output
```
[Answer]
# Python, ~~76~~ 72 bytes
```
f=lambda s,k=1:len(s)and(f(s,s[0])if s[0]*abs(k)/k-1else k+f(s[1:],2*k))
```
[Try it online!](https://tio.run/##dc/BCoMwDADQu1@Rm62rm93Ypcwv6XqIaJlUq9geHOK3uw42xDGhSSB5CbR/@kdnL4uGHO6LzhtsixLBMZNz0VSWOIq2JJo45mSmaK3hXRMsHDH0ZFJeNa4CcwhCcqHYOTGULhjOyQhAcga7T7H/Iv2JDd82V/Y59kUrXv1@CVpFke4GGKG2gCIs90NtPYkncbtmM0xzfAzzFj1xfiAjZaBDDl99AQ)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
sm*edt^2hdr8
```
[Try it online!](http://pyth.herokuapp.com/?code=sm%2aedt%5E2hdr8&test_suite=1&test_suite_input=%5B1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+1%5D%0A%5B1%2C+1%2C+1%2C+1%2C+1%2C+1%2C+-1%2C+-1%2C+-1%2C+-1%2C+1%2C+1%2C+1%5D%0A%5B-1%2C+-1%2C+1%2C+1%2C+-1%2C+-1%2C+-1%5D%0A%5B1%5D%0A%5B-1%5D%0A%5B-1%2C+1%2C+-1%2C+1%2C+-1%2C+1%2C+-1%2C+1%2C+-1%2C+1%2C+-1%2C+1%5D&debug=0)
[Answer]
# PHP, 51 bytes
```
while($d=$argv[++$i])$s+=$x=$d*$x>0?2*$x:$d;echo$s;
```
Run with `-n` or [try it online](http://sandbox.onlinephpfunctions.com/code/9843edffa5bddb9f4a4d9d5957ada0f6f13be38f).
[Answer]
## CJam (13 bytes)
```
{e`{(*2b}%1b}
```
[Online test suite](http://cjam.aditsu.net/#code=qN%2F%7B%5B~%5D%0A%0A%7Be%60%7B(*2b%7D%251b%7D%0A%0A~p%7D%2F&input=1%20%20%201%20%20%201%20%20%201%20%20%201%20%20%201%20%20%201%20%20%201%20%20%201%20%20%201%20%20%20%0A1%20%20%201%20%20%201%20%20%201%20%20%201%20%20%201%20%20%20-1%20%20-1%20%20-1%20%20-1%20%201%20%20%201%20%20%201%0A-1%20%20-1%20%201%20%20%201%20%20%20-1%20%20-1%20%20-1%0A1%0A-1%0A-1%20%20%201%20%20-1%20%20%201%20%20-1%20%20%201%20%20-1%20%20%201%20%20-1%20%20%201%20%20-1%20%20%201%0A). This is an anonymous block (function) which takes an array of ints on the stack and leaves an int on the stack. The last test shows that it handles an empty array correctly, giving 0.
The approach is straightforward run-length encoding followed by a manual run-length decode of each run and base conversion. Using the built-in for run-length decode I get one byte more with `{e`1/:e~2fb1b}` or `{e`{ae~2b}%1b}`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
γε2β}O
```
[Try it online!](https://tio.run/##MzBNTDJM/f//3OZzW43Obar1//8/2lBHAQ3pomEoigUA "05AB1E – Try It Online")
[Answer]
## Haskell, ~~54~~ 53 bytes
```
k#(a:b:c)=k+last(b:[k*2|a==b])#(b:c)
k#_=k
(#)=<<head
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1tZI9EqySpZ0zZbOyexuEQjySo6W8uoJtHWNilWU1kDJMWVrRxvm82VZquhrGlrY5ORmpjyPzcxM0/BViEln0tBQaGgKDOvREFFIU0h2jAWXUAHAXWREBiiK0ZIwdRhUQFVg4WI/Q8A "Haskell – Try It Online")
A simple recursion that either doubles the accumulator `k` or resets it to `1`/`-1` and adds the values of each step.
[Answer]
# Mathematica, 60 bytes
```
Tr[Last@*Accumulate/@(#[[1]]2^(Range@Tr[1^#]-1)&/@Split@#)]&
```
[Answer]
# Mathematica, 25 bytes
```
Tr[Fold[#+##&]/@Split@#]&
```
[Answer]
# Java, 91 bytes
```
int f(int[]a){int s=0,r=0,i=-1;while(++i<a.length)r+=s=s!=0&s>0==a[i]>0?2*s:a[i];return r;}
```
[Answer]
# Pyth, 11 bytes
```
s.b*t^2NYr8
```
[Try it online](https://pyth.herokuapp.com/?code=s.b%2at%5E2NYr8&input=%5B1%2C1%2C1%2C1%2C1%2C1%2C-1%2C-1%2C-1%2C-1%2C1%2C1%2C1%5D)
### How it works
```
r8 run-length encode input
.b map (N, Y) ↦
^2N 2^N
t minus 1
* Y times Y
s sum
```
] |
[Question]
[
Write a function which takes a list or array, and returns a list of the distinct elements, sorted in descending order by frequency.
Example:
Given:
```
["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"]
```
Expected return value:
```
["Doe","Harry","John","Dick"]
```
[Answer]
## APL (14)
```
{∪⍵[⍒+⌿∘.≡⍨⍵]}
```
This is a function that takes a list, e.g.:
```
names
John Doe Dick Harry Harry Doe Doe Harry Doe John
{∪⍵[⍒+⌿∘.≡⍨⍵]} names
Doe Harry John Dick
```
Explanation:
* `∘.≡⍨⍵`: compare each element in the array to each other element in the array, giving a matrix
* `+⌿`: sum the columns of the matrix, giving how many times each element occurs
* `⍒`: give indices of downward sort
* `⍵[`...`]`: reorder `⍵` by the given indices
* `∪`: get the unique elements
[Answer]
## Python 3 - 47 43; Python 2 - 40 39
For Python 3:
```
f=lambda n:sorted(set(n),key=n.count)[::-1]
```
For Python 2:
```
f=lambda n:sorted(set(n),cmp,n.count,1)
```
Demo:
```
>>> names = ["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"]
>>> f(names)
['Doe', 'Harry', 'John', 'Dick']
```
[Answer]
## Mathematica, 31
```
Sort[GatherBy@n][[-1;;1;;-1,1]]
```
>
> `{"Doe", "Harry", "John", "Dick"}`
>
>
>
(With `n = {"John", "Doe", "Dick", "Harry", "Harry", "Doe", "Doe", "Harry", "Doe", "John"}`)
[Answer]
## Mathematica (26 ~~37~~)
With `n = {"John", "Doe", "Dick", "Harry", "Harry", "Doe", "Doe", "Harry",
"Doe", "John"}`:
```
Last/@Gather@n~SortBy~Length//Reverse
```
>
> {"Doe", "Harry", "John", "Dick"}
>
>
>
---
**Mathematica V10+ (26)**:
```
Keys@Sort[Counts[n],#>#2&]
```
[Answer]
# Perl 6 (36 bytes, 35 characters)
`»` can be replaced with `>>`, if you cannot handle UTF-8. I'm almost sure this could be shorter, but the `Bag` class is relatively strange in its behavior (sadly), and isn't really complete, as it's relatively new (but it can count arguments). `{}` declares an anonymous function.
```
{(sort -*.value,pairs bag @_)».key}
```
Sample output (from Perl 6 REPL):
```
> my @names = ("John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John")
John Doe Dick Harry Harry Doe Doe Harry Doe John
> {(sort -*.value,pairs bag @_)».key}(@names)
Doe Harry John Dick
```
[Answer]
# Ruby: 34 ~~37~~ characters
```
f=->a{a.sort_by{|z|-a.count(z)}&a}
```
(edited: previous 30-char solution was the body of the function)
[Answer]
## GolfScript, 14 chars (19 as named function, also 14 as full program)
```
:a.|{[.]a\-,}$
```
This code takes an array on the stack and sorts its unique elements in descending order by number of occurrences. For example, if the input array is:
```
["John" "Doe" "Dick" "Harry" "Harry" "Doe" "Doe" "Harry" "Doe" "John"]
```
then the output array will be
```
["Doe" "Harry" "John" "Dick"]
```
**Note:** The code above is a bare sequence of statements. To turn it into a named function, wrap it in braces and assign it to a name, as in:
```
{:a.|{[.]a\-,}$}:f;
```
Alternatively, to turn the code into a full program that reads a list from standard input (using the list notation shown above) and prints it to standard output, prepend `~` and append ``` to the code. The `[.` [can be omitted in this case](https://codegolf.stackexchange.com/questions/5264/tips-for-golfing-in-golfscript/8758#8758) (since we know there will be nothing else on the stack), so that the resulting 14-character program will be:
```
~:a.|{]a\-,}$`
```
---
### How does it work?
* `:a` saves a copy of the original array in the variable `a` for later use.
* `.|` computes the set union of the array with itself, eliminating duplicates as a side effect.
* `{ }$` sorts the de-duplicated array using the custom sort keys computed by the code inside the braces. This code takes each array element, uses array subtraction to remove it from the original input array saved in `a`, and counts the number of remaining elements. Thus, the elements get sorted in decreasing order of frequency.
**Ps.** [See here](/revisions/17383/3) for the original 30-character version.
[Answer]
## R: 23 characters
```
n <- c("John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John")
names(sort(table(n),T))
## [1] "Doe" "Harry" "John" "Dick"
```
But it uses the not so nice shortcut of `T` to `TRUE`...
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 5 bytes
```
>#'=:
```
[Try it online!](https://tio.run/##y9bNS8/7/z/Nyk5Z3dbqf5qGkld@Rp6StZJLfiqIzEzOBlIeiUVFlUg0VBJMooqBdWv@BwA "K (ngn/k) – Try It Online")
* `=:` group the input, building a dictionary mapping unique values to the indices in which they appear
* `#'` take the count of each set of indices
* `>` sort the keys of the dictionary by their values, descending
[Answer]
if this could fit here : `In sql-server`
```
create table #t1 (name varchar(10))
insert into #t1 values ('John'),('Doe'),('Dick'),('Harry'),('Harry'),('Doe'),('Doe'),('Harry'),('Doe'),('John')
select name from #t1 group by name order by count(*) desc
```
OR
```
with cte as
(
select name,count(name) as x from #t1 group by name
)
select name from cte order by x desc
```
# [see it in action](http://www.sqlfiddle.com/#!6/c0032/3)
[Answer]
# PHP, 63 62 61 chars
```
function R($a){foreach($a as$v)$b[$v]++;arsort($b);return$b;}
```
Demo:
```
$c = array("John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John");
$d = print_r(R($c));
Array ( [Doe] => 4 [Harry] => 3 [John] => 2 [Dick] => 1 )
```
[Answer]
# Ruby: 59 characters
```
f=->n{n.group_by{|i|i}.sort_by{|i|-i[1].size}.map{|i|i[0]}}
```
Sample run:
```
irb(main):001:0> f=->n{n.group_by{|i|i}.sort_by{|i|-i[1].size}.map{|i|i[0]}}
=> #<Proc:0x93b2e10@(irb):2 (lambda)>
irb(main):004:0> f[["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"]]
=> ["Doe", "Harry", "John", "Dick"]
```
[Answer]
# Mathematica, 39 characters
```
f = Reverse[First /@ SortBy[Tally@#, Last]] &
names = {"John", "Doe", "Dick", "Harry", "Harry",
"Doe", "Doe", "Harry", "Doe", "John"};
f@names
```
>
> {Doe, Harry, John, Dick}
>
>
>
[Answer]
# JavaScript (ECMAScript5): ~~118~~ 113 characters
```
function f(n){m={}
for(i in n){m[n[i]]=m[n[i]]+1||1}
return Object.keys(m).sort(function(a,b){return m[b]-m[a]})}
```
<http://jsfiddle.net/mblase75/crg5B/>
[Answer]
# C#: 111 characters
```
List<string>M(List<string>l){return l.GroupBy(q=>q).OrderByDescending(g=>g.Count()).Select(g=>g.Key).ToList();}
```
(inside a class)
```
var names = new List<string> {"John", "Doe", "Dick", "Harry", "Harry", "Doe", "Doe", "Harry", "Doe", "John"};
foreach(var s in M(names))
{
Console.WriteLine(s);
}
```
>
> Doe
>
>
> Harry
>
>
> John
>
>
> Dick
>
>
>
A simple solution using LINQ.
[Answer]
**Haskell - 53 Characters**
```
import Data.List
import Data.Ord
f :: (Eq a, Ord a) => [a] -> [a]
f=map head.(sortBy$flip$comparing length).group.sort
```
Explanation: the first two lines are necessary imports, the next line of code is the type signature (generally not necessary), the actual function is the last line.
The function sorts the list by its natural ordering, groups equal elements into lists, sorts the list of lists by descending size, and takes the first element in each list.
total length including imports: 120
w/o imports but with type signature: 86
function itself: 53
[Answer]
# Clojure: 43 characters
Function:
```
#(keys(sort-by(comp - val)(frequencies %)))
```
Demo (in repl):
```
user=> (def names ["John","Doe","Dick","Harry","Harry","Doe","Doe","Harry","Doe","John"])
#'user/names
user=> (#(keys(sort-by(comp - val)(frequencies %))) names)
("Doe" "Harry" "John" "Dick")
```
[Answer]
# J, 8 bytes
```
~.\:#/.~
```
## Usage
The names are stored as an array of boxed strings.
```
'John';'Doe';'Dick';'Harry';'Harry';'Doe';'Doe';'Harry';'Doe';'John'
┌────┬───┬────┬─────┬─────┬───┬───┬─────┬───┬────┐
│John│Doe│Dick│Harry│Harry│Doe│Doe│Harry│Doe│John│
└────┴───┴────┴─────┴─────┴───┴───┴─────┴───┴────┘
f =: ~.\:#/.~
f 'John';'Doe';'Dick';'Harry';'Harry';'Doe';'Doe';'Harry';'Doe';'John'
┌───┬─────┬────┬────┐
│Doe│Harry│John│Dick│
└───┴─────┴────┴────┘
```
## Explanation
```
~.\:#/.~ Input: A
#/.~ Finds the size of each set of identical items (Frequencies)
~. List the distinct values in A
Note: the distinct values and frequencies will be in the same order
\: Sort the distinct values in decreasing order according to the frequencies
Return the sorted list implicitly
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÙΣ¢}R
```
[Try it online.](https://tio.run/##yy9OTMpM/f//8Mxziw8tqg36/z9aySs/I09JR8klPxVEZiZnAymPxKKiSiQaKgkmUcXAumMB)
**Explanation:**
```
Ù # Uniquify the (implicit) input-list
Σ # Sort this uniquified list by:
¢ # Get its count in the (implicit) input-list
}R # After the ascending sort: reverse the list, so it'll become descending
# (after which the result is output implicitly)
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
èó±☻₧╛╗
```
[Run and debug it](https://staxlang.xyz/#p=8aa2f1029ebebb&i=%5B%22John%22,%22Doe%22,%22Dick%22,%22Harry%22,%22Harry%22,%22Doe%22,%22Doe%22,%22Harry%22,%22Doe%22,%22John%22%5D)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Qċ@ÞṚ⁺
```
[Try it online!](https://tio.run/##y0rNyan8/z/wSLfD4XkPd8561Ljr/@F2b5VHTWsi//@PVvLKz8hT0lFyyU8FkZnJ2UDKI7GoqBKJhkqCSVQxsO5YHQA "Jelly – Try It Online")
There are quite a few ways to formulate this, but I find this to be the most amusing of several 6-byte alternatives. `ċ@Þ@QṚ` comes rather close.
```
Q Unique items of the input.
Þ Sort them by
ċ@ how many times they appear in the input
Ṛ reversed.
⁺ Duplicate the last link: reverse the sorted result.
```
[Answer]
## CJam, 15 bytes
```
q~$e`{0=W*}$1f=
```
This may use CJam features from after this challenge was posted. I'm too lazy to check.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
u↔Ö#¹
```
[Try it online!](https://tio.run/##yygtzv7/v/RR25TD05QP7fz//3@0kld@Rp6SjpJLfiqIzEzOBlIeiUVFlUg0VBJMooqBdccCAA "Husk – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 33 bytes
```
[ sorted-histogram keys reverse ]
```
[Try it online!](https://tio.run/##RY29CsJAEIT7PMW8gHkAbQP@FDZiJRbLuZojyV2yuxoO8dnPIwgWM8MMA9@dnEXJ59P@uF1jIGtrNTKv5p2CVGMJ5enJwbGiYwncYxQ2S6P4YJhmbKpqmt84xDagiYzGuw47Ekk/X8aif1u@n3yBRjG@rdpCjA@hoSCSQvjFooxrdtT3qPMX "Factor – Try It Online")
## Explanation
```
! { "John" "Doe" "Dick" "Harry" "Harry" "Doe" "Doe" "Harry" "Doe" "John" }
sorted-histogram ! { { "Dick" 1 } { "John" 2 } { "Harry" 3 } { "Doe" 4 } }
keys ! { "Dick" "John" "Harry" "Doe" }
reverse ! { "Doe" "Harry" "John" "Dick" }
```
[Answer]
## Perl
to meet given i/o spec I need 120 chars
```
s!"([^"]+)"[],]!$a{$1}++!e while(<>);print 'MostOccuring = [',join(',',map{qq("$_")}sort{$a{$a}<=>$a{$b}}keys %a),"]\n"
```
pure shortest code by taking one item per line and printing one item per line I only need 55 chars
```
$a{$_}++ while(<>);print sort{$a{$a}<=>$a{$b}}keys %a)
```
[Answer]
# Scala (71)
```
(x.groupBy(a=>a)map(t=>(t._1,t._2.length))toList)sortBy(-_._2)map(_._1)
```
Ungolfed:
```
def f(x:Array[String]) =
(x.groupBy(a => a) map (t => (t._1, t._2.length)) toList)
sortBy(-_._2) map(_._1)
```
[Answer]
# [Perl 5](https://www.perl.org/), 51 bytes
```
sub f{my%k;$k{$_}++for@_;sort{$k{$b}-$k{$a}}keys%k}
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrTq3UjXbWiW7WiW@Vls7Lb/IId66OL@opBoklFSrC6ISa2uzUyuLVbNr/zsk2qZpKHnlZ@Qp6Si55KeCyMzkbCDlkVhUVIlEQyXBJKoYWLemdXFipZJDotL/f/kFJZn5ecX/dX1N9QwMDQA "Perl 5 – Try It Online")
] |
[Question]
[
In a [certain chatroom](https://chat.stackexchange.com/rooms/106764/Vyxal), we like making acronym jokes about the build tool we use called [sbt](https://www.scala-sbt.org/). While it usually stands for "**S**cala **B**uild **T**ool", we aim to come up with all sorts of meanings, such as:
* Stupid Brick Teeth
* Sussy Baka Training
* Shady Blue Tourists
* Seriously Big Toes
* Silly Bear Topics
* Salacious Bacon Tripod
* Syringed Baby Toys
* Schadenfreude Bringing Trains
* Several Belated Tanks
* Slightly Better Tiet ([because piet doesn't start with a T](https://chat.stackexchange.com/transcript/message/63080289#63080289))
As you can see, the meaning of "sbt" changes each time, and the words used are never repeated. Today's challenge is to generalise this to a block of text.
## Challenge
Your task is to replace all instances of an acronym in a large block of text with a different meaning each time. To do so, you'll be given a string representing the haystack text and the acronym to change, as well as a list of words starting with each letter in the acronym.
For the acronym "sbt", you'll receive: the large text to change, the acronym, a list of words starting with "s", a list of words starting with "b" and a list of words starting with "t".
To each occurrence of the acronym, replace it with a uniformly randomly chosen word from each word list. To make sure the same set of words aren't used twice, one a word is chosen from a list, it can't be used again.
## Worked Example
Given the following text:
```
I think it might be possible to make an sbt wrapper to allow it to be
used without a shell. That means that instead of having to launch the
sbt console each time, you'll be able to use sbt commands straight
from the command line.
```
The acronym `"sbt"` and the following word lists:
```
["stupid", "sussy", "shady", "seriously", "silly", "salacious", "syringed", "several", "schadenfreude", "slightly"]
["brick", "baka", "blue", "big", "bear", "bacon", "baby", "bringing", "belated", "better"]
["teeth", "training", "tourists", "toes", "topics", "tripod", "toys", "trains", "tanks", "tiet"]
```
Valid outputs might include:
```
I think it might be possible to make an salacious bacon tripod wrapper to
allow it to be used without a shell. That means that instead of having to
launch the several big teeth console each time, you'll be able to use silly
blue toys commands straight from the command line.
I think it might be possible to make an stupid bear training wrapper to
allow it to be used without a shell. That means that instead of having to
launch the schadenfreude brick topics console each time, you'll be able to
syringed baka tripod sbt commands straight from the command line.
I think it might be possible to make an sussy baka toes wrapper to
allow it to be used without a shell. That means that instead of having to
launch the stupid brick teeth console each time, you'll be able to use
salacious baby topics commands straight from the command line.
```
Note that the above paragraphs have been line-wrapped for formatting reasons. They would otherwise be on a single line.
## Rules
* Only acronyms surrounded by spaces or EOF should be replaced. That means that `"sbt"` in something like `"whomsbted"` should not be replaced with an expanded meaning. `"sbt."` shouldn't be expanded either. But `"sbt"` at the start or end of the long text should be replaced.
* Acronyms will only contain distinct letters.
* The acronym will be case-sensitive. If the acronym is `"sbt"`, only `"sbt"` should be placed, not `"SbT"`, `"sbT"`, `"SBT"` and other variations.
* Inputs can be taken in any reasonable and convenient format.
* Inputs can be taken in any order.
* Output can be given in any reasonable and convenient format.
* Each word in expanded meanings should have an equal chance of being included given it hasn't already been used. This can be achieved by removing the chosen word from the word list.
* None of the inputs will be empty.
* You can assume that the word lists will have at least as many words as there are occurrences of the acronym in the large text. They may be different lengths to each other though.
## Test Cases
Format:
```
text
acronym
word lists
---
possible output
```
```
"I think it might be possible to make an sbt wrapper to allow it to be used without a shell. That means that instead of having to launch the sbt console each time, you'll be able to use sbt commands straight from the command line."
"sbt"
["stupid", "sussy", "shady", "seriously", "silly", "salacious", "syringed", "several", "schadenfreude"]
["brick", "baka", "blue", "big", "bear", "bacon", "baby", "bringing", "belated"]
["teeth", "training", "tourists", "toes", "topics", "tripod", "toys", "trains", "tanks"]
---
"I think it might be possible to make an salacious bacon tripod wrapper to allow it to be used without a shell. That means that instead of having to launch the several big teeth console each time, you'll be able to use silly blue toys commands straight from the command line."
```
```
"y'all ever just see a meme and rofl so hard that you rofl into a sharp object and rofl harder?"
"rofl"
["rinse", "rake", "randomise", "risky"]
["original", "orderly", "optimal", "omega"]
["flower", "flatten", "filibuster", "foxes"]
["linguistics", "legacies", "landings", "loses"]
---
"y'all ever just see a meme and rinse orderly flower landings so hard that you rake original filibuster loses into a sharp object and risky optimal flatten legacies harder?"
```
```
"Keg is a golfing language created by lyxal in 2018. Not to be confused with an actual beer keg, Keg is an acronym that stands for Keyboard Golfed. That's ironic, because Keg is horrible at golfing."
"Keg"
["Kaleidoscopes", "Keyboard", "King"]
["energetically", "eagerly", "entertains", "enrage"]
["goombas", "ginger", "google", "grams", "good"]
---
"Keyboard entertains ginger is a golfing language created by lyxal in 2018. Not to be confused with an actual beer keg, King eagerly grams is an acronym that stands for Keyboard Golfed. That's ironic, because Kaleidoscopes enrage goombas is horrible at golfing."
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the answer with the lowest boring young train egg count in each language wins.
*Update: Turns out jokes about acronymised software tools aren't as unique as I thought - npm seems to have been doing it for ages on their website. Rip lol*
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 93 bytes
-N bytes thanks to Arnoud and I4m2
```
(d,a,b)=>a.split` `.flatMap(e=>e==d?b.map(c=>c.splice(c.length*Math.random(),1)):[e]).join` `
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVK7qtwwEIWU-YKUg5rYwRGkCwFv6hS3S7cY7lgaW7qWJaPHXfZb0iwh-ajka6KHCQjOmdc5M6Afv6yT9Pi5jL9TXD5-_jN1csBh7scL8nAYHZ_hmS8G4xMeHY0XGkf5deZ7jsR4EbVHUCe4IbtG9eEJo-IerXR71w-f-v7Llaaevzhts1Iz-fvmnXA2OEPcuLVbOhbmyAb2DTJCVNpuoCPselURZoLDhaBnQxAd7LgRoC2dHG4ej4N8yaMx7lamMs8jKZCEm47KpQgIQZExHL4rzLKENmSXTLUNkVCCW0Dhq7ZrmTaYrFC5geo656ZAWJJ6pwHuLr03ptjguVW2O5v3Pd8eIESPdf3Fu71qnSUw2hJnw_XKQkyHlmwAFlII90oUykbIa5eCaYE2J0GDouRrcPd5Y2oC9EoeTaUia5BdPCVJbBreXtnstdhKbcYNK5pEFfVagdC3cj62kbn6zcUhv9aUP0F2q4qRKKqSLWfasyO65HWIoXE68dCiMa8PJ1vuHv7PNoZ2C2ya-r59kMej4T8)
[Answer]
# [><> (Fish)](https://esolangs.org/wiki/Fish), 429 bytes
```
i:>:?v~:>:?v~0i06.
1-/ \:i$fp
1f@:$~v?::i/.09-1p+
:@:i:/.29-1p$0+f+*@}}@:{:{~v?
.32-1p@i+f+*@}}@:{:{$@:$@:$/
.a1${~\
>:?v;.7*93^?('!':i~\
/ >1-}$:@$:@-fg:?!^i:@=?!v~1+{
("!"o?)0:::r-1rio~~&v?:&:$/.8+1f~v?
+bc-1ogf-&:&+]}:{[4:/.61r$0 ~?)2l/.8
>:?v~0$06.>{:}*$:@+f+0$:&g:?v~:1c./:&:&go1-fb.
\:f1+g0c. > :?^~00&p1-' 'o0a.
>:0>$:?v~0$:?v~3,$:@$:@)?v~
/-%1:,3< /a7$x$2+>3*$1-ac .
\$1+2c. \+d.\$1+/.ab~$+1/
```
[Try it, but only if you are very patient](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTo+Oj92fjo+Oj92fjBpMDYuXG4xLS8gIFxcOmkkZnBcbjFmQDokfnY/OjppLy4wOS0xcCtcbiA6QDppOi8uMjktMXAkMCtmKypAfX1AOns6e352P1xuIC4zMi0xcEBpK2YrKkB9fUA6ezp7JEA6JEA6JC9cbiAgICAuYTEke35cXFxuPjo/djsuNyo5M14/KCchJzppflxcXG4vICA+MS19JDpAJDpALWZnOj8hXmk6QD0/IXZ+MSt7XG4oXCIhXCJvPykwOjo6ci0xcmlvfn4mdj86JjokLy44KzFmfnY/XG4rYmMtMW9nZi0mOiYrXX06e1s0Oi8uNjFyJDAgfj8pMmwvLjhcbj46P3Z+MCQwNi4+ezp9KiQ6QCtmKzAkOiZnOj92fjoxYy4vOiY6JmdvMS1mYi5cbiAgIFxcOmYxK2cwYy4gICAgICAgICAgICAgICAgPiAgIDo/Xn4wMCZwMS0nICdvMGEuXG4+OjA+JDo/dn4wJDo/dn4zLCQ6QCQ6QCk/dn5cbi8tJTE6LDM8IC9hNyR4JDIrPjMqJDEtYWMgLlxuXFwkMSsyYy4gIFxcK2QuXFwkMSsvLmFifiQrMS8iLCJpbnB1dCI6IjMgMTE1IDk4IDExNiA5IDYgMTE1IDExNiAxMTcgMTEyIDEwNSAxMDAgNSAxMTUgMTE3IDExNSAxMTUgMTIxIDUgMTE1IDEwNCA5NyAxMDAgMTIxIDkgMTE1IDEwMSAxMTQgMTA1IDExMSAxMTcgMTE1IDEwOCAxMjEgNSAxMTUgMTA1IDEwOCAxMDggMTIxIDkgMTE1IDk3IDEwOCA5NyA5OSAxMDUgMTExIDExNyAxMTUgOCAxMTUgMTIxIDExNCAxMDUgMTEwIDEwMyAxMDEgMTAwIDcgMTE1IDEwMSAxMTggMTAxIDExNCA5NyAxMDggMTMgMTE1IDk5IDEwNCA5NyAxMDAgMTAxIDExMCAxMDIgMTE0IDEwMSAxMTcgMTAwIDEwMSA5IDUgOTggMTE0IDEwNSA5OSAxMDcgNCA5OCA5NyAxMDcgOTcgNCA5OCAxMDggMTE3IDEwMSAzIDk4IDEwNSAxMDMgNCA5OCAxMDEgOTcgMTE0IDUgOTggOTcgOTkgMTExIDExMCA0IDk4IDk3IDk4IDEyMSA4IDk4IDExNCAxMDUgMTEwIDEwMyAxMDUgMTEwIDEwMyA3IDk4IDEwMSAxMDggOTcgMTE2IDEwMSAxMDAgOSA1IDExNiAxMDEgMTAxIDExNiAxMDQgOCAxMTYgMTE0IDk3IDEwNSAxMTAgMTA1IDExMCAxMDMgOCAxMTYgMTExIDExNyAxMTQgMTA1IDExNSAxMTYgMTE1IDQgMTE2IDExMSAxMDEgMTE1IDYgMTE2IDExMSAxMTIgMTA1IDk5IDExNSA2IDExNiAxMTQgMTA1IDExMiAxMTEgMTAwIDQgMTE2IDExMSAxMjEgMTE1IDYgMTE2IDExNCA5NyAxMDUgMTEwIDExNSA1IDExNiA5NyAxMTAgMTA3IDExNSAyMjkgNzMgMzIgMTE2IDEwNCAxMDUgMTEwIDEwNyAzMiAxMDUgMTE2IDMyIDEwOSAxMDUgMTAzIDEwNCAxMTYgMzIgOTggMTAxIDMyIDExMiAxMTEgMTE1IDExNSAxMDUgOTggMTA4IDEwMSAzMiAxMTYgMTExIDMyIDEwOSA5NyAxMDcgMTAxIDMyIDk3IDExMCAzMiAxMTUgOTggMTE2IDMyIDExOSAxMTQgOTcgMTEyIDExMiAxMDEgMTE0IDMyIDExNiAxMTEgMzIgOTcgMTA4IDEwOCAxMTEgMTE5IDMyIDEwNSAxMTYgMzIgMTE2IDExMSAzMiA5OCAxMDEgMzIgMTE3IDExNSAxMDEgMTAwIDMyIDExOSAxMDUgMTE2IDEwNCAxMTEgMTE3IDExNiAzMiA5NyAzMiAxMTUgMTA0IDEwMSAxMDggMTA4IDQ2IDMyIDg0IDEwNCA5NyAxMTYgMzIgMTA5IDEwMSA5NyAxMTAgMTE1IDMyIDExNiAxMDQgOTcgMTE2IDMyIDEwNSAxMTAgMTE1IDExNiAxMDEgOTcgMTAwIDMyIDExMSAxMDIgMzIgMTA0IDk3IDExOCAxMDUgMTEwIDEwMyAzMiAxMTYgMTExIDMyIDEwOCA5NyAxMTcgMTEwIDk5IDEwNCAzMiAxMTYgMTA0IDEwMSAzMiAxMTUgOTggMTE2IDMyIDk5IDExMSAxMTAgMTE1IDExMSAxMDggMTAxIDMyIDEwMSA5NyA5OSAxMDQgMzIgMTE2IDEwNSAxMDkgMTAxIDQ0IDMyIDEyMSAxMTEgMTE3IDM5IDEwOCAxMDggMzIgOTggMTAxIDMyIDk3IDk4IDEwOCAxMDEgMzIgMTE2IDExMSAzMiAxMTcgMTE1IDEwMSAzMiAxMTUgOTggMTE2IDMyIDk5IDExMSAxMDkgMTA5IDk3IDExMCAxMDAgMTE1IDMyIDExNSAxMTYgMTE0IDk3IDEwNSAxMDMgMTA0IDExNiAzMiAxMDIgMTE0IDExMSAxMDkgMzIgMTE2IDEwNCAxMDEgMzIgOTkgMTExIDEwOSAxMDkgOTcgMTEwIDEwMCAzMiAxMDggMTA1IDExMCAxMDEgNDYiLCJzdGFjayI6IiIsInN0YWNrX2Zvcm1hdCI6Im51bWJlcnMiLCJpbnB1dF9mb3JtYXQiOiJudW1iZXJzIn0=)
Takes input like this, over stdin:
* Length prefixed acronym
* Length prefixed array of length prefixed options
* Length prefixed text
[](https://i.stack.imgur.com/A7Z75.png)
Works by inserting words into the code box at (length of acronym) \* word + index of letter position. Each word is reversed, and column 0 is the lengths.
To generate a random number, first we log3 the max value, then we repeat adding 0, 1 or 2 depending on where the `x` takes us. Then we need to check if we are more than the max, in which case restart. Because the log is inaccurate we there is a 2/3 chance of rejection for the example test case.
We set the length of each word to 0 to mark it as already covered. If we select a word that has been tried previously we also just retry the RNG.
## Slightly More Detailed Explanation
```
i:>:?v~:>:?v~0i06.
1-/ \:i$fp
```
This places the acronym at row F, and a column of (length of acronym - index in acronym) in the code box. Note this will place it in reverse order. We keep the length on the stack.
```
1f@:$~v?::i/.09-1p+
:@:i:/.29-1p$0+f+*@}}@:{:{~v?
.32-1p@i+f+*@}}@:{:{$@:$@:$/
.a1${~\
```
This is actually 3 nested loops, first over the lists of list of words, then over the words in each list, then over the letters in each word. The `{:{:@}}@*+f+` is the code to find the vertical position of each word, unfortunately it's very and and needs to be repeated twice :/ Once for writing the letters then again for writing the length.
```
.a1${~\
>:?v;.7*93^?('!':i~\
```
Now we start reading the actual text. For each letter, check if it matches the nth letter of the acronym. Repeat till the first error, or until the acronym ends.
```
("!"o?)0:::r-1rio~~&v?:&:$/.8+1f~v?
+bc-1ogf-&:&+]}:{[4:/.61r$0 ~?)2l/.8
```
Since we don't print the letters in case they match the acronym, in case of a error we need to print again the first N letters of the acronym. This is the bottom row. The top row prints the rest of the letters of the word, until a space or less.
```
>:?v~0$06.>{:}*$:@+f+0$:&g:?v~:1c./:&:&go1-fb.
\:f1+g0c. > :?^~00&p1-' 'o0a.
```
In case the acronym is matched, we jump here. First, `f+1g0c` gets the number of words for each letter. We then jump to `0c` which is the RNG.
When the RNG returns we get the word at that index, and print it. We also check if the word has already been used (it's length is 0) if so we retry another random number.
```
>:0>$:?v~0$:?v~3,$:@$:@)?v~
/-%1:,3< /a7$x$2+>3*$1-ac .
\$1+2c. \+d.\$1+/.ab~$+1/
```
This is the RNG. Since the one random instruction in ><> is x, this is a bit tricky. x changes the cursor to a random direction. The left loop does a log3, the right loop has a x, and adds either 0, 1, or 2 to the accumulator, then multiplies by 3. Finally, we check if the new number is indeed less than the target. (`)?v+`)If not we try again.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 15 bytes
```
ḲḢ€K$}⁵⁼$¡€KɓẊ€
```
[Try it online!](https://tio.run/##PZA7TsNAEIavMloh0UTcA9HSRSnG9iQ7eL1r7ewmckERSlpOADUVElKEqOg4RnIRsw8LydJ88/r/WT@QMdM8n08f59Pb5en97urxcvy8HL@vfl5z@vty/npOMM@zuoWg2fbAAQbe6QANwehEuDEEwcGAPQFakCbAweM4ks9lNMYd8lLitBGFOjhw0C4GQBCdLriBe41JldBKMknIVgJhB24LGvdsd3nbYLStTgNUPFpnxSVrwlzkgVYwuXhtTLbB5ahktwwPA9pOQILHcv3Wu6FoLS0wbOlGzWslIY7cqRUoiSJTAY1dBfLsopiasFkADba5XpLJp4OpCtCePJqCbdIgu/UUO1KbFaxV47ntc6/BHks0kUrkXQmEvrbTWys0xa/JDumrQwZDciuKgSjoXM2vtMtEcNGzBKlMSxy5reR5dF2tTfK/WwltL2ozpz/4Bw "Jelly – Try It Online")
*-4 bytes and fixed thanks to lyxal :P*
Full program taking the text, wordlists, and acronym as successive command line arguments.
```
Ḳ Split the text on spaces
ɓẊ€ and shuffle the wordlists.
€ For each word in the split text:
⁵⁼$¡ If it's equal to the acronym,
Ḣ€ } destructively take the head of each wordlist
K$ and join the words on spaces.
K Join the results on spaces.
```
I might have gotten too caught up earlier in thinking of a vectorization trick for checking if a word (right) matches the acronym as reconstructed from the wordlists (left), which also incorrectly replaces prefixes of the acronym:
```
a Apply vectorized logical AND
" to corresponding elements (leaving excess unchanged) of the lists and
W€} the word with each letter wrapped in its own list.
¥Ƒ Are the wordlists unchanged by this?
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
#Š€.røðý.;ðý
```
Inputs in the order \$sentence, words, acronym\$, where \$words\$ is a list of lists of strings.
[Try it online](https://tio.run/##PZA7bsMwDIb3noJwhy6BL9ATdO8WZKBsJiIsS4ZIJfDak/QAHTp26RT0Ir2Iq4dRwBA/8fH/lIOgYdq2x5/337ePPt6/7p/37/65nNv2AmrZT8AKM1@sgiFYgggbR6ABZpwI0IMYhVvEZaFY0uhcuJWhzHkiCY1wY7UhKSCIJed6eLWYVQm9ZJOM7EUJRwhnsHhlfynTDpMfbG6g6jEELyFbE5Ykz3SANaQn54oN7ktlu715ntGPAqIR6/bnGOaqtZfAsaf@4XjsRNPCY3eATpLIWsHi2IAihySuXdjtgA6Hkq@XNeaFqQnQlSK6ikPWIH@OlEbqTodjZyIPUykZnLBGl6hGvtRAGFs5P7WBqXamGOSvNTnUbFYElUhtSZY3@r1BQ4osKo1pjwsPjSIvYWy5Vf5nG6GfpDudHvIP/AM) or [verify all test cases](https://tio.run/##RVO9jtRADO7zFNZSXLNaAaJAoqADoZOorjuucBIn8e1kHI0nd5eWJ@EBKKgQDQ0nXoQXOeyZXZCi2PK/P38jii3T06t3T89@f/nz@eshPf54/Pb48/DG/0/7X9/ffnr6AHnieATOMPM4ZWgJFlHlNhBkgRmPBBhB2wz3CZeFkpsxBLn3JNMtY1Xq4Z7zJGsGBJ0ohANcTWhVCaNaE1M5aibsQQaY8I7j6NkB19hNFkClRydRxVoTupFn2sMm60UI3gZPQ1m7U/A8Y@wVNCcs0w9J5lLr5ILAkQ7N9fVO87pwv9vvdFXdXE7YF0mJZdVQdA5VYsDOra5vyUalkkp3lDC41lk2xSHR2tPuZn@9axN3R/O0eEQXYSUXPPqfMBWXbVdk601ar2tfCQiYrYUXykR5MpuvFKs7y5pYsxaVqli4K0riRfpi2fScVRSMR93d3DQGVNNsF3Yx8PHhdtUMSoam3Wb24/aQZAigYmdJfb2VgV6tHP3cdlJMC0h7S13@n@LxlN46vraM@sbJCFNE7GXmamI9bmU3SWwbFwTFMwvYstidq22mEUvgYPQix2wwYDI5agMHbm32apYHw8Ej7cDjauBUOIIV6LhAFGwC8xVVlAoWPnTTXNIIrLbUKGFwGlrouOJorEnkd4B2g7A9oG8PL5@/eH2Aj3Lmut1w@Md3fxrY5RWdnwbukcY9nOu7K0nc5gqp5sLVQZJFbK041u9tAurrU7lQYAvnbm@1OnSSnypNklJ5kFblNHPh9CUG4l60k6WsfC7rqjPH8aFIaSSDByu1yfasuFM0LPOJLhSTOUrGKDK36EZnZ4HbTGPwU44JZ62G3gG1AZvmarIZC6CZNJfJ2GtHzCz12tz5Yq70LDZMaaSxckWDvXOXETl4Vda/).
**Explanation:**
```
# # Split the first (implicit) input-sentence by spaces
Š # Triple-swap it with the other two implicit inputs, so the stack order
# becomes: sentence-list, acronym, words-2D-list
€ # Map over each inner list of words in the 2D list:
.r # Randomly shuffle them
ø # Zip/transpose; swapping rows/columns (discarding any trailing words)
ðý # Join each inner list of words by spaces
.; # Replace every first occurrence of the acronym with these parts one by one
# in the sentence-list
ðý # Join the sentence back together with space delimiter
# (after which it is output implicitly as result)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-S`](https://codegolf.meta.stackexchange.com/a/14339/), ~~15~~ 14 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
It's been a *long* day, so I'm happy I got this down from the 26 bytes I had on my first pass. There's still probably another byte or ~~3~~ 2 to be saved, perhaps with a different approach, but this'll do for now.
Takes the string as the first input, the acronym as the second, and the replacements, as a 2D array, as the third.
```
¸cȶV?WËjDÊö:X
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVM&code=uGPItlY/V8tqRMr2Olg&input=IkkgdGhpbmsgaXQgbWlnaHQgYmUgcG9zc2libGUgdG8gbWFrZSBhbiBzYnQgd3JhcHBlciB0byBhbGxvdyBpdCB0byBiZSB1c2VkIHdpdGhvdXQgYSBzaGVsbC4gVGhhdCBtZWFucyB0aGF0IGluc3RlYWQgb2YgaGF2aW5nIHRvIGxhdW5jaCB0aGUgc2J0IGNvbnNvbGUgZWFjaCB0aW1lLCB5b3UnbGwgYmUgYWJsZSB0byB1c2Ugc2J0IGNvbW1hbmRzIHN0cmFpZ2h0IGZyb20gdGhlIGNvbW1hbmQgbGluZS4iCiJzYnQiClsKWyJzdHVwaWQiLCAic3Vzc3kiLCAic2hhZHkiLCAic2VyaW91c2x5IiwgInNpbGx5IiwgInNhbGFjaW91cyIsICJzeXJpbmdlZCIsICJzZXZlcmFsIiwgInNjaGFkZW5mcmV1ZGUiXQpbImJyaWNrIiwgImJha2EiLCAiYmx1ZSIsICJiaWciLCAiYmVhciIsICJiYWNvbiIsICJiYWJ5IiwgImJyaW5naW5nIiwgImJlbGF0ZWQiXQpbInRlZXRoIiwgInRyYWluaW5nIiwgInRvdXJpc3RzIiwgInRvZXMiLCAidG9waWNzIiwgInRyaXBvZCIsICJ0b3lzIiwgInRyYWlucyIsICJ0YW5rcyJdCl0)
```
¸cȶV?WËjDÊö:X :Implicit input of string U, acronym V and 2D array W
¸ :Split U on spaces
c :Flat map by
È :Passing each X through the following function
¶V : Is equal to V
? : If so
WË : Map each D in W
j : Remove (mutating original) & return element at 0-based index
DÊ : Length of D
ö : Random number in range [0,DÊ)
:X : Else return X
:Implicit output, joined with spaces
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
⪫E⪪θ ⎇⁼ιη⪫Eη§⊞Oυ‽⁻Φζ⁼λ§ν⁰υ±¹ ι
```
[Try it online!](https://tio.run/##RZHBbtswDIZfhfBlCuAV23mnHTagBboVW29FD4zNWERoyRWlZN7LZ7RkdEBgfvrJn6SiwWMaIsrt9pQ4ZPcQObhHXNzvRTi7tx466A49PFMKmFb37a2gqOMevKnv1b6Hr/k@jPTHPRX1PxdKmGNypYdfGMY4u0cORd13lkzJ/e1hbyT/jaGHT4eDdS31@4MmzOQ@22HfgTd5w8OX2@2lu4fsOZyBM8w8@QxHgiWq8lEIcoQZzwQYQI8ZrgkX22mTUSReN5OxOYrSCFfOPpYMCOpJ5A6ePVpXwqA2xJCDZsIR4gk8XjhMm1uwhMFbAdUZQwwabTThJvJMPayxfBDZxuC@lI3bi@fZ/hgFzQnr9qcU59prT4FwoLvObmz1Fl46zWXhsSpFda3gcWxAiWNRaQeWHVBw2PR6WO2FJ2oN6GIvJBUH60HhlKiMtAnHxMO5Ap6xRiktwVMNhKml7cYNjutuDJP9WpHY69VZmSj7CnbTsOdzLIk1a2Pa48JDo8RLbOa46ru3EYazdq@vt48X@Qc "Charcoal – Try It Online") Link is to verbose version of code. Takes the list of all the words as a single argument. Explanation:
```
θ Input sentence
⪪ Split on spaces
E Map over words
ι Current word
⁼ Equals
η Input acronym
⎇ If true then
η Input acronym
E Map over letters
ζ Input words
Φ Filtered where
λ Current letter
⁼ Equals
§ ⁰ First letter of
ν Current word
⁻ Set difference with
υ Predefined empty list
‽ Random element
⊞Oυ Push to predefined empty list
§ ±¹ Last element (i.e. the one just pushed)
⪫ Join on spaces
ι Otherwise current word
⪫ Join on spaces
Implicitly print
```
27 bytes with a slightly more contrived input format:
```
⪫E⪪θ ⎇⁼ιη⪫Eη§⊞Oυ‽⁻§ζλυ±¹ ι
```
[Try it online!](https://tio.run/##PVGxbtwwDP0Vwkt1gBugazp16JACaYMmW3ADbfMswrLkiNJd3aLf7lKyG8AQH58e@USztxj7gG7bniL7ZL4F9uYRF/O8OE7mrYUGmlMLLxQ9xtV8fcvoxHALVtl3tW3hS3rwA/0yT1nsj4UiphBNbuEn@iHM5pF9FvNf9LsFp/X5dNLzO42YyHzS5HDjQhd4@rxtr80DJMt@Ak4w82gTdARLEOHOEaQAM04E6EG6BLeIi7oXGp0Lt1KkWCuy0AA3TjbkBAhiybk7eLGoXQm9qIlC9pIIBwgXsHhlP5Zqh9n3VgVUPfrgJag1YSF5phbWkD84V2zweJTaHeJ51l8gICliff0lhrn2Oq7Asae7RidWvYY/jTT38NpIygsPlc8iawUWhx1Q5JDF7Qm7A6DDvvA1WXWjI@0N6KobcRX22oP8JVIeqDkr01W3LnI/FUGHE9boMtXIYw2Ecb/W8XfQVdOu2Oi3i5yucqhtU22biJItV2V6f8hSyJElyY7piAv3O4q8hGHnVnmv3RH6SZrz3/P28er@AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: As above except
```
ζ Input dictionary
§ Indexed by
λ Current letter
```
25 bytes by assuming that the lists of words are in the same order as the acronym:
```
⪫E⪪θ ⎇⁼ιη⪫Eζ§⊞Oυ‽⁻λυ±¹ ι
```
[Try it online!](https://tio.run/##PVHBitwwDP0VkUs9kC703FMPPWxh26Xd2zAHJdGMRRw7a9kzTX8@le2wYNDT05OehUaLcQzo9v01sk/mR2BvXnA1f1bHybz30EF36uGNose4me/vGZ0Y7sEq@6H@18O39Own@mtes9hfK0VMIZrcw2/0U1jMC/ssxvWQTyft/Ek3TGS@aHI4cKELPH3d93P3DMmyn4ETLHyzCQaCNYjw4AhSgAVnAvQgQ4JHxFUdC43OhUdpUqwdWWiCBycbcgIEseTcE7xZ1KmEXtREIXtJhBOEK1i8s7@VbofZj1YFVD3G4CWoNWEheaEetpA/OVds8PiU2h3iZdG1BSRFrL@/xrDUWUcJHHt66nRj1Ws4nztJeeWpUllkq8Di1ABFDllcS9gdAB2Oha/Jpge8URtAdz2Aq3DUGeSvkfJE3UWduiHyOJfagDPW6DLVyLcaCGMr69INDNVvKA76msjpAac2MRElW9iyrj8UKeTIkqRhOuLKY0OR1zA1bpOP3obQz9JdLpf98939Bw "Charcoal – Try It Online") Link is to verbose version of code. Takes a list of word lists as the third argument. Explanation: As above except
```
ζ Input word lists
E Map over lists
λ Current list
⁻ Set difference with
υ Predefined empty list
‽ Random element
⊞Oυ Push to predefined empty list
§ ±¹ Last element (i.e. the one just pushed)
```
[Answer]
# [Go](https://go.dev), 207 bytes
```
import(."math/rand";."strings")
type Q=string
func f(s,a Q,W[][]Q)Q{S:=Split(s," ")
for i:=range S{w:=[]Q{}
for n:=range a{w=append(w,W[n][Intn(len(W[n]))])}
if S[i]==a{S[i]=Join(w," ")}}
return Join(S," ")}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PVKxitwwEIWU_opBzdmwcdpwwUXKSxGybEKKZYuxPV4Ly5KR5HMW4y9JswTyPakvX5OR5BwY5s3TzHsjjX_-upr7y8OEzYBXghGlzuQ4GetL0Y1evCZejiR-z757-_7lTyLzUozo-3cWdSs-lMJ5K_XViSLzt4ngWCUi62bdQJe7A8Lx8P18OV-OxXE9PVanSUnPvADu6YwF-VixGM9xWpfHiuvWLfL6P4_rUuE0kW7zhaX05fykvc4V6TxkRXEptkx2cDrLS1XhGuMnIzWXB5dtyyz52WqI5CmR6Vp_33yMk4Y3yAtYs-xE1OafzZIX5Tctf-RFkWVf-Epe6bzLxRP4XuoBpIdRXnsPNcFknJO1IvCGhQaeWIOrPSw2jG0DjUqZJTQx5o7ZUQuL9L2ZPSC4npQq4WuPrEqoHZswlNp5whZMBz0-86uGboU8b88FFD0ao51ha8JA8r4OcDPzg1LBBveh2G4vHkfemwNeEsbpO2vGqLUfgZKaSnEAwfUcwuLSRteVdz1Pso2Hs3O3CHpsEyArzexUSqTaASpsAh-TW9ChJEDPZFFF2LAG6c7S3JLYDrCK2spmCGc1DhijmilGeY2B0KZjvn4CdfSrgwN_qUihZ7eo6Il8H9hwcb1XeDNb6bxLmPY4ySYhKyfTJu7mXnsTQj04sW3h59j_pPs9xX8)
Pass in the arguments `sentence, acronym, wordlists`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~20~~ 14 bytes
*-6 bytes from @AndrovT*
```
⌈?\%VṄ?vÞ℅∩vṄ%
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLijIg/XFwlVuG5hD92w57ihIXiiKl24bmEJSIsIiIsIlwiS2VnIGlzIGEgZ29sZmluZyBsYW5ndWFnZSBjcmVhdGVkIGJ5IGx5eGFsIGluIDIwMTguIE5vdCB0byBiZSBjb25mdXNlZCB3aXRoIGFuIGFjdHVhbCBiZWVyIGtlZywgS2VnIGlzIGFuIGFjcm9ueW0gdGhhdCBzdGFuZHMgZm9yIEtleWJvYXJkIEdvbGZlZC5cIlxuXCJLZWdcIlxuW1tcIkthbGVpZG9zY29wZXNcIiwgXCJLZXlib2FyZFwiLCBcIktpbmdcIl0sW1wiZW5lcmdldGljYWxseVwiLCBcImVhZ2VybHlcIiwgXCJlbnRlcnRhaW5zXCIsIFwiZW5yYWdlXCJdLFtcImdvb21iYXNcIiwgXCJnaW5nZXJcIiwgXCJnb29nbGVcIiwgXCJncmFtc1wiLCBcImdvb2RcIl1dIl0=)
## Explanation
```
⌈?\%VṄ?vÞ℅∩vṄ%
⌈ # Split implicit first input (text) by spaces
? # Take second input (acronym)
\%V # Replace all instances of second input in first with "%"
Ṅ # Rejoin the split list with spaces
? # Take third input (list of lists of substitute words)
vÞ℅ # Randomly permute each of the lists in the third input
∩ # Transpose
vṄ # Join each row of transposed list
% # Format string: replace all "%" from original string with entries from the transposed list
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 110 bytes
```
Table[StringReplace[#1,RegularExpression["\\b"<>#2<>"\\b"]->i],{i,StringRiffle/@Transpose[RandomSample/@#3]}]&
```
[Try it online!](https://tio.run/##PVGxjtswDN3zFYQCtIt7h7brNejSodshl83ngbbpmLAsGaJ0aRDk21PKcgsI4NMjHx8pzRhHmjFyh4/hx@OEraX6LQZ25yMtFjuq91@rI52TxfDrzxJIhL2rzft7a14O@28vhxU2Xw7cVDeuNi0Pg6Xnn6eAThYvVB/R9X5@w3nJ/P57c28@PV61NtZDbX5DHNlNwBFmPo8RWgKVCes4ED3MOBGgA2kjXAIuC4VMo7X@kkWKVbFLQj1cOI4@RUCQkax9gtOI2pZ0EnVRyE4iYQ9@gBE/dNost5hcN2oB7bJJ55149SbMJM9UwdWnz9ZmH9ymUjsoxfOs6wlIDLiOvxuCn3Ozfzmw7OjJVDujAg23m5GYFu5NBUaSyHUFI/YFUGCfxJYL2w2gfkjm18s1PzSVBvRBAe0KO@1BbgiUejJ3dTJt4G7KuRYnXKNNtEY@r4EwlLRuXUC7@rXZQU8pshjVbe0YieKY2byv2yqiT4ElSsG0xYW7ggIvvi/cVf5rC0I3ibnfm@bxFw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python](https://www.python.org), ~~145 134~~ 133 bytes
```
lambda t,a,w,r='':[*map(shuffle,w)]+[x==a and[(r:=r+l.pop()+' ')for l in w]or(r:=r+x+' ')for x in t.split()]and r
from random import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVJNrpwwDJa6nFNYbIA3dKTuqidxgO67oywMmCGakESJ8xgO0FN0M1LV3qk9TfPDGxVF8md_tj_b4sdvs_Oi1ePn3H775Xn--PnPd4nrMCFwg83W2LYsX7uXFU3lFj_Pkpqt7s_dvW0RUE1dZV9be5YXo01Vn0so61lbkCAUbL22mb4_iXsk-OKMFFzVfegA9jRbvYINOBixGm35JQ_z98MnY4Xiaq5OkL7iC_Ai1A0EwyquC8NAYLRzYpAErGHFG4XBwA0Mm0VjyMYwSqm3WBRwqPCOJthE2N0zILiFpLzA1wVDV0LlgkiAQjkmnEDPsOCbUNdYLdGrcQkJlDRGrZwO0oQxKFZqYNe-lDLK4DFUkDuS1zWs6cCxxTR9Wj32OiiQQtGlaN7XDVVPp-sKx96IqWgC4Z3bE1hwyoCs0N7J7Ah5AJQ4xnhy9nDNK-UG9EYWZYJj6EFqtuQnKvp3PeiKwYrxFlMGvGGy0lOy4poMoc10uEMGQ5IdolB4OUkiB9H_GzMRL5GMh1BHImtvhWOXMR3WiDEjK4yecmx3z9qMUN1c0fenus5_zuOR7T8)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~416~~ ~~366~~ 347 bytes
* -69 thanks to ceilingcat
Takes acronym word lists in acronym letter order.
```
#define P putchar(j)
**A,b,c,j,k,l,u,*z;f(s,t,a)char*s,***a;{for(l=j=strlen(t),A=calloc(j+1,8);u=j--;*(A[j]=calloc(k,8))=k)for(k=0;a[j][k++];);for(;j=*s;s++)if(isspace(j))u=!P;else if(u)P;else if(strncmp(s,t,l)|!isspace(s[l])*s[l])u=P+1;else for(b=0,s+=l-1;z=A[b];z[c]=printf(" %s"+!b++,a[b][c-1]))for(k=rand(c=wcslen(z))%--*z;k--;)for(;z[++c];);}
```
[Try it online!](https://tio.run/##fVTBjpswEL3nK2ZZrYrBrDa3SpRKOVZaVXtoT4iDMSY4OIAYe6Nkm19vOjbZbrtSG0X4MTPP780YkNlWysvltlGtHhQ8weSs7MQc79gqSTa85pLveM8Ndzw55W2M3HLBfEmCPEkSkb@04xybYlegnY0aYsv4ppDCmFHGu3TNP7LcFbssy5N4U@6q11RPCVb0zLP74iEXlCv7NK1ylvtYvisSzDFNmW5jjTgJqcgVc8XNU64MKqC4Y2@Y5Ae5n4JDw37cvHKwNBVLwtUVT@l6IXiJunjgmBYmW@enYlPWVX4qZVVMsx5sG0dwh1F6U6cpF5QrZbau2NXuLIYmlsVBou/4xNhdltF4euoyVNBGaSp9K@fLrR6kcY2CT2gbo@v77vPqLWb1XvnIijRhL/QQP4@6YfCyApDjgBb8rIEGXVaFDwLEb/GkrNgLRGjdpJuIE3KIxwA60SxAzXp0aJYbba5AGCF9PNwcqeOtWjZQz2oWJkBSaNTQzoqcUuDr98dHOPN/eKhnLXtPq0UvwmqcCqvehkWJeUkTdQF1sFJ7cfovRUbYYOT/YlYp23mCnWlkV7Id3azR4oLVdZ20XNCsp7FZYkf8zV2QGHp8J@oxgXNOF382On93IlhEWFv4ArbTQw@ajk9vOwu1gmlE1LVRYEc6016BGIBqP6gGDrOYJjX7jH8PDp5HmEgOfVrbbnQWBGCnjLmHb52gjZUYkHQIkmOrRANjC514ps492wg3yI4KFETB/J@/4NIbH8mQEr6OnjkOx9F9MMYri6tVcgBL8X5PDzgC@hH5ntp53Iftrykw9LW498UR/1swsWEsUb6iOIb3xMvFfpyMhaj/iIDlIOj2fPkpWyO2eMkOvwA "C (gcc) – Try It Online")
Ungolfed version:
```
int **A, // shadow usage array
b, c, // row and column during array processing
j, // string processing current character
k, // selected index
l, // acronym string length
u, // string processing state
*z; // row alias
void f(const char *s, // input string
const char *t, // acronym string
const char ***a) { // word lists array
for(l=j=strlen(t), A=calloc(j+1, sizeof(int *)); // construct shadow array
j--; *(A[j]=calloc(k, sizeof(int)))=k) // zero-initialize each usage list and indicate size
for(k=0; a[j][k++];);
for(u=0; j=*s; s++) // process string, initial state is in whitespace
if(isspace(j)) putchar(j), u=0; // whitespace: print and set state
else // non-whitespace
if(u) putchar(j); // already in non-whitespace, will not be the acronym: print
else
if(strncmp(s,t,l) | // coming from whitespace: is the acronym?
!isspace(s[l])*s[l]) // is there whitespace or NUL after?
u=!!putchar(j); else // no, print and set non-whitespace
for(s+=l-1, b=0; z=A[b]; // position source and string; for each acronym letter
z[c]=printf(" %s"+!b++,a[b][c-1])) // mark word as used and print word
for(k=rand(c=wcslen(z))%--*z; k--;) for(; z[++c];); // get random word, skipping used words
}
```
[Answer]
# [Scala](https://www.scala-lang.org/), 215 bytes
Golfed version. [Try it online!](https://tio.run/##XVLBcpwwDL3zFRouNdOED9iEQ3vLIYct6eTQyUGAWNw1NmOLbJnMfvtWtrdNUwbQs/SkJwlCjwYvel6cZwjxUK@sTf0N7eDm4kOgd8ZQz9rZel4ZO0P1F@9x@7qOI/micN1PCcMjagtvF94Wgn3Tstf2UAw0wqjCbn@D8jzvUuKP/N6/vFS7ffP2igbaJtRhMZpVCWV1Nzqv9P1tW2s76J5ClUin5h9dSVeZaO9vn9@Jp8/Ns7KVypPUln7xg2UVfbUhe@Cpqs53elSt0lXTYJXsqZ6PueXUwPmu/c9xKQDiMLNMqdAfwg7yFJkkk8B3qxkaeBMmwFU@ELdEg2q3wDTX/eo9WX7SMz1qY3RQVVUk/iJV2Fg1qvIBeNL2CFJt1oeJoSNYXAhaNg/spIUjAVoIHcPJ47KQj240xp1ikmDJWAMNcNI8uZUBIUxkTA1PE0pVQhtERKC20hcO4EaY8FUGidkGV9tPQqCk0TsbnEgTRqe0fgObWz8ZE2Xw2pTIXcnzLKMHCOwxdT96N6da1xAYbakub6AUvpi0RpXfZeB10UMKriFsCUw4ZEBeuzWYfJD1ZSC/aB/96bDFj0G5AL2SR5NgLzXIjp7Wgcrqj2bZed0fI6HDIyZrVkpWH5Ih9DksO8igS6JdlJE7kwyySL6XZSKeYiiuwF5p7FavA4eM6WoX3Wfk9eKG7NvC39yM0B5DWcklf8q5OF9@Aw)
```
type Q=String
def f(s:Q,a:Q,W:Array[Array[Q]]):Q={val S=s.split(" ");for(i<-S.indices){val w=ArrayBuffer[Q]();for(n<-W.indices){w+=W(n)(Random.nextInt(W(n).length))};if(S(i)==a)S(i)=w.mkString(" ")};S.mkString(" ")}
```
Ungolfed vesrion. [Try it online!](https://tio.run/##ZVKxbtwwDN3vKwgvldHUHxD0hnbLkCF1igxFBtqmz@zJkiHRuR6KfPuVknxpiwCG@ETyPdLPjj1avFx4XnwQiOnWrMK2@YZu8PPuv0LvraVe2LtmXgU7S82XEPD8dR1HCrud735qGe6RHfzeAch5IXiAPbQS2B12mhpohNHEW3i4Aczn0y1kkR/lfHh@rm8zKSkAvKCFVm@xiYtlMRVUdS6MPoBh@PwJ2obdwD3FeuMU1klZ/6ynyqbeypnrEvfpPReU@XEPT8bVprjQOPold05MyjWW3EGm@qr1ukUewbSGa9jvAWsoEE7NfCxv/3fzwmjfVV6vBs1qoMFwiFdrSl8y5rtjefNm2y6StESDac9RaG76NQRy8sgz3bO1HI3umvsXVRHrzGiqO5CJ3RFUbebDJNARLD5G1o8K4nWFIwE6iJ3AKeCyUEhptNafEkmxMtZIA5xYJr8KIMSJrG3gcUJVJXRRhyhkp3vhAH6ECV/0RRLb4ur6SRsoz@i9i15HE6akrn4DZ79@sDaNwW0pHbc1z7O@eoQoAfP2Y/Bz1tpKYNlRU91Apf0aso2mnFWUdeEhF9cYzxlMOBRAgf0abbmofQXo39@nfL6c08egIkAvFNBm2KsGuTHQOlBVX2dWXeD@mBo6PGKOdqUc@ZADYShl9aCALg/t0hh9SpNF0ZF/ZYVIplRKFritTfwaOEosmLa4cF9Q4MUPJXeOb9yC0B1jVdd1@RFfd5fLHw)
```
import scala.util.Random
import scala.collection.mutable.ArrayBuffer
object Main {
type Q = String
def f(s: Q, a: Q, W: Array[Array[Q]]): Q = {
val S = s.split(" ")
for (i <- S.indices) {
val w = ArrayBuffer[Q]()
for (n <- W.indices) {
w += W(n)(Random.nextInt(W(n).length))
}
if (S(i) == a) S(i) = w.mkString(" ")
}
S.mkString(" ")
}
def main(args: Array[String]): Unit = {
Random.setSeed(System.currentTimeMillis())
println(f("I think it might be possible to make an sbt wrapper to allow it to be used without a shell. That means that instead of having to launch the sbt console each time, you'll be able to use sbt commands straight from the command line.", "sbt", Array(Array("stupid", "sussy", "shady", "seriously", "silly", "salacious", "syringed", "several", "schadenfreude"), Array("brick", "baka", "blue", "big", "bear", "bacon", "baby", "bringing", "belated"), Array("teeth", "training", "tourists", "toes", "topics", "tripod", "toys", "trains", "tanks"))))
}
}
```
[Answer]
# [Python](https://www.python.org), 112 bytes
```
lambda t,a,w:[t:=t.replace(a," ".join(x),1)for x in zip(*(sample(x,len(x))for x in w))]and t
from random import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TVJBjtswDAR6zCsIX2ov3AB7KxbYB_TeW5oDbdMxG1kSJGqT9Cu9BCjaP7WvKSV5tzUMzJAcckTZ33_5myzO3n_Mz19-Jpk_fPztDa7DhCA99pengzw9yz6QZkdqsW-g2X91bNtr1z92swtwBbbwjX370EZcvaH22hvKgn_lS9cd0U4guzm4FYJyBV69C_JQff-8e_SBrbRzu4PyNJ9AFrZnYIGVT4vAQOBdjDwYAnGw4pkALcRB4BLQewo5jca4S25Srh0p0gQX1jWTAEJcyJg9fF5QpxLaqCZK2UYhnMDNsOAL21PuNpjsuKiAisfobHRqTZiTvFIPN5feG5NtcDuU2m3iddU1I0QJWE5fVs-zthIYtrRv-td1testOByaKMnz1PRaSDHeCllwqoQCuxRNDdhsBPUj5XwJbnqbJ6oD6IUCmkJHnUF2DpQmao6vfnBohsDjOUsGPGNBk6ggnwoQhlrWe6hkKLZDNtK3igyKmv4_WIhkycV8EXYTikuBo8TKaUPPY2WBvZtq7hbfeitDe47N8bjruvrn3O8V_wI)
] |
[Question]
[
Given a list of floating point numbers, [*standardize it*](https://en.wikipedia.org/wiki/Standard_score).
### Details
* A list \$x\_1,x\_2,\ldots,x\_n\$ is *standardized* if the *mean* of all values is 0, and the *standard deviation* is 1. One way to compute this is by first computing the mean \$\mu\$ and the standard deviation \$\sigma\$ as
$$ \mu = \frac1n\sum\_{i=1}^n x\_i \qquad \sigma = \sqrt{\frac{1}{n}\sum\_{i=1}^n (x\_i -\mu)^2} ,$$
and then computing the standardization by replacing every \$x\_i\$ with \$\frac{x\_i-\mu}{\sigma}\$.
* You can assume that the input contains at least two distinct entries (which implies \$\sigma \neq 0\$).
* Note that some implementations use the sample standard deviation, which is not equal to the population standard deviation \$\sigma\$ we are using here.
* There is a [CW answer](https://codegolf.stackexchange.com/a/177602/24877) for all [trivial solutions](https://codegolf.meta.stackexchange.com/questions/11211/should-we-combine-answers-where-the-same-code-works-in-many-different-languages/11218#11218).
### Examples
```
[1,2,3] -> [-1.224744871391589,0.0,1.224744871391589]
[1,2] -> [-1,1]
[-3,1,4,1,5] -> [-1.6428571428571428,-0.21428571428571433,0.8571428571428572,-0.21428571428571433,1.2142857142857144]
```
(These examples have been generated with [this script](https://tio.run/##VY7NDoIwEITvPMUcOEACEvFmlJMXnwExqaECsV20P5H48rVFY/CyO5n9dmd7pm9cCOe0YdQy1Q4vju0W9WG0F8Eb5NVPR0tGYI/kNIV5MuXSpoUeOslS7OIKIgKePVccXgAUiuevapRHMrxTTCCG4NSZfoYBaT@MttLfLkCzO98M7kMZrJAUlPoWmPg//Vx@k51kA/mNuxrIeGr5c73OymzTuDc).)
[Answer]
# [R](https://www.r-project.org/), ~~51~~ ~~45~~ ~~38~~ 37 bytes
Thanks to Giuseppe and J.Doe!
```
function(x)scale(x)/(1-1/sum(x|1))^.5
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0@jQrM4OTEnFUjraxjqGuoXl@ZqVNQYamrG6Zn@T9NI1jDUMdIx1tTkgrKhLF1jHUMdEyA21dT8/x8A "R – Try It Online")
[Answer]
# CW for all [trivial entries](https://codegolf.meta.stackexchange.com/questions/11211/should-we-combine-answers-where-the-same-code-works-in-many-different-languages/11218#11218)
---
## [Python 3](https://docs.python.org/3/) + scipy, 31 bytes
```
from scipy.stats import*
zscore
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P60oP1ehODmzoFKvuCSxpFghM7cgv6hEi6uqODm/KPX/fwA "Python 3 – Try It Online")
# Octave / MATLAB, 15 bytes
```
@(x)zscore(x,1)
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQaNCs6o4Ob8oVaNCx1Dzf1p@UW5iiUJOfl46V2JesUa0rrGOoY4JEJvGav4HAA "Octave – Try It Online")
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~21~~ ~~20~~ 19 bytes
```
(-÷.5*⍨⊢÷⌹×≢)+/-⊢×≢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/7VHbBA3dw9v1TLUe9a541LXo8PZHPTsPT3/UuUhTW18XJABiAxUqHFpvrGCoYALEpgA "APL (Dyalog Classic) – Try It Online")
`⊢÷⌹` is sum of squares
`⊢÷⌹×≢` is sum of squares divided by length
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
tYm-t&1Zs/
```
[Try it online!](https://tio.run/##y00syfn/vyQyV7dEzTCqWP///2hdYx1DHRMgNo0FAA "MATL – Try It Online")
### Explanation
```
t % Implicit input
% Duplicate
Ym % Mean
- % Subtract, element-wise
t % Duplicate
&1Zs % Standard deviation using normalization by n
/ % Divide, element-wise
% Implicit display
```
[Answer]
# APL+WIN, ~~41,32~~ 30 bytes
9 bytes saved thanks to Erik + 2 more thanks to ngn
```
x←v-(+/v)÷⍴v←⎕⋄x÷(+/x×x÷⍴v)*.5
```
Prompts for vector of numbers and calculates mean standard deviation and standardised elements of input vector
[Answer]
# [R](https://www.r-project.org/) + pryr, ~~53~~ 52 bytes
-1 byte using `sum(x|1)` instead of `length(x)` as seen in @Robert S.'s solution
```
pryr::f((x-(y<-mean(x)))/(sum((x-y)^2)/sum(x|1))^.5)
```
For being a language built for statisticians, I'm amazed that this doesn't have a built-in function. At least not one that I could find. Even the function `mosaic::zscore` doesn't yield the expected results. This is likely due to using the population standard deviation instead of sample standard deviation.
[Try it online!](https://tio.run/##LYlBCoAgFAX3neQ/0CLNTdRVhAitRUpYQZ7@l@BiYJhJ7Gc@U07j6IleSXmSwS2RXgAdXU8oNcMqdIeL272XY1sD9rRSL5TQQFO9mtSiF8OPAZg/ "R – Try It Online")
[Answer]
# [Tcl](http://tcl.tk/), 126 bytes
```
proc S L {lmap c $L {expr ($c-[set m ([join $L +])/[set n [llength $L]].])/sqrt(([join [lmap c $L {expr ($c-$m)**2}] +])/$n)}}
```
[Try it online!](https://tio.run/##bYy9CsMgHMT3PsUNDpqSliTtW3TLKP@hiPQDNUYtFILPbm3okKHDwd3vjkvKlOLDpDDigsXYq4cCq1a/fQBnqpVRJ1hw@Zwe7lvtSRxX6CCN0e6W7hUTHSqPc0j8N5X/3pgVTdNnWl@YEzkX/0oRcsTSoceQabcF29gO6HCqOmcqHw "Tcl – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
_ÆmµL½÷ÆḊ×
```
[Try it online!](https://tio.run/##y0rNyan8/z/@cFvuoa0@h/Ye3n647eGOrsPT////H61rrGOoYwLEprEA "Jelly – Try It Online")
It's not any shorter, but Jelly's determinant function `ÆḊ` also calculates vector norm.
```
_Æm x - mean(x)
µ then:
L½ Square root of the Length
÷ÆḊ divided by the norm
× Multiply by that value
```
[Answer]
# Mathematica, 25 bytes
```
Mean[(a=#-Mean@#)a]^-.5a&
```
Pure function. Takes a list of numbers as input and returns a list of machine-precision numbers as output. Note that the built-in `Standardize` function uses the sample variance by default.
[Answer]
# [J](http://jsoftware.com/), 22 bytes
-1 byte thanks to Cows quack!
```
(-%[:%:1#.-*-%#@[)+/%#
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F9DVzXaStXKUFlPV0tXVdkhWlNbX1X5vyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvkKagqGCkYIxEgfGjDcG8kyA2PQ/AA "J – Try It Online")
# [J](http://jsoftware.com/), 31 23 bytes
```
(-%[:%:#@[%~1#.-*-)+/%#
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F9DVzXaStVK2SFatc5QWU9XS1dTW19V@b8ml5KegnqarZ66go5CrZVCWjEXV2pyRr5CmoKhgpGCMRIHxow3BvJMgNj0PwA "J – Try It Online")
```
+/%# - mean (sum (+/) divided (%) by the number of samples (#))
( ) - the list is a left argument here (we have a hook)
- - the difference between each sample and the mean
* - multiplied by
- - the difference between each sample and the mean
1#. - sum by base-1 conversion
%~ - divided by
#@[ - the length of the samples list
%: - square root
[: - convert to a fork (function composition)
- - subtract the mean from each sample
% - and divide it by sigma
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~33~~ 29 bytes
```
{d÷.5*⍨l÷⍨+/×⍨d←⍵-(+/⍵)÷l←≢⍵}
```
*-4 bytes thanks to @ngn*
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///vzrl8HY9U61HvStyDm8Hktr6h6cDqZRHbRMe9W7V1dDWB1Kah7fngAQ6FwE5tf/TwJJ9j/qmevo/6mo@tN74UdtEIC84yBlIhnh4Bv9PUzBUMFIw5gLTQBKoBsgyAWJTAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# Haskell, ~~80~~ ~~75~~ 68 bytes
```
t x=k(/sqrt(f$sum$k(^2)))where k g=g.(-f(sum x)+)<$>x;f=(/sum(1<$x))
```
Thanks to @flawr for the suggestions to use `sum(1<$x)` instead of `sum[1|_<-x]` and to inline the mean, @xnor for inlining the standard deviation and other reductions.
Expanded:
```
-- Standardize a list of values of any floating-point type.
standardize :: Floating a => [a] -> [a]
standardize input = eachLessMean (/ sqrt (overLength (sum (eachLessMean (^2)))))
where
-- Map a function over each element of the input, less the mean.
eachLessMean f = map (f . subtract (overLength (sum input))) input
-- Divide a value by the length of the input.
overLength n = n / sum (map (const 1) input)
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 7 bytes
```
▓-_²▓√/
```
[Try it online!](https://tio.run/##y00syUjPz0n7///RtMm68Yc2AalHHbP0//@PNtQx0jGO5QLRQFLXWMdQxwSITWMB "MathGolf – Try It Online")
## Explanation
This is literally a byte-for-byte recreation of Kevin Cruijssen's 05AB1E answer, but I save some bytes from MathGolf having 1-byters for everything needed for this challenge. Also the answer looks quite good in my opinion!
```
▓ get average of list
- pop a, b : push(a-b)
_ duplicate TOS
² pop a : push(a*a)
▓ get average of list
√ pop a : push(sqrt(a)), split string to list
/ pop a, b : push(a/b), split strings
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
_Æm÷²Æm½Ɗ$
```
[Try it online!](https://tio.run/##y0rNyan8/z/@cFvu4e2HNgGpQ3uPdan8//8/2lDHSMc4FgA "Jelly – Try It Online")
[Answer]
# JavaScript (ES7), ~~80~~ 79 bytes
```
a=>a.map(x=>(x-g(a))/g(a.map(x=>(x-m)**2))**.5,g=a=>m=eval(a.join`+`)/a.length)
```
[Try it online!](https://tio.run/##bYtLDoMwDET3PYlNkyCgLM1FqkpYNKSgfFBBiNunXiLRxbzFm5mZd16H77RsOqa3zSNlpo5N4AUO6uDQDhixFJ5cwKKoUWBa5UgOgezOXjZzmmJ/77Fk42102wfzkOKavDU@ORjhWalaNS/E29X/sbpRlXpIWinzDw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // given the input array a[]
a.map(x => // for each value x in a[]:
(x - g(a)) / // compute (x - mean(a)) divided by
g( // the standard deviation:
a.map(x => // for each value x in a[]:
(x - m) ** 2 // compute (x - mean(a))²
) // compute the mean of this array
) ** .5, // and take the square root
g = a => // g = helper function taking an array a[],
m = eval(a.join`+`) // computing the mean
/ a.length // and storing the result in m
) // end of outer map()
```
[Answer]
# [Python 3](https://docs.python.org/3/) + [numpy](http://www.numpy.org), 46 bytes
```
lambda a:(a-mean(a))/std(a)
from numpy import*
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRSiNRNzc1MU8jUVNTv7gkBUhzpRXl5yrkleYWVCpk5hbkF5Vo/S8oyswr0UjTiDbUMdIxjtXU5EIWQeHrGusY6pgAsSlQ@D8A "Python 3 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 59 bytes
```
(%)i=sum.map(^i)
f l=[(0%l*y-1%l)/sqrt(2%l*0%l-1%l^2)|y<-l]
```
[Try it online!](https://tio.run/##LYhLCoAgFAD3neItEjTS7LfLk0SBiyLpGZW2CLq7GbQYhplFu3VCDIESZpS7rLB6p6NhyQyoeioJZjcvCbLCHaenVez4vjNW7Lk7jkPwque1kHkZaX63Qg6J1WYDBftpNg8pzODDCw "Haskell – Try It Online")
Doesn't use libraries.
The helper function `%` computes the sum of `i`th powers of a list, which lets us get three useful values.
* `0%l` is the length of `l` (call this `n`)
* `1%l` is the sum of `l` (call this `s`)
* `2%l` is the sum of squares of `l` (call this `m`)
We can express the z-score of an element `y` as
```
(n*y-s)/sqrt(n*v-s^2)
```
(This is the expression `(y-s/n)/sqrt(v/n-(s/n)^2)` simplified a bit by multiplying the top and bottom by `n`.)
We can insert the expressions `0%l`, `1%l`, `2%l` without parens because the `%` we define has higher precedence than the arithmetic operators.
`(%)i=sum.map(^i)` is the same length as `i%l=sum.map(^i)l`. Making it more point-free doesn't help. Defining it like `g i=...` loses bytes when we call it. Although `%` works for any list but we only call it with the problem input list, there's no byte loss in calling it with argument `l` every time because a two-argument call `i%l` is no longer than a one-argument one `g i`.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 33 23 bytes
-10 bytes thanks to ngn!
```
{t%%(+/t*t:x-/x%#x)%#x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qukRVVUNbv0SrxKpCV79CVblCE4hr/6cp6BorGCqYALHpfwA "K (oK) – Try It Online")
First attempt at coding (I don't dare to name it "golfing") in K. I'm pretty sure it can be done much better (too many variable names here...)
[Answer]
# MATLAB, 26 bytes
Trivial-ish, `std(,1)` for using population standard deviation
```
f=@(x)(x-mean(x))/std(x,1)
```
[Answer]
# TI-Basic (83 series), ~~14~~ 11 bytes
```
Ans-mean(Ans
Ans/√(mean(Ans²
```
Takes input in `Ans`. For example, if you type the above into `prgmSTANDARD`, then `{1,2,3}:prgmSTANDARD` will return `{-1.224744871,0.0,1.224744871}`.
Previously, I tried using the `1-Var Stats` command, which stores the population standard deviation in `σx`, but it's less trouble to compute it manually.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÅA-DnÅAt/
```
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/177605/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f//cKujrksekCzR//8/WtdYx1DHBIhNYwE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeXiCvZLCo7ZJCkr2/w@3Ouq65AHJEv3/Ov@jow11jHSMY3UUQAwQpWusY6hjAsSmsbEA).
**Explanation:**
```
ÅA # Calculate the mean of the (implicit) input
# i.e. [-3,1,4,1,5] → 1.6
- # Subtract it from each value in the (implicit) input
# i.e. [-3,1,4,1,5] and 1.6 → [-4.6,-0.6,2.4,-0.6,3.4]
D # Duplicate that list
n # Take the square of each
# i.e. [-4.6,-0.6,2.4,-0.6,3.4] → [21.16,0.36,5.76,0.36,11.56]
ÅA # Pop and calculate the mean of that list
# i.e. [21.16,0.36,5.76,0.36,11.56] → 7.84
t # Take the square-root of that
# i.e. 7.84 → 2.8
/ # And divide each value in the duplicated list with it (and output implicitly)
# i.e. [-4.6,-0.6,2.4,-0.6,3.4] and 2.8 → [-1.6428571428571428,
# -0.21428571428571433,0.8571428571428572,-0.21428571428571433,1.2142857142857144]
```
[Answer]
# Pyth, ~~21~~ 19 bytes
```
[[email protected]](/cdn-cgi/l/email-protection)^-Jk2Q2
```
Try it online [here](https://pyth.herokuapp.com/?code=mc-dJ.OQ%40.Om%5E-Jk2Q2&input=%5B-3%2C1%2C4%2C1%2C5%5D&debug=0).
```
[[email protected]](/cdn-cgi/l/email-protection)^-Jk2Q2Q Implicit: Q=eval(input())
Trailing Q inferred
J.OQ Take the average of Q, store the result in J
m Q Map the elements of Q, as k, using:
-Jk Difference between J and k
^ 2 Square it
.O Find the average of the result of the map
@ 2 Square root it
- this is the standard deviation of Q
m Q Map elements of Q, as d, using:
-dJ d - J
c Float division by the standard deviation
Implicit print result of map
```
*Edit: after seeing [Kevin's answer](https://codegolf.stackexchange.com/a/177690/41020), changed to use the average builtin for the inner results. Previous answer: `mc-dJ.OQ@csm^-Jk2QlQ2`*
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 229 bytes
```
DEFINE('Z(A)')
Z X =X + 1
M =M + A<X> :S(Z)
N =X - 1.
M =M / N
D X =GT(X) X - 1 :F(S)
A<X> =A<X> - M :(D)
S X =LT(X,N) X + 1 :F(Y)
S =S + A<X> ^ 2 / N :(S)
Y S =S ^ 0.5
N A<X> =A<X> / S
X =GT(X) X - 1 :S(N)
Z =A :(RETURN)
```
[Try it online!](https://tio.run/##dZDNasMwEITP2qfYWySaP5vmEqKCwHJZsJUiySD7kEPPpTn0/XF3HUMLpRchNDPf7Orr8/5@/3ieVeNbCl5vJu3MxoAKQ@87tBTehgzKxYiWDzfqRTBAitB2WdP28YCET1ipc6vbIZglcaGXFaDOmgywoMI19q6jyTdouSpGtjLoCPQ/0IeGXdchMwntD4H5AiYzT6qgLeIH1aPt@eYuhdWkJ9lFxB1W@1U9YIBGIq9ZF4OLJkVJ5uYcryrnDnvmc3cSL49WtkHc61gjuxPatJbhDWshc4Q540O64XF/gvCbesAEf7qTlj@b2MLx6PMQg5l577mGCupv "SNOBOL4 (CSNOBOL4) – Try It Online")
Link is to a functional version of the code which constructs an array from STDIN given its length and then its elements, then runs the function `Z` on that, and finally prints out the values.
Defines a function `Z` which returns an array.
The `1.` on line 4 is necessary to do the floating point arithmetic properly.
[Answer]
# [Julia 0.7](http://julialang.org/), 37 bytes
```
a->(a-mean(a))/std(a,corrected=false)
```
[Try it online!](https://tio.run/##yyrNyUw0/59m@z9R104jUTc3NTFPI1FTU7@4JEUjUSc5v6goNbkkNcU2LTGnOFXzf0FRZl5JTp5Gmka0oY6RjnGspiYXqhiaiK6xjqGOCRCbAiX@AwA "Julia 0.7 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ 19 bytes
```
≧⁻∕ΣθLθθI∕θ₂∕ΣXθ²Lθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/983scCxuDgzPS8oMz2jRMM3M6@0WEfBJbMsMyVVI7g0V6NQU0fBJzUvvSQDyASyCzWtuQKKMvNKNJwTi0s0oCoLdRSCC0sTi1KD8vPhgiDtAfnlqUUgaSMUc0DA@v//6GhdYx1DHRMgNo2N/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
≧ Update each element
⁻ Subtract
Σ Sum of
θ Input array
∕ Divided by
L Length of
θ Input array
```
Calculate \$\mu\$ and vectorised subtract it from each \$x\_i\$.
```
θ Updated array
∕ Vectorised divided by
₂ Square root of
Σ Sum of
θ Updated array
X Vectorised to power
² Literal 2
∕ Divided by
L Length of
θ Array
I Cast to string
Implicitly print each element on its own line.
```
Calculate \$\sigma\$, vectorised divide each \$x\_i\$ by it, and output the result.
Edit: Saved 6 bytes thanks to @ASCII-only for a) using `SquareRoot()` instead of `Power(0.5)` b) fixing vectorised `Divide()` (it was doing `IntDivide()` instead) c) making `Power()` vectorise.
[Answer]
# [Factor](https://factorcode.org/), 34 bytes
```
[ dup demean swap 0 std-ddof v/n ]
```
[Try it online!](https://tio.run/##LYq9CsIwFEb3PsX3Ao0/1UUXN@niIk7SISS3GLRJyL1WRPrsMUWHj@9wOL02ElK@nNvTcYdBy02xaHEszjDulDw9fnqkuWTERCLvmJwX7KvqgxXWaDD9af66Kbgp22LKV9hnhKWBtAe/dMQSLLa2NvQYFx5dSZRS6GDCEAMTJLlD/gI "Factor – Try It Online")
Sadly, while Factor has the `z-score` word, it uses the sample standard deviation instead of the population standard deviation.
] |
[Question]
[
# Task
Given two positive integers (divid**e**nd and divis**o**r), calculate the **q**uotient and the **r**emainder.
Normally it would be calculated as `e = o*q+r` where `q*o<=e` and `0<=r<o`.
For this challenge it still `e = o*q+r` but `q*o>=e` and `-o<r<=0`.
For example `e=20` and `o=3`, normally it would be `20/3 -> 20=3*6+2`, since `18<=20` and `0<=2<3`. Here it will be `20/3 -> 20=3*7-1` where `21>=20` and `-3<-1<=0`
# Test Cases
```
Input -> Output
20, 3 -> 7, -1
10, 5 -> 2, 0
7, 20 -> 1, -13
100, 13 -> 8, -4
```
You don't need to handle `o=0`.
[Answer]
# [Python 3](https://docs.python.org/3/), 39 26 bytes
[Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender) saved 13 bytes
```
lambda x,y:(-(x//-y),x%-y)
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9JKQ1ejQl9ft1JTp0IVSP4vKMrMK9FI0zAy0DHW1FRQVjDXUdA15IIJGxromIKFjXQUDOCi5jpGBmBRQ5BiYyTVBjqGEGMsgDIm/wE "Python 3 – Try It Online")
## [Python 2](https://docs.python.org/2/), 25 bytes
```
lambda x,y:(-(x/-y),x%-y)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaFCp9JKQ1ejQl@3UlOnQhVI/i8oyswr0UjTMDLQMdbUVFBWMNdR0DXkggkbGuiYgoWNdBQM4KLmOkYGYFFDkGJjJNUGOoYQYyyAMib/AQ)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
NdN
```
[Try it online!](https://tio.run/##y0rNyan8/98vxe/////m/40MAA "Jelly – Try It Online")
### How it works
Abusing divmod again \o/. Look ma’ no unicode!
```
NdN - Full program / Dyadic chain. | Example: 7, 20
N - Negate the first input. | -7
d - Divmod by the second one. | [-1, 13]
N - Negate each again. | [1, -13]
```
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
```
n#k=[-div(-n)k,mod n(-k)]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0852zZaNyWzTEM3TzNbJzc/RSFPQzdbM/Z/bmJmnoKtQko@lwIQFBRl5pUoqCgYGSgoKxijCBmChExRhMyBIkYGaKpAygyN/wMA "Haskell – Try It Online")
[Answer]
# Mathematica, 21 bytes
```
{s=⌈#/#2⌉,#-#2s}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7v7rY9lFPh7K@stGjnk4dZV1lo@Jatf8BRZl5JQ5p0UYGOsaxXDCeoYGOKYJnrmNkgCxnoGNoHPsfAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
(s‰(
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fo/hRwwaN//8NDQy4DI0B "05AB1E – Try It Online")
**5 bytes**
```
(‰ćÄJ
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f41HDhiPth1u8/v83NOYyNDAAAA "05AB1E – Try It Online")
### How they work
Abuses Python's modulo! \o/
```
(s‰( | Full program. Let A and B be the two inputs. | Example: 100, 13.
( | Compute -A. | -100
s | Swap (reverse the stack, in this case). | 13, -100
‰ | Divmod. | [-8, 4]
( | Negative (multiply each by -1, basically). | [8, -4]
----------------------------------------------------
(‰ćÄJ | Full program. Takes input in reverse order.
( | Negative. Push -A.
‰ | Divmod
ć | Push head extracted divmod (make the stack [quotient, [remainder]].
Ä | Absolute value (operates on the quotient).
J | Join the stack.
```
[Answer]
## [Alice](https://github.com/m-ender/alice), 15 bytes
```
/O.
\io/R%e,R:R
```
[Try it online!](https://tio.run/##S8zJTE79/1/fX48rJjNfP0g1VSfIKuj/fyMDLmMA "Alice – Try It Online")
### Explanation
Ruby's integer division and modulo (on which Alice's are implemented) are defined such that using a negative divisor already sort of does what we want. If we negated the divisor we automatically get the correct modulo, and we get minus the quotient we want. So the easiest way to solve this is by negating a bunch of numbers:
```
/ Switch to Ordinal mode.
i Read all input as a string "e o".
. Duplicate the string.
/ Switch to Cardinal mode.
R Implicitly convert the top string to the two integer values it
contains and negate o.
% Compute e%-o.
e, Swap the remainder with the other copy of the input string. We can't
use the usual ~ for swapping because that would convert the string
to the two numbers first and we'd swap e%-o in between e and o instead
of to the bottom of the string.
R Negate o again.
: Compute e/-o.
R Negate the result again.
\ Switch to Ordinal mode.
O Output -(e/-o) with a trailing linefeed.
o Output e%-o.
The code now bounces through the code for a while, not doing much except
printing a trailing linefeed when hitting O again. Eventually, the IP
reaches : and attempts a division by zero which terminates the program.
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 18 bytes
```
x->y->-[-x\y,-x%y]
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7v0LXrlLXTjdatyKmUke3QrUy9n9BUWZeiUaahpGBpoaxpuZ/AA "Pari/GP – Try It Online")
[Answer]
# [Julia](http://julialang.org/), 18 bytes
```
x$y=.-fldmod(-x,y)
```
[Try it online!](https://tio.run/##yyrNyUw0@/@/QqXSVk83LSclNz9FQ7dCp1Lzf0FRZl5JTp6GkYGKsSYXjGdooGKK4JmrGBkgyxmoGBpr/gcA "Julia 0.6 – Try It Online")
`.-` is element wise negation, and `fldmod` returns a tuple made of the results of floored divison and corresponding residue.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~5~~ 4 bytes
```
_&\_
```
[Try it online!](https://tio.run/##y00syfn/P14tJv7/f0NjLkMDAwA "MATL – Try It Online")
*-1 byte thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)*
```
# implicit input
_ # unary minus (negates first input, o)
&\ # alternative output mod, returns remainder, quotient, implicitly takes e
_ # unary minus, takes the opposite of the quotient.
# implicit output, prints stack as remainder
quotient
```
[Answer]
# [J](http://jsoftware.com/), 16 bytes
```
([-]*a),~a=.>.@%
```
This is essentially the Jenny\_mathy's Mathematica solution rewritten in J.
# How it works:
`a=.>.@%` Finds the ceiling of the division of the left and right arguments and stores it into variable a
`,~` concatenated to (reversed)
`([-]*a)` subtracts a\*right argument from the left argument
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8F8jWjdWK1FTpy7RVs9Oz0H1vyaXkp6CepqtnrqCjkKtlUJaMRdXanJGvoKRgUKagjGEbQhim0LY5kCmkQFMHCRhaPwfAA "J – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~31~~ 29 bytes
*-2 bytes thanks to Giuseppe*
```
function(e,o)-c(e%/%-o,-e%%o)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jVSdfUzdZI1VVX1U3X0c3VVU1X/N/moaRgY6xJleahqGBjimINtcxMoDwDXQMjTX/AwA "R – Try It Online")
[Answer]
# Common Lisp, 7 bytes
Built-in function `ceiling` returns two values: the ceiling of the quotient, and the remainder to match:
```
$ clisp -q
[1]> (ceiling 20 7)
3 ;
-1
```
[Answer]
# JavaScript (ES6), ~~37~~ ~~31~~ ~~29~~ ~~27~~ 25 bytes
*Saved 2 bytes thanks to @Rod*
*Saved 2 bytes thanks to @ETHproductions*
Takes input in currying syntax. Returns **[q,r]**.
```
a=>b=>[q=~-a/b+1|0,a-q*b]
```
### Test cases
```
let f =
a=>b=>[q=~-a/b+1|0,a-q*b]
console.log(JSON.stringify(f(20)(3))) // -> 7, -1
console.log(JSON.stringify(f(10)(5))) // -> 2, 0
console.log(JSON.stringify(f(7)(20))) // -> 1, -13
console.log(JSON.stringify(f(100)(13))) // -> 8, -4
```
[Answer]
# [Perl 5](https://www.perl.org/), 30 + 1 (`-p`) = 31 bytes
```
say+($_-($\=$_%-($"=<>)))/$"}{
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJbQyVeV0MlxlYlXhVIK9na2GlqauqrKNVW//9vZMBl/C@/oCQzP6/4v66vqZ6BocF/3QIA "Perl 5 – Try It Online")
[Answer]
# [4](https://github.com/urielieli/py-four), ~~55~~ 50 bytes
```
3.711712114001231311141130013513213131211513115154
```
[Try it online!](https://tio.run/##HYm5EYAwDARzVSFSZvD49NhDQNEkpA7cCY0ImWjvdi1CSwc6BLBaIQpFTkDzqUMFS2X2VRxuEe9zz0GU4IOBdnaaI6e4U0laoy2hSvRXvlbiPcOvPw)
Represents the reminder by it's negation (`10` instead of `-10`), since the language uses byte input and output, deemed valid by OP comment.
[Answer]
# [Commentator](https://github.com/cairdcoinheringaahing/Commentator), 90 bytes
```
//
;{- -}
{-{-//-}e#<!-}
;{-{-{- -}-}-}
{-{-{-e#-}
;{-{- -}-}
{-%e#*/-}# /*-}e#*/
```
[Try it online!](https://tio.run/##S87PzU3NK0ksyS/6/19fn8u6WldBt5arWrdaV19ftzZV2UYRyLUG8cEyIMgF4aUqw2QUoKKqqcpaQE3KCnCgrwUyQ0v/////Rgb/jQE "Commentator – Try It Online")
Outputs the remainder, then the quotient, newline separated.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 43 bytes
```
f(x,y,z)int*x;{for(z=0;*x>0;*x-=y)z++;y=z;}
```
## Usage
```
main(){
int a=7,b=20,c;
c=f(&a,b);
printf("%d %d\n",c,a);
}
```
[Try it online!](https://tio.run/##FYtBCoMwEAC/EgRlV1eIeFy2L@klrqR4aBTxkET69jRe5jIzOn5US/EQKVHGLVx95NvvJ2Sx3MfXg1ES5mHgJJl/5eu2AHjX1DiZrKVFppmUjYqHztGCbI6zag9Nu5p2fYeGlBzW9w8 "C (gcc) – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 30 bytes
```
(i,j)->(i+j-1)/j+","+(i%j-j)%j
```
[Try it online!](https://tio.run/##hY4xD4IwEIV3fsWFhKQNLQLGOBDdHZxYSIxDhUpaoRAoBGP47VgRR3W45C7vvfueZD2jVc2VzG5TWrC2hSMT6mEBCKV5c2Uph@R1AsS6ESqHAR2MkvMGGIHPesGR8YxmWs20SCGBAXYwIUEkpnskXEkDvJKuTWwXCUdSiR05RZZJ1N2lMIkl2Fcig9J0QG/e6QwMzwXie6t56VWd9mqj6EKhwRtQ6JM1nvHfHIFPNr8dWxL6/374JFg4ozVOTw "Java (OpenJDK 8) – Try It Online")
```
7,-1
2,0
1,-13
8,-4
```
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 35 bytes
```
L*,@0$_$2D2D%V/1B]b\GLVB]-1Gx$pBcB*
```
[Try it online!](https://tio.run/##S0xJKSj4/99HS8fBQCVexcjFyEU1TN/QKTYpxt0nzClW19C9QqXAKdlJ6////@b/jQwA "Add++ – Try It Online")
[Answer]
# C (gcc) 41 bytes
```
f(a,b){b=(a+b-1)/b;}g(a,b){b=a-f(a,b)*b;}
```
This may be cheating, using two functions and it may fail other tests?
[Try it online](https://tio.run/##NU5LCsMgFNx7CgkEND6pJv0srCdJs9CEBBexJbgTz25tbRcDw3yYmfk2zzmvxICl0WpimOWSnqxK218zvNpdEfNunCc0IucDDqO8Tljj2AsYQAq4wA0Kl6JgSAqtz4N8gk4L5e5n5Rj7VU2phdF1/QRWfwmTk0Kvo5gradoFt8vDN1CXoX6hCiWU8hs)
[Answer]
# [Swift](https://swift.org), 47 bytes
```
func f(a:Int,b:Int){print((a+b-1)/b,(a%b-b)%b)}
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~124~~ ~~123~~ 105 bytes
```
E =INPUT
O =INPUT
Q =E / O
R =E - Q * O
EQ(0,R) :S(A)
R =R - O
Q =Q + 1
A OUTPUT =Q
OUTPUT =R
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/X8FVwdbTLyA0hEvBH84KVLB1VdBX8OdSCAKxdIECWiCea6CGgU6QpoJVsIajJlgyCCjpD9YQqKCtYMjlqOAfGgI0A8jngjODuFz9XP7/NzTgMgUA "SNOBOL4 (CSNOBOL4) – Try It Online")
Takes input as `E`, then `O`, separated by a newline and prints out `Q`, then `R`, separated by a newline.
[Answer]
# TXR: 8 bytes
Built-in function `ceil-rem`. E.g. `(ceil-rem 20 7)` yields `(7 -1)`.
[Answer]
# [Clean](https://clean.cs.ru.nl), 42 bytes
```
import StdEnv
f a b#c=(a-1)/b+1
=(c,a-c*b)
```
[Try it online!](https://tio.run/##Dcq7DkAwFADQ3VfcxOLVeCymbgwSmy@4vVSatCWUxM@7nPmQXdCz2@bLLuDQeDZu344AU5h7f0caEFRMMkFRp6XK60gmVKCgTKU8BfynBA0tNBW/pC2uJ4th5O7x6AydHw "Clean – Try It Online")
[Answer]
# [Deorst](https://github.com/cairdcoinheringaahing/Deorst), 23 bytes
```
@l0-%z]@l0-,l0-@l0-miE_
```
[Try it online!](https://tio.run/##S0nNLyou@f/fIcdAV7UqFkTpADGIzs10jf///7/5fyMDAA "Deorst – Try It Online")
## How it works
```
@ - Swap the inputs
l0- - Negate
% - Modulo
z] - Push the inputs
@ - Swap
l0- - Negate
, - Integer divide
l0- - Negate
@ - Swap
l0- - Negate
miE_ - Print
```
] |
[Question]
[
I'm designing a new space station for generic super-villain purposes (something something megalaser), but I'm having trouble designing the solar panels.
My genius team of scientists can calculate exactly how many square meters of paneling we need to power the station, but the problem is our solar panels only come in squares!
Thankfully due to a generous supply of duct tape, my minions can stitch together the right squares to make up the surface area needed, but my scientists have gone on strike (something about cyanide not being an ethical coffee sweetener) and my minions are too stupid to figure out what squares they need to connect.
That's where you come in ~~minion~~ loyal golfer. I need some code that will take the target surface area and tell me what size solar panels my minions need to tape together to reach it.
The minions have a tiny budget, so they still have to program their computer by punchcard. Time spent programming is time not spent taping, so make sure your code is as small as possible!
## The Challenge
Given a positive integer `n`, output the smallest list of square numbers that sums to `n`.
A square number is any integer that is the result of multiplying an integer by itself. For example `16` is a square number because `4 x 4 = 16`
This is [A000290](https://oeis.org/A000290)
For example:
For `n = 12`, you could achieve the desired size with 4 panels of sizes `[9, 1, 1, 1]` (note that this is the correct answer for the Google FooBar variant of this challenge), however this is not the smallest possible list, because you can also achieve the desired size with 3 panels of sizes `[4, 4, 4]`
For `n = 13`, you can achieve the desired size with only 2 panels: `[9, 4]`
If `n` is a square number, the output should be `[n]`.
### Input
A positive integer `n` representing the total desired surface area of the solar panels.
Note that `0` is [not positive](https://math.stackexchange.com/questions/26705/is-zero-positive-or-negative)
### Output
The smallest possible list of square numbers that sums to `n`, sorted in descending order.
If there are multiple smallest possible lists, you may output whichever list is most convenient.
### Testcases
```
1 -> [1]
2 -> [1,1]
3 -> [1,1,1]
4 -> [4]
7 -> [4,1,1,1]
8 -> [4,4]
9 -> [9]
12 -> [4,4,4]
13 -> [9,4]
18 -> [9,9]
30 -> [25,4,1]
50 -> [49,1] OR [25,25]
60 -> [49,9,1,1] OR [36,16,4,4] OR [25,25,9,1]
70 -> [36,25,9]
95 -> [81,9,4,1] OR [49,36,9,1] OR [36,25,25,9]
300 -> [196,100,4] OR [100,100,100]
1246 -> [841,324,81] OR one of 4 other possible 3-length solutions
12460 -> [12100,324,36] OR one of 6 other possible 3-length solutions
172593 -> [90601,70756,11236] OR one of 18 other possible 3-length solutions
```
[Answer]
# Python 3.8 with Numpy using Lagrange's four-square theorem, 92 bytes
A Numpy version with [Lagrange's four-square theorem](https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem) as exploited by others.
3 bytes shaved thanks to @ovs using the [`r_` trick](https://numpy.org/doc/stable/reference/generated/numpy.r_.html), literally called `index_tricks` in Numpy.
i.e. the Lagrange's four-square theorem together with Numpy save you 44 byte comparing to pure Python.
```
from numpy import*
lambda n:[r[r!=0][::-1]**2for i in ndindex(*[n+1]*4)if(r:=r_[i])@r==n][0]
```
Faster but use 1 more byte:
```
from numpy import*
f=lambda n:next(r[r!=0][::-1]**2for i in ndindex(*[n+1]*4)if(r:=r_[i])@r==n)
```
Fully written out:
```
from numpy import ndindex, square, sum
def f(n):
for i in ndindex(m := n + 1, m, m, m):
if sum(s := square(i)) == n:
return s[s!=0][::-1]
```
The version with `r_` is equivalent (but not identical) to
```
from numpy import ndindex, square, array
def f(n):
for i in ndindex(m := n + 1, m, m, m):
if (a := array(i)) @ a == n:
return a[a!=0][::-1]**2
```
# Python 3.8 using Lagrange's four-square theorem, 135 bytes
A pure Python version with [Lagrange's four-square theorem](https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem) as exploited by others.
i.e. the Lagrange's four-square theorem only save you one byte with pure Python.
```
from itertools import *
lambda n:[[a for a in s[::-1]if a!=0]for i,j,k,l in product(*[range(n+1)]*4)if sum(s:=(i*i,j*j,k*k,l*l))==n][0]
```
[Try it online!](https://tio.run/##TY3NbsMgEITvfoptegHqSsY/cYzkJ6EcaBNaWhsQJocqyrO72Lhu9/KNZmZ33Xf4sKY6OT/PytsRdLj4YO0wgR6d9QFIpvpBjq9nCYZxLkFZDxK0gYkz9kyFViAf@kIsvs4/8698WFLn7fn6FhDhXpr3CzJPFAtS41ifriOaWI80iX0SN0jcIQPGfW8EL0S2nlqO8Azi0HxFmVAl1AltwimhS6BblW5dusVVkfgIza6Ou2p31TW/qip2k5b18b/@C9qy6eInwVbDeW0CUoebvr@Em0Ia3w94nn8A "Python 3.8 (pre-release) – Try It Online")
Faster but use 1 more byte:
```
from itertools import *
lambda n:next([a for a in s[::-1]if a!=0]for i,j,k,l in product(*[range(n+1)]*4)if sum(s:=(i*i,j*j,k*k,l*l))==n)
```
[Try it online!](https://tio.run/##PYzfboMgFIfvfYqz7gaoS6RqrSQ8ifOCrdKxKhCkyZamz@5Q6M7Nd/5852d//ZfR5cm6ZZHOTKD84Lwx4wxqssZ5IJnko5g@zgI008OPR50AaRwIUBrmjrE32isJ4oUX/bpX@Xd@zcf1ap053z49Ip0T@jIgvae4JxUO@nyb0Mw4UiT4JHyQ8ENGjDnXONty1oQug1A033CIKCOqiCbiFNFG0KTS5NJ0LovIOvGY2CS29dMrnkHVMXavW1/8D82hbkN6z7aFdUp7JHd39Xj3d4kUfuzwsvwB "Python 3.8 (pre-release) – Try It Online")
Fully written out:
```
from itertools import product
def f(n):
for i, j, k, l in product(*[range(n + 1)] * 4):
if sum(s := (i * i, j * j, k * k, l * l)) == n:
return [a for a in s[::-1] if a != 0]
```
# Python 3.8, 136 bytes
A brute force version with no import.
```
g=lambda n:[[]]if n==0else sum(([l+[i*i]for l in g(r)]for i in range(1,n+1)if(r:=n-i*i)>=0),[])
lambda n:sorted(min(g(n),key=len))[::-1]
```
[Try it online!](https://tio.run/##TY3BboMwDIbvPEXUXZKVSgRKKZHSF8lyYGrCrAWDAjtUVZ@dMsLS@fJ9tn/Zw2366rE4D36eW@ma7vPaEBRKaQ2WoJSZcaMh409HqXJ7Be@gbe@JI4CkpZ6tHfx2vsHWUJ7injOw1AuJhyXOLjJjqdIssa/7Y@8nc6UdIG0psvTb3KQzyJgS4sB1Eo@qhCzF0xV5QBFwDKgCzgF1AN@ifMvybV1kgW@kjHaKVkWryz8rsjjk@fH031@LKi/r5ZMW62DwgBO1uzs8Pqa7pcAeOzbPTw "Python 3.8 (pre-release) – Try It Online")
Fully written out:
```
def g(n: int) -> list[list[int]]:
"""Calculate all combinations of set of square numbers that sum to n.
:param int n: >= 1
"""
if n == 0:
return [[]]
res = []
for i in range(1, n + 1):
r = n - i * i
if r >= 0:
res += [l + [i * i] for l in g(r)]
return res
def f(n):
"""Calculate the smallest set of square numbers that sum to n.
In decending orders.
"""
return sorted(min(g(n), key=len))[::-1]
```
# Test
```
for i in [
1,
2,
3,
4,
7,
8,
9,
12,
13,
18,
30,
50,
60,
70,
95,
300,
1246,
12460,
172593,
]:
print(f"{i}\t{f(i)}")
```
[Answer]
# [R](https://www.r-project.org/), ~~81~~ 79 bytes
-2 bytes thanks to pajonk
```
function(n,`!`=function(x)outer(x,x,`+`),x=which(n==!!(0:n)^2,T)[1,]-1)x[x>0]^2
```
[Try it online!](https://tio.run/##PcfBCoMwDADQu3/RW4IRWp1sDrKv8FYqBVnRSwRRzN932MMuD96eE@d0ynysm4BQNJH/VdzO47uDklKsI5LytazzAsJsDNi34NTSiN5RaByq148NU5sTPLBK4F7F7razt33xWRx6zD8 "R – Try It Online") (For large inputs, TIO will run into time-out/out-of-memory problems.)
By [Lagrange's four-square theorem](https://en.wikipedia.org/wiki/Lagrange%27s_four-square_theorem), the output is always of length at most 4. This constructs all the sums of 4 squares from \$0^2\$ to \$n^2\$ in a 4-dimensional arrays, and keeps the first value which is equal to \$n\$. Because of how `which` works, it will first find sums which include some 0s if there are any, guaranteeing that we find solutions with 1/2/3 squares if there are any. We then filter out the 0s with `x[x>0]^2`.
In more recent version of R (unavailable on TIO for now), this can be shortened to:
---
# [R](https://www.r-project.org/) >= 4.1.0, 65 bytes
```
\(n,`!`=\(x)outer(x,x,`+`),x=which(n==!!(0:n)^2,T)[1,]-1)x[x>0]^2
```
[Try it online!](https://tio.run/##HcRJCoAwDADAu7/oLcEIrQsuEF/hzYWCWPRSQRTz@4qdw1zBcZjAk1WWJxA8n3u7QEjIphZJ@N2PdQfPrBTozuOS04CjoTkzKKP0el7y4KDExIFp4sV/of@reB1vKwwf "R – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 46 bytes
```
# #&@@PowersRepresentations[#,4,2]/. 0->Set@$&
```
[Try it online!](https://tio.run/##JYqxCoMwFEX39xVCitOzTUzUOlTyCVJHcQgS0cFYNNCh1F9PX@hwLtxz72r8bFfjl9GE6RFYwlKt2@1t9@NpX7s9rPO0bu7oGSrMh9s14VnTWa8vaWj3xfmeZc2k2ZCe3Wjc@QGBkCNIBIVQIdwRagRBSpATVCVHKIiSqIi6iI7Hkyr/GUuVF7WEb/gB "Wolfram Language (Mathematica) – Try It Online")
Relies on the four-square theorem, then removes zeroes. Built-in does most of the work.
[Answer]
# [J](http://jsoftware.com/), 36 bytes
```
((i.~+/&>){])[:*:&.>@,4{\@$[:<1+i.@-
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NTQy9eq09dXsNKtjNaOttKzU9OwcdEyqYxxUoq1sDLUz9Rx0/2tycaUmZ@QraNjoWBlqKuhaKaQpGMKEDHVgQkZIQnBBY4RWE6iQCUzIRAdZpTlCGKbSAqHZEipkiaQKrs4QbrUlQsz4PwA "J – Try It Online")
Brute force. Relies on 4-square theorem, which I learned about from [Robin Ryder's answer](https://codegolf.stackexchange.com/a/237179/15469).
[Answer]
# JavaScript (ES6), ~~110~~ ~~81~~ 71 bytes
*-7 thanks to Mayube, -6 thanks to emanresu A, and -2 thanks to Arnauld*
```
f=(x,i=x**.5|0,r=i?[i*i,...f(x-i*i)]:[])=>s=i>1&&r[f(x,i-1).length]?s:r
```
Recursive solution. Lots of golfs along the way :p
[Try it online!](https://tio.run/##bc7dCoMgAIbh811FR6FhNltjGVgXIh5Ey@aIHBqjg92726AfyM4@eHjhe9bv2jZGvcZ40PfWOcnAhBSboghfP2dkmKq4ihTCGEswxb8JRcEFZKVlqiRhaLj8FzGBuG@HbnyIyhbGNXqwum9xrzsgQUAgDJIk4EScdpIugny7bHag2ayZJ7dF0HGZr@63dDa6F5Juld@R5Ss9sHw1KtwX)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ÅœéʒŲP}нR
```
[Try it online!](https://tio.run/##ARwA4/9vc2FiaWX//8OFxZPDqcqSw4XCslB90L1S//83 "05AB1E – Try It Online")
will be ridiculously slow for larger inputs
```
integer partitions
sort by length
filter
square? (implicit map)
product
(implicit truthy)
end filter
head
reverse
```
[Answer]
# [R](https://www.r-project.org/), 67 bytes
```
function(n,b=n+1){while(sum(T)-n)T=((F=F+1)%/%b^(0:3)%%b)^2;T[T>0]}
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTyfJNk/bULO6PCMzJ1WjuDRXI0RTN08zxFZDw83WDSijqq@aFKdhYGWsqaqapBlnZB0SHWJnEFv7P03DRJMrTcPQAkwag0hjAxBpCibNDTT/AwA "R – Try It Online")
Counts up from 1, converting each number to base-`n` digits, least-significant first, and returning the first set for which the sum of squares of the digits equals `n`.
---
*(previous version, with 4 bytes saved thanks to Robin Ryder)*:
**# [R](https://www.r-project.org/), ~~75~~ 71 bytes**
```
function(n,x=expand.grid(a<-0:n,a,a,a)^2,y=x[rowSums(x)==n,][1,])y[y>0]
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jT6fCNrWiIDEvRS@9KDNFI9FG18AqTycRBDXjjHQqbSuii/LLg0tzizUqNG1t83Riow11YjUroyvtDGL/p2mYaHKlaRhagEljEGlsACJNwaS5geZ/AA "R – Try It Online")
Uses a variation of [Robin Ryder's approach](https://codegolf.stackexchange.com/a/237179/95126), here constructing all combinations of four squares in one step using the built-in [R](https://www.r-project.org/) function `expand.grid`.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~77~~ 76 bytes
```
f=lambda n,i=1:min(`f`*(~i*~i>n)or f(n,i+1),n and[i*i]+f(n-i*i)or[],key=len)
```
[Try it online!](https://tio.run/##VVDJasMwEL3rKwZ6kZwpeMkO7o8YQ1RbSkTtsZFkQi75dVdy3EAvQvOWecMbH/42UD7Puuxk/91KIDRldu4N8Yu@JPxpkqf5IjFY0Dxwm0wggaS2MompNwH7DJ9AVzX@qEfZKRLzBzSyuRm6guy64e7AD2Angn5wPlBOOdYqvYgU1xM14swArHJT5x2U0JrGcxGgqLpbOY7K8kTaq1uEAEZDnIAGD4b@nC/uvaiKkjqsiwmrnb14P1n6L2NveM1jOjjXCwVjOhRAMSvDHAvc4gGPeMIsx6zA7IhFirsU9ykeUjztwpgGbrtfnjQeNlpDPrQbaxTzLw "Python 2 – Try It Online")
```
f=lambda n,i=1 # recursive function with input n and initial side length 1
n and ... or [] # If n is 0, return the empty list.
min(..., key=len) # Otherwise return the shortest of
`f`*(~i*~i>n) # - '<function <lambda> at ...>' if (i+1)**2 is larger than n
or f(n,i+1) # or the result of the recursive call f(n, i+1)
[i*i]+f(n-i*i) # - the shortest solar panel configuration starting with a length-i panel
# In case both have the same length, the first will be selected.
# This results in larger panels appearing first.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ŒṗƲẠ$ƇṪU
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7px9uO7Tp4a4FKsfaH@5cFfpf53A7SHiGirdm5P//hjpGOsY6JjrmOhY6ljqGRjqGxjrGBjqmBgA "Jelly – Try It Online")
```
ŒṗfƑƇ²€ṪU
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7p6cdm3is/dCmR01rHu5cFfpf53A7SHiGirdm5H9jAx1Tg/@GOkY6xjomOuY6FjqWOoZGOobGAA "Jelly – Try It Online")
Times out for test cases larger than 50.
## How they work
```
ŒṗƲẠ$ƇṪU - Main link. Takes n on the left
Œṗ - Integer partitions of n; Ways to sum positive integers to n
$Ƈ - Keep those partitions P for which the following is true:
Ạ - All elements are:
Ʋ - Square numbers
ṪU - Take the last (the shortest) and reverse it
ŒṗfƑƇ²€ṪU - Main link. Takes n on the left
Œṗ - Integer partitions of n; Ways to sum positive integers to n
€ - For each integer to n:
² - Yield its square
ƑƇ - Keep partitions that are unchanged after:
f ²€ - Removing all non-squares
ṪU - Take the last (the shortest) and reverse it
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 37 bytes
```
NθF⊕θF⊕ιF⊕κFE⊕λX⟦μλκι⟧²F⁼θΣμ⊞υμI⮌Φ⌊υι
```
[Try it online!](https://tio.run/##bc4xC8IwEAXg3V9x4wXioJPQURQ6VIKO4hDrSUOTtE1y9efHOHQQXb/j3Xttp0M7aJtz7UdOJ3Z3CjiJavUcAmDt20COfKJHQQE/aP5hv2Cjx6@DFRLU8CoNVyfBSuglmJuErVgSh4m1jThJuLBD93HFsUOW4MooFYxPuNcx4ZlmCpHwaGwqDxvjjSsRLhVllBBVzptdXs/2DQ "Charcoal – Try It Online") Link is to verbose version of code. Very slow. Explanation:
```
Nθ
```
Input `n`.
```
F⊕θF⊕ιF⊕κFE⊕λX⟦μλκι⟧²
```
Generate all sets of four squares in ascending order with the largest square not exceeding `n²`.
```
F⁼θΣμ⊞υμ
```
If the squares sum to `n` then save the set.
```
I⮌Φ⌊υι
```
Print the set with the most zeros, but without the zeros and in reverse order so that the largest element is printed first.
[Answer]
# JavaScript (ES6), 79 bytes
```
f=(n,i=o=1,l=[])=>(n?i>n||f(n-i*i,i,[i*i,...l])|f(n,i+1,l):l[o.length]?o:o=l,o)
```
[Try it online!](https://tio.run/##bc9NbsIwEAXgfU@Rpd0Ops4fMZLhCJW6jbxANAFXlqcCxIq7p05kE2RnFSnfezPj38P9cD1e9N9tZfGnG4ZeEgtaouRgZKuo3BG71zv7ePTErvS7Bg3t@GGMGUXHv6A/XJhuTYvMdPZ0O6s9blEaQDoc0V7RdMzgifQk45Rm63XWcvUWSR4EUitmW9DSa5nIJggsN5unp13hTcTC87mV9ni4VSxY87RkavHpLa/c2OTUKnApHGZf31Mwr@Jc/ZIT05unbFEDr6dz5@rocX0T6q4wJmIXlfeGu3oZxrtlriBetvkNavgH "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~201~~ ~~92~~ 91 bytes
```
.+
$*
^((^1|11\2)*?)((1(?(4)1\4))*?)((1(?(6)1\6))*?)((1(?(8)1\8))+)$
$.7 $.5 $.3 $.1
+` 0$
```
[Try it online!](https://tio.run/##Tcm9CsJAEATgfp4ixQm7OQi7939VSl8ihFhY2FiIpe9@WWy0mGE@5nV/P563caHrMRYPN2Mn2vWjugWeVyZSWimxbol/Luby52ZuzJ4d3FInt2RLtCj8MYnDGIqAiISKhg4N0AhtiIIsKIIq6Nko9qXyLZs15B5P "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
^((^1|11\2)*?)((1(?(4)1\4))*?)((1(?(6)1\6))*?)((1(?(8)1\8))+)$
```
Try to match 3 squares lazily, plus a 4th square (greedily, since that's golfier). This is based on my answer to [Three triangular numbers](https://codegolf.stackexchange.com/questions/132834/) but adjusted to match squares instead. (I'm not sure where the original square matching pattern was devised but Retina's entry in the [Showcase of Languages](https://codegolf.stackexchange.com/questions/44680/showcase-of-languages/) has it.) The lazy matching of the first three squares generates the squares in ascending order, with the first squares as low as possible (preferably zero).
```
$.7 $.5 $.3 $.1
```
List the matched squares in descending order.
```
+` 0$
```
Delete any trailing zeros.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 54 bytes
```
n->forpart(p=n,prod(i=1,#p,issquare(p[i]))&&return(p))
```
[Try it online!](https://tio.run/##JYrNCoNADAZfJViQDURw/a0HfRHxsFAtC2WNUQ99@m2WHuYjM4Sd@OLNcYMxhmLadmEnl@ExEMv@Mn609GDy53ncTlbDs18Q81zW65ZgGDE65s/XBCgmYPHh0jNLksFmAiLBbAkqgpqgIegJngQDgdVktVnVuiRolU7plaFNrUxPTfffJH3VDvWC8Qc "Pari/GP – Try It Online")
Port of [wasif's 05AB1E answer](https://codegolf.stackexchange.com/a/237176/9288). PARI/GP has a built-in to iterate over integer partitions, sorted by length.
[Answer]
# [Core Maude](http://maude.cs.illinois.edu/w/index.php/The_Maude_System), 245 bytes
```
mod S is pr LIST{Nat}. ops([_])([_})({_]): Nat ~> Nat . var A B : Nat . eq[A]=[A
0]. ceq[A B]=[A B}if A ={[A B}]. eq[A B]=[A s B][owise]. eq[A s B}=((s B rem
s A)^ 2)[A(s B quo s A)}. eq[A 0}= nil . eq{A X:[Nat]]= A +{X:[Nat]]. eq{nil]=
0 . endm
```
The result is obtained by reducing the `[_]` operator with the input value, e.g., `[300]`.
### Example Session
```
Maude> red [1] . --- Expected: [1]
result NzNat: 1
Maude> red [2] . --- Expected: [1,1]
result NeList{Nat}: 1 1
Maude> red [3] . --- Expected: [1,1,1]
result NeList{Nat}: 1 1 1
Maude> red [4] . --- Expected: [4]
result NzNat: 4
Maude> red [7] . --- Expected: [4,1,1,1]
result NeList{Nat}: 4 1 1 1
Maude> red [8] . --- Expected: [4,4]
result NeList{Nat}: 4 4
Maude> red [9] . --- Expected: [9]
result NzNat: 9
Maude> red [12] . --- Expected: [4,4,4]
result NeList{Nat}: 4 4 4
Maude> red [13] . --- Expected: [9,4]
result NeList{Nat}: 9 4
Maude> red [18] . --- Expected: [9,9]
result NeList{Nat}: 9 9
Maude> red [30] . --- Expected: [25,4,1]
result NeList{Nat}: 25 4 1
Maude> red [50] . --- Expected: [49,1] OR [25,25]
result NeList{Nat}: 49 1
Maude> red [60] . --- Expected: [49,9,1,1] OR [36,16,4,4] OR [25,25,9,1]
result NeList{Nat}: 49 9 1 1
Maude> red [70] . --- Expected: [36,25,9]
result NeList{Nat}: 36 25 9
Maude> red [95] . --- Expected: [81,9,4,1] OR [49,36,9,1] OR [36,25,25,9]
result NeList{Nat}: 81 9 4 1
Maude> red [300] . --- Expected: [196,100,4] OR [100,100,100]
result NeList{Nat}: 196 100 4
Maude> red [1246] . --- Expected: [841,324,81] OR one of 4 other possible 3-length solutions
result NeList{Nat}: 1156 81 9
Maude> red [12460] . --- Expected: [12100,324,36] OR one of 6 other possible 3-length solutions
...
```
Maude didn't find a solution for \$n = 12460\$ before I got bored and killed the interpreter. But Maude has unbounded integers, so it would have found it eventually (see below).
### Ungolfed
```
mod S is
pr LIST{Nat} .
ops ([_]) ([_}) ({_]) : Nat ~> Nat .
var A B : Nat .
eq [A] = [A 0] .
ceq [A B] = [A B} if A = {[A B}] .
eq [A B] = [A s B] [owise] .
eq [A s B} = ((s B rem s A) ^ 2) [A (s B quo s A)} .
eq [A 0} = nil .
eq {A X:[Nat]] = A + {X:[Nat]] .
eq {nil] = 0 .
endm
```
The program is pure brute force. We keep a counter and interpret it as a base \$n + 1\$ number. So, e.g., for \$n = 30\$ we would interpret a counter value of \$1026 = 1 \times 31^2 + 2 \times 31 + 3\$ as the list \$[1, 2, 3]\$ and check if \$1^2 + 2^2 + 3^3 = 30\$. (It doesn't.) This checks *a lot* of impossible candidates (something like \$(n - \sqrt{n})^4\$ more than necessary), but Maude doesn't have an integer square root function to limit the search. (And that would cost bytes anyway.)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 78 bytes
```
f=->n,r=[[]]{r.find{|q|q.sum==n}||f[n,r.product([*-n..-1]).map{|x,y|x+[y*y]}]}
```
[Try it online!](https://tio.run/##LclLCsMgEADQfU/RZfNxwIBLe5FhFvkgZBFrTAXF8ewmJV29xfNhSrUaLd629xqRKHswq10y77zDETatbWE2eD04/1nC/H1hKyyAkNTANrrMsU8cO0xtokKluqdBSY8fw438O6hbpaie "Ruby – Try It Online")
## Old version, with squares in ascending order (wrong)
# [Ruby](https://www.ruby-lang.org/), 76 bytes
```
f=->n,r=[[]]{r.find{|q|q.sum==n}||f[n,r.product([*1..n]).map{|x,y|x+[y*y]}]}
```
[Try it online!](https://tio.run/##Lck7CoQwEADQfk9huf4GIqTMXmSYwg8BC2OMGzBkcvaoaPWK5/wQctaq/ZnGKUSi6EDPZoq88Qa7X5QyiVnj9WDdOvnx/8VKABgqYelt5KMJfNQYqkCJUraFRkGfm@5BvHbyUUrKJw "Ruby – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
~+.~^₂ᵐ≜∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXf6oY7mSgq6dglK52qO2DY@amh7u6qx9uHXC/zptvbo4EH/rhEedc4DK/v@PNtQx0jHWMdEx17HQsdQxNNIxNNYxtNAxNtAxNdAxM9AxN9CxNAVyDYByJmZgAsg0NzK1NI4FAA "Brachylog – Try It Online")
```
~+.~^₂ᵐ≜∧ the input
~+ is the sum of
. the output
~^₂ᵐ whose elements are squares
(√ doesn't work as it support floats)
≜ get a solution (that luckily is in the right order)
∧ return the output
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
ṄµL;'∆²A;Rh
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%B9%84%C2%B5L%3B%27%E2%88%86%C2%B2A%3BRh&inputs=7&header=&footer=)
```
Ṅ # Integer partitions
µL; # Sorted by length
' ; # Filtered by...
A # All...
∆² # Are square
h # Get first (And therefore shortest)
R # Reversed
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
ɾ²Þ×'∑?=;tṘ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C9%BE%C2%B2%C3%9E%C3%97%27%E2%88%91%3F%3D%3Bt%E1%B9%98&inputs=3&header=&footer=)
[Answer]
# TI-Basic, 88 bytes
```
Input N
{1→A
While N≠sum(ʟA²
1+ʟA(1→ʟA(1
For(I,1,dim(ʟA
If N≤ʟA(I
Then
1→ʟA(I
If I<dim(ʟA
1+ʟA(I+1
Ans→ʟA(I+1
End
End
End
ʟA²
```
works with any number of panels (more than 4 if it was possible). It's basically an addition with a carry (up to N and starting at 1) because recursion is ~~impossible~~ a real pain in TI-Basic (all variables are global)
It is quite slow, it could be optimized for speed by setting the limit to `√N` instead of `N` and a condition such as `ʟA(I+1)≤ʟA(I)`
[Answer]
# TI-Basic, ~~80~~ 83 bytes
```
Input N
For(I,0,N
For(J,0,N
For(K,0,N
For(L,1,N
If I²+J²+K²+L²=N and not(Ans(1
{L,K,J,I}²→S
End
End
End
End
sum(not(not(Ans→dim(ʟS
ʟS
```
Output is stored in `Ans` and displayed.
---
Faster but longer solution:
### ~~100~~ 103 bytes
```
Input N
√(N
For(I,0,Ans
For(J,0,Ans
For(K,0,Ans
For(L,1,Ans
If I²+J²+K²+L²=N:Then
{L,K,J,I}²→S
√(N→I
Ans→J
Ans→K
Ans→L
End
End
End
End
End
sum(not(not(ʟS→dim(ʟS
ʟS
```
[Answer]
# Python 3, 104 bytes:
Pure Python, no imports, brute force:
```
def f(n,c):yield from([x for k in range(1,n+1)for x in f(n-k*k,c+[k*k])],[c])[n==0]
min(f(13,[]),key=len)
```
] |
[Question]
[
The [fast growing hierarchy](https://en.wikipedia.org/wiki/Fast-growing_hierarchy) is a way of categorizing how fast functions are growing,
defined the following way (for finite indices):
* \$ f\_0(n)=n+1 \$
* \$ f\_k(n)=f\_{k-1}^n(n)\$ with \$f^n\$ meaning repeated application of the function f
## Examples
```
f0(5) = 6
f1(3) = f0(f0(f0(3))) = 3+1+1+1= 6
f2(4) = f1(f1(f1(f1(4)))) = 2*(2*(2*(2*4))) = 2‚Å¥*4 = 64
f2(5) = f1(f1(f1(f1(f1(5))))) = ... = 2⁵*5 = 160
f2(50) = f1⁵⁰(50) = ... = 2⁵⁰*50 = 56294995342131200
f3(2) = f2(f2(2)) = f2(f2(2^2*2))) = f2(8) = 2^8*8 = 2048
f3(3) = f2(f2(f2(3))) = f2(f2(2³*3)) = f2(2²⁴*24)=2⁴⁰²⁶⁵³¹⁸⁴*402653184 = ...
f4(1) = f3(1) = f2(1) = f1(1) = f0(1) = 2
f4(2) = f3(f3(2)) = f3(2048) = f2²⁰⁴⁸(2048) = ...
...
```
shortcuts:
```
f1(n) = f0(...f0(n))) = n+n*1 = 2*n
f2(n) = f1(... f1(n)...) = 2^n * n
```
Your goal is to write a program of function that given two positive integers \$k\$ and \$n\$ outputs \$f\_k(n)\$
## Rules
* Given unlimited time and using unbounded integer types the *algorithm* you program is using should compute the correct result of f\_k(n) for arbitrarily large `n` and `k` (even if the program will not finish in the lifetime of the universe)
* Your *program* only has to work for values that fit in a signed 32-bit integer
* Supporting the case \$k=0\$ is optional
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest solution in bytes wins
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 16 bytes
```
{{y x/y}x}/[;1+]
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qurlSo0K+srajVj7Y21I7l4kqLNoiNNo0F0oax0cYg2ig22gRKg8WNY4FMIG0SC1QCALztE+o=)
A curried function that takes `k` and then `n`. Call it as `f[k][n]`. (`f[k;n]` doesn't work.)
The trick here is to iterate directly on the function `f`. The formula \$f\_k(n) = f\_{k-1}^{n}(n)\$ can be seen as a transformation on a function \$f\_{k-1}\$ to \$f\_k\$. Given a function `x` (\$f\_{k-1}\$) and input value `y` (\$n\$), \$f\_k(n)\$ can be written as `y x/y`, and `{y x/y}x` is the partially applied function \$f\_k\$ that we want. We can iterate this transformation `k` times to \$f\_0\$ (`1+`) to get \$f\_k\$. However, `k{y x/y}/(1+)` invokes a wrong overload of `/` because `{y x/y}` itself is syntactically dyadic. So I put it in `{...x}` to make it monadic.
[Answer]
# x86 32-bit machine code, 18 bytes
```
4A 78 0C 51 89 C1 E8 F5 FF FF FF E2 F9 59 48 40 42 C3
```
[Try it online!](https://tio.run/##jZJNb9swDIbP0q9gMwSQZmfIkh5aO94OO@@y04BlCBRZjpnZciDbmfP11@tR7leGXqqDSEp8H5KC9GSjdd@rugQBP0aCZxFLjQaTdpxtazhytmvrHIymuKz23gnBqI67iGlVFJBxVlTVDhxlkhkSBwLlHCOG9tF9dDzVmYbLkYz5aqWaxuG6bcxqJYQzm51ypZhJKQFtA5nw@59wCKyMYV9hCkbIuP9AtKJNDSzqJsXqU/6F@6RSoRWSn6gVR3EmRnD2lVhWORhoW0jgc0zmJoF7skEgOVytF934FkchbL34@WxpJ8Hknev/qkhVpzGZRQJzsr4qoy6v0GM8Uz30MuYlBZbYkIykpIGvMIMI7vzt21mIOqQ/zcNeuU9jZGIbovTsy/U4S/td6RytAV2lJhp69uDOtxvCgcK0gtMrbDr7SbRDIkRra9xYk4LOlfsoM/mrC4LfMr7A3xwLA@LgX3jafZtfvyCIMcL60JhaLi2ROn9J/6F1lt6HX/oHnRVqU/eTcj6jjb5lQkpT/AM "C (gcc) – Try It Online")
Following the `regparm` calling convention, this takes *n* in EAX and *k* in EDX, and returns a number in EAX. For easier recursion, this function also preserves the values of EDX and ECX (ending with them unchanged).
In assembly:
```
f: dec edx # Subtract 1 from k in EDX.
js z # Jump if the result is negative (k was 0).
push ecx # Save the value of ECX onto the stack.
mov ecx, eax # Set ECX to n. This will be the iteration count.
r: call f # Recursive call, to apply fₖ₋₁ to EAX.
loop r # Subtract 1 from ECX and jump back to repeat if it's nonzero.
pop ecx # Restore the value of ECX from the stack.
dec eax # Subtract 1 from EAX, cancelling out the next instruction.
z: inc eax # Add 1 to n in EAX.
inc edx # Add 1 to EDX, restoring the value of k.
ret # Return.
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 19 bytes
```
{y$[x;o@x-1;]/y+~x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6quVImusM53qNA1tI7Vr9Suq6jl4kqLNrA2jQVShtbGIMrI2gRCAQX1FcAMA5CAsbURRMAYos7E2hDCNwFKAACwYxhf)
```
{y$[x;o@x-1;]/y+~x} / function with arguments x:k, y:n
$[x;o@x-1;] / if x>0, f_(k-1), else identity function
y / / Apply the selected function n times to:
y+~x / n + [0=k]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
F²⊞υNW⊖Lυ«≔⊟υθ≔⊟υη¿η«Fθ⊞υ⊖η⊞υθ»⊞υ⊕θ»Iυ
```
[Try it online!](https://tio.run/##XY67CsIwFIbn5CnOeAJ1KTh1El0Ekb5CradNIE3bXHSQPntMCtLi@t@@v5WNbcdGx9iNFrAUUAcnMRRwNVPw9zA8yKIQFX9LpQnwQq2lgYynJ97I9D6FhRDw4ezknOoN1uOUpALmVPrXZNZUByjXBluh8wbdr8tMZexnrXMLZ6Qd7U5u@TnnF15bZTyeG@fzsSrGEo7x8NJf "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υN
```
Push `k` and `n` to the predefined empty list.
```
W⊖Lυ«
```
Repeat until the list only contains one value.
```
≔⊟υθ≔⊟υη
```
Extract `k` and `n` for the deepest recursion depth.
```
¿η«
```
If `k` is non-zero, then...
```
Fθ⊞υ⊖η
```
... push `n` copies of `k-1`, representing the recursive calls...
```
⊞υθ
```
... and push `k` back as the argument.
```
»⊞υ⊕θ
```
Otherwise just push `n` incremented as the result of `f0(n)`.
```
»Iυ
```
Output the final value.
52 bytes for a version optimised for `k<3`:
```
F²⊞υNW⊖Lυ«≔⊟υθ≔⊟υη≡η⁰⊞υ⊕θ¹⊞υ⊗θ²⊞υ×X²θθ«Fθ⊞υ⊖η⊞υθ»»Iυ
```
[Try it online!](https://tio.run/##XY/NCsIwEITP7VPsMYEKWvBiT6IXQaQHXyDGbRNIU5sfexCfPSYVqQq7l5lZZj8umOE9UyE0vQFSUqi9FcQXcNA3706@u6AhlFb5KKRCIHvkBjvUDq/kiLp1MUwphUeeba2VrSZ1f4tSAUM8@tdE0uwoHRdAxHTFmUVYbr5654IhFb8Tqzmx7/1F/brl7J5lhzYWjvHvMn2RNgWv2DCv3CaVZhPtMNN@Y4kpnn2sieOZ5pnXRmpHdsy6RF2FUMJ6GRZ39QI "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 30 bytes
```
Nest[fÔí°Nest[f,#,#]&,#+1&,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCQ67f2khRCGjrKOcqyajrK2oRqI8T@gKDOvJLpaWblW1y4tWjnWQdkoVs3BwaGaq9pAx7RWh6vaUMcYRBnpmEAosKCxjhGIMtExrOWq/Q8A "Wolfram Language (Mathematica) – Try It Online")
Input `[k][n]`.
[Answer]
# [J](https://www.jsoftware.com), 24 bytes
```
>:@]`(<:@[$:^:]])@.(0<[)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrscPOyiE2QcPGyiFaxSrOKjZW00FPw8AmWhMifTNIkys1OSNfwUzBFqg1TcEUyjUB8o2AfBMI39DMACoAVWBkYGIBFDEGihhBRYBcEyDXEGLyggUQGgA)
*-4 thanks to Bubbler for this straightforward approach*
# [J](https://www.jsoftware.com), ~~28~~ 27 bytes
```
>:@]`(]$:/@,~]#_1+[)@.(0<[)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsdvOyiE2QSNWxUrfQacuVjneUDta00FPw8AmWhOi4maQJldqcka-gpmCLVB3moIplGsC5BsB-SYQvqGZAVQAqsDIwMQCKGIMFDGCigC5JkCuIcTkBQsgNAA)
*-1 using thanks to Bubbler's `0<]` instead of `0=]` idea*
This approach conceives uses a reduction which expands its left argument in place recursively:
```
2 f 3
1 1 1 f 3
1 1 0 0 0 f 3
1 1 0 0 f 4
1 1 0 f 5
1 1 f 6
1 0 0 0 f 6
... etc ...
```
And this is what the above code does:
* `@.(0=[)` If the left arg is 0...
* `(1+])` Return 1. Otherwise...
* `]#_1+[` Repeat "left arg minus 1" as many times as the right arg...
* `]...,~` Prepend the right arg...
* `$:/@` And continue reducing the result using this fn.
[Answer]
# [J](https://www.jsoftware.com), 15 bytes
```
'>:'".@,'^:]'&,
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FNVUtFK8NYM0UrS3V1LiU99TQFWysFdQUdBQMFKyDW1VNwDvJxW1pakqZrsV7dzkpdSc9BRz3OKlZdTQciejNGkys1OSNfwUzBFqgjTUHdVB0qYAIUMQKJmEBFDM0MYEIwRUYGJhZAMWOQmBFMDChgAhIwVIfYsWABhAYA)
Takes `k` on the left as a number, and `n` on the right as a string.
Without `".@`, the function constructs the expression `>:^:]^:] ... ^:]n` as a string, where `^:]` is repeated `k` times.
`f^:]n` applies `f` `n` times to the initial value `n`. \$f\_0\$ is increment, which is `>:`. \$f\_1(n) = f\_0^n(n)\$ is `>:^:]n`. In general, \$f\_k(n) = f\_{k-1}^n(n)\$ can be expressed as `(f_{k-1})^:]n`, and expanded recursively down to `k=0`, we get the expression above.
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ẋ@⁾¹¡”‘;v
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//4bqLQOKBvsK5wqHigJ3igJg7dv///zL/NQ "Jelly – Try It Online")
The same strategy applied to Jelly. `‘` (increment) plus `¹¡` (repeat *argument* times) repeated `k` times, evaluated and applied to `n`.
[Answer]
# [R](https://www.r-project.org/), 50 bytes
```
f=function(k,n){if(k)for(i in 1:n)n=f(k-1,n);n+!k}
```
[Try it online!](https://tio.run/##JYo7CoNAEEB7TzFiM4MTcP00igdIlSY3CBkYlsyCWSvx7Ouq1YP33pKSzLLaJ2ow9Gy0qaAnCQsqqIEbjWzO6uFynKwu/Z4EGx6oEHTcnWi5v5FldbEhqCDq7/uHsEYIBu/nKy8dt@fZs6N0AA "R – Try It Online")
[Answer]
# Python 3, ~~96 79 70 69 63 61 59~~ 58 bytes
```
g=lambda k,n:-~n*(k<1)or eval(f"({'n:=g(k-1,n),'*n})")[-1]
```
It takes time to compute k=2, n=50, but it should be completed after some time...
While this answer is longer, I'm keeping it because it inspired the other two winning answers in Python:
>
> ~~70 67~~ 65 bytes if Python could handle huge nested parentheses ([this answer is allowed, but other golfs based on this are already present](https://codegolf.stackexchange.com/questions/264852/golf-the-fast-growing-hierarchy#comment578646_264852), with the other answers being [this one by xnor](https://codegolf.stackexchange.com/a/264860/110681), and [this other one by SUTerliakov](https://codegolf.stackexchange.com/a/264926/110681)):
>
> `f=lambda k,n:n+1if k>1else eval(f"{n*('f(%d,'%(k-1))}{n}{')'*n}")`
>
>
>
[Answer]
# [Haskell](https://www.haskell.org/), 31 bytes
```
0%n=n+1
k%n=iterate((k-1)%)n!!n
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/30A1zzZP25ArG0hnlqQWJZakamhk6xpqqmrmKSrm/c9NzMxTsFUoKMrMK1FQUTBSNf0PAA "Haskell – Try It Online")
Writing out the definition.
**34 bytes**
```
q((>>=)id.q)(+1)
q=((!!).).iterate
```
[Try it online!](https://tio.run/##BcFLCoAgEADQvacwSJghEgpajidpI6YlWfg7f9N7l223T4kD7VwAjCGMhy4I04KiEMAwoEYdu6@2ewaFFMRj4ytJ5hrfLke5qo0/F5I9G88u5x8 "Haskell – Try It Online")
A pointfree mess.
[Answer]
# JavaScript (ES6), 39 bytes
A shorter version with a single recursive function suggested by [@att](https://codegolf.stackexchange.com/users/81203/att).
```
f=(k,n,i=n)=>k*i?f(k-1,f(k,n,i-1)):n+!k
```
[Try it online!](https://tio.run/##ZY5RCsIwEET/PcX6t4lpm03TUoToTQRRI7WSior/3kkv5EVq2kRBSwZmM8s89rC@rS@bc326Jq7d7rrOGmyEE7VxzCwaXi8tNgkJG9KEGJu72bTpNq27tMddemz3aFEKKBiDLINy8rshAXnYWIlB/s/AQD6j/plRRQnQsUL4lY@GmuL4kY7J6/7g2g@lHpOKMcmrYJGWpmkgPHnhByrlHyIXoCJCoZcaanFeKa7YJ6iGW1YVr3qXuvojaQEUSTlSLAWn6DK46t4 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 42 bytes
```
f=(k,n)=>k--?(g=i=>f(k,--i?g(i):n))(n):n+1
```
[Try it online!](https://tio.run/##ZY5RCsIwEET/PcV@7sakTdK0FCH1JoKoLbWSior/3kkv5EVqbKKgJQOzmWUeu19f1@fNqT1ehOu3u2GoLXbcka06IZbY2NZWtU@EaJcNtrRwROi8zdWw6d25P@ySQ99gjZJDTgRpCsXsd6M4ZGFTSwzyfwIL2Vy9n51UNAcTKwq/8tFY0ww/MjF53u7M@KEwU1I@JXnlFGlJkgTCg@V@UIX8Q2QcdERo9NJjLc4rzTR9gnK8ZVWy8u3SlH8kw0FFUoYqloKr6DK4Hl4 "JavaScript (Node.js) – Try It Online")
### Commented
```
f = (k, n) => // f is a recursive function taking (k, n)
k-- ? // if k is not 0 (decrement it afterwards):
( g = i => // g is another recursive function taking a counter i
f( // do a recursive call to f:
k, // pass the updated value of k
--i ? // decrement i, if it's not 0:
g(i) // use the result of a recursive call to g for n
: // else:
n // final call: use n
) // end of recursive call to f
)(n) // initial call to g with i = n
: // else (k = 0):
n + 1 // f0(n) = n + 1
```
[Answer]
# [Python](https://docs.python.org/3.8/), 50 bytes
```
f=lambda k,n:k and eval(n*'f(k-1,'+'n'+')'*n)or-~n
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P802JzE3KSVRIVsnzypbITEvRSG1LDFHI09LPU0jW9dQR11bPQ@INdW18jTzi3Tr8v4XFGXmlWikaRjpmGpq/gcA "Python 3.8 (pre-release) – Try It Online")
Based on the [second solution of UndoneStudios](https://codegolf.stackexchange.com/a/264855/20260). In practice gives a `MemoryError` for larger values from trying to generate huge strings of Python code.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
x@‚Äô√ü∆í‚Å∏ ã‚Äò‚Åπ?
```
A dyadic Link that accepts \$n\$ on the left and \$k\$ on the right and yields \$f\_k(n)\$.
**[Try it online!](https://tio.run/##ASIA3f9qZWxsef//eEDigJnDn8aS4oG4yovigJjigbk/////Nf8y "Jelly – Try It Online")**
### How?
```
x@‚Äô√ü∆í‚Å∏ ã‚Äò‚Åπ? - Link: integer, n; integer, k
? - if...
‚Åπ - ...condition: chain's right argument, k -> k > 0?
ã - ...then: last four links as a dyad - g(n, k):
’ - decrement {k} -> k-1
@ - with swapped arguments:
x - {k-1} repeated {n} times -> [k-1,k-1,...,k-1]
⁸ - chain's left argument, n
ƒ - reduce {[n, k-1,k-1,...,k-1]} by:
ß - {current value} this Link {next value}
‘ - ...else: increment {n} -> n+1
```
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 41 bytes
```
f(k,n,i=n)=if(k*i,f(k-1,f(k,n,i-1)),n+!k)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNzXTNLJ18nQybfM0bTOBbK1MHSCpa6gDFdc11NTUydNWzNaEakhKLCjIqdRIVNC1Uygoyswr0UiMNoxVUNJRUFJIjDYCskAySgppYHEdsBjQCIXoaAMdUyA_2lDHGEQZ6ZhAKLCgsY4RiDLRMYyNhdoEcyIA)
A port of [@Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/264858/9288).
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 49 bytes
```
f(k,n,i)=if(i,f(k,f(k,n,i-1)),k,f(k-1,n,n-1),n+1)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY49CgIxEEavMqRK8AvsZFew0YuEILGIBCWEZS08i802smfyNiYxVt-8N8zPa8t-judrXtf3Ywn68OEgb0iI6hiDjKjUjWal0Ehz4VQYaceqD158zven9KRPlOeYFuktOxIgQd6aUtWOoNA8misLydoB-8KWMdYwmH7R5AhTYwI71y_9X_0C)
[Answer]
# [Python](https://docs.python.org/3.11/), 53 bytes
```
g=lambda k,n:k and[n:=g(k-1,n)for _ in[0]*n][-1]or-~n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3TdNtcxJzk1ISFbJ18qyyFRLzUqLzrGzTNbJ1DXXyNNPyixTiFTLzog1itfJio3UNY_OLdOvyoJrLE4uLU4tKFNI1DHRMNRVsbRXMuOBChjrG6EJGOiYQIRNkMYhOQzMDhKCxjhFY0MjAxAIhaqJjCBGFWA_zAwA)
Does not support \$ n = 0 \$; supports \$ k = 0 \$.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 39 bytes
```
f=->k,n{k>0?n.times{n=f[k-1,n]}:n+=1;n}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y5bJ686287APk@vJDM3tbg6zzYtOlvXUCcvttYqT9vW0Dqv9n@BQlq0gY5pLBeIYahjDGEY6ZjAGEApZSjLACJmrGMEFTOGqTfRMYQKmQAl/wMA "Ruby – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 92 bytes
```
({}<>)(()){{}((){[()](<({}[()])<>(({})<>){({}[()]<(({}))>)}{}{}>)}{}){({}<>{})(<>)}{}([])}<>
```
[Try it online!](https://tio.run/##LYkxCoBADAS/Yrlb2Ah2IR85rjgLQRQL25C3xxhkixlmt2cc97xf44yAuSgB0swT1sAOyfwJRZGaoP1JKlDplivUJ5oCqYDWmSFimdYX "Brain-Flak – Try It Online")
Supports \$k=0\$ and \$n=0\$. Large outputs take an unreasonable amount of time to compute, since no shortcuts are taken for \$f\_1\$ or \$f\_2\$.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~51~~ ~~46~~ 43 bytes
```
f(k,n,i){for(i=n;k*i--;)n=f(k-1,n);k=n+!k;}
```
[Try it online!](https://tio.run/##NY7NDoIwEITvfYoVA2m1NfJ3qvVJvJCWSlNcDGA8EJ69FhIn2cPufDNZLZ5ah2Cp58gdW@wwUqdQ@pMTQjJU0RE5Rya9wvPByzUcHer@Y1q4TbNxw6W7E@JwhlfjkDJYCERtB88B5b59O9e3dNINWpqkBlLzwIRDFokMGSgFBdvBTe8xhiNnU0NTE90/vvVx2F4FZEySNVyhJjmUpIAqTk1KKEgF@Q8 "C (gcc) – Try It Online")
5 bytes shaved off thanks to the `n+!k` trick I saw others do, and 3 more thanks to c-- :)
] |
[Question]
[
Given n, k, and p, find the probability that a weighted coin with probability p of heads will flip heads at least k times in a row in n flips, correct to 3 decimal digits after decimal point (changed from 8 because I don't know how to estimate the accuracy of double computation for this (was using arbitrary precision floating points before)).
Edits:
Examples:
```
n, k, p -> Output
10, 3, 0.5 -> 0.5078125
100, 6, 0.6 -> 0.87262307
100, 9, 0.2 -> 0.00003779
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~40~~ ~~39~~ ~~18~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
**Brute-force approach:**
```
0Lα1ݲãʒγOà³@}èPO
```
Byte-count more than halved by porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/249352/52210), which uses a similar approach as [@DominicVanEssen's top R answer](https://codegolf.stackexchange.com/a/249333/52210), so make sure to upvote them as well!
Inputs in the order \$p,n,k\$.
Very slow, so use small \$n\$ in order to run it on TIO.
[Try it online.](https://tio.run/##yy9OTMpM/f/fwOfcRsPDcw9tOrz41KRzm/0PLzi02aH28IoAf6CcnimXoQGXMQA)
**Original mathematical ~~40~~ 39 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
÷L®s©>m²®¹*-D>®/$-*I+s®<cI®¹*m$-®<m)øPO
```
Inputs in the order \$k,n,p\$.
[Try it online.](https://tio.run/##yy9OTMpM/f//8HafQ@uKD620yz206dC6Qzu1dF3sDq3TV9HV8tQuPrTOJtkTLJqrogvk5Goe3hHg//@/GZehgQGXgZ4ZAA)
**General explanation of the larger original program:**
Even though the challenge description was just a single sentence, it lead me on a chase down the rabbit hole. After quite a long search, I came across this MathExchange answer: [Probability for the length of the longest run in *n* Bernoulli trials](https://math.stackexchange.com/questions/59738/probability-for-the-length-of-the-longest-run-in-n-bernoulli-trials), for which [the accepted answer](https://math.stackexchange.com/a/59749/368863) contains the generalized formula for this challenge, originally solved by *de Moivre* in 1738:
$$\mathbb{P}(\ell\_n \geq k)=\sum\_{j=1}^{\lfloor n/k\rfloor} (-1)^{j+1}\left(p+\left({n-jk+1\over j}\right)(1-p)\right){n-jk\choose j-1}p^{jk}(1-p)^{j-1}$$
Where \$\mathbb{P}(\ell\_n \geq k)\$ is the probability that a consecutive run of the same unfair coin result with a length \$\ell\_n\$ is at least \$k\$ flips. \$p\$, \$k\$, and \$n\$ are as given by the challenge description, with \$p\$ being a decimal probability (e.g. 0.70 for 70%), and \$k\$ and \$n\$ being integers.
**Code explanation:**
```
0L # Push pair [1,0]
α # Get the absolute difference with the first (implicit) input p:
# [1-p,p]
1Ý # Push pair [0,1]
²ã # Get the second input n'th cartesian product
# (creating all n-sized lists with 0s/1s)
ʒ # Filter this list by:
γ # Group the 0s/1s into consecutive adjacent items
O # Sum each group
à # Pop and push the maximum
³@ # Check if this largest group of 1s is >= the third input k
}è # After the filter: (0-based) index each 0/1 into pair [1-p,p]
P # Take the product of each inner list
O # Take the sum of all values
# (after which the result is output implicitly)
```
```
÷ # Integer divide the first two (implicit) inputs: n//k
L # Pop and push a list in the range [1,n//k] (its values are j)
® # Push -1
s # Swap so the list is at the top
© # Store it in variable `®` (without popping)
> # Increase each j in the list by 1
m # Pop both, and calculate -1**(j+1) for each
® # Push the list `®` containing j again
¹* # Multiply each j by the first input k
² - # Subtract each from the second input n
D # Duplicate this n-jk list, since we need it again later
> # Increase each by 1
®/ # Divide each by j
$ # Push 1 and the third input p
- # Subtract: 1-p
* # Multiply this to each (n-jk+1)/j
I+ # And add the third input p to each
s # Swap so the n-jk list is at the top again
® # Push list `®` containing j again
< # Decrease each j by 1
c # Calculate the binomial coefficients of n-jk and j-1
I # Push the third input p again
® # Push list `®` containing j again
¹* # Multiply each j by the first input k again
m # Pop both, and calculate p**(jk)
$ # Push 1 and the third input p again
- # Subtract again: 1-p
® # Push list `®` containing j again
< # Decrease each j by 1 again
m # Calculate (1-p)**(j-1)
) # Wrap these five lists on the stack into a list of lists
ø # Zip/transpose; swapping rows/columns
P # Get the product of each inner list
O # And finally sum everything together
# (which is output implicitly as result)
```
[Answer]
# [Python](https://www.python.org), 66 bytes (-1 @xnor)
```
f=lambda n,k,p:n>=k and(1-p*(n>k))*(1-f(n+~k,k,p))*p**k+f(n-1,k,p)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY9BDoIwEEX3nKJh1ZZiQCNRElh4AC9giEGggRSmTS0LY_AibtjonbyNFWH35mcy78_zrW6mljCOr95wf_c58KTNu0uZI2CCqRjSRKAcShz6imJIBSHUMsfgPcRvw86KUuHZxA-nYL40cC07xHsojJTtFTWdktqgVvfnIi_qyrGmhfFRQkUwJw6X-m9GDaBTGLANC1bbjFkMWGQ5mnlveZ3FDlK6AYO5e7cNJn8cDe5cYnnrCw)
Adapted from my [answer to a similar challenge](https://codegolf.stackexchange.com/a/248518/107561). Note that I add memoization in the footer. This in theory doesn't change the result but it greatly accelerates the recursion.
### How?
Uses the recurrence
\$f(n,k,p)=f(n-1,k,p)+p^k(1-p)(1-f(n-k-1,k,p))\$
(valid for *n*>*k*) which is obtained by accounting for words that have k consecutive heads somewhere in the first n-1 tosses, words that end in a tail followed by k heads and the overlap of these two groups.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 15 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ø.ṗṣ1ZṫɗƇ_⁵AP€S
```
A full program accepting `n`, `k`, and `p` that prints the result.
**[Try it online!](https://tio.run/##AS4A0f9qZWxsef//w5gu4bmX4bmjMVrhuavJl8aHX@KBtUFQ4oKsU////zEw/zP/MC42 "Jelly – Try It Online")** (`n=100` is too big for such an inefficient program.)
### How?
Creates all \$2^{n}\$ possible outcomes, filters them to those containing a run of at least \$k\$ heads and then sums the probability of each occurrence.
The probability of a given occurrence is the product of `p`'s and `(1-p)`s identified by heads and tails respectively. For example the chance of `[tails, tails, heads, heads, heads]` is the product of `[(1-p), (1-p), p, p, p]` i.e. \$p^3(1-p)^{2}\$.
```
Ø.ṗṣ1ZṫɗƇ_⁵AP€S - Main Link: integer n, integer k (p is accessed later)
Ø. - [0,1]
ṗ - ([0,1]) Cartesian power (n)
-> all length-n tosses with 0 as heads and 1 as tails
Ƈ - filter keep those for which:
ɗ - last three links as a dyad - f(Outcome, k):
ṣ1 - split at 1s -> runs of heads
Z - transpose
ṫ - tail from index k -> empty (falsey) if longest run < k
⁵ - third program argument, p
_ - subtract -> valid outcomes with heads: -p; tails: 1-p
A - absolute values -> valid outcomes with heads: p; tails 1-p
P€ - product of each -> valid outcome probabilities
S - sum -> total probability of any valid outcome
```
---
If we could take the probability of tails (\$1-p\$) instead of heads (\$p\$) 14 byes taking `1-p`, `n`, `k`:
```
C©Ƭṗṣ®ZṫɗƇ⁵P€S
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef//Q8KpxqzhuZfhuaPCrlrhuavJl8aH4oG1UOKCrFP///8uNP8xMP8z)
[Answer]
# [R](https://www.r-project.org/), ~~129~~ ~~122~~ 116 bytes
*Edit: -2 bytes thanks to pajonk (which led to -4 more...)*
```
function(n,k,p)sum(apply(which(array(T,rep(2,n)),T)-1,1,function(v,r=rle(v))prod(p*v+(1-p)*!v)*(max(r$l[!r$v])>=k)))
```
[Try it online!](https://tio.run/##lY9NboMwEIX3nGKiZjEDThQQpt3QU2RXtcgiIFsQ2xoSKKenQKWqaumimyfN3/ve8NQUulKXrjC2UAW7IZ/quy1vxlm0ohGeuvsVlfftiIM2pUbFrEY8C648JsISiTMdYhGLr7tecM5thT2RZ3dBH/YRxgdP4a6nEK/qHXnfvux437/Sc94Q0fQApVa2rMDVkMAaCYwFBXMkGMxNg7PtOI/q1vhu2VJQK8NQunkth9MxkcHPX@Z8iThKCoLv9nLTPvvbWb7JaNFsrU5p9vS4wcqE/M1K/89Ko0/iImsrTjZp6UKbPgA "R – Try It Online")
Exact solution: calculates the probability of every possible outcome of `n` coin flips, and sums those that contain at least `k` heads-in-a-row.
**How?**
```
function(n,k,p){
a=expand.grid(rep(list(1:0),n)) # a is a matrix of all possible outcomes of n flips
# with heads represented as 0, tails as 1
pvals=apply(a,1,function(v)prod(p*v+(1-p)*!v))
# pvals are the probabilities of each outcome
# by multiplying the probability of each single flip
itsarun=apply(a,1,function(v)max(rle(v)$l[!rle(v)$v])>=k)
# itsarun is TRUE if the longest run of 0s in each row is >=k
# (rle(v)$l = length of each run, rle(v)$v = value of each run)
return(sum(pvals*itsarun)) # return the sum of all the pvals for successful outcomes
}
```
---
# [R](https://www.r-project.org/), 98 bytes
```
function(n,k,p){while((T=T+1)<1e19)F=F+(max((r=rle(sample(1:0,n,T,c(1-p,p))))$l[!r$v])>=k);F/1e19}
```
[Try it online with a low-accuracy version](https://tio.run/##dY5BDoIwEEX3nGKMLtpQEYhFo9YlJ2BnlDQVQgO0pKhojGfHwsoYncVMJvP/f2P6Mi0yfm5TqVKeGt2xPr8qcZFaIUVK0uBnV8gqQyhhiRvgXZBRHLPYRTW/I2SYsbeW140dwcYniiREoGDeWKetWXWYmNntiPesxNt4Yd2vfgqi4EpkoHMIYcSDVMDB4qGTlwK0qh72lFeyaQcVh5xLA0JbGQPfC6nz/TcKSUg8ih3nM57@jI/@J9MTdYcejZu/jNarH6yI0IHVvwE "R – Try It Online")
Brute-force approach: performs `1e19` series of `n` flips, and counts the number of times we get `k` heads-in-a-row. With this number of repetitions, the answer has a very high chance of being accurate to 8 decimal places, but there is a low-but-finite chance that this won't be the case...
We need to do them one-after-the-other in a `while` loop (rather than the more idiomatic vectorized [R](https://www.r-project.org/) approach of building a matrix and checking the rows) since the number of iterations needed to obtain 8 decimal places of accuracy is too big to be contained in an [R](https://www.r-project.org/) matrix.
The test link substitutes `1e5` in place of `1e19`, for a lower-accuracy output without timing-out. Feel free to run the high-accuracy version on your own computer if you have the time to wait.
---
# [R](https://www.r-project.org/), 83 bytes
```
function(n,k,p,m=cbind(rbind(1-p,diag(k)*p),!k:0))Reduce(`%*%`,rep(list(m),n))[k+1]
```
[Try it online!](https://tio.run/##lc7BToQwEAbgO08xZrNJu4wbaChuTHgJr0bZWoo0ZadNYbPx6RHwYhQPXv6k08n/TZxc3RnVDLWlWtXR36qpvZIerSdG6DDgpdJvlhoW18zvAzZWvTPHD4HjnXvMOH8yzVUbdt4f9meMJrDeDiO7cCTOn12av0w70J0ibcC3IGAVwRIomEW42bEDT/3H/NX2NgzLloJW2Qjaz2sVZEchk5@nMoECj5Inyfd6uVlf/t0sX2W6ZLm@sqI8PWxYJcrfVvF/q0i/xCXWUS42tWLRpk8 "R – Try It Online")
Port of [dancxviii's Markov method](https://codegolf.stackexchange.com/a/249365/95126) - upvote that one - but sadly still longer than [pajonk's R answer](https://codegolf.stackexchange.com/a/249376/95126)...
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 23 bytes
```
2$ÞẊ'2€vLG›¹>;⁰⌐⁰"$İvΠ∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCIyJMOe4bqKJzLigqx2TEfigLrCuT474oGw4oyQ4oGwXCIkxLB2zqDiiJEiLCIiLCIxMFxuM1xuMC42Il0=)
Port of Jelly. Really slow.
Previous answer (much faster):
# [Vyxal](https://github.com/Vyxal/Vyxal) `ḋ`, 41 bytes
```
ḭɾ:£›u$e¹¥□h*-:›¥/⁰⌐*⁰+$¥‹ƈ?¥?*e⁰⌐¥‹eWƒ*∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyLhuIsiLCIiLCLhuK3JvjrCo+KAunUkZcK5wqXilqFoKi064oC6wqUv4oGw4oyQKuKBsCskwqXigLnGiD/CpT8qZeKBsOKMkMKl4oC5ZVfGkiriiJEiLCIiLCI2XG4xMDBcbjAuNiJd)
Port of 05AB1E.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 53 bytes
```
k->p->g(n)=if(n>=k,p^k*(1-p*(n>k))*(1-g(n---k))+g(n))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMHiNAXbpaUlaboWN02zde0KdO3SNfI0bTPTNPLsbLN1CuKytTQMdQu0gNxsTU0QGyivq6sL5GiDVGpCNG8pKMrMK9FI0zDW1DDQM9XUMDSASS1YAKEB)
A port of [loopy walt's Python answer](https://codegolf.stackexchange.com/a/249360/9288). Takes input in the the form `(k)(p)(n)`
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 56 bytes
```
f(n,k,p)=Pol((1-y=p*x)/(t=1-x)/(t/y^k+x-y)+O(x^n*x))\x^n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNy3SNPJ0snUKNG0D8nM0NAx1K20LtCo09TVKbA11wbR-ZVy2doVupaa2v0ZFXB5QUjMGSEP1hyQWFORUaiQq6NopFBRl5pUAmUogjpJCcmJOjkaajkKipqaOQnS0oYGOgrGOgoGeaSyQa2gA5JqBuGZwriWIaxQbqwkxG-ZGAA)
The generation function of the sequence (for given \$p, k\$) is \$\frac{p^k\ x^k\ (1-p\ x)}{(1-x)(1-x+(1-p)\ p^k\ x^{k+1})}\$.
---
This generation function can be derived from loopy walt's recurrence formula:
\$f(n,k,p)=f(n-1,k,p)+p^k(1-p)(1-f(n-k-1,k,p))\$.
This recurrence formula is valid when \$n>k\$. In addition,
when \$n=k\$, we have \$f(n,k,p)=p^k\$ when \$n=k\$, and \$f(n,k,p)=0\$ when \$n<k\$.
Let \$F(k,p)\$ be the generation function (for given \$p, k\$), we have
\$\begin{align}
F(k,p) &= \sum\_{n=0}^{\infty}f(n,k,p)\ x^n \\
&= p^k\ x^k+\sum\_{n=k+1}^{\infty}f(n,k,p)\ x^n \\
&= p^k\ x^k+\sum\_{n=k+1}^{\infty}(f(n-1,k,p)+p^k(1-p)(1-f(n-k-1,k,p)))\ x^n \\
&= p^k\ x^k+\sum\_{n=k+1}^{\infty}f(n-1,k,p)\ x^n+p^k(1-p)\sum\_{n=k+1}^{\infty}(x^n-f(n-k-1,k,p)x^n) \\
&= p^k\ x^k+x\sum\_{n=0}^{\infty}f(n,k,p)\ x^n+p^k(1-p)\sum\_{n=0}^{\infty}(x^{n+k+1}-f(n,k,p)x^{n+k+1}) \\
&= p^k\ x^k+x\ F(k,p)+p^k(1-p)(\frac{x^{k+1}}{1-x}-x^{k+1}F(k,p))
\end{align}\$.
Solving this equation, we have \$F(k,p)=\frac{p^k\ x^k(1-p\ x)}{(1-x)(1-x+(1-p)\ p^k\ x^{k+1})}\$.
[Answer]
# JavaScript (ES7), 106 bytes
Quickly computes the probability, using the formula [found by Kevin Cruijssen](https://codegolf.stackexchange.com/a/249334/58563).
```
(n,k,p,q=1-p)=>(g=s=>(x=n-(y=j*k))<0?0:s*(p-~x/j*q)*(h=k=>--k?h(k)*(x-k+1)/k:p**y*q**~-j++)(j)+g(-s))(j=1)
```
[Try it online!](https://tio.run/##bcnLDoIwEIXhvU/BcmbagVYjicTBZzFe0JZAscbAxlevdWni5uQ/@dzxdYynxz08eRjPl3SVBIP2OuhJLAeUFjqJeWcZGBZx5BH35mCaSBD4PVeOJiS4iZeW2R9u4POd2SuLlW8C0UIT0ZudUggOVQccMZdYTKdxiGN/KfuxgysU1uhiowtTbhFXv2ZNtvpr9X/bfW2NmD4 "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES12), 58 bytes
Using [loopy walt's recursive formula](https://codegolf.stackexchange.com/a/249360/58563) is much shorter and much slower. This version uses a cache to speed it up (-7 bytes without the cache).
Expects `(k)(p)(n)`.
```
k=>p=>g=n=>g[n]||=n>=k&&p**k*(1-p*(n>k))*(1-g(--n-k))+g(n)
// \_____/
// cache
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kLz8ldcGiNNulpSVpuhY3rbJt7Qps7dJt84BEdF5sTY1tnp1ttppagZZWtpaGoW6BlkaeXbamJoidrqGrm6cL5Gina-RpQk0ISs7PK87PSdXLyU_XSNMw1tQw0DPV1DA00NTkQpUyA0mZgaQw5SxBckZQOYjJCxZAaAA)
[Answer]
# PARI-GP, 75 bytes
[Port of below solution](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN73TNPJ0snUKNG01chNLijIrNLK1tYECiTpJOhqJuoa2tkmaWgXaGok2RppaGkk22UDSULdAEyiinWRrm62drakZl6cZna1jGAsxcl9BUWZeiUaahqEBDOgYmhroGOhZmJtqakIUwewHAA) (can run n ~ 1000000000, k ~ 150)
```
f(n,k,p)=(matrix(k++,k,a,b,(a-1==b)*p+(a<2)*(b<k)*(1-p)+(a+b==k+k))^n)[k,1]
```
# Python (Numpy), 104 bytes
Noone has the markov method yet:
The states are the number of consecutive heads starting at state 0, with the final state as state k. State i (i < k) goes to state i+1 with probability p and state 0 with probability 1-p. State k always goes to state k. The matrix is:
\$
\begin{bmatrix}
1 - p & 1 - p & 1 - p & \dots & 1 - p & 0 \\
p & 0 & 0 & \dots & 0 & 0 \\
0 & p & 0 & \dots & 0 & 0 \\
\dots & \dots & \dots & \dots & \dots & \dots \\
\dots & \dots & \dots & \dots & \dots & \dots \\
0 & 0 & 0 & \dots & p & 1 \\
\end{bmatrix}
\$
Taking this matrix to the nth power and multiplying it by the vector \$\left[1, 0, 0, \dots, 0 \right]^T \$ gives the answer.
This [solution](https://ato.pxeger.com/run?1=RY1NCsIwEIXX5hRZJvaHBARFyN47lCBd9Ce0kwwxRetV3HSjd-ptTLXQ4Q3fvPcW8_rgGFpnp_lSewfUDoAjNYDOB7onW5b3xpZ9s1XEUkWliEO6eB0EwQiRH99DqLPT3IJ6Vt7dGOsSmcblnNTOU0ONpb60TcU6fiY7KIQujFYyw8WYRP4sEig6HaUkQW9sYFAGbx5XdPfKM0gtX3qh-f_ftGLlFw) is not an clean mathematical sum but it is much more computationally efficient then the sum.
```
m=zeros((k+1,k+1))
for i in range(k):
m[0][i]=1-p
m[i+1][i]=p
m[k][k]=1
print(matrix_power(m,n)[k][0])
```
[Answer]
# Desmos, 80 bytes
```
P(p,k,n)=∑_{j=1}^{n/k}-(-1)^j(p+(n-jk+1)(1-p)/j)nCr(n-jk,j-1)p^{jk}(1-p)^{j-1}
```
[Try it on Desmos](https://www.desmos.com/calculator/on5h94g72s) or [prettified](https://www.desmos.com/calculator/pgfnarlcg3).
Thanks to Kevin Cruijssen for finding this formula.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 133 bytes
```
[| n k p | n k /i [1,b] [| j | -1 j 1 + ^ n j k * - :> z z 1 + j
/ 1 p - * p + z j 1 - nCk p j k * ^ * 1 p - j 1 - ^ * * * ] map Σ ]
```
[Try it online!](https://tio.run/##PY/BTsMwDIbvfYr/vNGuZWISQ@LCAXHhgjhVnZSFdKTtnJCkBxh7Gt6HVypOMyErdv7vty25FTIYN72@PD0/btErR2rAYKQYPI4ivM@paEeSQRtKrJDmuNckeFDLC3KCDuryH0lL86bg1ceoSDK2ToXwaZ2mgLssO@GEqsQaZXGD8yxKbFht/tUtq2tW56n@BqGHRaorjbq62jdg3jHLKy4Vltix3XHDAjm29/jiiLjLVlwtwwXnJdPYnoMe4s40sOOXepIXdYyG77H4/UEz1Wi182HNjI@xxqvZ80HIvpj@AA "Factor – Try It Online")
Translation of the formula given in Kevin Cruijssen's [05AB1E answer](https://codegolf.stackexchange.com/a/249334/97916).
[Answer]
# [R](https://www.r-project.org/), 70 bytes
```
`[`=function(k,n,p)`if`(n<k,0,(1-p*(n>k))*(1-k[n-k-1,p])*p^k+k[n-1,p])
```
[Try it online!](https://tio.run/##lY/BisIwEIbvfYqBvSTtVNqSRA/WFxFtQ9fQEJmEqohPX5suC6Ldw16G@ecf/m9mGF3Tn/T3pbHU6Gbw93ps921tbtRdrSfmkDDw1pqW0dZhgazMQ8po5zhPp97tKXd5ieHA03B0WdSzGr@g6zV1J/AGKpghYAk0TBC422sPns6PyTJnGy5xS4PRdoDOT2s1FKtKJu/XsQorXEmeJK/xcjFe/Z0sjzKLVc2qEGqzXmBJVJ8s8X@WyH6Iscyjcukz8Uv7cBSK6IxP "R – Try It Online")
Port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/249360/55372).
For different approaches in [R](https://www.r-project.org/) see [@Dominic van Essen's answer](https://codegolf.stackexchange.com/a/249333/55372).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 35 bytes
```
NθNηNζIΣEΦEX²θ⍘ι²№ι×1η×XζΣιX⁻¹ζ⁻θΣι
```
[Try it online!](https://tio.run/##XYzLCsIwEEX3@YrQ1QRGaSuuurNQcFEp1B@IpdhA01cShf58nBAQcVZzztw73SC3bpaj99dpcfbm9KPfYBUF@@Xhj3fiZlOThVIaC63TUMsFKjVauoa1md@05chXgfwiTd9ayj9BIc8FqXJ21Ca6K90bSLIE@SDCJYrY35GH3yr4aGo1OQMZ8p1UhPUbilN4n6XsxNLj2R9e4wc "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Brute force approach.
```
NθNηNζ
```
Input `n`, `k` and `p`.
```
EX²θ⍘ι²
```
Get all of the binary numbers up to `2ⁿ`.
```
Φ...№ι×1η
```
Keep only those with `k` consecutive heads, I mean `1`s.
```
E...×XζΣιX⁻¹ζ⁻θΣι
```
Compute their probabilities, which is `pⁱ(1-p)ⁿ⁻ⁱ`, where `i` is the number of `1`s in each relevant row.
```
IΣ...
```
Output the grand total.
A 40-byte port of @dancxviii's approach is much more efficient:
```
Nθ≔E⊕N¬ιηFN«≔⊟ηζ≔⁺⟦×Ση⁻¹θ⟧×ηθη⊞η⁺ζ⊟η»I⊟η
```
[Try it online!](https://tio.run/##XY09D4IwEIZn@is6XhM0sLA4GScGCIluxqFitU1ogX44YPzttRRDjNPdPe/HtZzqtqed96UanK2dvDINI9mhvTHioaCiA5Sq1UwyZdkNfm2EpLjuLYh54SFz7zX@c@AXSr5VTT8AD84pOFfWOQPnk5DMwNHJqFdCBZineCTkkuJF5PFc3iSNM3wmMT2FGZtJkN6o0UJZOFBjYcXeZ9sCFSjPMr95dh8 "Charcoal – Try It Online") Link is to verbose version of code. Takes inputs in the order `p`, `k`, `n`. Expects `k>1` (+1 byte to support `k=1`). Explanation:
```
Nθ
```
Input `p`.
```
≔E⊕N¬ιη
```
Create an array of `1` `1` and `k` `0`s.
```
FN«
```
Repeat `n` times.
```
≔⊟ηζ
```
Remove the last entry of the array.
```
≔⁺⟦×Ση⁻¹θ⟧×ηθη
```
Multiply the array by `p`, then prefix the sum of the array multiplied by `1-p`.
```
⊞η⁺ζ⊟η
```
Add the previous last entry to the current last entry.
```
»I⊟η
```
Output the last entry in the array.
I had been planning on working out how to solve the problem using dynamic programming but I'm pretty sure it would have resulted in the same algorithm.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~30~~ ~~19~~ 17 bytes
```
ṁoΠm≠²fö≥⁰▲mΣgπḋ2
```
[Try it online!](https://tio.run/##ATIAzf9odXNr///huYFvzqBt4omgwrJmw7biiaXigbDilrJtzqNnz4DhuIsy////MS8y/zX/Ng "Husk – Try It Online")
Port of [my R answer](https://codegolf.stackexchange.com/a/249333/95126).
Input is arg1=p, arg2=k, arg3=n.
```
πḋ2 # cartesian arg-3-th power of binary digits of 2
# so: all possible combinations of n heads/tails;
fö # now consider only those with runs: filter by
▲ # the maximum of
mΣg # the sums of each group of identical elements
≥⁰ # is greater than or equal to arg-2;
# now convert the 1s & 0s to probabilities:
mo -² # subtract the probability of heads from each
a # and get the absolute values
# so 1s become (1-p) and 0s become p;
ṁo # finally map across each group & sum the result
Π # product of the probabilities
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 59 bytes
```
kpIf[#>=k,(1-Boole[#>k]p)(1-#0[#-k-1])p^k+#0[#-1],0]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7P/v9pIUFQOyZFq1sZ5uto2Go65Sfn5MK5GXHFmgCucoG0cq62bqGsZoFcdnaYJ5hrI5BrNr/gKLMvBIFB4W0aOPYaAM909hoQ4PY/wA "Wolfram Language (Mathematica) – Try It Online")
Port of Python. Takes `f(k)(p)(n)`.
[Answer]
# [J](http://jsoftware.com/), 49 bytes
```
1 :'0{_1{[:+/ .*^:(u-1)~(1,~]#0:),.~(*=@i.),~1-['
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRWs1A2q4w2ro6209RX0tOKsNEp1DTXrNAx16mKVDaw0dfTqNLRsHTL1NHXqDHWj1f9rcqUmZ@QrGOiZKmgYGiikaSoYw0TMQCJgITOYkBFcyPI/AA "J – Try It Online")
Almost identical to dancxviii's Markov chain approach.
] |
[Question]
[
Given an input string and a wrapping string, find the location of the first input string char in the wrapping string and replace it with the wrapping string char 1 step to the right of that, find the second char in the wrapping string and replace it with the char 2 steps to the right, find the third and replace it with the char 3 steps to the right, and so on. If there are not enough chars in the wrapping string, wrap around.
The wrapping string does not have duplicates and the input string will always be made of chars in the wrapping string.
# Reference implementation
```
s, wrap = input(), input()
n = 1
res = ""
for char in s:
res += wrap[(wrap.index(char) + n) % len(wrap)]
n += 1
print(res)
```
# Test Cases
```
abc abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ => bdf
xyz abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ => yAC
ZZZ abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ => abc
<empty string> <empty string> => <empty string>
abcdefg abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ => bdfhjln
123 0123456789 => 246
121212 12 => 222222
```
# Scoring
This is code golf, so the shortest answer wins!
[Answer]
# [J](http://jsoftware.com/), 14 bytes
```
[{~#@[|i.+#\@]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o6vrlB2iazL1tJVjHGL/a3KlJmfkK6gnpaSpK@gCNSQmJaekpqVnZGZl5@Tm5RcUFhWXlJaVV1RWOTo5u7i6uXt4enn7@Pr5BwQGBYeEhoVHREapK6SBNapDDat0dKbQMKAKmGEgcykzLCoqSh3hzYysnDzKvQrSCDMUYhpYBiZkZGIGETUwNDI2MTUzt7AEywN5cCVgAFFlaASVBUH1/wA "J – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 15 bytes
```
(b(b@?B)+U_MEa)
```
Takes the two strings as command-line arguments. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhbrNZI0khzsnTS1Q-N9XRM1IaJQyZtO0UqRkZEpqWnpSjpKiUnJIFZGZlZ2Tm5efkFhUXFJaVl5RWWVo5Ozi6ubu4enl7ePr59_QGBQcEhoWHhEZJRSLNQoAA)
### Explanation
```
(b(b@?B)+U_MEa)
a First command-line arg
ME Enumerate and map this function to each index, character pair:
b Second command-line arg
@?B Find index of character
( )+ To that, add
U_ One plus the index from map-enumerate
(b ) Use each of the resulting numbers to index into 2nd cmdline arg
Autoprint, joined together (implicit)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Thanks to @ovs for suggesting looking at swapping the argument order and hence saving a byte!
```
J+i@€ị
```
A dyadic Link that accepts the instruction on the left and the wrapping characters on the right and yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8/99LO9PhUdOah7u7////rx4VFeUSlZaarv5fPTEpOSU1LT0jMys7Jzcvv6CwqLiktKy8orLK0cnZxdXN3cPTy9vH188/IDAoOCQ0LDwiMkodAA "Jelly – Try It Online")**
### How?
```
J+i@€ị - Link: instruction, I; wrapping characters W
J - range of length of I -> [1,2,3,...,length(I)]
€ - for each c in I:
@ - with swapped arguments - f(W, c):
i - first index of c in W
+ - add together -> [index(i1 in W)+1,index(i2 in W)+2,...]
ị - index into W (modular)
```
[Answer]
# [R](https://www.r-project.org), ~~41~~ 40 bytes
```
\(s,w)rep(w,l<-sum(s|1))[match(s,w)+1:l]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3NWI0inXKNYtSCzTKdXJsdItLczWKaww1NaNzE0uSM8CS2oZWObEQ9beYgjLzSkLyQ0vSLDTSNIBiFiH5nnklGkqJSclKmjqoAimpaekZmVnZObl5-QWFRcUlpWXlFZVVjk7OLq5u7h6eXt4-vn7-AYFBwSGhYeERkVFKmpqaygq2dgpJKWlcOCwCGkBFiyodnXFZFBUVRUWLgJpxWYRqC1gHLqVQJ1A3pDOycvJwWWhoZIxqmQFQxMTUzNzCEm6EkYkZbu0giGoCiA_TCQaQpLVgAYQGAA)
Takes input and outputs as vectors of char codes.
**Explanation outline:**
* `match` finds positions of the elements from `s` in the wrapping string `w`.
* We add a sequence from 1 to the length of `s` to account for "gradually" in the challenge.
* We need to index that to `w` with wrapping: using modular arithmetic or repeating `w` sufficiently many times - the latter turns out shorter.
[Answer]
# [APL (dzaima/APL)](https://github.com/dzaima/APL), 10 bytes
Tacit function taking the wrapping string on the left.
```
⍳⊃¨⌽⍨ᑈ∘⍳∘≢
```
[Try it online!](https://tio.run/##SyzI0U2pSszMTfzvpvCobYKCxv9HvZsfdTUfWvGoZ@@j3hUPJ3Y86pgBEgOSnYv@a3JxPeqbClaqlJiUnJKalp6RmZWdk5uXX1BYVFxSWlZeUVnl6OTs4urm7uHp5e3j6@cfEBgUHBIaFh4RGaWkoOAG1qlEDXOASqhiTlRUFJI58RDBeCUqeRWkE8ksA0MjYxNTM3MLS4gKIBdJ1tAIJgqCSv8B "APL (dzaima/APL) – Try It Online")
`⍳∘≢` Indices from 1 to the length of the right argument.
`⌽⍨ᑈ` For each of those numbers, rotate the wrapping string by that amount. This gives a copy of the wrapping string for each character in the right argument, each rotated one further.
`⍳` Indices of the right argument in the wrapping argument.
`⊃¨` Use each of these indices to pick a char from a rotated copy of the wrapping string.
Would be 12 bytes without dzaima/APL's each-right: [`⍳⊃¨{⌽∘⍺¨⍳≢⍵}`](https://tio.run/##SyzI0U2pTMzJT////1Hv5kddzYdWVD/q2fuoY8aj3l2HVoDEOhc96t1a@9/tUduER719j/qmevqD1K03ftQ2EcgLDnIGkiEensH/1ROTklNS09IzMrOyc3Lz8gsKi4pLSsvKKyqrHJ2cXVzd3D08vbx9fP38AwKDgkNCw8IjIqPUFRTcFEA61bko0A9UQpH@qKgooH4ImyKDoDqBZhgYGhmbmJqZW1hCZIBcoKihEYwHguoA).
[Answer]
# JavaScript (ES6), 43 bytes
Expects `(p)(q)`, where `p` is an array of characters and `q` is a string. Returns an array of characters.
```
p=>q=>p.map((c,i)=>(q+=q)[q.indexOf(c)-~i])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/A1q7Q1q5ALzexQEMjWSdT09ZOo1DbtlAzulAvMy8ltcI/TSNZU7cuM1bzf3J@XnF@TqpeTn66RppGtJ6enlJiUrJSrKYGiE5JTUvPyMzKzsnNyy8oLCouKS0rr6iscnRydnF1c/fw9PL28fXzDwgMCg4JDQuPiIxS0tTLys/M01BX19TkwmI2UDPNzI6KiqKZ2WCDCSmCWkwzRxgaGYPNNgAyTEzNzC0sCesAQbAmIIWk@D8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
kā+è
```
I/O as a list of characters. (The wrapped string input can be either a string or list of characters, doesn't really matter.)
[Try it online](https://tio.run/##yy9OTMpM/f8/@0ij9uEV//9HKyUq6SglAXGyUixXYlJySmpaekZmVnZObl5@QWFRcUlpWXlFZZWjk7OLq5u7h6eXt4@vn39AYFBwSGhYeERkFAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9WeaQ9@OhCeyWFR22TFJTsKxNcioL/Zx9p1D684r/O/@hopcSkZCUdEJmSmpaekZmVnZObl19QWFRcUlpWXlFZ5ejk7OLq5u7h6eXt4@vnHxAYFBwSGhYeERmlFKujEK0EVEKR/qioKIr0AzVDGBAjKDLL0MgYqN8ASJmYmplbWMJEQRAoASSgNmWhWKMUGwsA).
**Explanation:**
```
# e.g. inputs: ["a","b","j"], "abcdefghij"
k # Get the indices of the characters of the first implicit input-list in the
# second implicit input
# STACK: [0,1,9]
ā # Push a list in the range [1,length] (without popping)
# STACK: [0,1,9], [1,2,3]
+ # Add the values at the same positions in the lists together
# STACK: [1,3,12]
è # Use that to (modular) index into the second (implicit) input
# STACK: ["b","d","c"]
# (after which the list of characters is output implicitly)
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.regressive.org/snobol4/csnobol4/), ~~120~~ 116 bytes
```
W =DUPL(INPUT,SIZE(I =INPUT))
N I POS(P) @Q LEN(1) . X @P :F(O)
W X LEN(Q) LEN(1) . R
O =O R :(N)
O OUTPUT =O
END
```
[Try it online!](https://tio.run/##RYzJDoIwFEXX7Ve8ZZsYExNXJCSoFK1iW4YKshNnRVBx/nkkxMTlvSfnlHmRFlm3qlAEpq2VS7hQOmwFPGGEg9ksSrFAHJQMiKJgeeAyQToU2hCDpZDhEElxHYgb4NE/9zGSYErwkUEExRJJHdbB@sJM2FW1SJer9Wa72x@O2Skvzpdrebs/nq/3p9cf2MwZjvh44k6FVJ4fhHoWxfME/6Qv "SNOBOL4 (CSNOBOL4) – Try It Online")
Takes input as Wrapping String, then Input string, separated by a newline.
Slightly outdated explanation (algorithm is basically the same, though):
```
I =INPUT ;* input string
W =DUPL(INPUT,SIZE(I)) ;* wrapping string: duplicated length(I) times
N I POS(P) LEN(1) . X @P :F(O) ;* match the next character in I as X (and its position as P), and on failure goto O
W X LEN(P - 1) LEN(1) . R ;* In W, match X, then P - 1 characters, then 1 character as R
O =O R :(N) ;* append R to O and goto N
O OUTPUT =O ;* print (with a newline)
END
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), ~~27~~ ~~23~~ ~~19~~ 16 bytes
```
(1+⊐+⊒˜∘⊢)⊏+○≢⥊⊣
```
Anonymous function; takes the wrapping string as left argument and the input string as right argument.
[Try it at BQN online](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgKDEr4oqQK+KKksuc4oiY4oqiKeKKkeKMnMK34ouIK+KXi+KJouKliuKKowoKImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoiIEYgIlpaWmRlZmci)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 60 bytes
```
f=lambda i,w,l=1:i and(w+w)[l+w.find(i[0])]+f(i[1:],w+w,l+1)
```
[Try it online!](https://tio.run/##pVHJTsMwEL37K0bh4FiJqqYtpURKpVL2fV9SckibuHVJ3ZAY0oD49jAJhQPiVOwZa@bNe5Y9E@dqMpfNTpwUBXcifzYMfBBmZkaOZQvwZaBnRsYGkZHVuMBMDOoe8wyOgWV7JhbNyLBYocJUpeCApmn@cAToQcjHEzF9imZyHj8nqXp5zRb5W2@rv72zu7d/cHh0fHJ6dn5xeXV9c3t3/@CC04VhwAmSVtbnvT5xXXdlPerIUvufP0ymkSRWowl1PFrr7Y3OZllptNqIlhvQSqBa2DNC@DwBBUJC1claGkdC6fRRUmaTciLYW/WNllLKcBI/AGUE/D8olkcgToRUejlU6nSpycuQmZzq4SIORyoMbHj3Pxhe8cXUNBNtya2SX2ykwhqEs1jlkCrUjKtHF58 "Python 3.8 (pre-release) – Try It Online")
Improved recursive solution by @tsh
## 69 bytes
```
lambda i,w,o='':([(o:=o+(w:=2*w)[len(o)-~w.find(a)])for a in i],o)[1]
```
[Try it online!](https://tio.run/##pVFJU4MwGL3nV3yDhySKnW7WygydqXXf9wXKgRZoaWmCEKXo6F/HBKsHvdXkSyZ5eS@TvBfnYsxZox0nRWD2i8idDTwXQj3TuYmxQWzCDZOvkcww66sZtSOfEU7XP7JKEDKPuNShAU9AShiEjs6pXXMK4aciBRM0TXMHQ5DD84PROJxMoxnj8VOSiueXbJ6/drd7O7t7@weHR8cnp2fnF5dX1ze3d/cPjxaYHRh4AZKkpfV5t4csy1paL3Voof3PH8aTiKFavQFVOTU3WpvtLXVSb7YkqjrIUkDZpGcIKUuFsrR0spLGUSgI7jNMDaTCkd6Kb1RJMbWrzg@AKZKB/KXUHARxEjJBVL7Y7GA9UEuqB5j489gfCt8z4M19p/KKL6am6bIW3HLziy2psAL@LBY5pEJqRuWji08 "Python 3.8 (pre-release) – Try It Online")
Takes 2 strings as input, outputs a string.
[Answer]
# [Perl 5](https://www.perl.org/) + `-plF`, 45 bytes
I feel like this should be easier, so I must be missing a trick somewhere...
```
@l{@F}=0..@F;$_=<>;s/./$F[($l{$&}+"@+")%@F]/g
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiQGx7QEZ9PTAuLkBGOyRfPTw+O3MvLi8kRlsoJGx7JCZ9K1wiQCtcIiklQEZdL2ciLCJhcmdzIjoiLXBsRiIsImlucHV0IjoiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWlxuYWJjXG5hYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ekFCQ0RFRkdISUpLTE1OT1BRUlNUVVZXWFlaXG54eXpcbmFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpcblpaWlxuXG5cbmFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVpcbmFiY2RlZmdcbjAxMjM0NTY3ODlcbjEyM1xuMTJcbjEyMTIxMiJ9)
## Explanation
Creates a lookup hash `%l` using the keys from the "wrapping string" (implicitly stored in `@F` via `-F`) and the values as the numbers from `0` to `@F` (when a list is used in scalar context, the length of the list is used). Then each char in the input string (`$_=<>`) is `s///`ubstituted with the corresponding char at the required index in `@F`, using the current "end of match" list `@+` as a string, modulo the list length.
[Answer]
# [TECO](https://almy.us/teco.html), ~~66~~ ~~60~~ 52 bytes
```
-1^XGa:Qb<JQiQbUmS^EUm^[.+QiUk^[Qk-(Z*(Qk/Z))J0A:^Ur^[%i^[>
```
Note that `^X` or `^[` are ASCII control codes, thus each counts at 1 byte. The two string arguments are fetched from Q-register a, b, and result is saved to Q-register r
## Explanation
```
^Ua12^[ ! register a !
^Ub121212^[ ! register b !
-1^X ! Case sensitive search !
1Un ! n = 1; i = 0 !
Ga ! Load register a to buffer !
:Qb< ! Do len(b) times !
J ! Jump to zero !
QiQbUm ! Set b[i] to register m !
S^EUm^[ ! Search to the b[i] in buffer !
.-1Uk ! Save position to k !
(Qk+Qn)-(Z*((Qk+Qn)/Z))J ! Locate wrapping !
0A:^Ur^[ ! Append to register r !
%n^[%i^[ ! n++; i++ !
> ! Od !
:Gr ! print register r !
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 16 bytes
Anonymous tacit infix function, taking the wrapping string as left argument and the input string as right argument.
```
⊣⊇⍨≢⍤⊣|1+⍳⍤≢⍤⊢+⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/qG@qp/@jtgkG/x91LX7U1f6od8WjzkWPepcAuTWG2o96N4PYUJFFIP7/NKDyR719j7qaH/WuedS75dB640dtE4EGBQc5A8kQD8/g/@qJSckpqWnpGZlZ2Tm5efkFhUXFJaVl5RWVVY5Ozi6ubu4enl7ePr5@/gGBQcEhoWHhEZFR6gppCiCN6lzkaweqoER7VFQUJdqhGoFGGBgaGZuYmplbWIIlgDygoKERlAOCQD6Ypw4A "APL (Dyalog Extended) – Try It Online") (last case also works in current version of the language)
`⍳` index of each input string char in the wrapping string
…`+` add to that:
`⍳` the indices
`⍤` of the
`≢` length
`⍤` of the
`⊢` right argument (the input string)
`1+` increment
…`|` compute the division remainder when divided by:
`≢` the length
`⍤` of the
`⊣` left argument (the wrapping string)
`⊇` select those elements
`⍨` from:
`⊣` the left argument (the wrapping string)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 51 bytes
```
->s,w{k=0;s.chars.map{|c|(w*k+=1)[/#{c}.*/][k]}*''}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf165Yp7w629bAulgvOSOxqFgvN7Gguia5RqNcK1vb1lAzWl@5OrlWT0s/Njo7tlZLXb32f4FCWrSWarlGYlKyAhCnpKalZ2RmZefk5uUXFBYVl5SWlVdUVjk6Obu4url7eHp5@/j6@QcEBgWHhIaFR0RGacb@BwA "Ruby – Try It Online")
[Answer]
# [Factor](https://factorcode.org), 60 bytes
```
[ [ 1 + [ tuck index ] dip + rotate first ] with map-index ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owS3GqaHBnn7uVgqJxcX5ycUKuYklGQrZqUV5qTkKmfkKxamFpal5yanFeqkVJUWJxQgBBWsurmouBSCoVlBKTEpOSU1Lz8jMys7JzcsvKCwqLiktK6-orHJ0cnZxdXP38PTy9vH18w8IDAoOCQ0Lj4iMUgJrU1KopdAQoDzlhkRFRSEZogRClBoJ1YZkkIGhkbGJqZm5hSVQGshGkjI0AguBIEi0dmlpSZquxU2baIVoBUMFbSBZUpqcrZCZl5JaoRCrkJJZABQsyi9JLElVSMsEOggoWJ4JjLrcxAJdqCqIGXuiFQqKMvNACpLzcwvyi1MhUa2bmpicAVGyYAGEBgA)
Rotating the wrapping string and taking the first character is quite a bit shorter than modular arithmetic or `<circular>` indexing.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 70 bytes
```
i;f(s,w)char*s,*w;{for(i=1;*s;)*s++=w[(index(w,*s)-w+i++)%strlen(w)];}
```
[Try it online!](https://tio.run/##vVNbT9swFH7nV3iRkOykFb1wlddJXcdlwLgVGJRWU3CdNjRNsjjMKVX/OuE4cdrSaU@TcJQc@/h837mGlQeMpalLHSxKkrChHZmiZEo6dYIIu40qNQUlprCshnzArt/nCZYlU5CytFzLIusijjzuY0l6dJa6fozGtutjgqZrCFbGh2Iu4l/ioYcaaGrYj8woISOZvCjR6XSUUC9c9LkzUNtqrZ4L9RgzusolF1wKMnSfRt7YD8LfkYif/0jgbn5tfds/ODz6fnxy@uPs/OLyqn19c/vz7r6z5OrDcP@DrUAxNre2d3b38pK8LwdPQs5i3tcFeew7ymrSbGmXhXe4GD55vtrWNrczka05W@CLWHOyIWcjHmnKbrJf6yZ7LXi3FG7pXC/QMCsIq@ZnAwKwCtXbz0i4LzxwcBEo2dAKc66hyLIya5KR5ZOzSLENfHqCMqseXTEQYDC2PS9gWE9jmyALVcnCEPQsnMCIozZZhcuCX/7FH0aQlIONrrEuupB8LlH5C4IDkMklMvUDvVPoBgH7vEmr/KpkoS1UAp9UiONQkXDyrwgQfPzcddEkBe8thxFxjoVWzNZm6StzPHsg0rJ8Aw "C (gcc) – Try It Online")
Inputs two strings.
Returns the answer in the first input string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
⭆θ§η⁺⌕ηι⊕κ
```
[Try it online!](https://tio.run/##FYnLEoIgAAB/hSPO0Bd0sodFZVH29EZAQiIqolk/T7qXnZ1lklpWUu09sco4mLhBWUwrWCMQOmy46KFEgOi2gZEyfAwVIIANs6IQxgkO82Bk6n3//QH6ZFy8MqneuS5MWdW2cW33GVY4my@W0WqNN9tdvD@Q4yk5X663@yP1k07/AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
⭆ Map over characters and join
η Wrapping string
§ Cyclically indexed by
⌕ Index of
ι Current character in
η Wrapping string
⁺ Plus
κ Current index
⊕ Incremented
Implicitly print
```
[Answer]
# [Python](https://www.python.org), 62 bytes
```
lambda s,w:[w[(w.index(c)+i+1)%len(w)]for i,c in enumerate(s)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY37XISc5NSEhWKdcqtosujNcr1MvNSUis0kjW1M7UNNVVzUvM0yjVj0_KLFDJ1khUy8xRS80pzU4sSS1I1ijVjIabcYswvVrBViOZST0xKVtfhUq-orAJRUVFRIAqEgRIpqWnpIKahkTGEAkEgK5aLq7wosQBuAEhdRmZWdk5uXn5BYVFxSWlZOdBARydnF1c3dw9PL28fXz__gMCg4JDQsPCIyCgk8-mmjxK9BsAQMDE1M7ewhISDug4wCEAhnJafr5OUWAQK5arMAg1gnADDRdOKi7OgKDOvRCNNA6pAUxMS7gsWQGgA)
Outputs as a list of characters
[Answer]
# [MATL](https://github.com/lmendo/MATL), 7 bytes
```
y&mtf+)
```
[Try it online!](https://tio.run/##y00syfn/v1IttyRNW/P/f/XEpOSU1LT0jMys7JzcvPyCwqLiktKy8orKKkcnZxdXN3cPTy9vH18//4DAoOCQ0LDwiMgodS6YNnUA "MATL – Try It Online")
Takes input as `'wrapping string'` then `'input string'`, separated by a newline.
```
% implicit input w,i
y % dup from below. Stack: w,i,w
&m % ismember: find the index of each element of i in w
t % duplicate.
f % find: return truthy index. Since all are truthy, this returns 1:length(i)
+) % add and index modularly into w
% implicit output
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 73 bytes
```
s,w=gets.split;n=1;s.chars.each{|i|print w[(w.index(i)+n)%w.length];n+=1}
```
The method used is similar to the reference implementation.
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsGCpaUlaboWNz2Ldcpt01NLivWKC3IyS6zzbA2ti_WSMxKLivVSE5MzqmsyawqKMvNKFMqjNcr1MvNSUis0MjW18zRVy_VyUvPSSzJirfO0bQ1rIQZCzV2w0tAIBBUMjSACAA)
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 16 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
⊢⊏˜≠∘⊢|1+⊒˜∘⊣+⊐˜
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqi4oqPy5ziiaDiiJjiiqJ8MSviipLLnOKImOKKoyviipDLnAoKIlpaWmRlZmd6enoiIEYgImFiY2RlZmdoaWprbG1ub3BxcnN0dXZ3eHl6QUJDREVGR0hJSktMTU5PUFFSU1RVVldYWVoiCg==)
-5 from DLosc.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
vḟ:ż+$i
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJ24bifOsW8KyRpIiwiIiwiYWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNERUZHSElKS0xNTk9QUVJTVFVWV1hZWlxueHl6Il0=)
Port of Jelly answer.
## How?
```
vḟ:ż+$i
vḟ # For each element in the (implicit) second input, find its index in the (implicit) first input
:ż # Duplicate and push a length range [1, length]
+ # Add top two things on stack together
$ # Swap so (implicit) first input is pushed to the stack
i # Index the list into the string
```
] |
[Question]
[
Challenge Taken from [here](https://code.google.com/codejam/contest/4214486/dashboard#s=p3) and also [here](https://bo.spoj.com/problems/AI_BRACK/)
An **n** parentheses sequence consists of **n** `(`s and **n** `)`s.
A valid parentheses sequence is defined as the following:
>
> You can find a way to repeat erasing adjacent pair of parentheses "()" until it becomes empty.
>
>
> For example, `(())` is a valid parentheses, you can erase the pair on the 2nd and 3rd position and it becomes `()`, then you can make it empty.
> `)()(` is not a valid parentheses, after you erase the pair on the 2nd and 3rd position, it becomes `)(` and you cannot erase any more
>
>
>
**Task**
Given a number **n** you need to generate all correct parenthesis sequence in [lexicographical order](https://en.wikipedia.org/wiki/Lexicographical_order)
Output can be an array, list or string (in this case a sequence per line)
You can use a different pair of parenthesis such as `{}`, `[]`, `()` or any open-close sign
**Example**
* n = 3
```
((()))
(()())
(())()
()(())
()()()
```
* n = 2
```
(())
()()
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 36 bytes
```
{grep {try !.EVAL},[X~] <[ ]>xx$_*2}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAobqkqFJBUc81zNGnVic6oi5WwSZaIdauokIlXsuo9n9afpGCoZ6esUJ1cWKlgp5aWu1/AA "Perl 6 – Try It Online")
Finds all lexographically sorted combinations of \$2n\$ `[]`s and filters the ones that `EVAL` correctly. Note that all valid combinations (even stuff like `[][]`) evaluate to `[]` (which is falsey, but we `not` it (`!`) to distinguish from `try` returning `Nil`)
### Explanation:
```
{ } # Anonymous code block
<[ ]> # Create a list of ("[", "]")
xx$_*2 # Duplicate this 2n times
[X~] # Find all possible combinations
grep { }, # Filter from these
.EVAL # The EVAL'd strings
try ! # That do not throw an error
```
[Answer]
# [R](https://www.r-project.org/), ~~112~~ ~~107~~ 99 bytes
Non-recursive approach. We use "<" and ">" because it avoids escape characters in the regex. To allow us to use a shorter specification for an ASCII range, we generate 3^2n 2n-character strings of "<", "=" and ">" using `expand.grid` (via their ASCII codes 60, 61 and 62) and then grep to see which combinations give balanced open and close brackets. The "=" possibilities will get ignored, of course.
Via <http://rachbelaid.com/recursive-regular-experession/>
```
function(n)sort(grep("^(<(?1)*>)(?1)*$",apply(expand.grid(rep(list(60:62),2*n)),1,intToUtf8),,T,T))
```
[Try it online!](https://tio.run/##HcpBCsIwEAXQuxQX88sopkiRUuwlokuhtEkJlElIp6BePqKrt3m5@P5Y/C6Thigk2GJWWrJLVD2pp8GgvuHPoeIxpfVN7pVGmU9LDjP94ho2pfbctQ24qQVgw0HUxrv6K5gtW6A83KQxh48jDzLdBeUL "R – Try It Online")
## Explanation
```
"^(<(?1)*>)(?1)*$" = regex for balanced <> with no other characters
^ # match a start of the string
( # start of expression 1
< # open <>
(?1)* # optional repeat of any number of expression 1 (recursive)
# allows match for parentheses like (()()())(()) where ?1 is (\\((?1)*\\))
> # close <>
) # end of expression 1
(?1)* # optional repeat of any number of expression 1
$ # end of string
function(n)
sort(
grep("^(<(?1)*>)(?1)*$", # search for regular expression matching open and close brackets
apply(
expand.grid(rep(list(60:62),2*n)) # generate 3^(2n) 60,61,62 combinations
,1,intToUtf8) # turn into all 3^(2n) combinations of "<","=",">"
,,T,T) # return the values that match the regex, so "=" gets ignored
) # sort them
```
# [R](https://www.r-project.org/), 107 bytes
Usual recursive approach.
-1 thanks @Giuseppe
```
f=function(n,x=0:1)`if`(n,sort(unique(unlist(Map(f,n-1,lapply(seq(x),append,x=x,v=0:1))))),intToUtf8(x+40))
```
[Try it online!](https://tio.run/##HYxBCsIwEEWvM4MjpNCFFHoEd@q6pWZgIEzSZCrRy8fo23ze4r/cGs986GYSFZTq7KYBF@GlS4nZ4FDZD98nSDG4rgmY9DxQWFMKbyh@h4rUxeuz3yu9/okfJGq3eDe@QD2NDrE9/GYxy8cDI7hpxPYF "R – Try It Online")
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~36 35~~ 37 bytes
```
{"()"(|/'0>+\'1-2*)_(x=+/')#+!2|&2*x}
```
[Try it online!](https://ngn.bitbucket.io/k#eJxLs6pW0tBU0qjRVzew045RN9Q10tKM16iw1dZX11TWVjSqUTPSqqjl4kpTMAYA46cJ8Q==)
`+!2|&2*x` all binary vectors of length 2\*n
`(x=+/')#` only those that sum to n
`(|/0>+\'1-2*)_` only those whose partial sums, treating 0/1 as 1/-1, are nowhere negative
`"()"` use 0/1 as indices in this string
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 13 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
„()©s·ãʒ®õ:õQ
```
[Try it online](https://tio.run/##ASEA3v9vc2FiaWX//@KAnigpwqlzwrfDo8qSwq7DtTrDtVH//zM) or [verify some more test cases](https://tio.run/##AS8A0P9vc2FiaWX/N0ZOPyIgLT4gIj9O/@KAnigpwqlzwrfDo8qSwq7DtTrDtVH/fSz/Mw).
**Explanation:**
```
„() # Push string "()"
© # Store it in the register without popping
s· # Swap to get the (implicit) input, and double it
ã # Cartesian product that many times
ʒ # Filter it by:
® # Push the "()" from the register
õ: # Infinite replacement with an empty string
õQ # And only keep those which are empty after the infinite replacement
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 114 bytes
```
f(n,x,s,a,i){char b[99]={};n*=2;for(x=1<<n;x--;s|a<0||puts(b))for(s=a=i=0;i<n;)a|=s+=2*(b[n-i]=41-(x>>i++&1))-81;}
```
[Try it online!](https://tio.run/##XYzNioMwFIXX@hRZDUnjBS1dTIm3rzGL0kXMNJ0L9lqSCIL66k11O5vD4Ts/Dh7O5ewlV1MVK1uRmt2fDaK7ns83nFfDBzwaPwQ5YdO2bCYAExfb1svyGlOUnVJ7GtEiYW1oqyi7YNR4PMjuykA3PDUgp8uFtP5qlILvxqyZOImnJZZKzGWxXQi5I8LGCGrxtKnWqiwKL0mZsgj3NAYWtSnX/Ha@t4@Y4YcHoOerJ0cJtvk/4kd2iQaG37vrbbC7/wA "C (gcc) – Try It Online")
Should work for n <= 15.
### Explanation
```
f(n,x,s,a,i){
char b[99]={}; // Output buffer initialized with zeros.
n*=2; // Double n.
for(x=1<<n;x--; // Loop from x=2**n-1 to 0, x is a bit field
// where 1 represents '(' and 0 represents ')'.
// This guarantees lexicographical order.
s|a<0||puts(b)) // Print buffer if s==0 (as many opening as
// closing parens) and a>=0 (number of open
// parens never drops below zero).
for(s=a=i=0;i<n;) // Loop from i=0 to n-1, note that we're
// traversing the bit field right-to-left.
a|= // a is the or-sum of all intermediate sums,
// it becomes negative whenever an intermediate
// sum is negative.
s+= // s is the number of closing parens minus the
// number of opening parens.
x>>i++&1 // Isolate current bit and inc i.
41-( ) // ASCII code of paren, a one bit
// yields 40 '(', a zero bit 41 ')'.
b[n-i]= // Store ASCII code in buffer.
2*( )-81; // 1 for ')' and -1 for '(' since
// we're going right-to-left.
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~91~~ ~~88~~ ~~84~~ 81 bytes
```
f=lambda n:n and sorted({a[:i]+'()'+a[i:]for a in f(n-1)for i in range(n)})or['']
```
[Try it online!](https://tio.run/##RcsxCsMwDEbhvafQZovQoYUshpzEeFBw3AqS30H1UkrP7uKp4@Pjne/2rLj3XpZdjjULIYAEmV7V2pb9R2LQNDnPbpKoIZVqJKSg4nG98UgdaYLH5sFfrhadS30I/jJzuNBpijZO7j8 "Python 2 – Try It Online")
-3 bytes thanks to pizzapants184
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 bytes
```
f=->n{n<1?['']:(0...n).flat_map{|w|f[n-1].map{|x|x.insert w,'()'}}|[]}
```
[Try it online!](https://tio.run/##KypNqvz/P81W1y6vOs/G0D5aXT3WSsNAT08vT1MvLSexJD43saC6prwmLTpP1zBWD8yrqKnQy8wrTi0qUSjXUdfQVK@trYmOrf0P0memCVNToBBdoZMWXRELlAEA "Ruby – Try It Online")
[Answer]
# Japt, ~~15~~ 13 bytes
```
ç>i<)á Ôke/<>
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=5z5pPCnhINRrZS88Pg==&input=MwotUg==)
---
## Explanation
```
ç :Input times repeat the following string
>i< : ">" prepended with "<"
) :End repeat
á :Get unique permutations
Ô :Reverse
k :Remove any that return true (non-empty string)
e/<> : Recursively replace Regex /<>/
```
[Answer]
# [Perl 5](https://www.perl.org/) `-n`, ~~41~~ 39 bytes
*-2 bytes with angle brackets*
```
s/<(?R)*>//gr||say for glob'{<,>}'x2x$_
```
[Try it online!](https://tio.run/##K0gtyjH9/79Y30bDPkhTy05fP72opqY4sVIhLb9IIT0nP0m92kbHrla9wqhCJf7/f0MuIy5jLpN/@QUlmfl5xf918/7r@prqGRgaAAA "Perl 5 – Try It Online")
Port of my Perl 6 answer.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 42 bytes
```
{grep {!S:g/\(<~~>*\)//},[X~] <( )>xx$_*2}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAoVox2CpdP0bDpq7OTitGU1@/Vic6oi5WwUZDQdOuokIlXsuo9n9BaYmCHlBXWn6RgqGenvF/AA "Perl 6 – Try It Online")
Uses a recursive regex. Alternative substitution: `S/[\(<~~>\)]*//`
**38 bytes** with 0 and 1 as open/close symbols:
```
{grep {!S:g/0<~~>*1//},[X~] ^2 xx$_*2}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzq9KLVAoVox2Cpd38Cmrs5Oy1Bfv1YnOqIuViHOSKGiQiVey6j2f0FpiYIeUEdafpGCoZ6e8X8A "Perl 6 – Try It Online")
### Explanation
```
{ } # Anonymous block
<( )> # List "(", ")"
xx$_*2 # repeated 2n times
[X~] # Cartesian product with string concat
# yields all strings of length 2n
# consisting of ( and )
grep { }, # Filter strings
S:g/ # Globally replace regex match
\( # literal (
<~~> # whole regex matched recursively
* # zero or more times
\) # literal )
// # with empty string
! # Is empty string?
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 50 bytes
```
.+
$*
1
11
+%1`1
<$'¶$`>
Gm`^(?<-1>(<)*>)*$(?(1).)
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRYvLkMvQkEtb1TDBkMtGRf3QNpUEOy733IQ4DXsbXUM7DRtNLTtNLRUNew1DTT3N//@NAQ "Retina 0.8.2 – Try It Online") Uses `<>`s. Explanation:
```
.+
$*
```
Convert to unary.
```
1
11
```
Double the result.
```
+%1`1
<$'¶$`>
```
Enumerate all of the 2²ⁿ 2n-bit binary numbers, mapping the digits to `<>`.
```
Gm`^(?<-1>(<)*>)*$(?(1).)
```
Keep only balanced sequences. This uses a balanced parentheses trick discovered by @MartinEnder.
[Answer]
# JavaScript (ES6), ~~112~~ 102 bytes
This is heavily based on [nwellnhof's C answer](https://codegolf.stackexchange.com/a/175419/58563).
```
f=(n,i)=>i>>2*n?'':(g=(o,k)=>o[2*n]?s|m<0?'':o:g('()'[m|=s+=k&1||-1,k&1]+o,k/2))(`
`,i,m=s=0)+f(n,-~i)
```
[Try it online!](https://tio.run/##ZcxBDoIwEAXQPQexM1IU0BVx4CCEBIK0qdCOscZV49VrXRpXk7z//9ym1@Tnh7k/C8fXJUZF4KRBak3b1nvXCdGAJmC5JuM@0dD5YC/lN@FGgwAUvQ3kc1p3VQhFJdMd8rQ41ogwZqM00pKnEnOVnhdvg3Fm53lbDhtrUJB62a@c/uSMGD8 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 214, 184 136 bytes
```
func[n][g: func[b n][either n = length? b[if not error? try[load b][print b]return 0][g append copy b"["n g append copy b"]"n]]g""2 * n]
```
[Try it online!](https://tio.run/##XY0xCsMwEAR7v2K5MmAISSpD8B/SHios62QbzEkccuHXKyLp3M1sMWsS6kcCuy4ONR46szpeBvzQo4lsZRWD4o1ddCnrCM9bhKYCMUs2otjJe5oCvONsm5YGJuUwxb3VMOUsGjCnfMITk@K6OVLnFqIHbu2zRjy7f4j6vqcu4nHxV/0C "Red – Try It Online")
Uses Jo King's approach. Finds all possilble arrangements of brackes using recursion (they are generated in lexicographic order) and print it if the arrangement evaluates as a valid block.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to [ChartZBelatedly](https://codegolf.stackexchange.com/users/66833/chartz-belatedly)! (Use a better fixed-point built-in.)
```
ḤØ(ṗœṣØ(F$ÐLÐḟ
```
A monadic Link accepting \$n\$ that yields a list of lists of characters.
**[Try it online!](https://tio.run/##ASkA1v9qZWxsef//4bikw5go4bmXxZPhuaPDmChGJMOQTMOQ4bif/8OHWf//NA "Jelly – Try It Online")** (footer formats the list as lines.)
### How?
```
ḤØ(ṗœṣØ(F$ÐLÐḟ - Link: integer, n
Ø( - literal ['(', ')']
Ḥ - double (n)
ṗ - Cartesian power -> all length 2n lists of '(' and/or ')' (already sorted)
Ðḟ - filter discard if:
ÐL - repeat until a fixed point is reached applying:
$ - last two links as a monad, f(current, initially proposed):
œṣ - split at:
Ø( - literal ['(', ')']
F - flatten
} -> empty list if balanced (only empty lists are falsey)
```
[Answer]
# [Haskell](https://www.haskell.org/), 80 bytes
```
f n=[x|x<-mapM("()"<$f)[1..2*n],0:y<-[scanr(\b->(sum[2|b>'(']-1+))0x],all(>=0)y]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzza6oqbCRjc3scBXQ0lDU8lGJU0z2lBPz0grL1bHwKrSRje6ODkxr0gjJknXTqO4NDfaqCbJTl1DPVbXUFtT06AiVicxJ0fDztZAszL2f25iZp4tyKx4hYLSkuCSIp88lTQFk/8A "Haskell – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
Ø+xŒ!QÄAƑ>ṪƊ$Ƈ=1ịØ(
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//w5greMWSIVHDhEHGkT7huarGiiTGhz0x4buLw5go/8OHKy/igqzFkuG5mP//Mw "Jelly – Try It Online")
Output clarified over TIO.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 84 bytes
```
f=(n,s='')=>n?f(n-=.5,s+'[')+f(n,s+']'):[...s].some(t=>(n+=t<']'?1:-1)<0)|n?'':s+`
`
```
[Try it online!](https://tio.run/##ZclLDoIwEADQPReZmRQa8bNpGHoQQgLB1mhgapzGlXevujRu37vNz1mXx/WeG0nnUEpklFoZgLgXH1EatqdaDQxAJn7PwAjkBmutjlbTFjBzj2I4d5/xrWta6nb0Eg/g1EzVVJYkmtZg13TBiHui6lcOf3IkKm8 "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 90 bytes
```
f=(n,s='')=>n?f(n-=.5,s+'[')+f(n,s+']'):eval("try{eval(s.split``+``),s+`\n`}catch(_){''}")
```
[Try it online!](https://tio.run/##ZYrLCsIwEADvfkYvu0vaHHxchNQPUXFDbLQSktINBSn99vi4ibdhZh52suLGfshNTNeuFG8w1mIAyLTx4DE2Ru9qUXAEUv7TFJyB9t1kA1Z5fM5fEi1D6DOzYqb3w6fIi7PZ3fFCM8BSUXEpSgqdDumGHtdEq1@z@TNbovIC "JavaScript (Node.js) – Try It Online")
Is it an array?
] |
[Question]
[
## Introduction:
Apparently I keep coming up with word search related challenges lately. :)
When I do the word search in the Dutch news paper, some words are very easy to find because they contain letters that aren't too common in Dutch words, like `x` or `q`. So although I usually look for the first letter or prefix of a word I'm searching, in some cases looking for these letters in the grid is faster to find the words.
#### Brief explanation of what a word search is*†*:
*† Although it's not too relevant for the actual challenge this time.*
In a [word search](https://en.wikipedia.org/wiki/Word_search) you'll be given a grid of letters and a list of words. The idea is to cross off the words from the list in the grid. The words can be in eight different directions: horizontally from left-to-right or right-to-left; vertically from top-to-bottom or bottom-to-top; diagonally from the topleft-to-bottomright or bottomright-to-topleft; or anti-diagonally from the topright-to-bottomleft or bottomleft-to-topright.
## Challenge:
Given a grid of letters and a list of words, output for each word the lowest count of the letters within this word within the grid.
**For example:**
```
Grid:
REKNA
TAXIJ
RAREN
ATAEI
YCYAN
Words:
AIR
ANKER
EAT
CYAN
NINJA
RARE
TAXI
TRAY
XRAY
YEN
```
For `AIR` we see the following frequency of the letters in the grid: `[A:6, I:2, R:3]`, of which the lowest is `I:2`. Doing something similar for the other words, the result would be `AIR:2, ANKER:1, EAT:2, CYAN:1, NINJA:1, RARE:3, TAXI:1, TRAY:2, XRAY:1, YEN:2`.
## Challenge rules:
* You can take the inputs in any reasonable format. Could be from STDIN input-lines; as a list of lines; a matrix of characters; as codepoint-integers; etc.
* You can optionally take the dimensions of the grid as additional input.
* The output can be in any reasonable format as well. Can be a key-value map of word + integer as above, but can also just be a list of the integers (e.g. `[2,1,2,1,1,3,1,2,1,2]` for the example above.
* You can assume the list of words are always in alphabetical order.
* The list of words is guaranteed to contain at least one word, and all words are guaranteed to be present in the given grid.
* All words are guaranteed to have at least two letters.
* You can assume each word is only once in the grid.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer with [default I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/), so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code (e.g. [TIO](https://tio.run/#)).
* Also, adding an explanation for your answer is highly recommended.
## Test cases:
Outputs are displayed as integer-lists.
```
Inputs:
REKNA
TAXIJ
RAREN
ATAEI
YCYAN
AIR
ANKER
EAT
CYAN
NINJA
RARE
TAXI
TRAY
XRAY
YEN
Output:
[2,1,2,1,1,3,1,2,1,2]
```
---
```
Inputs:
ABCD
EFGH
IJKL
MNOP
AFK
BCD
FC
PONM
Output:
[1,1,1,1]
```
---
```
Inputs:
WVERTICALL
ROOAFFLSAB
ACRILIATOA
NDODKONWDC
DRKESOODDK
OEEPZEGLIW
MSIIHOAERA
ALRKRRIRER
KODIDEDRCD
HELWSLEUTH
BACKWARD
DIAGONAL
FIND
HORIZONTAL
RANDOM
SEEK
SLEUTH
VERTICAL
WIKIPEDIA
WORDSEARCH
Output:
[1,1,2,1,1,4,1,1,1,3]
```
---
```
Inputs:
JLIBPNZQOAJD
KBFAMZSBEARO
OAKTMICECTQG
YLLSHOEDAOGU
SLHCOWZBTYAH
MHANDSAOISLA
TOPIFYPYAGJT
EZTBELTEATAZ
BALL
BAT
BEAR
BELT
BOY
CAT
COW
DOG
GAL
HAND
HAT
MICE
SHOE
TOP
TOYS
ZAP
Output:
[5,5,1,5,4,3,1,3,3,2,4,3,4,3,4,3]
```
[Answer]
# [R](https://www.r-project.org), 43 bytes
```
\(w,g,`*`=sapply)w*\(i)min(i*\(j)sum(!g-j))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=RZLBbtswDIaBHfkUWU9259x7WA60JduyZNGV1bk2MqBFsQQpmjSY0xV9ll1SYHuo7WlGxVt3kSmTH_nzt7-_fj3-WM0-zn8-HVbzi18fltFzsk5uzm8W4-1-__ASP58vo0283eyiDUf38fi0jd6v5_dxPCG_332-e9x9my1my2iMJyga7253UXJ2Fidcc-Ef1e6QjJvt_mGzelmMMRy-jAceysjzItBRHiez9RT6OF4FEVNVFAMqB2i1dCDRQ9ajBatsheDQSfB4rcA77OE6HL20AE5qi6dMdSqygB6lgv4Ev_XNNaSZgDyDhmwNgOEm86IEVWkDtaXmrTjFTHfoBAiFBVk0kCsroCSnBrKe7w6toBpaKTW0Rl75Ej5J51XGuU5p1UhGoSMnWokuKwG6f3mGiTDPTYspYOaUUegJgRsKTbYTGQinZUskhAaSshlkYVQHdatUSSgdAhqnnVOObdIklJDC8TalNN1fMf834XkpO5myDD4MR9RDFrylDgQVULDkEsN6_LJWmYS2JLaa_fDUtzAgG1MZlTZ2uCSsBOg0x3poQ0sCQu0DlfnLAnpjAiyQiiv2peQZQ-p7LKEOI1ok1RoMvVXeNz0WlQc5-KCLPzcO0192PE7PPw)
Since we are allowed to input integer codepoints, here it goes. Takes input as a list of codepoint vectors for words, and codepoint matrix for grid.
[Answer]
# [Python 3](https://docs.python.org/3/), 42 bytes
```
lambda g,W:[min(map(g.count,w))for w in W]
```
[Try it online!](https://tio.run/##HcuxCoMwFIXh/T5FcDEBcelW6HApGaKQIQQ01A62RRswMdgU6dOn6vIv53zhF9@zP6Xh0qWpd49XT8aiOd@c9dT1gY7lc/76WKyMDfNCVmI9ae4pLNZHOtAsyxSvJYLGVlSgUHEJqJELMFeDErZDsQeFApQ1V8BRwzFJISs8yKFBKzTQ7jFcbqT8hMlGmnc@Z4ylPw "Python 3 – Try It Online")
Takes the grid as a string, with any non-letter separator, and an iterable of strings.
[Answer]
# [Haskell](https://www.haskell.org), 41 bytes
```
g#d=[minimum[sum[1|x<-g,x==c]|c<-w]|w<-d]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8GCpaUlaboWNzXTlVNso3Mz8zJzS3Oji4HYsKbCRjddp8LWNjm2JtlGtzy2ptxGNyUWqqElNzEzT8FWoaAoM69EQUVBKcjV288xJi_EMcLTKyYvyDHI1S8mzzHE0dUzJi_SOdLRT0lBWSFaydEzSElHQcnRz9sVzHB1DAFRYAVA2s_Tz8sRxAAZAKJB5oHpIMdIEB0BpSNd_ZSgboF5AgA)
-3 bytes thanks to @ovs
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ε¢W
```
**[Try it online!](https://tio.run/##yy9OTMpM/f//3NZDi8L//4@OVnJU0lHyBOIgpVgdBQjXD4i9gdgVIQxigqRCIFxnIDMSKuQHEfKDmgOivcBSYOEgqKogsHlgoRCoUARYB1wIpjISIhSBKRQJdRPQxlgupSBXbz9HhRDHCE8vhSDHIFc/BccQR1dPhUjnSEc/JQA "05AB1E – Try It Online")**
### How?
Note: Uses the current interpretation of <https://codegolf.meta.stackexchange.com/a/2216/52210> that seems to be being used, that not only may a string be provided as a list of characters but that it may be provided as a list of single-character strings.
```
ε¢W - inputs are: words (list of lists of strings of length one);
wordsearch (space separated string)
ε - for each word:
¢ - count occurrences of each length-one-string in the wordsearch
W - minimum
```
---
Original 4 that does not use a list of lists of strings for the words...
```
ε€¢W
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3NZHTWsOLQr//z9aydEzSElHQcnRz9sVzHB1DAFRzpGOfiDaz9PPyxHECHIMcgXRIY4RnmA6yDESREdA6UhXP6VYLqUgV28/RwWQIi8FkBY/BccQR1dPhUiwgQA "05AB1E – Try It Online")
### How?
```
ε€¢W - inputs are: words (list of strings); wordsearch (space separated string)
ε - for each word:
€ - for each letter:
¢ - count occurrences in the wordsearch
W - minimum
```
---
\* Taking the words as a list of lists of strings would work, but seems like pre-processing rather than loose IO to me.
[Answer]
# [Haskell](https://www.haskell.org/), ~~71 64~~ 51 bytes
```
g#l=[[x|x<-[1..],c<-w,x==sum[1|e<-g,e==c]]!!0|w<-l]
```
[Try it online!](https://tio.run/##VVJNb9swDL33V7jujk4xN8stOdCWbMuSRVdW5/rrUHRBVyzVhnVDc8h/TyknA9aD@GiKFB/5/P3h9cd2tzsen652m2HYH/brxRBfX0/R43rxFu03m9e/L0N82K4XT9F2s3mcpsvLz4e39WI3HV8enl2wCb79vAh@/X52f4JPQWi41DA6C/eiHJ0Bw/XowAIXo@vSDnQYXA0hCBNGIWjJPXKwZOfLKNRCl0DoSwn8Qx4MdAT3J@i4Dqf/mkKSstHxLC9GJ0qpRldprKlTQK0ySRWUQDZLydSoqw/V7VdurEhBUZ1BhCxTDSTEOjVCCbBI82iGTKJuWTo6ZiRvEBmTo0PO657nSrTUsxGiQOCG8kEZaYww3IxOIhOMM@M5Fly1jeJ3tghpDQmksgXjqTEBOWpQnqXQPlKgET1qO8cMEIOKnIZzP8/5jSj8x53cVkhRc3rI@2hYw8GkxYdRSyWSWve3CCWRkUkGVd8klIc0CkhbiZSn9jYnrZRqCuQMML8bXaOKFNs@sR3QiquC2DSAolFeaqxF1tUd5KUlEXqbcGVJUuhPAiS0WK/ALLLvNYOav9CrmZ7kx9avAXOy@TyP7zKDv/bM/NzEyf8OpK63XUPQQ01DHoebKI78iaPl2buZLoZ4jsRn73T/5RSLlhRdRSvyVhRbzpVLyvH@@Uzv "Haskell – Try It Online")
* Massively outgolfed by [@pxeger](https://codegolf.stackexchange.com/users/97857/pxeger) answer, [check it out](https://codegolf.stackexchange.com/a/246193/84844).
Full list comprehension solution
* saved 13 Bytes thanks to @Unrelated String
*Old 71 bytes*
```
g#w=sum.f<$>((\y->[1|l<-g,l==y])<$>)<$>w
f(h:t)|h<f t=h|1>0=f t
f[]=[2]
```
[Try it online!](https://tio.run/##VVLBbtswDL3nKwy3hxZwhyVZLkMcgLZkW5EsurI6145zKLClKZZqw5qiKJB/zygnA9aD@GiKFB/5vH14@fljtzseHy/e4pfX50@b@eXi6qp/v1msxofd/OYx2sXx@/qawv68jTZX26/768N2vgn28fYwXnyOyRttVut4NVkfnx@eXBAH33@Ngt9/ntw@uAxCw6WG3lm4F8veGTBc9w4scNG7Nm1Bh8HFKgRhwigELblHDpbscBmFWuglEPpSAv@QBwMtwf0JWq7D9X9NIUlZ73iWF70TS6l6V2qsqFNArTJJFZRANkvJVKjLD9XNN26sSEFRnUGELFM1JMQ6NUIJsEjzaIZMom5Y2jtmJK8RGZO9Q86rjudKNNSzFqJA4IbyQRlpjDDc9E4iE4wz4zkWXDW14ne2CGkNCaSyAeOpMQE5alCepdA@UqARHWo7xAwQg5KcmnM/z/mNKPzHndxGSFFxesj7aFjNwaTFh1GXSiSV7m4RlkRGJhmUXZ1QHtIoIG0pUp7a25y0UqoukDPA/K53tSpSbLrEtkArLgtiUwOKWnmpsRJZW7WQLy2J0NmEK0uSQncSIKHFegUGkX2vAdTwhV7N9CQ/Nn4NmJPNh3l8lwH8tWfm5yZO/ncgdb1ta4IOKhryuJpE48ifcTQ9e5P1aDUeIuOzd7r/copFU4rOohl5M4pNh8op5Xj/fNZ/AQ "Haskell – Try It Online")
`g#w` takes `g` grid as a string with newlines and `w` words as a list of words.
Each word is transformed into a list of lists of 1's by `g` before using `f` to select the shortest(lexicographically) character.
`f` has an edge case = *[2]* for the end of the list which is always greater.
Then sum each selection to obtain the output
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~73~~ ~~69~~ 63 bytes
```
g=>l=>l.map(w=>Math.min(...[...w].map(c=>g.split(c).length-1)))
```
[Try it online!](https://tio.run/##fU9La9tAEL7Pr9AtWnAEvRWCDGPtyFrvateM1CqOa4hQY1lFfmCL5FD62921SCk5tMzOwDLfa37Ur/WlOXen4f7183UbX9t42vsX7etT@BZP83rYRfvuEEZRtPb9thk3TTxto8up74awEVH/cmiH3f0nIcT1Ada@noFJW4QSH9UCGJksYImkYJWs0MJzNJy7fSgmHomKAa0mBsISxrVVdoEjbVSAknEFj7exor/k9wB33w53AjaT0RZniQRK5xmohTaQW7f8aJZquEHSBJbO5v/Vqr4SlypBY4CdwzQ1Bc4AE1ZGYekQrHRSO1vJBCRrKpyTUoMjWj7R3KgK8kKpzCExAhrWzIr9mdpJJUmyj5GRqQpDX8rsQ8oZJrpCliAVzp1FA6myHu1YPTlb@j@jN8@hINLwLvAnLVRKqyV5KlSOZUHISfaPQ2ETbY9nqptdGK7bc/d9EvTdZdiIIJ4GPyEImuPhcuxfov7YhtvwhhDhDSHEA/wScP0N "JavaScript (V8) – Try It Online")
*-4 bytes thanks to emanresu A*
*-6 bytes thanks to Matthew Jensen*
# [JavaScript (Node.js)](https://nodejs.org) + [Ramda](https://ramdajs.com/), 56 bytes
```
g=>d=>d.map(w=>R.min(...R.map(c=>R.count(x=>x==c,g),w)))
```
[Try it online!](https://ramdajs.com/repl/?v=0.28.0#?const%20f%20%3D%20g%3D%3Ed%3D%3Ed.map%28w%3D%3ER.min%28...R.map%28c%3D%3ER.count%28x%3D%3Ex%3D%3Dc%2Cg%29%2Cw%29%29%29%0Af%28%22REKNA%5CnTAXIJ%5CnRAREN%5CnATAEI%5CnYCYAN%22%29%28%5B%22AIR%22%2C%20%22ANKER%22%2C%20%22EAT%22%2C%20%22CYAN%22%2C%20%22NINJA%22%2C%20%22RARE%22%2C%20%22TAXI%22%2C%20%22TRAY%22%2C%20%22XRAY%22%2C%20%22YEN%22%5D%29)
# JavaScript + [Sugar](https://sugarjs.com/), 52 bytes
```
g=>d=>d.map(w=>[...w].map(c=>[...g].count(c)).min())
```
```
Sugar.extend();
f=g=>d=>d.map(w=>[...w].map(c=>[...g].count(c)).min())
console.log(f("REKNA,TAXIJ,RAREN,ATAEI,YCYAN")(["AIR", "ANKER", "EAT", "CYAN", "NINJA", "RARE", "TAXI", "TRAY", "XRAY", "YEN"]).join(', '));
console.log(
f("JLIBPNZQOAJD,KBFAMZSBEARO,OAKTMICECTQG,YLLSHOEDAOGU,SLHCOWZBTYAH,MHANDSAOISLA,TOPIFYPYAGJT,EZTBELTEATAZ")
(["BALL","BAT","BEAR","BELT","BOY","CAT","COW","DOG","GAL","HAND","HAT","MICE","SHOE","TOP","TOYS","ZAP"])
.join(', ')
);
```
```
<script src="https://cdnjs.cloudflare.com/ajax/libs/sugar/2.0.6/sugar.min.js"></script>
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 46 bytes
```
->g,w{w.map{|x|x.chars.map{|c|g.count c}.min}}
```
[Try it online!](https://tio.run/##NY7BasJAEEDv@xWLILRg8wctjDsTM@yakdm0C0oPGtD2oBVbicXk29NA6PEdHu9drrvffv/cP70cZs29yY7b8729tbes/thevkes20NWf11PP7busuPnqev6s91vJumNtGIHIRgVgTwPEeYGnHJgqARMiYJeyoTOoHqKIojeCNFqTYvAySwjcyFACgaCelVWUuMFGQnVoSkopBjotSom49HMTpuHOTifQNEiw0JKCDbnEm0hymspq4EVhvbSRiJvR9/@z9rEnlc0qDaJYiRQVzy@938 "Ruby – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 6 bytes
```
ƛƛ⁰O;g
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwixpvGm+KBsE87ZyIsIiIsIlsnQkFMTCcsJ0JBVCcsJ0JFQVInLCdCRUxUJywnQk9ZJywnQ0FUJywnQ09XJywnRE9HJywnR0FMJywnSEFORCcsJ0hBVCcsJ01JQ0UnLCdTSE9FJywnVE9QJywnVE9ZUycsJ1pBUCddXG5KTElCUE5aUU9BSkQsS0JGQU1aU0JFQVJPLE9BS1RNSUNFQ1RRRyxZTExTSE9FREFPR1UsU0xIQ09XWkJUWUFILE1IQU5EU0FPSVNMQSxUT1BJRllQWUFHSlQsRVpUQkVMVEVBVEFaIl0=)
## Explained
```
ƛƛ⁰O;g
ƛ # Map the first input
ƛ ; # Map for each letter in the word
⁰O # Count how many times the letter appears in the second input
g # Get the minimum
```
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 5 bytes
### taking words as list of list of characters instead of list of strings
```
ƛ⁰vOg
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwixpvigbB2T2ciLCIiLCJbW1wiQlwiLFwiQVwiLFwiTFwiLFwiTFwiXSxbXCJCXCIsXCJBXCIsXCJUXCJdLFtcIkJcIixcIkVcIixcIkFcIixcIlJcIl0sW1wiQlwiLFwiRVwiLFwiTFwiLFwiVFwiXSxbXCJCXCIsXCJPXCIsXCJZXCJdLFtcIkNcIixcIkFcIixcIlRcIl0sW1wiQ1wiLFwiT1wiLFwiV1wiXSxbXCJEXCIsXCJPXCIsXCJHXCJdLFtcIkdcIixcIkFcIixcIkxcIl0sW1wiSFwiLFwiQVwiLFwiTlwiLFwiRFwiXSxbXCJIXCIsXCJBXCIsXCJUXCJdLFtcIk1cIixcIklcIixcIkNcIixcIkVcIl0sW1wiU1wiLFwiSFwiLFwiT1wiLFwiRVwiXSxbXCJUXCIsXCJPXCIsXCJQXCJdLFtcIlRcIixcIk9cIixcIllcIixcIlNcIl0sW1wiWlwiLFwiQVwiLFwiUFwiXV1cbkpMSUJQTlpRT0FKRCxLQkZBTVpTQkVBUk8sT0FLVE1JQ0VDVFFHLFlMTFNIT0VEQU9HVSxTTEhDT1daQlRZQUgsTUhBTkRTQU9JU0xBLFRPUElGWVBZQUdKVCxFWlRCRUxURUFUQVoiXQ==)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 5 bytes
```
ċⱮⱮṂ€
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700KzUnp3LBgqWlJWm6FuuOdD_auA6IHu5setS0ZklxUnIxVOpmT7RSkKu3n2NMXohjhKdXTF6QY5CrX0yeY4ijq2dMXqRzpKOfko6CUnSMkqNnUAyQCWT4ebtCma6OIRAGSB2E5efp5-UIYYLMgrBAhkNZQY6REFYEnBUJtFEpVikW6igA)
Hmmm.
[Answer]
# [Factor](https://factorcode.org), 38 bytes
```
[ [ counts values infimum ] with map ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY49asNAFIR7nWJwkc6uQ1I9whLWhi02ClhYLpZlRUSkJ2l_ogSTi8SNGvtOvk0ilGaGYeaDOV8rY2Pnp9vP64tUzw8wIXQ2bNxn9Cb8JwQ3JMfWBbw7z65B712MX72vOWIY8ZhlKy12ikrOaS-3JWvSQpVMOQlZcvFUkFpl2TCeQFKD1E5oCMoxF1BSbQkzghlHrqnAfpZCKHxfUqzW97e7Aw6wXeIY8GGa9Pem5qpuU4sjxjq-oTU9jsv6ak3TYLOEaVr8Fw)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
mo▼m#
```
[Try it online!](https://tio.run/##yygtzv7/Pzf/0bQ9ucr///9XCnL19nMMcYzw9ApyDHIFMV09I50jHf2U/kcrOXoGKekoOfp5u4JoV8cQIAmW01Hy8/TzcgTSIF1ACmQCiApyjARSERAq0tVPKRYA "Husk – Try It Online")
```
m # map over each word in second arg
o # compose 2 functions:
▼ # get minimum of
m # mapping
# # number of occurrences in first arg
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 22 bytes
```
Min/@Map@Counts@#/@#2&
```
[Try it online!](https://tio.run/##TVFBbtswELzPM2wgJxcBem@hFbmSKFJchWSqSEEOQpA0Bho3cNVT4Le7lJsCPXABcmdnZjmv8/Ly9Dov@8f5/Pzl3O0P10U3vxXq5@/D8qvYXhfbz1fn/rg/LPfbT1@f79XLfJwfl6djbu7@u8QlY77Htx/7JY88PFwVRfGO901g6wmJ7kyLQIE9KBEbjGokv9ltyASQtxzAlLA@whvf0gV8mUMKNOJuLSP7zWmHTEul0uCqbmBa69B56VeyymJtVAq9@O4DO3zjkIwi5xBEqKpcpBKkgnGGkhC8Fm3FD1pBB8tRRGsLYe4nrp0Z0EVjGiEOBHLBhmBCNmxFG806ZMGG3RAd36YmuyhJ2YGChjZUiyeHyviMkWAm8SnfA2XJDpHZ4u8Y/nnEYKzpOY9ikKAjU1DNxyKtM2XvpxuhVsOWFXVTLDNAIGRTZxSrdFNjdC42wpqkvs30jZJhKtNIDbomC0cSE13ORHpTjf1IdZvAUyrZpZwBTZcV8meVOZCVHmsHpYxQa0QyQEuNOntd6XJJWLWxiq6s@YwRE/WbE07nPw "Wolfram Language (Mathematica) – Try It Online")
Input `[grid, {words...}]`, where both the grid and words are 1d lists of characters.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 14 bytes
```
{&/'(#'=,/x)y}
```
[Try it online!](https://ngn.codeberg.page/k#eJxdVGFv2jAQ/X6/ImLTChIUBdpNAu2DkzhgEmLqpKNQVWpE0xaVQUdSrWjafvvsxBdnIwp6duy7d2e/9zj69al/1v5w9rXbf++cfgMko18fb09/jqNH69x6H98fXsbt+8d0uxu/j0/jY+dOrbltt1uCBhFpgSV/rYTcsJnGgggaaUwSQpnGK3dFolZHDdotwgQuiQKKmJJEo3JtBSMWzUgjdiMlQkFWGt4YuJIsOirdwLLL17aGGg3udA3EcT3M7U+mGrJZEGo4j/ii5uwHetbs8l0NFjyaV+ns6sEUy29UJMwlIYYUnBPfD2PiYAdcwUJGEo5VRh73Ah4tPQzuiYDGnHseEuCULtZ0ErIl8owZm3JCBcYgoQiEYKLubcA95lFP1NSnNFzGIb1Opq2OmqiKdIgbLInARR4jEx4R5O6zqN7OBVvzKKm/CSJ5z/UgphS56hzVAJuhh0sWsAWVSXDMhRdTItyp6WV1dBe6r0Ps6yxkziJaX3EyQ0qB45P5OnZkAI6NIkEyZy51k6sJ3oswjKeceoRPrmuKU5cv106yIkh0PpXlxISzOKwvOV8wf7VYkckMryldJw4NE3lvyfrfLtbH7dR3WvGqYVjPcrywrrn9HM/V40h7UjdNMashblFFYjWyOkO5RqtYwzVZVN29lI8t34tSGEP5DEqs3zsLoA/PRfGaj/r9zeEhezrsHs/zIt28ZO+b53T/lJ1vDt/7P96yvNge9nl/cPHZ/jLs/zwcH/Lez23x3MvS/NTbZUWRHfPedt9Le+pjL8/S4+ZZHqXcaW3SPMtHAPyteH0rcis9ZtbDNn/dpafswUpza7svsqfs2Ntt8yI/B2B7tW4EpQVBaT5Q2g6UhgOl1QBIk4HSXkAeEJRzpZmUa8ttoKwDlGmAtAtkMILbQdfuqtfuDjVSnoF5lW2AMgxQVgHKJGQ2PwA177ugzKARzC4D2Y0AxhTA2AEYIwBjAWDED0b2YAQPRupgRA5G3gAoakA5gxIyGAlDJV5QsgW9CylCLVIw8vyvuqpVF1Wd3WGj0qZMoSlQaEoTmqKEphyhKURoShCa4lM1ymZKsYGKDuoDSGmBq06eL0EKCaSEQEWTfwmo1KByqqCg5AFSGI26LruXspZLWdWwvAZDWaXC+pU1/gX9Lq0b)
Takes the grid of letters as `x` (the first arg), and the list of words as `y` (the second arg).
* `(#'=,/x)`
+ `,/x` flatten the grid of letters into a single string
+ `#'=` build a dictionary mapping the unique letters to the number of times they occur
* `(...)y` index into this with the list of words
* `&/'` get the number of times the least common letter in each word appears in the grid (and implicitly return)
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 6 \log\_{256}(96) \approx \$ 4.94 bytes
```
ez1scm
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbLUqsMi5NzIRyo2IKbt6KjlRyVdJQ8gThIKVZHAcL1A2JvIHZFCIOYIKkQCNcZyIyECvlBhPyg5oBoL7AUWDgIqioIbB5YKAQqFAHWAReCqYyECEVgCkVC3QS0MZZLKcjV289RIcQxwtNLIcgxyNVPwTHE0dVTIdI50tFPCeJFAA)
#### Explanation
```
ez1scm # Implicit input
e # Map:
sc # Count of each in
z1 # Second input
m # Minimum
# Implicit output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
WS≔⁺ωιωWS⟦I⌊Eι№ωκ
```
[Try it online!](https://tio.run/##bY6xbsMwDER3foVHGUi/IBMjMTEh2TIotwJSdDCCIhHqOEFsN5/vami3cuLh3vF4uvSP060f1vV5ScNnoXi8L3OYH2k8q7IscJrSeVTtsEzquSlSuSme5Rb@h9u8zOpd99Os6jSm63JVdX9XaVPo25KtfOGrzPNRbtc1vpF0rNE5EO9xv3cBd4Ba2DF2HqEx3ljfRKPBiKXgvTEWPFF7pIPjCHVgrjySIKATK8JCAtYbNmREG6jIxeDotasAdqhtRDFgGA@@QQd7bjLihY@@6bIWzI01BCILv6m/FyGy5ZZyFKIXEwhFV7C@fA8/ "Charcoal – Try It Online") Link is to verbose version of code. Takes input as two newline-separated lists of newline-terminated strings. Explanation:
```
WS≔⁺ωιω
```
Input and flatten the grid.
```
WS
```
For each word in the list...
```
⟦I⌊Eι№ωκ
```
... output the minimum count of all of its letters in the flattened string.
Save 6 bytes by using a more awkward input format:
```
IEη⌊Eι№⪫θωλ
```
[Try it online!](https://tio.run/##NY/PboMwDMbvPAXiRKXsCXpyE1O8BIwcNqRWPaBeikRh69rt8RlJN5@@n/9@Pl/623nux2VpbsN0z3X/dc@r/iO/qLQapuH6uEYcVKrnx9rwOg9T/qnSn41Kx02M7bIcj0nWvaO0pMG5TCWZMENROA@7QKCFHEHLEKg2bCzXndGBjFj0zMbYQIzYHHDvqAtUeaKSASXOgRMrQoISyLIhg0a0CVSi67zDt7bMkpNa7exA2w4kFg3BnmuIxgqqnwMsdOC6fWYFVlNVUB4xGvlbtqr/v4LuyFKD674ILMYjiA43T8vL9/gL "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
η Word list
E Map over words
ι Current word
E Map over letters
№ Count of
λ Current letter in
θ Grid
⪫ Joined with
ω Empty string
⌊ Take the minimuim
I Cast to string
Implicitly print
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 74 bytes
```
\G(.+)¶
$1
ms`(?<=^(.+)¶.+)$
;$1
1A`
%(`\G(.)(?=(.*?\1)+)
$#2¶
A`;
O#`
1G`
```
[Try it online!](https://tio.run/##NY7BSsNgEITv8xqNkFgoxGstZZvdJMv/N1s20R9KkXjw4EEP6rP5AL5Y/EW9DMwwHzNvTx/Pr4/LcunKzbr6@kRR4@V9Lve3u4ffJEuBbY5rmnFVzj/Nqtzvys31/lJX6wrF6iaDNG9hqxl1Ny9LuheftKEY4WbUtnGkA6hxjUqTEQY2DjYkbsAeZDRjDjCR01m6qAnHUbU3EidQ9OCuLo5grCzsDaOXmMYod1MPHKgJiZzBSp0NFNHqkCvmerZhyt4pLx4xigT8Uf8XkTToSTKKZM6jkDf9Nw "Retina 0.8.2 – Try It Online") Explanation:
```
\G(.+)¶
$1
```
Flatten the grid.
```
ms`(?<=^(.+)¶.+)$
;$1
```
Append a copy of the grid to each word in the list.
```
1A`
```
Delete the original grid.
```
%(`
```
Repeat for each pair of word and flattened grid.
```
\G(.)(?=(.*?\1)+)
$#2¶
```
Count the number of times each letter in the word appears in the grid. (Note that when a letter in the word is repeated then the count is only correct for the last letter but this doesn't affect the final result.)
```
A`;
```
Delete the grid.
```
O#`
```
Sort the counts.
```
1G`
```
Keep only the first (i.e. smallest).
[Answer]
# [Perl 5](https://www.perl.org/) + `-MList::Util+(min)`, 44 bytes
```
sub{$g=pop;map{min map$g=~s/$_/$_/g,/./g}@_}
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoic3VieyRnPXBvcDttYXB7bWluIG1hcCRnPX5zLyRfLyRfL2csLy4vZ31AX30iLCJoZWFkZXIiOiIkZj0iLCJmb290ZXIiOiI7XG5wcmludCBqb2luJC8sJGYtPihARixqb2luXCJcIiw8Pik7IiwiYXJncyI6Ii1NTGlzdDo6VXRpbCsobWluKVxuLWEiLCJpbnB1dCI6IkFJUiBBTktFUiBFQVQgQ1lBTiBOSU5KQSBSQVJFIFRBWEkgVFJBWSBYUkFZIFlFTlxuUkVLTkFcblRBWElKXG5SQVJFTlxuQVRBRUlcbllDWUFOIn0=)
## Explanation
Not entirely dissimilar to other solutions, this is a function submission in Perl (unusual I know, but 1 byte shorter than [my best "standard" attempt](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiQEc9PD47c2F5IG1pbiBtYXAkLT0oKT1cIkBHXCI9fi8kXy9nLC8uL2cgZm9yQEYiLCJhcmdzIjoiLWFcbi1NTGlzdDo6VXRpbCsobWluKVxuLU01LjEwLjAiLCJpbnB1dCI6IkFJUiBBTktFUiBFQVQgQ1lBTiBOSU5KQSBSQVJFIFRBWEkgVFJBWSBYUkFZIFlFTlxuUkVLTkFcblRBWElKXG5SQVJFTlxuQVRBRUlcbllDWUFOIn0=).
Takes the last argument as a string containing the grid, and every other argument as words to find. Iterates over each word (implicitly stored in `$_`, splits (`/./g`) and `map`s over each letter, returning the number of `s///`ubstitutions replacing the letter for itself, taking the `min`imum for each word.
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 43 bytes
```
f(g,d)=[vecmin([#[1|x<-g,x==c]|c<-w])|w<-d]
```
A port of [pxeger's Haskell answer](https://codegolf.stackexchange.com/a/246193/9288).
Takes the grid as a list of characters, and the word as a list of list of characters.
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc-_DoIwEAbwV2nq0kY6uDnAcDEdCkmHhhhIaYzhXxhsCEFh4C0cXViMz-TbaBGn3zfcfbl7vNpz15zqdp6f175i-_e2IrVX0EDfyvzSWKI3ejeNPqu9MQhyM-U-GwydBp8VZl25t11je1KRY5kTrHgkIbMxJCLMrALFZWYhBi4ymx5SkJh6SLvRgaIJDchnSGMQCnsIg4z4EjjEjmX-qxQyBBdcn9PVLypInclqyiU2htLfaf-vPg)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 18 bytes
```
f:qsv^mjlnm{)gv<]}
```
[Try it online!](https://tio.run/##HYsxCoNAFAX7dwy7XEFtHvKLVfjFZ4vdIhYBEwgqGtFGPPtKtplimHntv3HY1n1IBVBU1dKnd7luRz99x3k6H5@jfl4pmXRKeAbXwmiioKc4xCZSAToDtROD0CM7ddoyt3mDN0aEP6LoDQ "Burlesque – Try It Online")
```
f: # Count frequency (as {count val}) in grid
qsv # Save in global map
^m # Apply to each frequency
j # Swap
ln # Split into lines
m{ # Map over words
)gv # Map over each letter get value from global map
<] # Minimum
}
```
] |
[Question]
[
## The task
Given the set
$$S = \left[{1,2,3,4,5,6,7,8}\right]$$
and an integer
$$0 \leq N < 2^{|S|}$$
find the Nth subset.
## Input/Output
*N* is given as an unsigned integer on stdin. You must print the Nth subset in a format suitable for your language (this may include `[1,2,3]`,`{1,2,3}`,`[1, 2, 3]`,`1 2 3`,`1,2,3` etc. for as long as it is a human readable *text* format).
## A little bit about subsets
There is a relationship between subsets and numbers in base two. Each digit
$$d\_{i}$$ specifies whether the *i*th element of the set is within the subset.
For example *00000000* would be the empty set and *10000001* is the subset containing `[1,8]` (the last and first element). You get the Nth subset by converting the number into base 2 and then the subset includes all elements where $$d\_{i} > 0$$. The 3rd subset (3 = 00000011) thus contains `[1,2]`. The rightmost digit is digit #0. It's ok to print `[2,1]`. The set does not have to be sorted.
**Addendums:**
Yes, the set is fixed to `1..8`. The set is not part of the input. Input is just *N*.
Yes, you may use alternate input forms.
All expected outputs for all *N*: <https://tio.run/##SyotykktLixN/f/fyNS02qIoP8soJd1CwSAg2kY32LPWPaoqs7jg/38A>
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
BUT
```
[Try it online!](https://tio.run/##y0rNyan8/98pNOS/kamZwsMd2xQObVU4ukfhcPujpjUKWSDiUeM2Bff/AA "Jelly – Try It Online")
### How it works
```
BUT Main link. Argument: n
B Binary; convert n to base 2.
U Upend; reverse the resulting array, so it starts with the LSB.
T Truth; find all 1-based indices of set bits.
```
[Answer]
# [R](https://www.r-project.org/), ~~52~~ 26 bytes
```
which(intToBits(scan())>0)
```
[Try it online!](https://tio.run/##K/r/vzwjMzlDIzOvJCTfKbOkWKM4OTFPQ1PTzkDzv5Gx8X8A "R – Try It Online")
Converts the input to its bits and returns the 1-based indices of where they are `TRUE`. That makes this a port of [Dennis' Jelly answer](https://codegolf.stackexchange.com/a/176463/67312).
Returns `integer(0)`, the empty list of integers, for input of `0`.
[Answer]
# [Python 2](https://docs.python.org/2/), 40 bytes
```
lambda x:[i+1for i in range(8)if x>>i&1]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUaHCKjpT2zAtv0ghUyEzT6EoMS89VcNCMzNNocLOLlPNMPZ/QVFmXolCmkZmXkFpiYam5n8jI3MA "Python 2 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 33 bytes
```
(1..*Zxx*.base(2).flip.comb).flat
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfw1BPTyuqokJLLymxOFXDSFMvLSezQC85PzcJxEws@W/NxVWcWKmQpmGgaQ1lGcNZhkaWcLaRMVD8PwA "Perl 6 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 42 bytes
```
f=lambda n,k=1:n*[k]and n%2*[k]+f(n/2,k+1)
```
[Try it online!](https://tio.run/##FcsxDoMgAAXQuT3FX4igmEaaOpjoRUwHGkUN9mtQh54e7faWt/72caGJ0dWz/X46C2pfFxXT1r8tO1CYPzMn@TDaZ4WKbgkgJiJYDr00r1JV99saJu5IxPNA3kBsCQQkNa6oVDwB "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~55~~ 54 bytes
```
s n=[x|(x,d)<-zip[8,7..]$mapM(pure[0,1])[1..8]!!n,d>0]
```
Outputs the set in reversed order, [try it online!](https://tio.run/##HYyxDoIwAAV3v@JBGCCUBhZlABZXnRxrhyY0QKSFtCUQ479X6/Zyd3mjsC85z95b6JYdn/QgfdYU72llNblQyhMl1nu6bkayklQ8YxWlNY8iTfqu5F6JSaPFsIDCSNGjbRoM0l0X7aR2FvsojTwhFCEMb0ifquiwbu7hzE0jgR2XHQp5jhg/E4f1Z6mFyjKwklLNfXX@Ag "Haskell – Try It Online")
### General version, 56 bytes
This will work for sets larger than \$\{i\}\_{i=1}^8\$:
```
s n=[x|(x,d)<-zip[n,n-1..]$mapM(pure[0,1])[1..n]!!n,d>0]
```
[Try it online!](https://tio.run/##DcixCsMgFAXQX3mBDgkY0XbVLp37BeIg@Gilya2ohVDy7ybDWc471A8vS@@VYN22j5uIk5n/KTsIzFpKf1lDfo75V9gpof3kzoQfBoh4V76vIYEs5ZLQSFI9FQ6RrDH04vb4ojFa7Vpdbwc "Haskell – Try It Online")
## Explanation
The term `mapM (pure [0,1]) [1..n]` generates the list (`n=4`) `[[0,0,0,0],[0,0,0,1],[0,0,1,0],..,[1,1,1,1]]` - ie. the binary representations of `[0..2^n-1]`. Indexing into it with `n` gives us the binary representation of `n`.
Now we can just `zip` it with the reversed numbers `[1..n]` and only keep the elements where the binary-digit is non-zero:
```
[ x | (x,digit) <- zip [n,n-1,..1] binaryRepN, digit > 0 ]
```
[Answer]
# [K4](http://kx.com/download/), 7 bytes
**Solution:**
```
1+&|2\:
```
**Example:**
First 10...
```
q)k)(1+&|2\:)@'!10
`long$()
,1
,2
1 2
,3
1 3
2 3
1 2 3
,4
1 4
```
**Explanation:**
```
1+&|2\: / the solution
2\: / convert to base-2
| / reverse
& / indices where true
1+ / add 1
```
[Answer]
## MATLAB/[Octave](https://www.gnu.org/software/octave/), ~~31~~ ~~29~~ 27 bytes
```
@(n)9-find(dec2bin(n,8)-48)
```
* reduced of 2 bytes thanks to [alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha)
* reduced of 2 bytes thanks to [Giuseppe](https://codegolf.stackexchange.com/users/67312/giuseppe)
[Try it online!](https://tio.run/##NcndCkBAEEDhV5m7nSk2NspPynvIBXa35sKQxesvJXdf52zLOd0ueuhAax17FKpTz2LRusXMLChJRWlRUfTbAdxljSlLsBx2HORaTTgPZEpANaBGar/j3/RbqVdObMwf)
[Answer]
# Japt, 7 bytes
```
ì2 Ôi ð
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=7DIg1Gkg8A==&input=ODg=)
```
ì2 :Convert to base-2 digit array
Ô :Reverse
i :Prepend null element
ð :0-based indices of truthy elements
```
---
```
¤¬²Ôð¥1
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=pKyy1PClMQ==&input=ODg=)
```
¤ :Convert to base-2 string
¬ :Split
² :Push 2
Ô :Reverse
ð :0-based indices of elements
¥1 : Equal to 1
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
`fN↔ḋ
```
Takes input as command-line argument not on *stdin* ([I hope this is ok](https://codegolf.stackexchange.com/questions/176460/nth-subset-of-a-set#comment424937_176460)), [try it online!](https://tio.run/##yygtzv7/PyHN71HblIc7uv///28GAA "Husk – Try It Online")
## Explanation
```
`fN↔ḋ -- example input: 6
ḋ -- convert to binary: [1,1,0]
↔ -- reverse: [0,1,1]
` -- flip the arguments of
fN -- | filter the natural numbers by another list
-- : [2,3]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
↓⭆⮌↨N²×ιI⊕κ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMPKJb88T0chuATIS/dNLNAISi1LLSpO1XBKBBKeeQWlJX6luUmpRRqaOgpGmkAiJDM3tVgjU0fBObG4BKgiuSg1NzWvJDVFI1sTBKz//zcyNv6vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. If printing the answer horizontally without spaces is acceptable then the first character can be removed. Explanation:
```
N Input as a number
↨ Converted to base
² Literal 2
⮌ Reversed
⭆ Map over bits and join
κ Current index (0-indexed)
⊕ Incremented
I Cast to string
ι Current bit
× Repeat string
↓ Print vertically
```
[Answer]
# JavaScript (ES6), 37 bytes
[+4 bytes](https://tio.run/##DYzBDoIwEAXvfMU70W4WlXrgAFa@hSAlNWSXUOLF@O21p8kcZt7TZ0rzEffzIvpacg7eShO9I/@U0UrtxsgGpjeGOFi53ZvIjormoIcVeLQDBA@4rpCZ8K2AWSXptlw3XcsOJSSqfvkP) if a separator is mandatory
[+3 bytes](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfT1lDT1i7PXiNPzdA@Wicz1kpdXVM7TSNP30gnU9tQE8j9n5ZfpJGnYKtgYK2Qp2CjYGgGpLW1NRWquRQUkvPzivNzUvVy8tOBpikANWpqctX@BwA) if this separator is a comma and a leading comma is allowed
```
f=(n,i=1)=>n?(n&1?i:'')+f(n/2,i+1):''
```
[Try it online!](https://tio.run/##DYw7DsIwEAV7n@JVxCvngykoII7PEiUxMrJ2kYNoopzduBpNMfOef/O@5Pj5dizrVkpwmtvoLLmJveaL9fHRNGSC5uHWRmOpagmSNcPh@gRjhL1XGkM4FLAI75K2PsmrrlBDInWWPw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 21 bytes
```
{1 X+grep $_+>*%2,^8}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/2lAhQju9KLVAQSVe205L1UgnzqL2vzVXcWKlQpqGSrymQlp@kYKBjoKxjoKhkaWOgpGxsfV/AA "Perl 6 – Try It Online")
Alternative:
```
{grep $_*2+>*%2,1..8}
```
[Answer]
# Common Lisp, 57 bytes
```
(lambda(x)(dotimes(i 7)(format(logbitp i x)"~a "(1+ i))))
```
[Try it online!](https://tio.run/##DcQxDoAgDAXQqzRMv3Fi0fMUUdMEhEAHJq@OvOGdSXudqE1fI0wkySEKBiMW03x1KB2Mu7QshlSeoFZJabD7hBz8RsrL3P3qBw)
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
s n=[x+1|x<-[0..7],odd$div n$2^x]
```
[Try it online!](https://tio.run/##HY2xDoIwFEV3v@KGMECQRhx0KS6uOjliTZq0oUT6SmgVBv@9Wrebc05yjfRPPY4xelDbrVXzWXnd7Rg7iq1TKlfDG5TvH6uIVg6EFr0Dw6ylQss5eh3OjoKm4LEYPesNUpFCK6crirutT5he4RbmCyGHN26BRVUhw89kaf1Z4WHLEumbRGwOXw "Haskell – Try It Online")
---
**37 bytes**
```
concat.(mapM(\i->[[],[i]])[8,7..1]!!)
```
[Try it online!](https://tio.run/##HYy7DoIwAEV3v@JCHNoAjSzqACyuOjmWDk2tQKSP0Br@3ipuN@ec3FGGl57nFNo@KWeVjIwY6W@kn6qOc1HySQjKz@WJsVpkGU1GThYtBgeGRcsH2qbBoOPF2ahtDFhHvegdtmILtzeQ3lQd/Dve43K12COMboVBUSDHz@Tb@jMSYCgFPzBmRaqPH/Wc5RBSpbz/Ag "Haskell – Try It Online")
Test cases from nimi.
[Answer]
# [J](http://jsoftware.com/), 13 10 bytes
```
-3 bytes thanks to Bubbler
1+I.@|.@#:
```
[Try it online!](https://tio.run/##y/qfVmyrp2CgYKVg8N9Q21PPoUbPQdnqvyaXkp6CepqtnrqCjkKtlUJaMRcXV2pyRr6CsZGCoZmKjkasdZqmgpqdQqaekanZfwA "J – Try It Online")
[Answer]
# Japt, 7 bytes
```
¢Ô¬ðÍmÄ
```
[Test it online](https://ethproductions.github.io/japt/?v=1.4.6&code=otSs8M1txA==&input=MTU=)
---
# Japt, 7 bytes
```
¤Ôð1 mÄ
```
[Test it online](https://ethproductions.github.io/japt/?v=1.4.6&code=pNTwMSBtxA==&input=MTM=)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 47 bytes
```
x=>{for(int y=0;y<8;)if((1&x>>y++)>0)Print(y);}
```
[Try it online!](https://tio.run/##RYuxCsIwFEX3fsWjg7xHVdpFxLQBBzcHcXEQhxoSfaAppBUSSr89xi5OF845V/Ur1XPcq4E7W7MdJBhoom/kaDqHCUBoShHqrSA2iNXCSxmKgmRJJ5c0BhJTFFmWct2qJ8wfD2zhYD9v7dr7S6/PrX1oLJfVhgjGDODieNBHthp9ke@uOYkEDfp5/zK//cwUvw "C# (Visual C# Interactive Compiler) – Try It Online")
Looks similar to the Java solution now, although I came up with mine independently.
[Answer]
## Python 3.6, 58 bytes
```
f=lambda n:[8-v for v,i in enumerate(f'{n:08b}')if int(i)]
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 32 bytes
```
Pick[r=Range@8,BitGet[#,r-1],1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/A/IDM5O7rINigxLz3VwULHKbPEPbUkWlmnSNcwVscwVu2/S350QFFmXkl0noKunUJadF5srI5CdZ6OgoGOgpGpaW3sfwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 31 bytes
```
n->[x|x<-[1..8],bittest(n,x-1)]
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y66oqbCRjfaUE/PIlYnKbOkJLW4RCNPp0LXUDP2f1p@kUYeUKGBjoKRqamOQkFRZh5QVkFJQdcOSKRp5Glqav4HAA "Pari/GP – Try It Online")
[Answer]
# APL+WIN, 13 bytes
Prompts for N:
```
((8⍴2)⊤⎕)/⌽⍳8
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5raFg86t1ipPmoawlQRlP/Uc/eR72bLf4DJf@ncRkaAwA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
((8⍴2)⊤⎕) prompt for N and convert to binary
/⌽⍳8 generate a vector from 1 to 8, reverse and select integers according to 1s in binary
```
Returns subset in reverse order
[Answer]
## Burlesque - 8 bytes
```
8roR@j!!
```
[Try it online.](https://tio.run/##SyotykktLixN/a9jZGz836IoP8ghS1Hx/38A)
[Answer]
# Oracle SQL, 77 bytes
```
select*from(select rownum r,value(p)from t,table(powermultiset(x))p)where:n=r
```
Test in SQL Plus
```
SQL> var n number
SQL> exec :n:=67;
PL/SQL procedure successfully completed.
SQL> with t as (select ku$_vcnt(1,2,3,4,5,6,7,8) x from dual)
2 select*from(select rownum r,value(p)from t,table(powermultiset(x))p)where:n=r
3 /
67
KU$_VCNT('1', '2', '7')
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 8 bytes
```
â^mÉ┤\*─
```
[Try it online!](https://tio.run/##y00syUjPz0n7///worjcw52PpiyJ0Xo0peH/f3NjhWhDHSMdYx0THVMdMx1zHYtYAA "MathGolf – Try It Online")
## Explanation
```
â Convert first input to binary list
^ Zip with [1,2,3,4,5,6,7,8] (other input)
mÉ Map 2D array using the next 3 instuctions
┤ Pop from right of array
\* Swap top two elements and repeat array either 0 or 1 times
─ Flatten to 1D array
```
## Alternate output format
With a more flexible output format (that I personally think looks quite good) I can come up with a 6-byter:
```
â^É┤\*
```
Instead of mapping, I use the implicit for-each, and I skip the flattening. Output looks like this:
```
[1][2][][4][5][6][7][]
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 31 bytes
```
->n{n.times{|a|n[a]>0&&p(-~a)}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vOk@vJDM3tbi6JrEmLzox1s5ATa1AQ7cuUbO29r9CWrSFaSwXkDI0N4j9DwA "Ruby – Try It Online")
[Answer]
# [F# (Mono)](http://www.mono-project.com/), 45 bytes
```
let m x=Seq.where(fun y->x>>>y-1&&&1>0)[1..8]
```
[Try it online!](https://tio.run/##SyvWzc3Py///Pye1RCFXocI2OLVQrzwjtShVI600T6FS167Czs6uUtdQTU3N0M5AM9pQT88i9n9afpFChUJmnkK0gZ6eoWmsQko@l0JBUWZeSVqegpKqo5KCBtAwzf8A "F# (Mono) – Try It Online")
I also implemented a generic/recursive function, but its pretty ugly and the byte count is a ***lot*** larger...
# [F# (Mono)](http://www.mono-project.com/), 107 bytes
```
let rec g y i=
if y>0 then seq{
if y%2>0 then yield i
yield!g(y/2)(i+1)
}else Seq.empty
let f x=g x 1
```
[Try it online!](https://tio.run/##NcxBCsIwFATQfU4xFgoJYm0LLlvwDC7Flf2pH9KkTbNoEM8eY8HVDI9h9HqanHUpGQrw9MSICO4EWCP2NcKLLFZa3gI7le0fI5MZwNn3dhhlPLdK8rFRAh8yK@FGS0XTHKL4vWts3YgNTdLO52SLe11VzeWBwQnMnm3QFkV5LSDzWKUv "F# (Mono) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
bRSƶ0K
```
[Try it online](https://tio.run/##yy9OTMpM/f8/KSj42DYD7///jYwA) or [verify all possible test cases](https://tio.run/##yy9OTMpM/f@oqdHNz15J4VHbJAUle7//SUHBx7YZeP/X@Q8A).
**Explanation:**
```
b # Convert the (implicit) integer input to binary
# i.e. 22 → "10110"
R # Reverse it
# i.e. "10110" → "01101"
S # Convert it to a list of 0s and 1s
# i.e. "01101" → ["0","1","1","0","1"]
ƶ # Multiply each with its 1-indexed index
# i.e. ["0","1","1","0","1"] → [0,2,3,0,5]
0K # Remove all 0s (and output implicitly)
# i.e. [0,2,3,0,5] → [2,3,5]
```
[Answer]
# Java 8, 58 bytes
```
n->{for(int i=0;i<8;)if((1&n>>i++)>0)System.out.print(i);}
```
[Try it online.](https://tio.run/##dU/BCoJAEL37FYOH2EWUCopoc/8gLx6rw7ZpjNkqugkhfrvNWocgmsMMM@/x3ptCdSosLrdRl6ptYa/Q9B4AGps1udIZJG4F6Cq8gGZ0B8MFnQaPWmuVRQ0JGIhhNKHs86qZSBjPBe42gmPO2GJmpMQg4HLO02drs3tUPWxUN8RkyMUwCqdWP84lqX1EJ8c75WGpJeL1cALF32G@TQB3y9WaBsm/UYBfj8DfHq0/BXdlIu18/9BLwz7YMD06jC8)
**Explanation:**
```
n->{ // Method with integer as parameter and no return-type
for(int i=0;i<8;) // Loop `i` in the range [0,8):
if((1&n>>i++)>0) // If 1 AND `n` bitwise right-shifted to `i` is larger than 0
// (with `i` increased by 1 afterwards with `i++`)
System.out.print(i);} // Print `i+1`
```
] |
[Question]
[
A [piggy bank](https://en.wikipedia.org/wiki/Piggy_bank) is a container used to collect coins in. For this challenge use the four US coins: [quarter, dime, nickel, and penny](https://en.wikipedia.org/wiki/Coins_of_the_United_States_dollar).
# Challenge
Your challenge is to create an electronic piggy bank. Write a program (or function) that when run (or called), outputs (or returns) the count of each coin you have, as well as the total amount the coins amount to.
# Input
A string, array, etc...(your choice) of the coins into your piggy bank(case insensitive).
```
Q - Quarter(Value of 25)
D - Dime(Value of 10)
N - Nickel(Value of 5)
P - Penny(Value of 1)
```
# Output
The count of coins from the input and the total amount, separated by the non-integer delimiter of your choice. (The order in which you output the coin totals does not matter, but the total coin value(sum) must be the last element)
# Examples
```
Input -> Output
P -> 1,0,0,0,1 or 0,0,0,1,1 or 0,0,1,0,1 or 1,1
N -> 0,1,0,0,5
D -> 0,0,1,0,10
Q -> 0,0,0,1,25
QQQQ -> 0,0,0,4,100
QNDPQNDPQNDP -> 3,3,3,3,123
PPPPPPPPPP -> 10,0,0,0,10
PNNDNNQPDNPQND -> 3,6,3,2,113
```
# Rules
[Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are not allowed.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes for each language wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 73 bytes
-3 bytes thanks to @Rod
```
C=map(input().count,'QDNP')
print C+[sum(map(int.__mul__,C,[25,10,5,1]))]
```
[Try it online!](https://tio.run/##JcqxCoAgEADQva9wU@mIChqbbI6cI0QqKMhT8hz6egta3vTCQ4fHNmfVOxvEiSGRkNXqExJwPYwTl0W4TySmyjkmJ/5GlTEuXcaAgrntoKnhY5FyyZlrPY3M4saidzuj28aDvw "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 63 bytes
```
a,b,c,d=map(input().count,'PNDQ')
print a,b,c,d,a+b*5+c*10+d*25
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P1EnSSdZJ8U2N7FAIzOvoLREQ1MvOb80r0RHPcDPJVBdk6ugKDOvRAGqTidRO0nLVDtZy9BAO0XLyPT/f6AyPxc/v8AAF7@AQD8XdQA "Python 2 – Try It Online")
---
# [Python 2](https://docs.python.org/2/), 63 bytes
```
l=map(input().count,'PNDQ')
a,b,c,d=l
print l+[a+b*5+c*10+d*25]
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8c2N7FAIzOvoLREQ1MvOb80r0RHPcDPJVBdkytRJ0knWSfFNoeroCgzr0QhRzs6UTtJy1Q7WcvQQDtFy8g09v9/oGI/Fz@/wAAXv4BAPxd1AA "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~28~~ 27 bytes
```
1 5 10 25(⊢,+.×)'PNDQ'+.=¨⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRDBVMFQwMFI1ONR12LdLT1Dk/XVA/wcwlU19azPbTiUVcTUJmCjnqAOheI8oNQLhAqEEoBAZTl5xIAwxCRADiA8v38XPz8AgNc/ECK1AE)
Tacit function. Takes input as a vector in the format `,'<input>'`.
Thanks to ngn for one byte!
### How?
```
1 5 10 25(⊢,+.×)'PNDQ'+.=¨⊂ ⍝ Main function, tacit.
⊂ ⍝ Enclose
¨ ⍝ Each character of the input
+.= ⍝ Sum the number of matched characters
'PNDQ' ⍝ From this string
1 5 10 25( +.×) ⍝ Multiply the values with the left argument, then sum them.
⊢, ⍝ And append to the original vector of coins.
```
[Answer]
# [R](https://www.r-project.org/), ~~70~~ 69 bytes
```
function(n)c(x<-table(factor(n,c("P","N","Q","D"))),x%*%c(1,5,25,10))
```
[Try it online!](https://tio.run/##LcyxCsMgEIDhvU8hlsBdMdAUsmV0PuIcMqSiJRBU9AJ5eyu0w799/Ll6MfXVn8HyHgMEtHBNPW/vw4HfLMcMQVmQs1SSWqalJSKqq3t0FgY1qteohidi9dCg@aNfiDcPhXNJx87tQqSJzKxpNqSbkLgsw7qiuAsfs3BbcSJ6wa7wHj4inTnF4kr9Ag "R – Try It Online")
Takes input as a vector of individual characters. Converts them to `factors` and `tabulate`s them, then computes the values with a dot product.
For ease of testing purposes, I've added a way to convert from test cases above to the input that the function is expecting.
This barely beats out storing the coin names as vector `names`, which means that the approach below would be likely be golfier if we had more coin types:
# [R](https://www.r-project.org/), ~~71~~ 70 bytes
```
function(n)c(x<-table(factor(n,names(v<-c(P=1,N=5,Q=25,D=10)))),x%*%v)
```
[Try it online!](https://tio.run/##TcqxCsMgFEDRvV/xsASexUBTyBY3Z9E5ZLCiJZCqqAn5e5uxF852c/Mw9c3vwdY1BgzU4jn11bw3h97YGjMGFszXFTym3qLiA5N8ZJq/Rib48KRX7Owe3UGbR4tEE/aH0pvHUnNJ21qRKCmFlFoJqbQU10HoPA/LQuEOPmZwpjiIHqordQ0fSHtOsbjSfg "R – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
ċЀ“PNDQ”µæ.“¢¦½ı‘ṭ
```
[Try it online!](https://tio.run/##AUEAvv9qZWxsef//xIvDkOKCrOKAnFBORFHigJ3CtcOmLuKAnMKiwqbCvcSx4oCY4bmt////IlBOTkROTlFQRE5QUU5EIg "Jelly – Try It Online")
### How it works
```
ċЀ“PNDQ”µæ.“¢¦½ı‘ṭ Main link. Arguments: s (string)
Ѐ“PNDQ” For each char in "PNDQ":
ċ Count the occurrences of the char in s.
Collect the results in an array. Call this a.
µ Start a new monadic chain. Argument: a
æ. Take the dot product of a with
“¢¦½ı‘ [1, 5, 10, 25].
ṭ Tack this onto the end of a.
```
[Answer]
# JavaScript (ES6), ~~63~~ 61 bytes
*Saved 2 bytes thanks to Shaggy*
Takes input as an array of characters. Outputs `P,N,D,Q,total`.
Inspired by [ovs' Python answer](https://codegolf.stackexchange.com/a/160699/58563).
```
a=>eval(a.join`++,`+`++,[P,N,D,Q,P+N*5+D*10+Q*25]`,P=N=D=Q=0)
```
[Try it online!](https://tio.run/##fdBBC4IwFMDxe59it6lba7Pstk47P7azCA7TUMRFRV/ftLAMnI@33X784TX2ae/Frb4@tp07l30leytP5dO2gWWNq7ucEJqT8U81BaqooZpAlBAVCU5MFCdZTrUEqaSRPOwL191dW7LWXYIqSBljWGM0nywM0W6HUiQo4tMKlG0WKHjoKCaaLFPlp18t@LI1q/bDY0/XDIPX7GHs@sKg9PTwDO/pb0W8X8b6O/j/znx@aE9ZAygAoxWMcTwvH9/ZeLBiKPcv "JavaScript (Node.js) – Try It Online")
---
# Original answer, 73 bytes
Takes input as an array of characters. Outputs `Q,D,N,P,total`.
```
a=>a.map(c=>o[o[4]+='521'[i='QDNP'.search(c)]*5||1,i]++,o=[0,0,0,0,0])&&o
```
[Try it online!](https://tio.run/##fZG9DsIgFEZ3n4LJ21rEUq0bTp0JnQkDwVZrVJrWOPnulfhTO4Af32U7OYF70nfdm65pb8ur3VdDzQbNdppcdBsZtrPSyo1KGOQZBdkwKAsugPSV7swxMrFa5I8HxY1KEmyZTPHnqHg@t4Ox196eK3K2h6iOJCEEBKBpVByj1QpJlOJPqStSMw/K/6L0ded@tAijdBSnfrYMsCPomgW8pQt42M2EpWlIzAvxHZjAa/wrzdZ@WIyBwD//ebLgvOC8FG7XTg4jnL2c27eZOvPwBA "JavaScript (Node.js) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~22~~ 20 bytes
```
!'PNDQ'=Xst[l5X25]*s
```
[Try it online!](https://tio.run/##y00syfn/X1E9wM8lUN02orgkOsc0wsg0Vqv4/3@goJ@Ln19ggItfQKCfizoA) Or [verify all test cases](https://tio.run/##y00syfmf8F9RPcDPJVDdNqK4JDrHNMLINFar@L9BcoRLyH/1AHUudT8gdgHiQBAGAhDl5xIAw0BuAByAOH5@Ln5@gQEufiBpdQA).
### Explanation with example
Consider input `'PNNDNNQPDNPQND'` as an example. The stack contents are shown upside down, i.e. the top element appears below.
```
! % Implicit input: string (row vector of chars). Transpose into a
% column vector of chars
% STACK: ['P';
'N';
'N';
'D';
'N';
'N';
'Q';
'P';
'D';
'N';
'P';
'Q';
'N';
'D']
'PNDQ' % Push this string (row vector of chars)
% STACK: ['P';
'N';
'N';
'D';
'N';
'N';
'Q';
'P';
'D';
'N';
'P';
'Q';
'N';
'D'],
'PNDQ'
= % Implicit input. Test for equality, element-wise with broadcast
% STACK: [1 0 0 0;
0 1 0 0;
0 1 0 0;
0 0 1 0;
0 1 0 0;
0 1 0 0;
0 0 0 1;
1 0 0 0;
0 0 1 0;
0 1 0 0;
1 0 0 0;
0 0 0 1;
0 1 0 0;
0 0 1 0]
Xs % Sum of each column
% STACK: [3 6 3 2]
t % Duplicate
% STACK: [3 6 3 2],
[3 6 3 2]
[l5X25] % Push array [1 5 10 25]
% STACK: [3 6 3 2],
[3 6 3 2],
[1 5 10 25]
* % Multiply, element-wise
% STACK: [3 6 3 2],
[3 30 30 50]
s % Sum
% STACK: [3 6 3 2],
113
% Implicitly display
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~25~~ 22 bytes
*Saved 3 bytes thanks to @Shaggy*
```
`p˜q`¬£èX
pUí*38#éìH)x
```
[Test it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=YHCYcWCso+hYCnBV7SozOCPp7EgpeA==&input=InBubmRubnFwZG5wcW5kIg==) Takes input in lowercase
### Explanation
```
`p˜q`¬ Split the compressed string "pndq" into chars, giving ["p", "n", "d", "q"].
£ Map each char X to
èX the number of occurrences of X in the input.
<newline> Set variable U to the resulting array.
Uí* Multiply each item in U by the corresponding item in
38#é 38233
ìH converted to base-32, giving [1, 5, 10, 25].
x Take the sum.
p Append this to the end of U.
Implicit: output result of last expression
```
[Answer]
## Excel (Polish language version), 150 bytes
The input is in A1. The formulas are in cells `B1`-`F1`:
```
cell formula
------------------------------
B1 =DŁ(A1)-DŁ(PODSTAW(A1;"Q";""))
C1 =DŁ(A1)-DŁ(PODSTAW(A1;"D";""))
D1 =DŁ(A1)-DŁ(PODSTAW(A1;"N";""))
E1 =DŁ(A1)-DŁ(PODSTAW(A1;"P";""))
F1 =B1*25+C1*10+D1*10+E1
```
resulting in output of number of quarters, dimes, nickels, pennys and the sum in cells `B1`, `C1`, `D1`, `E1` and `F1` respectively.
**English language version (162 bytes):**
```
cell formula
------------------------------
B1 =LEN(A1)-LEN(SUBSTITUTE(A1;"Q";""))
C1 =LEN(A1)-LEN(SUBSTITUTE(A1;"D";""))
D1 =LEN(A1)-LEN(SUBSTITUTE(A1;"N";""))
E1 =LEN(A1)-LEN(SUBSTITUTE(A1;"P";""))
F1 =B1*25+C1*10+D1*10+E1
```
[Answer]
# APL+WIN, ~~33~~ 27 bytes
5 bytes saved thanks to Adam
Prompts for screen input of coin string.
```
n,+/1 5 10 25×n←+⌿⎕∘.='PNDQ'
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~30~~ ~~26~~ ~~22~~ ~~21~~ 19 bytes
```
X5T25)s.•50†•S¢=*O=
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/wjTEyFSzWO9RwyJTg0cNC4B08KFFtlr@tv//F@TlpeTlFRak5BUUAgA "05AB1E – Try It Online")
---
```
X # Push 1.
5 # Push 5.
T # Push 10.
25 # Push 25.
)s # Wrap stack to array, swap with input.
.•50†• # Push 'pndq'.
S # Push ['p','n','d','q'] (split).
¢ # Count (vectorized).
= # Print counts, without popping.
* # Multiply counts by [1,2,10,25]
O # Sum.
= # Print.
```
---
# Dump:
```
Full program: X5T25)s.•50†•S¢=*O=
current >> X || stack: []
current >> 5 || stack: [1]
current >> T || stack: [1, '5']
current >> 2 || stack: [1, '5', 10]
current >> ) || stack: [1, '5', 10, '25']
current >> s || stack: [[1, '5', 10, '25']]
current >> . || stack: [[1, '5', 10, '25'], 'pnndnnqpdnpq']
current >> S || stack: [[1, '5', 10, '25'], 'pnndnnqpdnpq', 'pndq']
current >> ¢ || stack: [[1, '5', 10, '25'], 'pnndnnqpdnpq', ['p', 'n', 'd', 'q']]
current >> = || stack: [[1, '5', 10, '25'], [3, 5, 2, 2]]
[3, 5, 2, 2]
current >> * || stack: [[1, '5', 10, '25'], [3, 5, 2, 2]]
current >> O || stack: [[3, 25, 20, 50]]
current >> = || stack: [98]
98
stack > [98]
```
Printed Output:
```
[3, 25, 20, 50]\n98 or [P, N, D, Q]\n<Sum>
```
Because something was printed, the ending stack is ignored.
[Answer]
# [J](http://jsoftware.com/), 29 bytes
```
1 5 10 25(],1#.*)1#.'PNDQ'=/]
```
[Try it online!](https://tio.run/##TYoxC4MwFIR3f8Vhh1cljUbIIjj56FQeL@5OpVJc/P9TjIOagzu@O26NpaUFQw@CQYs@@WUxTp93dPBwLTr/nI172LpKQSocaGjmWBUoft//hgWGlG6WjDnjcDGFpKwJ6@l71UvZJsIiQVmOM8Ud "J – Try It Online")
## Explanation:
`'PNDQ'=/]` creates an equality table
```
'PNDQ' =/ 'PNNDNNQPDNPQND'
1 0 0 0 0 0 0 1 0 0 1 0 0 0
0 1 1 0 1 1 0 0 0 1 0 0 1 0
0 0 0 1 0 0 0 0 1 0 0 0 0 1
0 0 0 0 0 0 1 0 0 0 0 1 0 0
```
`1#.` finds the sum of each row of the table, thus the number of occurences of each value
```
1#. 'PNDQ' =/ 'PNNDNNQPDNPQND'
3 6 3 2
```
`1#.*` finds the dot product of its left and right argument
```
1 5 10 25(1#.*)3 6 3 2
113
```
`],` appends the dot product to the list of values
```
1 5 10 25(],1#.*)1#.'PNDQ'=/] 'PNNDNNQPDNPQND'
3 6 3 2 113
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~163~~ 136 bytes
Thanks to @raznagul for saving alot of bytes there!
```
n=>{var m="";int c=0,i=0,k=0;for(var v=new[]{1,5,10,25};i<4;m+=k+",",c+=k*v[i++],k=0)foreach(var x in n)k+=x=="PNDQ"[i]?1:0;return m+c;}
```
[Try it online!](https://tio.run/##pZNBa4MwFMfP81M8vFRnJnasl9l0h5bt0ollhx3EQ8jSNlQjJKnrED@7i5stdbCtYOAP7yX5/94L5FF1QwvJGpoRpSCWxUaSHCrrSmmiOYWy4G/wTLhwlJZcbJIUiNwo11yxXj6UZrn/uBd02sXzIssY1bwQyn9igklO/SVXekq3RM4QfENmsAbcCDyrSiIhx7YdcqGB4gBxox0OwnUhnfawxIK9J2k1RhM0DtDtpA759C7MPbzzbGQjaoLrMuGel7Y@1/gYodsv7wG4AOHuPHzA2I6jxcpOePowvg9CyfReCsg9GtZNaFlwtlqrZkrPiWIKMJgG4KLnJWmPU/Wydl1MqkbxqEYwBBANBSyGAlYGMMyPzjScFRktjOKO@Xs@rFbcMf/W8BrRWc/HeNXxj3v9t9W9kvWPf9@NDjjHAWjH5zQI7j9/@9S4UEXG/FfJNVtywZy10zJcN@wXt6yr2qqbTw "C# (.NET Core) – Try It Online")
---
Old version:
```
n=>{var v=new[]{1,5,10,25};string l="PNDQ",m="";int c=0,i,j,k;for(i=0;i<4;i++){for(j=0,k=0;j<n.Length;j++)k+=n[j]==l[i]?1:0;m+=k+",";c+=k*v[i];k=0;}m+=c;return m;}
```
[Try it online!](https://tio.run/##hVE9T8MwEJ3Jrzh5SoipUkQXXJehEVOJUjEwRBki46bOhyPZbhCK8tuDQ0shUImTfLbfez77@Zi@YY3iA6syrSFWTa6yGjrnSpvMCAZtI17hKRPS1UYJmScpZCrXnpU4z@/a8Hr2eJBseWQxHOcV7IAOkq66NlPQUsnfkrSb4wWeB/h20ZOjDCqK4ijcIlxThIiQBhgNsMAFLsmuUa6gARHLOyJ83@tGoLB0acFiKWcbLnOzJ4XlSp/KpEgprRKRPszvA1L7tPQRRoTZxXVrYTKe6y3OiOLmoCTUpB@I48CPOJs0XJt1prkGCvb1Z2Ki7ia7MVCMMKBoTOGYrLW/mq2Ni3gUxl/jEh@f4yIbRWEUbeMwGgugiaD/ZdN@Jc/YHk5N/XQLQn679v7xeWr9upG6qfjsRQnDN0Jyd@eONTyPTO93nKve6YcP "C# (.NET Core) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 18 bytes
```
«∨λð«fvO:»TM»₄τÞ•J
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCq+KIqM67w7DCq2Z2TzrCu1RNwrvigoTPhMOe4oCiSiIsIiIsInBubmRubnFwZG5wcW5kIl0=)
```
«∨λð«fvO:»TM»₄τÞ•J
«∨λð« # Compressed string "pndq"
f # Convert to list of characters
vO # For each, how many times does it appear in the input?
: # Duplicate it
»TM» # Compressed integer 21241
₄τ # To base-26 as list: [1, 5, 10, 25]
Þ• # Dot product of this and the other list
J # Append this to the list
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pF`, 59 bytes
```
for$i(P,N,D,Q){say s:$i:$\+={P,1,Q,25,D,10,N,5}->{$&}:eg}}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0glUyNAx0/HRSdQs7o4sVKh2Eol00olRtu2OkDHUCdQx8gUKGdoAFRiWqtrV62iVmuVml5bW/3/f0AgELr4@fn9yy8oyczPK/6v62uqZ2Bo8F@3wA0A "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 66 bytes
```
->s{t=0;{P:1,N:5,D:10,Q:25}.map{|c,v|t+=v*m=s.count(c.to_s);m}<<t}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664usTWwLo6wMpQx8/KVMfFytBAJ9DKyLRWLzexoLomWaespkTbtkwr17ZYLzm/NK9EI1mvJD@@WNM6t9bGpqT2f4FCWrRSgFIsF5jhB2O4wBiBcAYQwNl@LgEwDBMLgAO4iJ@fi59fYICLH0ihUux/AA "Ruby – Try It Online")
Not great.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
```
"PNDQ"S¢D•Ωт•₂в*O)˜
```
[Try it online!](https://tio.run/##MzBNTDJM/V9TVvlfKcDPJVAp@NAil0cNi86tvNgEpB41NV3YpOWveXrO/0qlw/sVdO0UDu9X0vkfwOXH5cIVyBUIBFyBfi4BMMwVAAdcAX5@Ln5@gQEufiApAA "05AB1E – Try It Online")
**Explanation**
```
"PNDQ" # push this string
S # split to list of chars
¢ # count the occurrences of each in input
D # duplicate
•Ωт• # push 21241
₂в # convert to a list of base 26 digits
* # element-wise multiplication
O # sum
)˜ # wrap in a flattened list
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 148 bytes
```
c->{int q=0,d=0,n=0,p=0;for(char w:c){if(w=='Q')q++;if(w=='D')d++;if(w=='N')n++;if(w=='P')p++;}return ""+q+","+d+","+n+","+p+","+(q*25+d*10+n*5+p);}
```
[Try it online!](https://tio.run/##rU@xboMwFNzzFU8s2DhBtFKWIipVZa0FyhhlcG1onRJjjEkUIb6dugQ1S7LlSe@k03t3utuzI1vVulB78TPyirUtfDCp@gWAVLYwJeMF0H5jjVRfYBD/Zma7A47jwb20llnJgUIHCYx89do7ETRJtBRulVudRHFZX3RweuG4lyU6JYmf@7ghJJ5Z6mNxZdTH6soyH2vHBlPYzijwPNIQb@kRMaGaUE@ImuB5TUTwFBEVrIl2IcfYxdTdZ@VizmmPtRRwcCXRpdV2x/BfX4DNubXFIaw7G2p3sZVCXWiQl@cpzbzQ1u@uxZsx7IwwxvE9zf3L7JbnDzPL/oem9GGut52GxTD@Ag "Java (OpenJDK 8) – Try It Online")
Well it's only one byte shorter than the [other](https://codegolf.stackexchange.com/a/160745/78407) Java submission, but hey- shorter is shorter :D
**Explanation:**
```
int q=0,d=0,n=0,p=0; //Initialize too many integers
for(char w:c){ //Loop through each coin
if(w=='Q')q++;if(w=='D')d++;if(w=='N')n++;if(w=='P')p++; //Increment the correct coin
}return ""+q+","+d+","+n+","+p+","+(q*25+d*10+n*5+p); //Return each coin count and the total monetary value
```
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), 47 bytes
```
5R0TiE!vD;
5+@P@@t>b%m$.
a+$P$t
PrPrt
9s+r$P$rt
```
[Try it online!](https://tio.run/##S8/PScsszvj/3zTIICTTVbHMxZrLVNshwMGhxC5JNVdFjytRWyVApYQroCigqITLsli7CMgtKvn/PwAI/Pz8XFwCAQ "Gol><> – Try It Online")
The output format is `[P Q N D Value]`.
### How it works
```
5R0TiE!vD;
>b%m$.
5R0 Repeat command '0' (push 0) 5 times
T Set teleport location for later
i Input a char
E Pop if the last input was EOF; skip next otherwise
If the last is EOF, the following is run:
! D; Skip 'v', print the contents of the stack from bottom to top, then exit
Otherwise the following is run:
v
>b%m$. Take the top (input) modulo 11, and jump to (-1, input % 11)
P%11 = 3, N%11 = 1, D%11 = 2, Q%11 = 4
5+@P@@t Runs if the input is N
5+ Add 5 to top
@ Rotate top 3 (the 3rd comes to the top)
P Increment the top
@P@@ Increment the 3rd from top
t Teleport to the last 'T'
a+$P$t Runs if the input is D
a+ Add 10 to top
$ Swap top two
$P$ Increment the 2nd from top
t Teleport to the last 'T'
PrPrt Runs if the input is P
P Increment the top
r Reverse the stack
rPr Increment the bottom
t Teleport to the last 'T'
9s+r$P$rt Runs if the input is Q
9s+ Add 25 to the top ('s': add 16 to the top)
r$P$r Increment the 2nd from bottom
t Teleport to the last 'T'
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 47 bytes
```
#!/usr/bin/perl -p
P1N5D10Q25=~s:\D:$\-=-$'*($n=s/$&//g);say$n:egr
```
[Try it online!](https://tio.run/##K0gtyjH9/z/A0M/UxdAg0MjUtq7YKsbFSiVG11ZXRV1LQyXPtlhfRU1fP13TujixUiXPKjW96P//QD@XABgO@JdfUJKZn1f8X7cg8b@ur6meoYGeIQA "Perl 5 – Try It Online")
[Answer]
# Pyth, ~~23~~ ~~27~~ 26 bytes
```
+Jm/Qd"PNDQ"s.b*NYJ[h05T25
```
Saved a byte thanks to @RK. Outputs as [P, N, D, Q, value].
[Try it here](http://pyth.herokuapp.com/?code=%2BJm%2FQd%22PNDQ%22s.b%2aNYJ%5Bh05T25&input=%22PNNDNNQPDNPQND%22&debug=0)
### Explanation
```
+Jm/Qd"PNDQ"s.b*NYJ[h05T25
Jm/Qd"PNDQ" Save the count of each coin (in PNDQ order) as J.
[h05T25 [1, 5, 10, 25].
.b J For each pair of count and value...
*NY ... take the product...
s ... and get the sum.
+ Stick that onto the list of counts.
```
[Answer]
# [C (clang)](http://clang.llvm.org/), 112 bytes
```
f(char *i){int c,d,v[5]={0};for(;c=*i++;v[d=(c|c/2)&3]++,v[4]+="AYJE"[d]-64);for(c=0;c<5;printf("%d,",v[c++]));}
```
[Try it online!](https://tio.run/##fZFBb4IwGIbv/RVfWFxawFlAvSAmS9hlhwaPi@FgWkESVxHQi/O3sxbFKcS9TUl5vrdvKR8f8u1KpvVLJvn2INYwKyuR7d42c9QiRYpMphrVCeabVQFmRk6ZrIDbwj4uJ3Fwomc/2RXY54GZWZZ/XIoA8x8@csmrF1uWco1jKzDevz4/jKWIh9MxaTbwgPp8NvFzdUSVYGMgbEOZuWXFhPjnOr0eWBI4odYEgxJgOAcwbCiJjxKsn2eE9Dd9rzKJtRul2IgM4ueHqsSGWmjAuiDsgkUPKPUYC6N2dmvRTb0KYyFjiyhkemO3mneB7ALRBfseUOoxKfJ29s68qVeRUki5z4XUGx@qSsW6OhQSaPPXRyaCCB6km9PIsWkzHNgVcF3@vThtRTEE7EnGxUftCYLwqeUaRgHB4h@TtrkqSDf1uWesgqgy3XX53uTZl@G4nrr5TZ2b0/bqKumx8/dJU5Xj2o7jIXNU/wI "C (clang) – Try It Online")
Output seq is now of P,Q,D,N,total-value
Works with both lower-case and upper-case inputs.
**Explanation:**
`"AYJE"` or `{64+1,64+25,64+10,64+5}` is. 64+value-of-coin.
`d=(c|c/2)&3` (used as index) has value `1,2,3,0` for `q,d,n,p` inputs respectively, in both upper and lower case.
[Answer]
## [Kustom](https://help.kustom.rocks/s1-general/knowledgebase/top/c2-functions), 146 bytes (sort of)
It's hard to find challenges where this language works lol
```
$tc(count,gv(i),P)$
$tc(count,gv(i),N)$
$tc(count,gv(i),D)$
$tc(count,gv(i),Q)$
$gv(P)$,$gv(N)$,$gv(D)$,$gv(Q)$,$gv(P)+gv(N)*5+gv(D)*10+gv(Q)*25$
```
This is technically not one script, instead each line except the last is a global value, counting one byte extra for the name of each global ("i", "P", "N", "D", and "Q").
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/learn/what-is-dotnet), 156 bytes
```
s=>{Func<char,int>f=i=>{return s.Split(i).Length-1;};var a=new[]{f('P'),f('N'),f('D'),f('Q')};return$"{string.Join(",",a)},{a[0]+a[1]*5+a[2]*10+a[3]*25}";};
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 149 bytes
```
a->{int[]c={0,0,0,0,0};for(String g:a){if(g=="P")c[0]+=1;if(g=="N")c[1]+=5;if(g=="D")c[2]+=10;if(g=="Q")c[3]+=25;}c[4]=c[0]+c[1]+c[2]+c[3];return c;}
```
[Try it online!](https://tio.run/##XZDBboMwDIbvPIXVEwiKaDcuy5hUaddNm3ZEHEIIKB0NCEKnCeXZmZOmHWpycPT9ju3fR3qm267n8lh9L/1UtoIBa@k4whsVcvYAj5CKDzVlHA5wIY7mBVD/Sw1CNuYZECtqz4ZRUYXFDkAhg4VuX2b7g2VzErmrSd0NrgA0TzSYRe03Wbb52AQsT4ow2xFH3g3ZIUmv5NWQvclJrujToAdE@5Rolj8Wma1iP9pco5KBq2mQwIheyGVU59tNfO5EBSd0v7I2NGOw8n4TSvQm@c8NzDhDhKNFOLAmd7uqMJnG1C@Df8UsAFUQqCUEwzOkGMJw3c62/B0VP8XdpOIee6lW@lUuilUp7bavveUP "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 50 bytes
```
P
P_
N
N5*
D
D10*
Q
Q25*
^
PNDQ_
O`.
(.)(\1*)
$.2¶
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8D@AKyCey4/Lz1SLy4XLxdBAiyuQK9AIyIvjCvBzCYzn8k/Q49LQ09SIMdTS5FLRMzq07T9Qkx9QNVAhEHAF@rkEwDBXABwAtfu5@PkFBrj4gaQA "Retina – Try It Online") Outputs in the order D, N, P, Q, total. Explanation:
```
P
P_
N
N5*
D
D10*
Q
Q25*
```
Calculate the total by inserting `_`s corresponding to the value of each coin.
```
^
PNDQ_
```
Insert an extra copy of each character so there is at least one of each to match.
```
O`.
```
Sort the characters into order.
```
(.)(\1*)
$.2¶
```
Count the number of each character after the first.
[Answer]
# SmileBASIC, 70 bytes
```
INPUT C$P=N+D+Q
WHILE""<C$INC VAR(POP(C$))WEND?P,N,D,Q,P+N*5+D*10+Q*25
```
Example:
```
? PNDNDNDQP
2 3 3 1 72
```
Explanation:
```
INPUT COINS$
P=N+D+Q 'create variables
WHILE COINS$>"" 'loop until the coin list is empty
'pop a character from the coin list
'and increment the variable with that name
INC VAR(POP(COINS$))
WEND
PRINT P,N,D,Q,P+N*5+D*10+Q*25
```
[Answer]
# C, 149 bytes
```
f(char*s){int a[81]={},b[]={1,5,10,25},c=0;char*t,*v="PNDQ";for(t=s;*t;a[*t++]++);for(t=v;*t;printf("%d,",a[*t++]))c+=a[*t]*b[t-v];printf("%d\n",c);}
```
[Try it online!](https://tio.run/##TY7NasMwEITveYpFoaCfTYkKgYKinHwOzlnVwVnXiaB1iq3qYvzsqmVy6GlnZz92hnY3orwNPX39tp9wHGMbHq/3U@443ZtBjmIKfYTGvWtvpxmvbhkaD6j3@HaYkezerGBEmSyrz9WFme4x8GhHI6NpnIxKeaXE003F/RmWpx1nLy0yfCJCkLJFe3l1cZf8P@qjZ0jCzLl0@W5Cz9dSw40QSjpIuSxJwLQBgNDxcjppAatKTnthNnPOdX05V9Uf "C (gcc) – Try It Online")
C doesn't have associative arrays, so I fake it (very inefficiently, memory-wise!) and then loop through again with a lookup array to add up the coins. It won't calculate foreign currency, though :-)
[Answer]
# [Julia](https://julialang.org), 45 bytes
```
!s=(t=count.(["DNPQ"...],s);[t;[10 5 1 25]t])
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZDPasMwDMbZbfVTqO6hCbghTpcxKB475NKLZsN2Mj6EJYWO0UDiPM0uufShtqeZ_6RrJYzgJ32fjL7Pn-PXsZ5-7-5X0PVN2wNABYAAEkCRFczBc4DSFShKQpra1kITWlHxvHChOctD8twwQvGCHQi49FReaeTcU3VLPS_CsHIRO3PjwXkHc4WVvDw_obcsJi-2Yc1_BH3cdv2bRKwQlazQO8wGj05eMM69gTmP9rB5-tksB5FY8dGNJ5slmnoBzbLMsCHdabvT7iJluIexJp1F60PXQ7JH9vr-lgp_JrJ4qYeh7S0s9yiE46Q9NXF8mmL9Aw)
] |
[Question]
[
# Challenge
Given input in the form `<n1>, <n2>` where number can be -1, 0, or 1, return the corresponding [cardinal direction](https://en.wikipedia.org/wiki/Cardinal_direction). Positive numbers move East in the x-axis and South in the y-axis, Negative numbers move West in the x-axis and North in the y-axis.
Output must be in the form `South East`, `North East`, `North`. It is case-sensitive.
If the input is 0, 0, your program must return `That goes nowhere, silly!`.
# Sample Input/Outpot:
`1, 1` -> `South East`
`0, 1` -> `South`
`1, -1` -> `North East`
`0, 0` -> `That goes nowhere, silly!`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~55~~ 51 bytes
```
`
SÆ
Nư `·gV +`
E†t
Wƒt`·gU ª`T•t goƒ Í2€e, Ðéy!
```
### Explanation
```
// Implicit: U, V = inputs
`\nSÆ \nNư ` // Take the string "\nSouth \nNorth ".
· // Split it at newlines, giving ["", "South ", "North "].
gV // Get the item at index V. -1 corresponds to the last item.
+ // Concatenate this with
`\nE†t\nWƒt`·gU // the item at index U in ["", "East", "West"].
ª`T•t goƒ Í2€e, Ðéy! // If the result is empty, instead take "That goes nowhere, silly!".
// Implicit: output result of last expression
```
[Try it online!](https://tio.run/nexus/japt#@5/AFXy4jUOBy@9w26ENCgmHtqeHKWgncLkeaivhCj/UXAISCVU4tCoh5NDUEoX0/EPNCod7jQ41pOooHJ5weGWl4v//hgq6hgA "Japt – TIO Nexus")
[Answer]
# Python, ~~101~~ 87 bytes
Really naive solution.
```
lambda x,y:['','South ','North '][y]+['','West','East'][x]or'That goes nowhere, silly!'
```
Thanks to @Lynn for saving 14 bytes! Changes: Using the string.split method actually makes it longer ;\_; And also, negative indexes exist in python.
[Answer]
# PHP, 101 Bytes
```
[,$b,$a]=$argv;echo$a|$b?[North,"",South][1+$a]." ".[West,"",East][1+$b]:"That goes nowhere, silly!";
```
[Answer]
# [Perl 6](https://perl6.org), 79 bytes
```
{<<'' East South North West>>[$^y*2%5,$^x%5].trim||'That goes nowhere, silly!'}
```
[Try it](https://tio.run/nexus/perl6#RY6xCsIwGAb3PsWnWJPIb7GCLmo3VxcFBWuh1GiF1kgStcH22avi4HIc3HJ3I/GYBtnMKx36mTpKLNrXfM4YlqmxWKu7zbFS@sOtNDaK9r3EDcb@hHpJ5U8OgdWXsq7ZJk8tzkoaXNUzl1oSzKUoXIc17Ulp8GFIIwoFdn8dRuBxRbETeHmASR04r8iJ4FRazvyxYYIEoRvbLuE796s3qQuvad8 "Perl 6 – TIO Nexus")
## Expanded:
```
{ # bare block lambda with placeholder parameters 「$x」 and 「$y」
<< '' East South North West >>\ # list of 5 strings
[ # index into that with:
# use a calculation so that the results only match on 0
$^y * 2 % 5, # (-1,0,1) => (3,0,2) # second parameter
$^x % 5 # (-1,0,1) => (4,0,1) # first parameter
]
.trim # turn that list into a space separated string implicitly
# and remove leading and trailing whitespace
|| # if that string is empty, use this instead
'That goes nowhere, silly!'
}
```
[Answer]
# JavaScript (ES6), 106 100 97 93 bytes
It's a very simple approach. It consists of a few ternary operators nested together -
```
f=a=>b=>a|b?(a?a>0?"South ":"North ":"")+(b?b>0?"East":"West":""):"That goes nowhere, silly!"
```
**Test Cases**
```
f=a=>b=>a|b?(a?a>0?"South ":"North ":"")+(b?b>0?"East":"West":""):"That goes nowhere, silly!"
console.log(f(1729)(1458));
console.log(f(1729)(-1458));
console.log(f(-1729)(1458));
console.log(f(-1729)(-1458));
console.log(f(0)(1729));
console.log(f(0)(-1729));
console.log(f(1729)(0));
console.log(f(-1729)(0));
```
[Answer]
# JavaScript (ES6), 86 bytes
```
a=>b=>["North ","","South "][b+1]+["West","","East"][a+1]||"That goes nowhere, silly!"
```
# Explanation
Call it with currying syntax (`f(a)(b)`). This uses array indices. If both `a` and `b` are 0, the result is a falsy empty string. In that case, the string after the `||` is returned.
# Try it
Try all test cases here:
```
let f=
a=>b=>["North ","","South "][b+1]+["West","","East"][a+1]||"That goes nowhere, silly!"
for (let i = -1; i < 2; i++) {
for (let j = -1; j < 2; j++) {
console.log(`${i}, ${j}: ${f(i)(j)}`);
}
}
```
[Answer]
## Batch, 156 bytes
```
@set s=
@for %%w in (North.%2 South.-%2 West.%1 East.-%1)do @if %%~xw==.-1 call set s=%%s%% %%~nw
@if "%s%"=="" set s= That goes nowhere, silly!
@echo%s%
```
The `for` loop acts as a lookup table to filter when the (possibly negated) parameter equals -1, and concatenating the matching words. If nothing is selected then the silly message is printed instead.
[Answer]
## [GNU sed](https://www.gnu.org/software/sed/), 100 + 1(r flag) = 101 bytes
```
s:^-1:We:
s:^1:Ea:
s:-1:Nor:
s:1:Sou:
s:(.*),(.*):\2th \1st:
s:0...?::
/0/cThat goes nowhere, silly!
```
By design, sed executes the script as many times as there are input lines, so one can do all the test cases in one run, if needed. The TIO link below does just that.
**[Try it online!](https://tio.run/nexus/sed#FYixCgIxEET7fEXsVLK5XcttrGxtFGwO4ZBgDo5byUbEnzdmi5l5b5ryHYhviV0n4tNk0J@zFCPii7wNtnG/C1Y8Hmr2I2m1G2OMR2Y34PC45qn6pyT1q3xyKil4nZflu2kNAzoM1APkqAsF2y5gBqZg/pNXnWXVBuUP)**
**Explanation:**
```
s:^-1:We: # replace '-1' (n1) to 'We'
s:^1:Ea: # replace '1' (n1) to 'Ea'
s:-1:Nor: # replace '-1' (n2) to 'Nor'
s:1:Sou: # replace '1' (n2) to 'Sou'
s:(.*),(.*):\2th \1st: # swap the two fields, add corresponding suffixes
s:0...?:: # delete first field found that starts with '0'
/0/cThat goes nowhere, silly! # if another field is found starting with '0',
#print that text, delete pattern, end cycle now
```
The remaining pattern space at the end of a cycle is printed implicitly.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 56 bytes
```
N¬¥0?`T•t goƒ Í2€e, Ðéy!`:` SÆ Nư`¸gV +S+` E†t Wƒt`¸gU
```
[Try it online!](https://tio.run/nexus/japt#@@93aM2hpQb2CSGHppYopOcfalY43Gt0qCFVR@HwhMMrKxUTrBIUgg@3cSj4HW47tCHh0I70MAXtYO0EBddDbSUK4YeaS0Biof//G@oYAgA) | [Test Suite](https://tio.run/nexus/japt#@58bWh0dGhZrG2oNorSDtTVA9KE1h5YaGNgnhByaWqKQnn@oWeFwr9GhhlQdhcMTDq@sVEywSlAIPtzGoeB3uO3QhoRDO9LDFIB6ExRcD7WVKIQfai4BiYX@/x8drWuoo2sYqwOiDSAUkMcVbQARNQALGkDEoCohCkHqYnWDAA)
### Explanation:
```
N¬¥0?`Tt go Í2e, Ðéy!`:` SÆ Nư`¸gV +S+` Et Wt`¸gU
Implicit U = First input
V = Second input
N´0?`...`:` ...`qS gV +S+` ...`qS gU
N¬ Join the input (0,0 → "00")
¥0 check if input is roughly equal to 0. In JS, "00" == 0
? If yes:
... Output "That goes nowhere, silly!". This is a compressed string
` ` Backticks are used to decompress strings
: Else:
` ...` " South North" compressed
qS Split on " " (" South North" → ["","South","North"])
gV Return the string at index V
+S+ +" "+
` ...` " East West" compressed
qS gU Split on spaces and yield string at index U
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~48~~ ~~45~~ 43 bytes
```
õ'†Ô'…´)èUõ„ƒÞ „„¡ )èXJ™Dg_i“§µ—±æÙ,Ú¿!“'Tì
```
[Try it online!](https://tio.run/nexus/05ab1e#@394q/qjhgWHpwDJZYe2aB5eEXp466OGeccmHZ6nAKSB6NBCBaBwhNejlkUu6fGZjxrmHFp@CKhmyqGNh5cdnqlzeNah/YpAUfWQw2v@/zfk0jUEAA "05AB1E – TIO Nexus")
**Explanation**
```
õ'†Ô'…´) # push the list ['','east','west']
èU # index into this with first input
# and store the result in X
õ„ƒÞ „„¡ ) # push the list ['','south ','north ']
èXJ # index into this with 2nd input
# and join with the content of X
™ # convert to title-case
Dg_i # if the length is 0
“§µ—±æÙ,Ú¿!“ # push the string "hat goes nowhere, silly!"
'Tì # prepend "T"
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~84~~ ~~82~~ 81 bytes
*1 byte saved thanks to @seshoumara for suggesting `0...?` instead of `0\w* ?`*
```
(.+) (.+)
$2th $1st
^-1
Nor
^1
Sou
-1
We
1
Ea
0...?
^$
That goes nowhere, silly!
```
[Try it online!](https://tio.run/nexus/retina#U9VwT/ivoaetqQAiuFSMSjIUVAyLS7jidA25/PKLuOIMuYLzS7mAvPBULkMu10QuAz09PXsurjgVrpCMxBKF9PzUYoW8/PKM1KJUHYXizJycSsX//w0UDLkMwdgAiIG6DUCEriGUNAARIEEDAA "Retina – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 40 bytes
```
Ṛị"“¡ƘƓ“¡+9“»,“wµ“¡ḳ]“»Kt⁶ȯ“¬ɼ¬<¬O÷ƝḤẎ6»
```
[Try it online!](https://tio.run/nexus/jelly#@/9w56yHu7uVHjXMObTw2Ixjk8EMbUsQtVsHSJYf2goWerhjcyxY0LvkUeO2E@tB7DUn9xxaY3Nojf/h7cfmPtyx5OGuPrNDu////2@oo6BrCAA "Jelly – TIO Nexus")
[Answer]
# Swift 151 bytes
```
func d(x:Int,y:Int){x==0&&y==0 ? print("That goes nowhere, silly!") : print((y<0 ? "North " : y>0 ? "South " : "")+(x<0 ? "West" : x>0 ? "East" : ""))}
```
[Answer]
# PHP, 95 bytes.
This simply displays the element of the array, and if there's nothing, just displays the "default" message.
```
echo['North ','','South '][$argv[1]+1].[East,'',West][$argv[2]+1]?:'That goes nowhere, silly!';
```
This is meant to run with the `-r` flag, receiving the coordenates as the 1st and 2nd arguments.
[Answer]
## [C#](http://csharppad.com/gist/f3393e3949a9c9bdf47151cabd6bbf26), ~~95~~ 102 bytes
---
**Golfed**
```
(a,b)=>(a|b)==0?"That goes nowhere, silly!":(b<0?"North ":b>0?"South ":"")+(a<0?"West":a>0?"East":"");
```
---
**Ungolfed**
```
( a, b ) => ( a | b ) == 0
? "That goes nowhere, silly!"
: ( b < 0 ? "North " : b > 0 ? "South " : "" ) +
( a < 0 ? "West" : a > 0 ? "East" : "" );
```
---
**Ungolfed readable**
```
// A bitwise OR is perfomed
( a, b ) => ( a | b ) == 0
// If the result is 0, then the 0,0 text is returned
? "That goes nowhere, silly!"
// Otherwise, checks against 'a' and 'b' to decide the cardinal direction.
: ( b < 0 ? "North " : b > 0 ? "South " : "" ) +
( a < 0 ? "West" : a > 0 ? "East" : "" );
```
---
**Full code**
```
using System;
namespace Namespace {
class Program {
static void Main( string[] args ) {
Func<Int32, Int32, String> f = ( a, b ) =>
( a | b ) == 0
? "That goes nowhere, silly!"
: ( b < 0 ? "North " : b > 0 ? "South " : "" ) +
( a < 0 ? "West" : a > 0 ? "East" : "" );
for( Int32 a = -1; a <= 1; a++ ) {
for( Int32 b = -1; b <= 1; b++ ) {
Console.WriteLine( $"{a}, {b} = {f( a, b )}" );
}
}
Console.ReadLine();
}
}
}
```
---
**Releases**
* **v1.1** - `+ 7 bytes` - Wrapped snippet into a function.
* **v1.0** - `95 bytes` - Initial solution.
---
**Notes**
*I'm a ghost, boo!*
[Answer]
# Scala, 107 bytes
```
a=>b=>if((a|b)==0)"That goes nowhere, silly!"else Seq("North ","","South ")(b+1)+Seq("West","","East")(a+1)
```
### [Try it online](https://ideone.com/ERXRLb)
To use this, declare this as a function and call it:
```
val f:(Int=>Int=>String)=...
println(f(0)(0))
```
### How it works
```
a => // create an lambda with a parameter a that returns
b => // a lambda with a parameter b
if ( (a | b) == 0) // if a and b are both 0
"That goes nowhere, silly!" // return this string
else // else return
Seq("North ","","South ")(b+1) // index into this sequence
+ // concat
Seq("West","","East")(a+1) // index into this sequence
```
[Answer]
# C, 103 bytes
```
f(a,b){printf("%s%s",b?b+1?"South ":"North ":"",a?a+1?"East":"West":b?"":"That goes nowhere, silly!");}
```
[Answer]
# Java 7, 130 bytes
```
String c(int x,int y){return x==0&y==0?"That goes nowhere, silly!":"North xxSouth ".split("x")[y+1]+"WestxxEast".split("x")[x+1];}
```
**Explanation:**
```
String c(int x, int y){ // Method with x and y integer parameters and String return-type
return x==0&y==0 ? // If both x and y are 0:
"That goes nowhere, silly!" // Return "That goes nowhere, silly!"
: // Else:
"North xxSouth ".split("x"[y+1] // Get index y+1 from array ["North ","","South "] (0-indexed)
+ "WestxxEast".split("x")[x+1]; // Plus index x+1 from array ["West","","East"] (0-indexed)
} // End of method
```
**Test code:**
[Try it here.](https://tio.run/nexus/java-openjdk#hY4xb8IwEIX3/IrDQ2WLECUrKOrUEZYgdYgY3NQilowd@S5gK8pvD0awdKhY3g3v07tv6YxEhP2UASBJ0h005LU9Q8e1JQj5I6OYvKLRWwh1XX7EFJ/s2EuCs1MI1t165VUOqI2JK7ZlB@ephxAaN6bLChyMJs4CE21cV6c1@1ZIIXxJpD9lSOVuzpLMMP6YJPNyujr9CxepLX/atSeQ4uEM0EQkdSnSo2JIFRnLO17lUAmx@x8o3wFpYfN2onwCczYvyx0)
```
class M{
static String c(int x,int y){return x==0&y==0?"That goes nowhere, silly!":"North xxSouth ".split("x")[y+1]+"WestxxEast".split("x")[x+1];}
public static void main(String[] a){
System.out.println(c(1, 1));
System.out.println(c(0, 1));
System.out.println(c(1, -1));
System.out.println(c(0, 0));
}
}
```
**Output:**
```
South East
South
North East
That goes nowhere, silly!
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 68 bytes
```
"
South
North
East
West"N/3/l~W%.=s_Q"That goes nowhere, silly!"?
```
[Try it online!](https://tio.run/nexus/cjam#i67@r8QVnF9akqHA5ZdfBKK4XBOLS7jCU4tLlPz0jfVz6sJV9WyL4wOVQjISSxTS81OLFfLyyzNSi1J1FIozc3IqFZXs//vVWmrF/o/WNVTQNYzlAtEGEArEM4AIGoDFDMBCUHUQZSBVAA "CJam – TIO Nexus") or [verify all test cases](https://tio.run/nexus/cjam#i67@r8QVnF9akqHA5ZdfBKK4XBOLS7jCU4tLlPz0jfVz6sJV9WyL4wOVQjISSxTS81OLFfLyyzNSi1J1FIozc3IqFZXs//vVWmrF/o/WNVTQNYzlAtEGEArEM4AIGoDFDMBCUHUQZSBVAA)
Prints one trailing space on `[0 -1]` or `[0 1]` (`North` or `South`).
**Explanation**
```
"\nSouth \nNorth \n\nEast\nWest" e# Push this string
N/ e# Split it by newlines
3/ e# Split the result into 3-length subarrays,
e# gives [["" "South " "North "]["" "East" "West"]]
l~ e# Read and eval a line of input
W% e# Reverse the co-ordinates
.= e# Vectorized get-element-at-index: accesses the element
e# from the first array at the index given by the
e# y co-ordinate. Arrays are modular, so -1 is the last
e# element. Does the same with x on the other array.
s e# Cast to string (joins the array with no separator)
_ e# Duplicate the string
Q"That goes nowhere, silly!"? e# If it's non-empty, push an empty string. If its empty,
e# push "That goes nowhere, silly!"
```
[Answer]
# [Röda](https://github.com/fergusq/roda), 100 bytes
```
f a,b{["That goes nowhere, silly!"]if[a=b,a=0]else[["","South ","North "][b],["","East","West"][a]]}
```
[Try it online!](https://tio.run/nexus/roda#ZU5BCsIwEDy3r1j3HME@oEevXhQ8xBw2dGsCNdEkRaT27TVpj8IyM8wszCw9kNCTxIuhBHfPEZx/Gw4sINph@OxQ2V5SqwW1B8VDZCkRBZ79mAxkcfKhCCW1EmtypJgyXTmTkqTUvDzIOpjqKvIL9o2ABr7Q@wAEna@rP1tvdvUco8nzcks5nfGWsARlNOj1JViXAIvbecf1hvPyAw "Röda – TIO Nexus")
This is a trivial solution, similar to some other answers.
] |
[Question]
[
Let's have a ragged list containing no *values*, only more lists. For example:
```
[[[],[[]],[],[]],[],[[],[],[]],[]]
```
And the list will be finite, meaning that eventually every path terminates in an empty list `[]`.
It's simple enough to determine if two of these are structurally equal. Check each element in order for equality and recurse. However what if we don't care about the order of the lists for equality? What if we only care that they have the same elements?
We can define this shapeless equality like so:
>
> Two lists \$A\$, and \$B\$ are shapeless equal if for every element in \$A\$ there are as many elements in \$A\$ shapeless equal to it as there are in \$B\$, and vice-versa for the elements of \$B\$.
>
>
>
Your task will be to take two ragged lists and determine if they are "shapeless equal" to each other. If they are you should output some consistent value, if they are not you should output some distinct consistent value.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being the goal.
## Testcases
```
[] [] -> 1
[[],[[]]] [[[]],[]] -> 1
[[],[[],[[]]]] [[],[[[]],[]]] -> 1
[[],[[],[[]]]] [[[[]],[]],[]] -> 1
[[]] [] -> 0
[[],[]] [[[]]] -> 0
[[],[]] [[]] -> 0
[[[],[],[]],[[]]] [[[],[]],[[],[]]] -> 0
[[],[],[[]]] [[],[[]],[[]]] -> 0
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
p↰ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v@BR24aHWyf8/x8dHasDxUAA5QLZOiA@AA "Brachylog – Try It Online")
### Explanation
This takes the first list as the input variable, and the second list as the output variable. The interpreter then prints `true.` if it is possible to satisfy this predicate with these variables, and `false.` otherwise.
```
p The output is a permutation of the input
↰ᵐ Recursively call this predicate on each element of the input
```
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
```
lambda x,y:g(x)==g(y)
g=lambda a:sorted(map(g,a))
```
[Try it online!](https://tio.run/##ZY7BboMwDIbP5SmsnBzJmzrthpQ9xW6MQxCBRkohCukGT8/sAq2mSbES/9/v34lLvozD@9qZrzXYa9NamGkpe5y1MT0uuujNrttyGlN2LV5txJ6s1uvPxQcHn@nmyuJkCRow4Id4y6hfpxh8RgUvH6B0cRLUjGNAP2RsNCszwcKipLlvGwjsPiMwMelQLNzEJEPSECTeQqB4wLcKfHe4wHA@uDA5UH7YsF6rGvjwF96KqqqJq2ZFLuL6AzYoVJ6742k5gs6b/4j5pz2Vu0T3oMfao31kn38B "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), 41 bytes
Expects `(a)(b)`. Returns a Boolean value.
```
a=>b=>(g=a=>1+a.map(g).sort()+0)(a)==g(b)
```
[Try it online!](https://tio.run/##jZBNDoMgEIX3PYXLmUhRD4AXMSzQKmljxajp9SlI1f6AlWTCY/G9x5ubeIixGq79dO7UpdYN04LlJctBMiOyWNC76EEiHdUwAcYpgkDGJJSoK9WNqq1pqyQ0UHC0g9GfkyRRdvpCC07McOtgb2LGZxRGHT7zVr883kwOoQv3me9HD7U1aOpLXZuGHfZRvhftRWfWlds2vbzXZQVTN8pJ8vN7i@on "JavaScript (Node.js) – Try It Online")
### How?
We can't compare nested arrays in JS by simply coercing them to strings because everything is flatten and empty arrays are turned into empty strings. (Basically, only commas would remain with the arrays we're dealing with in this challenge.)
We could use `JSON.stringify`:
```
a=>JSON.stringify(a.map(g).sort())
```
but this is a bit lengthy.
Instead, we do a custom conversion to a string by prepending a `1` at the beginning of each call and appending a `0` at the end.
For an already sorted array, this effectively replaces opening brackets with 0's and closing brackets with 1's, while leaving commas unchanged.
For instance:
```
[[],[[],[[]]]]
"110,110,110000"
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
߀Ṣ
Ç€E
```
A monadic Link accepting a list of the two ragged lists that yields `1` if they are "shapeless equal".
**[Try it online!](https://tio.run/##y0rNyan8///w/EdNax7uXMR1uB3IcP0Ppv7/j46OjtVRiI6N5dIBM4E4FiQAonVAbIQ4RA4sGauDUABVgWoK3Ax0IZgAWAQsiGQjjA81NxYA "Jelly – Try It Online")**
### How?
Recursively sort the containers of any nested lists and compare the results for equality.
```
߀Ṣ - Helper Link, recursively sort container lists and their content: List, X
€ - for each element in X:
ß - call this Link
Ṣ - sort
Ç€E - Link, the main function: List, A
€ - for each of the two lists in A:
Ç - call the Helper Link
E - all equal?
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->l,m{g=->a{a.sort.map &g};g[l]==g[m]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5HJ7c63VbXLrE6Ua84v6hELzexQEEtvdY6PTon1tY2PTo3tvZ/gUJaNAjE6gBxLJCE4WgYhooAwX8A "Ruby – Try It Online")
(Stolen from hyper neutrino's python answer)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes
```
SameQ@@Sort//@#&
```
[Try it online!](https://tio.run/##dU7BagMhFLzvV4gppQVD2vOS4CE5FHpoa2/WgywmfbCr4r5AIOTbt881m5CWguK8mXkzdha/XWcRGjtsl4OynXuXUoWEi4Wc3Q/roKsjeMHCHk9syVrwrq7AE/wMm0NMru8heKkwgd99uNjaxmmu@XzFX6FHzc1ZU7EFlODr6o1G1JQxX7GtzOGcPfCxguAjN5U45h7ByubmgMk2qO9UkyDii497LIrgX56a6lrwHDZCczKDNowOMc@V1kbQNcTkR9C9EYqY1QzPjv8sk36TMnU9Ff/U9Ie7MiNVci4/m0bxe/XiKUhcs38A "Wolfram Language (Mathematica) – Try It Online")
Input `[{A, B}]`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
"®δ.V{"©.VË
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/240851/52210), but without having access to recursive functions.
Input as a pair of nested lists.
[Try it online](https://tio.run/##yy9OTMpM/f9f6dC6c1v0wqqVDq3UCzvc/f9/dHR0rA4UA4GOQjRIBMiF4FgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/pUPrzm3RC6tWOrRSL@xw93@d/9HR0bE6CtGxQEIBzAZiEAfEBnJiUSQgkmBZEBumAocSmDyyKWh2wW3CEIOLgIUgxiBcBuOjWY@kBsKEuiYWAA).
**Explanation:**
```
"..." # Push the 'recursive' string explained below
© # Store it in variable `®` (without popping)
.V # Execute it as 05AB1E code
# (using the implicit input-pair in the first call)
Ë # Check if both lists in the pair are now equal
# (after which the result is output implicitly)
δ # Map over each inner list:
® .V # Do a recursive call by executing string `®` as 05AB1E code
{ # Then sort each inner list
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü╙ûÆ╙X○Γfó¡↓↓▄
```
[Run and debug it](https://staxlang.xyz/#p=81d39692d35809e266a2ad1919dc&i=%5B%5D+%5B%5D+%0A%5B%5B%5D,%5B%5B%5D%5D%5D+%5B%5B%5B%5D%5D,%5B%5D%5D+%0A%5B%5B%5D,%5B%5B%5D,%5B%5B%5D%5D%5D%5D+%5B%5B%5D,%5B%5B%5B%5D%5D,%5B%5D%5D%5D+%0A%5B%5B%5D%5D+%5B%5D+%0A%5B%5B%5D,%5B%5D%5D+%5B%5B%5B%5D%5D%5D+%0A%5B%5B%5B%5D,%5B%5D,%5B%5D%5D,%5B%5B%5D%5D%5D++%5B%5B%5B%5D,%5B%5D%5D,%5B%5B%5D,%5B%5D%5D%5D+&m=2)
Sort arrays till the lowest depth and compare for equality. ~~`G` might be usable here, but a reusable recursive function *feels* shorter (recursive will probably prove me wrong).~~ (I proved myself wrong. -1)
[Answer]
# Python3, 78 bytes:
```
s=sorted
l=len
f=lambda a,b:l(a)==l(b)and all(f(j,k)for j,k in zip(s(a),s(b)))
```
[Try it online!](https://tio.run/##RYtNCgMhDEb3niJLA9l1UwqeZOgi4khtUxV1017eZn6ggZAvLy/1Mx4lX661zdldL22swYiTNZvohN8@MDD5m1hG58R65ByARWy0T3phLA10QsrwTdV21airhThrS3motix3OluL4Mi60AYQzV/cLjs@ZDrJ@b/b8wc)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 47 bytes
```
⊞υθ⊞υηFυFι⊞υκWυ«≔⊟υι≔⟦⟧ζWι⊞ζ⊟ιW⁻ζιF№ζ⌊κ⊞ι⌊κ»⁼θη
```
[Try it online!](https://tio.run/##VY/BCsIwDIbP9il6bKA@wU4iHoXdi4cy1IZ1q1uNwsRnr@lsQQulf/4vSZPO2bkL1qfUUnSKtJygEVU71pcwS0Ug1xdBVtYzezr055W@xGYXI15H1YYbG1oi8@qZk5ZLjktBbbNomdMRftgRR4qZsPv9dB9ovGeHEQ40qB6gNMA/sxFv0c7IyYeJrI9qyitAk5IxPEK5fIo0WeU4bR/@Aw "Charcoal – Try It Online") Link is to verbose version of code. Not easy due to lack of recursion or sorting primitives. Explanation:
```
⊞υθ⊞υηFυFι⊞υκ
```
Get all of the lists and sublists from the input.
```
Wυ«≔⊟υι
```
Process them in reverse order.
```
≔⟦⟧ζWι⊞ζ⊟ι
```
Move the elements of this (sub)list into a temporary list.
```
W⁻ζιF№ζ⌊κ⊞ι⌊κ
```
Put them back but in sorted order.
```
»⁼θη
```
Now that the input lists have been sorted in-place, we can just compare them directly.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 116 bytes
```
+`(?=(((\[)|(?<-3>])|,)+(?(3)^)),(?!\1)(((\[)|(?<-6>])|,)+(?(6)^))(.*))(.*)\[.*(?=\4\7$)\8].*(?=\7$)
$4,$1
^(.+) \1$
```
[Try it online!](https://tio.run/##bY09DsIwDIX3nKJIQbKbEClqVRiAjBzCTlUGBpYOiLF3D/khtAODE39@z8@vx/s538MeblNQE7gLADDhAu586K4eF40KHHQ4ImpwO7a4cQyrY0gOMG15mEwbw7jno0Q@@UKxF7LX0ooRjMKGrQyBfENeEHkdy0dIn45VZ2WehNR@xT9qlerumltTt5ghU9n53a6Yr3wA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
+`
```
Repeat until no more lists need exchanging.
```
(?=(((\[)|(?<-3>])|,)+(?(3)^)),(?!\1)(((\[)|(?<-6>])|,)+(?(6)^))(.*))
```
Look ahead to capture two balanced lists and the tail of the string.
```
(.*)\[.*(?=\4\7$)\8].*(?=\7$)
```
Check whether the second list should precede the first list. The lookaheads ensure that we only compare the two lists captured above. Note that this could inefficiently swap two lists back and forth before it's finished sorting their sublists, but once all of the sublists are sorted the lists will eventually sort stably.
```
$4,$1
```
If so then exchange the two lists.
```
^(.+) \1$
```
Now that the input lists have been sorted, just compare them directly.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 56 bytes
```
f(a,b)=s=vecsort;#a==#b&&prod(i=1,#a,f(s(a)[i],s(b)[i]))
```
[Try it online!](https://tio.run/##bY7BCsMgDIZfRSqUBNLDzsO9iHhIu3UIZRUtgz29tauubuyg@fLlJ@rY2@7uYhyBqUcV1PM2hNkvZ8lKyb5tnZ@vYNWJJNMIARi1NRSg3ypiZOemF7DoLsJ5@1gSNlvTiIGnCUYSjEhCa23SbUzGdAqnxtR@n73FxiXwP1HGVO@r3/nYX3UsoCy1/g7lWrkjsmP@iMG4Ag "Pari/GP – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 59 bytes
```
sub f{@_>1?f(pop)eq f(pop):"(@{[sort map{f($_)}@{pop()}]}"}
```
[Try it online!](https://tio.run/##lZJRT4MwEMff@RQX0oWindtMfIF042FvJu7Ft9oQpoUsyqgUjAvDr46FMt3QLErScNf@f/nfXU6K/OWmaVS5hrgKwvlsEWOZSVe8ggk8GwcVU1leQBrJKsYodOug0k/YrXlt102pBCyjIvK8ZZlKkftWnOXYYgCMExh8jA9vgM5hBsBJR2hEH34EsjYn@pwlDGUwk/YU/xtxkH8ZDYhhJ7/3MT3xOIU6C/4/gvOzHh1iqjYzY@w775v/6XEy4MMgCDuelSHcygJANnVCx9dRusMoImhNkHBpgEI/3aGETi9jc@22GplvtkVsjxTAZivLwoPR@Hqqs/4H4l2Kx0I8eYCETpNMS1DS2o7Gs1bxpvrwYWsTq31AglItWYCTPTvggXO3uofVrUMA640Es3TtWtIPNXlQ@6sLuvcnkyQnpi7SybrFJYdK6@YT "Perl 5 – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Fold a List in Half](/questions/136887/fold-a-list-in-half)
(58 answers)
Closed 5 years ago.
The rules are as follows:
* Take in a string of integers separated by spaces. Add the first and last numbers, the second and second-last numbers, and so on.
* The program must output the numbers separated by newlines.
* The program must handle negative numbers, but may not handle decimals.
* If an odd amount of integers are inputted, just print the lone integer at the end.
* This is code golf, fewest bytes wins.
Here are some test cases:
```
> input
output
more output
etc.
-------------------
> 2 2
4
> 1 2 3 4 5 6
7
7
7
> 3 4 2 6
9
6
> 1 2 3 4 5
6
6
3
> -5 3 -8 2
-3
-5
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 9 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
*Thanks to Weijun Zhou for -1 bytes*
It actually conforms with the required output format!
```
Φ┴⌐Öâ9|Ö
```
[Run and debug it](https://staxlang.xyz/#p=e8c1a99983397c99&i=2+2%0A1+2+3+4+5+6%0A3+4+2+6%0A1+2+3+4+5%0A-5+3+-8+2&a=1&m=2)
Here's the ungolfed ascii representation of the program.
```
L Concatenate all inputs into list
2M Create two equal-ish size batches, with the bigger piece first
Er Push the two parts to the stack, and reverse the second one
LM Put two parts back together as 2-row matrix, then transpose
m|+ For each zipped pair, print the sum on a separate line
```
[Run this one](https://staxlang.xyz/#c=L%09Concatenate+all+inputs+into+list%0A2M%09Create+two+equal-ish+size+batches,+with+the+bigger+piece+first%0AEr%09Push+the+two+parts+to+the+stack,+and+reverse+the+second+one%0ALM%09Put+two+parts+back+together+as+2-row+matrix,+then+transpose%0Am%7C%2B%09For+each+zipped+pair,+print+the+sum+on+a+separate+line&i=2+2%0A1+2+3+4+5+6%0A3+4+2+6%0A1+2+3+4+5%0A-5+3+-8+2&a=1&m=2)
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 23 bytes
```
#!/usr/bin/perl -a
say$'*s//a/+pop@F for@F
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVJFXatYXz9RX7sgv8DBTSEtv8jB7f9/QwUjBWMFEwWzf/kFJZn5ecX/dRP/6/qa6hka6BkAAA "Perl 5 – Try It Online")
Perl is unusual in that it is valid to change an array while you are looping over it. So you can have `$_` walking from front to back while using `pop` to effectively walk from back to front while removing array elements which will stop the loop when they meet in the middle:
```
say$_+pop@F for@F
```
This however fails for an odd number of elements because in the middle both `$_` and `pop@F` are that middle element so you get twice the value.
So instead I use another odd fact of perl loops: the loop variable is not a copy of the corresponding array position but is an alias for it. If you change `$_` then you change the corresponding array element. In this case I want to both get the value of `$_` ***and*** change it to `0` so that the `pop@F` returns zero when processing the middle element. The shortest way (without needing `()`) to do that is `s//a/` which changes e.g. `6` to `a6` which evaluates to `0` in a numeric context. The part after the substitution is preserved in `$'` which will be `6` in the example. And since `s///` returns the number of substitutions (`1` in this case) the expression `s//a/*$'` will both set `$_` to zero and return the original value.
This however would require a space after `say`. So finally I use yet another perl oddity, the fact that the expression stack also uses aliases of the values and variables you are processing. Therefore `$'*s//a/` also works. When `$'` is put on the expression stack it is not set yet but when next `s//a/` is executed it changes to the old value of `$_` in place just before the multiplication is done. This is also the reason why the simpler seeming
```
say$_+($_=0)+pop@F for@F
```
does ***not*** work. The first `$_` gets changed to `0` just before the first addition. You would need to force a copy with something like
```
say "$_"+($_=0)+pop@F for@F
```
to make that work
[Answer]
# [Python 3](https://docs.python.org/3/), 57 bytes, relaxed I/O
```
def f(a):
try:x,*a,y=a;return[x+y]+f(a)
except:return a
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1HTikuhpKjSqkJHK1Gn0jbRuii1pLQoL7pCuzJWGyTPpZBakZxaUGIFkVBI/F9QlJlXopGmEW2ko2AUq6nJBRcwBAroKBjrKJjoKJjqKJjhlkSRgYgZoWvQNQUr17WAWPMfAA "Python 3 – Try It Online")
First time to see `try..except` in golfing.
## `print` version, 57 bytes
```
def f(a):
try:x,*a,y=a;print(x+y);f(a)
except:print(*a)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/PyU1TSFNI1HTikuhpKjSqkJHK1Gn0jbRuqAoM69Eo0K7UtMaJM2lkFqRnFpQYgUR10rU/A9hpWlEG@koGMVqanLBBQyBAjoKxjoKJjoKpjoKZrglUWQgYkboGnRNwcp1LSDW/AcA "Python 3 – Try It Online")
`print`ing instead of `return`ing gives the same length.
# [Python 3](https://docs.python.org/3/), 73 bytes, strict I/O
```
a=*map(int,input().split()),
while len(a)>1:x,*a,y=a;print(x+y)
print(*a)
```
[Try it online!](https://tio.run/##RYzBCsIwEETv@Yq9JRtToVsjUqn/skiggRhDjTT5@hjx4GXm8Rgm1bw@49RccXclpWy86Acn5WM2PqZ3Vnh8peB7oxH76oOD4KJivI1zMZpNXfiatr5X5VBR/FAztv6mLTYCEiMQTHACC@c/i29SN4PtYrgAfQA "Python 3 – Try It Online")
This prints an extra newline at the end if the number of elements is even.
[Answer]
## [JavaScript ES6](https://developer.mozilla.org/bm/docs/Web/JavaScript), 100 97 bytes
```
_=>{for(_=_.split(' ').map(Number);0<_.length;)console.log(1<_.length?_.shift()+_.pop():_.pop())}
```
<https://jsbin.com/nufanenehu/edit?js,console>
First golfing answer ever. Be gentle.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
#2ä`R+»
```
[Try it online!](https://tio.run/##MzBNTDJM/f9f2ejwkoQg7UO7///XNVUwVjBR0LVQMAIA "05AB1E – Try It Online")
**Explanation**
```
# # split input on spaces
2ä # divide into 2 parts
` # split separately to stack
R # reverse the second one
+ # add the lists of numbers
» # join on newlines
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~77~~ 58 bytes
```
a=>g(a.split` `)
g=a=>+a.shift()+~~a.pop()+`
`+(a+a&&g(a))
```
[Try it online!](https://tio.run/##fcvLDsIgEIXhPU8xq3YmRKJ42dFnYVILYkghQlz21SkLVya6O/n@nCe/ucyvkOthTfelOdPYTB5ZlRxDtWBJeNNJdnkEV5HktrHKKfdlhZXIkoehP4janNaS4qJi8uhw1KBHIvGlJ9Bwhgtc4fav/mjHT2s7 "JavaScript (Node.js) – Try It Online")
Thanks to @Neil for chopping off 17 bytes at once. Also, I found that `~~` works instead of `|0`, which removes a pair of parens.
# Original submission, 77 bytes
```
a=>g(a.split` `.map(x=>+x))
g=a=>a.shift()+(a.pop()|0)+`
`+(a.length?g(a):'')
```
[Try it online!](https://tio.run/##fczNCgIhFAXg/TzF3elFksl@FoHTqyiTOoappMQsenczaBXU8pzvcK76oct897luYrqYZmXTcnJU85KDrwoUv@lMVzmxFXFwsmu3xdtKkfVZTpnic0SmBvXOwURXl3N/wBMh2OYUSwqGh@SopUSAIP3nq92CgB3s4QDHf/rDxo@1Fw "JavaScript (Node.js) – Try It Online")
Input as a space-delimited string, output as a newline-delimited string. First converts the input string into an array, then passes to a recursive function that generates the output string.
[Answer]
# [Brainfuck](https://github.com/TryItOnline/brainfuck), 61 bytes
```
>>+[>,]<[<]>->[[-<<+>>]>[>]<[[<]<<+>>>[>]<-]<[<]>]<<<[<]>[.>]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v/fzk472k4n1ibaJtZO1y46WtfGRtvOLtYu2g4oBhQEc8E8XYgioAiYjtazi/3/38bAVtHY0A4A "brainfuck – Try It Online")
This program takes a null-terminated list of base-256 ASCII numbers as input :)
**Commented Version**
```
Read input chars until \0
>>+[>,]<
Clear initial 1
[<]>->
[
Copy two to the left
[-<<+>>]>
Head to right side
[>]<
Subtract from right side add to left side repeat
[[<]<< +>>> [>]< - ]
Start at next spot
<[<]>
]
Print it all out
<<<
[<]
>[.>]
```
**Satisfying I/O requirements, 81 bytes**
```
>>+[>,>,[-]<]<[<]>->[[-<<+>>]>[>]<[[<]<<+>>>[>]<-]<[<]>]<<<[<]>[.[-]++++++++++.>]
```
In this version the input characters must be separated and the output is split by newlines.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
œs2U2¦S
```
[Try it online!](https://tio.run/##y0rNyan8///o5GKjUKNDy4L///9vqKNgpKNgrKNgoqNgCgA "Jelly – Try It Online")
Takes a list of integers, such as `[1, 2, 3, 4, 5]`. Outputs as an array, such as `[6, 6, 3]`.
[11 bytes](https://tio.run/##y0rNyan8///hjk1hj5rWHJ1cbBRqdGhZcOT///8NFYwUjBVMFEwB) to conform to the strict input specifications.
[Answer]
# J, 28 bytes
```
>.@-:@#({.|:@,:@+/@,:|.@}.)]
```
## ungolfed
```
>.@-:@# ({. |:@,:@+/@,: |.@}.) ]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/7fQcdK0clDWq9WqsHHSsHLT1gWSNnkOtnmbsf00urtTkjHyFNAVDBSMFYwUTBVOIgLo6hoSCGboUSNhIwew/AA "J – Try It Online")
My J is rusty and surely this could be improved -- suggestions encouraged. Almost all the complexity arises from the odd length case and the newline requirement. I had 22 bytes before I noticed the newline requirement:
```
>.@-:@# ({. +/@,: |.@}.) ]
```
[Answer]
# [R](https://www.r-project.org/), ~~68~~ 66 bytes
```
cat(c((n=scan())[y<-1:(x=sum(n|1)/2)],rep(0,x!=x%/%1))+rev(n[-y]))
```
[Try it online!](https://tio.run/##BcFLCoAgEADQq0wLYYYUPxFE5EnEhYjLJLRCobvbe2WMGG6MiNnWGDISuX4IvWOz9Tkxf5qkIc9LulDxNtnGJNNEc0kvZie6JxpihQUUiA3M@AE "R – Try It Online")
Takes input from stdin as in the examples, and prints the output on stdout. Since using `scan()` is typically shorter than defining a function and taking an array as input, this is the shortest way to take input.
Reads in data, takes the first half (rounded down) of the list, and appends a zero (if necessary), then adds it to the reverse of the second half of the list.
[Answer]
# [Python 2](https://docs.python.org/2/), 46 bytes
```
f=lambda x:x[1:]and[x[0]+x[-1]]+f(x[1:-1])or x
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRocKqItrQKjYxLyW6ItogVrsiWtcwNlY7TQMkDGRq5hcpVPwvKMrMK9FI04g20lEwitXU5IILGAIFdBSMdRRMdBRMdRTMcEuiyEDEjNA16JqCletaQKz5DwA "Python 2 – Try It Online")
`x[1:]` is just a shorter way to write `len(x)>1`
[Answer]
# [Python 3](https://docs.python.org/3/), 70 bytes
```
lambda a:[a[i]+a[~i]for i in range(len(a)//2)]+len(a)%2*[a[len(a)//2]]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHRKjoxOjNWOzG6LjM2Lb9IIVMhM0@hKDEvPVUjJzVPI1FTX99IM1YbwlY10gIqh4vHxv4vKMrMK9FI04g21DHSMdYx0TGN1dTkwhTVMQOK/wcA "Python 3 – Try It Online")
+32 bytes for strict input:
# [Python 3](https://docs.python.org/3/), 102 bytes
```
a=[*map(int,input().split())]
l=len(a)
for q in[a[i]+a[~i]for i in range(l//2)]+l%2*[a[l//2]]:print(q)
```
[Try it online!](https://tio.run/##FYwxDsIwDEX3nsILUtwiKlJYkHqSyIOHApaM64YwsHD1kE5P/@nr@bc8V5tq5Tn1L/YgVo5i/ikBT29XaUTqdNbFAmN3XzNsIJY4CQ2cfkK7kqYgsz2WoOMYkQY9xL6d9kV089y6YcNazxBhggtc/w "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) + `-p`, 52 bytes (spec compliant)
```
a=$_.split.map(&:to_i);loop{puts a.shift+(a.pop||0)}
```
[Try it online!](https://tio.run/##KypNqvz/P9FWJV6vuCAns0QvN7FAQ82qJD8@U9M6Jz@/oLqgtKRYIVGvOCMzrURbI1GvIL@gpsZAs/b/f0MFIwVjBRMF03/5BSWZ@XnF/3ULAA "Ruby – Try It Online")
A full program, taking a string of space-separated integers and printing the results separated by newlines.
Normally the `-p` flag forces you to reassign the `$_` variable, as it will be implicitly printed at the end of the program. However this code terminates with an `NoMethodError` when it calls `+` on `nil` (the result of `shift`ing the head off an empty array), before that implicit print can happen.
# [Ruby](https://www.ruby-lang.org/), 33 bytes (relaxed IO)
```
->a{puts a.shift+(a.pop||0);redo}
```
[Try it online!](https://tio.run/##PY7BCsIwEETv/YoBL4rbotGKIPojpYfYJrRQmpKkFDF@e9y26G3eDLM7dny@or7H9CHfw@gdZOaaVvv9VmaDGUI47G5W1eYTiwQoBImSZnEkQSc6U06X1ZhB/OCfrpjmTOmVu0mZKVk1qA1C2/PDwLkuFlnCKleNCn3bYQM3ya4zE5S1xkJ6@EZB9TWMxnKj4pzb8@qE/Ri/ "Ruby – Try It Online")
This lambda skips the integer parsing code, and it is able to save 2 bytes by replacing `loop{}` with `redo` since it is already inside of a repeatable block. This also terminates with `NoMethodError`.
[Answer]
# [Haskell](https://www.haskell.org/), ~~93~~ 80 bytes
Saved 13 bytes thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni)!
```
f s|x<-read<$>words s=mapM print$zipWith(+)(take(div(1+length x)2)x)$reverse$0:x
```
[Try it online!](https://tio.run/##bYxLCsIwAAX3nuIRskiQgI1WRFpv4Np1IKkN/ZKEGsS7x7aCq/J2b5iplW9M26ZUwX9iIZxRuqC31@C0hy87Nd4xOtsH@rbjw4aa7TkLqjFM24ll@9b0z1Ajcskjp85MxnlDD9eYOmV7lNDDDqhAMkgccUKOM5mftQkiBPlhiXVb6G9uwQXI7aTIZ01clmj6Ag "Haskell – Try It Online")
[Answer]
# [Clojure](https://clojure.org/), 124 bytes
```
#(loop[l(map bigint(.split %" "))](println(+(first l)(or(last(rest l))0)))(if(>(count l)2)(recur(concat(butlast(rest l))))))
```
[Try it online!](https://tio.run/##VcvBCsIwEATQX1kiwixSkYrgyR8pHtLQSmRNwmbz/bH15tzmDRMkv5suHf0AyblMgo8vNMdXTIZzLRKNjo4c8xNFN5SEE9ao1UgYWSG@GnT5db4wM@KKB0JuaaeRtzE03SAFb5ib/T32dDfc6ErDnUbH/Qs "Clojure – Try It Online")
Ungolfed:
```
#(loop [l (map bigint (.split % " "))]
(println (+ (first l) (or (last (rest l)) 0)))
(if (> (count l) 2)
(recur (concat (butlast (rest l))))))
```
An anonymous function that takes the input string and splits it. `loop` is rerun with every iteration with the "middle" items of the changing list if there are enough items left. Combining `butlast` and `rest` creates the "middle" list.
Interesting is the part where the sum is printed. Simply adding `(first l)` and `(last l)` only works for an even number of items. When an uneven number of items is passed, `first` and `last` will hit the same item. Using `rest` will remove the first item, in this case the only one, and return an empty list. Using `last` will return `nil` which is converted into zero by the `or` function.
[Answer]
# [Haskell](https://www.haskell.org/), ~~78~~ ~~72~~ ~~70~~ 67 bytes
```
mapM print.f.map read.words
f(x:r@(_:_))=(x+last r):f(init r)
f e=e
```
[Try it online!](https://tio.run/##PYzRCoIwAEXf/YrLnjZsQisjBCXotUDoJciQkc5GtmQz8uuzWdDbOVzuuUp3q9t2bNJivMtuj85q00cq8gJbyyp6PWzlAkWHxG5omZSMpXQIW@l6WJYoqo2eKFCo09o3tEGKb4oWjmfonv2htzsDClKYDARhCAeGLEMDx3AiAoLMQOYQWGCJGKtJJxQ//C@T8NgzX/vPeXxfVCsbN/LjNs8/ "Haskell – Try It Online")
*Edits:*
* -6 bytes by using `mapM print` instead of `unlines.map show` from [GolfWolf's Haskell answer](https://codegolf.stackexchange.com/a/159694/56433).
* -2 bytes by removing `+0` which I though was necessary for type inference but wasn't. Thanks to GolfWolf for pointing out.
* -3 bytes by adding `r@(_:_)` to make the `f[x]=f[x]` pattern superfluous. Thanks again to GolfWolf.
[Answer]
# [Perl 6](https://perl6.org) `-n`, ~~58~~ 42 bytes
```
.&{$_,{S:s/(\S+) (.*?) (\S+)?$ {say $0+($2//0)}/$1/}...''}
```
[Try it](https://tio.run/##K0gtyjH7/19PrVolXqc62KpYXyMmWFtTQUNPyx5Igtj2KgrVxYmVCioG2hoqRvr6Bpq1@iqG@rV6enrq6rX//xsqGCkYK5gomP7LLyjJzM8r/q@bBwA "Perl 6 – Try It Online")
```
.say for .=words[^*/2]Z+ |.[$_-1...$_/2],0
```
[Try it](https://tio.run/##K0gtyjH7/1@vOLFSIS2/SEHPtjy/KKU4Ok5L3yg2SluhRi9aJV7XUE9PTyUeKKJj8P@/oYKRgrGCiYLpv/yCksz8vOL/unkA "Perl 6 – Try It Online")
---
If the input/output restrictions are relaxed **40 bytes**
```
*.[^*/2,{$_-1...$_/2}].&roundrobin».sum
```
[Test it](https://tio.run/##VZDdasJAEIXv5ykOkkpM3A1GTVtCgreF0pv2Tq20ZguBmCz5gYrow7SXfYTSG1/IR0gnMfSHYZcz35yd2V2t8sSrN1v011mkENSWnD9ajjvcGSsxklIaK8fdL2U/z6o0yrPnOD1@yqLa1D6RYd3cySKpco3DAQ4BJi/g9PUW8vYOc3FvD2xcNKQFi7Q1/PA275RNDvfkq8xKVZQIYB8/DGdu@RxLHnobFyUbqkLhQTVSJ0/p2ey4Pr1keXdShJjFqa7KIWbqVat1qSLseFBciEgpnWzRPNY8m9q@gz/WIXpdRfPnmAME4W@xYz3a1yFcuDQhCjFiOcYEU3h02QbDBrgMrsn75@HUo3GDxJSJuOIuYkxi@g0 "Perl 6 – Try It Online")
[Answer]
# [Java (OpenJDK 9)](http://openjdk.java.net/projects/jdk9/), 76 bytes
```
a->{for(int i=0,l=a.length;i<l--;)System.out.println(i<l?a[i++]+a[l]:a[i]);}
```
[Try it online!](https://tio.run/##bZBBT4QwEIXv/Io5grSNomt0u6wHz572SDhUtmCxtIQOmxjCb8fCEiPRJpM232vnvWktLoLaVpr6/Pk8qaa1HULtIetRaVb2pkBlDbvhQaGFc/AmlIEhAGj7d60KcCjQbxerztB4LTxhp0yV5SC6ykXLVYBXa1zfyO6gDGb5EUpIg0nQ41DaLvQMVHpLdCqYlqbCD64OmlIenb4cyobZHlnru6I2oVdeRKbiOI9FpvO9P@cRHye@@CztvTdKhw7S1X1eAyQEEhjJL3JHZnhP4IHAjsDjVr3y5A/fvNpKdLcI9GljNV6zraOu6fbXjNFPxJKJopAthjOP@Er/@YFVG4O5xukb "Java (OpenJDK 9) – Try It Online")
## With strict input
# [Java (JDK 10)](http://jdk.java.net/), 115 bytes
```
s->{var a=s.split(" ");for(int i=0,l=a.length;i<l--;)System.out.println(i<l?new Long(a[i++])+new Long(a[l]):a[i]);}
```
[Try it online!](https://tio.run/##bY9NT4QwEIbv/IoJJ@oujaJrzHZZD171tMcNh8oWLJaW0AFjNvx2LB9BTGwyaeZ5J5NnCt7ysLh89rKsTI1QuJ42KBXNGp2iNJreMC9V3Fp441LD1QOomnclU7DI0X2tkRcoXRacsJY6PyfA69yScRTgxWjblKI@TOkRMoi93obHa8tr4LGltlISAx98wjJTB1IjyPh2q2JOldA5fjB5UGHIyOnboiipaZBWbhcqHbjkWYsveDU6D/hZbjYJ2ayASsje4YSwrmejzyKJwqKFeNYcnh9B5G9/2zuI4B4eYAePazyg6C9aJtcw3DkWPq12dpPCcOWkMUrsJxWymGSUp6moMBg4YTP95/o567yhuv4H "Java (JDK 10) – Try It Online")
## Credits
* -10 bytes on strict input thanks to Kevin Cruijssen
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 56 bytes
```
f=x=>([a,m='',b]=x.split(/ (.*) | /),b?a- -b+`
`+f(m):a)
```
[Try it online!](https://tio.run/##hc6xDoIwAIThnae4ra1tIVYxRlN9EDWhIDWYQokQw@C7V1wcdOh2w5fLfzdPM1SPph9l5691CFZP@kBPRrSaEFFe9JQOvWtGmoGmC4YXMibKo5GQJS@Sglvasp1hofLd4F2dOn@jsBREQREwcJBzN4998ieWUFhhjRybiPwoFVXfv4iT@czk9qcvvAE "JavaScript (Node.js) – Try It Online")
Split the string by all the middle numbers and capture them all as a group, add the ends (coercing strings to numbers via `a- -b`, which is shorter than any alternatives I know of), and concatenate the result with a line break and `f(all captured middle numbers)` where available.
[Answer]
# [Python 3](https://docs.python.org/3/), 108 bytes
```
i=[*map(int,input().split())]
l=len(i)
for a,b in zip(i,i[:int(l/2-.5):-1]):print(a+b)
if l&1:print(i[l//2])
```
[Try it online!](https://tio.run/##LYtBCsMgEADvvmJPxW1NRNNchLxEPBho6MJ2I6k9tJ@3FnoaGGbKu953mVqjJZ4fuWiSakjKq2ocn4WpE5PihW@iCdW2H5DNCiTwoV4biqEvmq0fxhnD4BKGcvxUvqyoaAM@ub@hyNb6hK058DDBFeYv "Python 3 – Try It Online")
Non competitive, just thought it would be nice to share this zip approach :)
Too bad slicing and reversing in python is a bit finicky
[Answer]
# [Python 2](https://docs.python.org/2/), ~~111~~ ~~107~~ 103 bytes
```
i=map(int,input().split())
for y in[i[x]+i[-(x+1)]for x in range(len(i)/2)]+[i[x+1]]*(len(i)%2):print y
```
[Try it online!](https://tio.run/##LczLCsIwEIXhvU8xFISM8UJi7ULwScIsuqg6UKdDTCF5@piCqwMfh19Lei/ia@XHZ1TDko4suiaD56/O3BZ3zyVCAZbAIZPlcDLZOqSNc2OIo7wmM09iGC8eyW5H64gOf9x7vGtsbSi1dg48XKGHGwzdDw "Python 2 – Try It Online")
Takes input in "strict" format (space separated string of numbers) ~~and outputs a trailing newline if the count is even~~. Works because in Python 2, list comprehensions leak the last value of the variable `x` so it can be used later to identify the middle number.
# [Python 2](https://docs.python.org/2/), ~~79~~ ~~75~~ 69 bytes
```
lambda i:[i[x]+i[-(x+1)]for x in range(len(i)/2)]+[i[x+1]]*(len(i)%2)
```
[Try it online!](https://tio.run/##LcrBCoQgEADQX5lL4KQRuu1loS@xORhlO1BTSAf7eiPo@njHdf53cSX2Q1nDNk4B@OfZZ9LsG5W1RYp7ggwskIIss1pnUYytQ9JP1JaofrFyWI7EckJU3hpnPqYzX8JyAw "Python 2 – Try It Online")
Shorter version with input and output as lists. ~~Adds an empty string to the output for even numbers.~~
[Answer]
# **FORTH** 76 Bytes
```
: A BEGIN DEPTH 1 - ROLL + CR . DEPTH 2 <= UNTIL DEPTH 1 = IF CR . THEN ;
```
**Output:**
```
1 2 3 4 5 a
6
6
3 ok
2 2 A
4 ok
-5 3 -8 2 A
-3
-5 ok
```
[Answer]
# Python 2, 112 bytes
```
def f(s):
s=[int(i)for i in s.split(' ')];s.insert(len(s)//2,0)
for i in range(len(s)//2):print s[i]+s[-i-1]
```
[Answer]
# [Perl 6/Rakudo](https://perl6.org/) 45 bytes
`Perl6 -ne`
```
{say .shift+(.pop||0) while $_}(.words.Array)
```
Super simple, shifts and pops, Perl makes the empty list (with odd count) easy with `.pop||0`.
[Answer]
# [Red](http://www.red-lang.org), 105 bytes
```
func[s][b: to-block s
l: length? b
repeat n l / 2[print b/(n) + b/(l - n + 1)]if odd? l[print b/(n + 1)]]
```
[Try it online!](https://tio.run/##XcyxCsMgFIXh3ac4ODUECbFNKS55h6ziUKO2oWKCsc9vDYHSdLrw/YcbrcmDNZCKOJHdO4xyVVILpJlpP48vrMQLeBse6dlDk2gXe08I8GjA5RKnkKCbU6hQb9eDlVijrdTkMBvTw/@s9qKyA@XglOyFUlKgBccZF3S4HsOG/B@/6yOzrii7ld/5Aw "Red – Try It Online")
# [Red](http://www.red-lang.org), 91 bytes (Relaxed IO - a list ot integers)
```
func[b][l: length? b
repeat n l / 2[print b/(n) + b/(l - n + 1)]if odd? l[print b/(n + 1)]]
```
[Try it online!](https://tio.run/##XcxBCoMwEIXhfU7xcFWRIKa1FDfeodshi8ZMWiGkEtLzpxGhVFcD3/@YyDbf2YK0cEN2nzCR0eQHeA7P9BphROSFHwkBHi0ULXEOCaY9hRrNej1kiQ26Ws8Ob2tH@L/VVnR2IAWlxVaqShTooHDGBT2u@7CiOuJvvWfZF5W38jt/AQ "Red – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 136 bytes
```
def f(x):
x,o=[int(i) for i in x.split()],[];y=len(x)
for i in range(int(y/2)):o+=[x[i]+x[-i-1]]
if y%2!=0:o+=[x[int(y/2)]]
return o
```
[Try it online!](https://tio.run/##RcvNCgIhFIbhvVdxWsR4mJl@nN2EVyIugrQODEcxA716Syjafu/zxZofgZfWbs6DlwVXAWUK2hBnSQg@JCAghnJ4xo2yRDsZe6l6c/zR4g/Sle9O9ls9KsQ1jNoUQ3YsZqb5bK0A8lD3aqdPv/jFvSWXX4khtJj67OWgQA2I7Q0 "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 67 bytes
This can probably be improved, but I'm not sure how...
```
def x(a);puts a.shift.to_i+a.pop.to_i;return if a.length==0;x a;end
```
[Try it online!](https://tio.run/##HcpLCoAgEADQq8yyaJD@BeJJIsJISwgTG8FOb9HuLZ4P65PSpjTETObcBbpBsvswmhhdiykkc5f7yb2i4C0Y/Y1T2Z0OIUoeQXJltxRhqrDGBlvssMcBRxzn9AI "Ruby – Try It Online")
[Answer]
# C, 128 bytes
This version is more in keeping with the terms of the challenge, but has a hard-coded maximum of 9 numbers that it can accept.
```
i[9],j,k;f(char*s){for(s=strtok(s," ");j++,s;i[j]=atoi(s),s=strtok(0," "));while(--j>=++k)printf("%d\n",i[j]+(j==k?0:i[k]));}
```
[Try it online!](https://tio.run/##XY3LDoIwFET3fMWNxqQPanzExAjFD0EWWChcwGIAdUH49lqMG13OOZMZJQql7BKNah5ZDmE/ZA1e12Xk/TBs/1GHpnDMol/5rA40UWXaMdbTsZYEzcBoH7xKbHLSx5xjQusYE5kOLTrg4ldyXoVSCKR3NzhoslhlF7Pw5zInKGV13pzquEooDSbrGnBL0cz7kHaF8mF@BcZceFIYPQBADWR2EMGWgiYfFXiTteJg91Yc7e4N "C (gcc) – Try It Online")
I let C do the tokenizing for me, which allows me to send each string directly to `atoi()`. Afterwards, I just add the mirror indexes until the start>end.
As I couldn't get a array length and `strtok()` destroys the original string, making backtracking difficult, and I didn't want to have to `realloc()` to resize arrays, I hard-coded an array with a maximum of 9 values.
# C, 107 bytes (uses `argv`)
```
i,j,*k;f(char**s){k=(int*)s;while(s[++i])k[i]=atoi(s[i]);while(++j<=--i)printf("%d\n",k[i]+(i==j?0:k[j]));}
```
[Try it online!](https://tio.run/##XY3LDoIwFET3fMWNxqQPanzExAjFD0EWWChcwGIAdUH49lqMG13OOZMZJQql7BKNah5ZDmE/ZA1e12Xk/TBs/1GHpnDMol/5rA40UWXaMdbTsZYEzcBoH7xKbHLSx5xjQusYE5kOLTrg4ldyXoVSCKR3NzhoslhlF7Pw5zInKGV13pzquEooDSbrGnBL0cz7kHaF8mF@BcZceFIYPQBADWR2EMGWgiYfFXiTteJg91Yc7e4N "C (gcc) – Try It Online")
This version makes use of the fact that `argv` already has been tokenized; as a bonus, it doesn't have a hard-coded limit on the number of numbers! It does, however, assume that `sizeof(int)==sizeof(char*)`, which is truly evil and non-portable.
[Answer]
# **PHP**, 107 bytes
New to this, so please forgive my lack of correct formatting.
```
for($i=0,$a=explode(" ",$argv[1]),$c=count($a);$i<$c/2;$i++)echo$i==$c-$i-1?$a[$i]:$a[$i]+$a[$c-$i-1]."\n";
```
[Try it online!](https://tio.run/##JcvtCoIwFMbxWzmM82FDrbQ3SJcXYiJjTh3EztAVXX3L8NOPPw@Pn3yMVT3QzNHKQ4pKmo9/Um84A7bmPL6bvBUpaqnp5QJHJUq0Fep9sZokAoyeCNa3RJ2hzfIaVYO2vW0kf7ah3bGHY2V9jzHmUMARTnCGC1y/5IMlt8Ssh2WiOXTkjeuCGiW5Hw "PHP – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 163 bytes
```
a->{String[] b=a.split(" ");int c=b.length;a="";for(int d=0;d<c/2;d++){a+=(Integer.parseInt(b[d])+Integer.parseInt(b[c-1-d]))+"\n";}if(c%2>0){a+=b[c/2];}return a;}
```
[Try it online!](https://tio.run/##pY@xasMwEIb3PMUhKEgYO4nalIKq7B2aJWOa4SzJrlJHNrIcKMbP7srB7dRM2XT3/3z67oQXTOvGuJP@GlWFbQvvaF2/ALAuGF@gMrDr98FbV4Kn8wOZGGKlDRisgh04kDBiup2LhyPkErO2qWygBAgTEQZK5lllXBk@BUpCRFF7Ou21XAn9qpZc6CRhPSaSvsW/S@OzBn1r4kDzgz6y5J@1StdpjFhCPhwRgy2oeuDb1RUT0yU/isGb0HkHKIZRROumy6toPctfaqvhHG@mv@7IpvMB9t9tMOes7kLWxCRUjrrMU7IGDo/wBBt4JoyJW93byZUyEfhdhD@POxjpJiLSF@AzY1gM4w8 "Java (OpenJDK 8) – Try It Online")
Well It’s sure not going to win me the bounty, but all in all I’m pretty happy with my work here.
**Explanation:**
```
a->{String[] b=a.split(" "); //Create String array to get rid of the pesky spaces
int c=b.length;
a=""; //Since we now only need the array, we can reuse the original string to save a few bytes
for(int d=0;d<c/2;d++){ //Loop half(even) or half-1(odd) of the array length
a+=(Integer.parseInt(b[d])+
Integer.parseInt(b[c-1-d]))+ //Add the ‘rainbow pairs’ to the output string
"\n";} //Add a newline to each sum and end the loop
if(c%2>0){a+=b[c/2];} //If the number of input numbers is odd, print the middle digit
return a;} //the Output string is the Input string
```
] |
[Question]
[
The [characteristic polynomial](https://en.wikipedia.org/wiki/Characteristic_polynomial) of a square matrix \$A\$ is defined as the polynomial \$p\_A(x) = \det(Ix-A)\$ where \$I\$ is the [identity matrix](https://en.wikipedia.org/wiki/Identity_matrix) and \$\det\$ the [determinant](https://en.wikipedia.org/wiki/Determinant). Note that this definition always gives us a [monic polynomial](https://en.wikipedia.org/wiki/Monic_polynomial) such that the solution is unique.
Your task for this challenge is to compute the coefficients of the characteristic polynomial for an integer valued matrix, for this you may use built-ins but it is discouraged.
### Rules
* input is an \$N\times N\$ (\$N \ge 1\$) integer matrix in any convenient format
* your program/function will output/return the coefficients in either increasing or decreasing order (please specify which)
* the coefficients are normed such that the coefficient of \$x^N\$ is 1 (see test cases)
* you don't need to handle invalid inputs
### Testcases
Coefficients are given in decreasing order (ie. \$x^N, x^{N-1}, ..., x^2, x, 1\$):
```
[0] -> [1 0]
[1] -> [1 -1]
[1 1; 0 1] -> [1 -2 1]
[80 80; 57 71] -> [1 -151 1120]
[1 2 0; 2 -3 5; 0 1 1] -> [1 1 -14 12]
[4 2 1 3; 4 -3 9 0; -1 1 0 3; 20 -4 5 20] -> [1 -21 -83 559 -1987]
[0 5 0 12 -3 -6; 6 3 7 16 4 2; 4 0 5 1 13 -2; 12 10 12 -2 1 -6; 16 13 12 -4 7 10; 6 17 0 3 3 -1] -> [1 -12 -484 3249 -7065 -836601 -44200]
[1 0 0 1 0 0 0; 1 1 0 0 1 0 1; 1 1 0 1 1 0 0; 1 1 0 1 1 0 0; 1 1 0 1 1 1 1; 1 1 1 0 1 1 1; 0 1 0 0 0 0 1] -> [1 -6 10 -6 3 -2 0 0]
```
[Answer]
# [SageMath](http://www.sagemath.org/), 3 bytes
*5 bytes saved thanks to @Mego*
```
fcp
```
[Try it online!](http://sagecell.sagemath.org/?z=eJwrKMrMK9FISy7Q8E0sKcqs0IiONtRRMNJRMIjVUYgG0rrGOgqmILaBjgJQxjA2VlNTEwC44w37&lang=sage)
Takes a `Matrix` as input.
[`fcp`](http://doc.sagemath.org/html/en/reference/matrices/sage/matrix/matrix_symbolic_dense.html#sage.matrix.matrix_symbolic_dense.Matrix_symbolic_dense.fcp) stands for **f**actorization of the **c**haracteristic **p**olynomial,
which is shorter than the normal builtin [`charpoly`](http://doc.sagemath.org/html/en/reference/matrices/sage/matrix/matrix_symbolic_dense.html#sage.matrix.matrix_symbolic_dense.Matrix_symbolic_dense.charpoly).
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~16~~ 4 bytes
@BruteForce just told me that one of the functions I was using in my previous solution can actually do the whole work:
```
poly
```
[Try it online!](https://tio.run/##y08uSSxL/Z9m66Cnp/e/ID@n8r91SmZxgUaaRrSFgYKFgbWCqbmCuWGspuZ/AA "Octave – Try It Online")
**16 Bytes:** This solution computes the eigenvalues of the input matrix, and then proceeds building a polynomial from the given roots.
```
@(x)poly(eig(x))
```
But of course there is also the boring
```
charpoly
```
(needs a `symbolic` type matrix in Octave, but works with the usual matrices in MATLAB.)
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0KzID@nUiM1Mx3I1PyfkllcoJGmEW1hoGBhYK1gaq5gbhgLFAcA "Octave – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 8 bytes
```
charpoly
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D85I7GoID@n8n9BUWZeiUaaRrSJjpGOoY6xtYKJjq6xjqWOgbWCriFQxAAkZmSgo2uiY6pjZBCrqfkfAA "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 14 bytes
```
m->matdet(x-m)
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9X1y43sSQltUSjQjdX839BUWZeiUaaRrSJjpGOoY6xtYKJjq6xjqWOgbWCriFQxAAkZmSgo2uiY6pjZBCrqfkfAA "Pari/GP – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 53 bytes
```
function(m){for(i in eigen(m)$va)T=c(0,T)-c(T,0)*i
T}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNXszotv0gjUyEzTyE1Mz0VJKJSlqgZYpusYaAToqmbrBGiY6CplckVUvs/TSM3saQoswIoY6hjqKnJBRdI1jDUgQjqGOkYocpYGOiYmusASXOY7H8A "R – Try It Online")
Returns the coefficients in increasing order; i.e., `a_0, a_1, a_2, ..., a_n`.
Computes the polynomial by finding the eigenvalues of the matrix.
# [R](https://www.r-project.org/) + [pracma](https://cran.r-project.org/web/packages/pracma/pracma.pdf), 16 bytes
```
pracma::charpoly
```
`pracma` is the "PRACtical MAth" library for R, and has quite a few handy functions.
[Answer]
# Mathematica, 22 bytes
```
Det[MatrixExp[0#]x-#]&
```
-7 bytes from alephalpha
-3 bytes from Misha Lavrov
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yW1JNo3saQos8K1oiDaQDm2Qlc5Vu1/QFFmXolDWnR1tYmOkY6hjnGtDpCla6xjqWMAZOoaAsUMwKJGBjq6JjqmOkYGtbWx/wE "Wolfram Language (Mathematica) – Try It Online")
and... of course...
# Mathematica, 29 bytes
```
#~CharacteristicPolynomial~x&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7X7nOOSOxKDG5JLUosxgoGJCfU5mXn5uZmFNXofY/oCgzr8QhLbq62kTHSMdQx7hWB8jSNdax1DEAMnUNgWIGYFEjAx1dEx1THSOD2trY/wA "Wolfram Language (Mathematica) – Try It Online")
both answers output a polynomial
[Answer]
# [Haskell](https://www.haskell.org/), ~~243 223~~ 222 bytes
```
s=sum
(&)=zip
z=zipWith
a#b=[[s$z(*)x y|y<-foldr(z(:))([]<$b)b]|x<-a]
f a|let c=z pure[1..]a;g(u,d)k|m<-[z(+)a b|(a,b)<-a#u&[[s[d|x==y]|y<-c]|x<-c]]=(m,-s[s[b|(n,b)<-c&a,n==m]|(a,m)<-a#m&c]`div`k)=snd<$>scanl g(0<$c<$c,1)c
```
[Try it online!](https://tio.run/##LYxBb4MwDIXv/ApLRSjZkgra7bAu6WWnnXfYIbK0EChFJWlFwtQi/jsLaJJt2X7ve2ftL3XXzbOXfrAJyagc21syLvO7DedEb0qplE9H8kTv8Jgegp@uXdWTkRwoJQpFWtISp7vgGpMT6KmrAxg5wm3oa1Vst6jfGzKwil4mK7gayTPVUE5Es5JGaDNkMV9V013KBy75Zk0ziJJYxn0Uo9utbpNp5qS0uOB2xW1m8Kdqf38uVHpXifTojXYdNCQXqYnFCmpmq1sHEm596wJs4RSb9LWu4HCArxC/DfAjKPXpAiIFKQQ0dfi4ulC74GelXhjsGBQM9shgufiewRuDfDl5sUr5v7qLC4@W18jkiH8 "Haskell – Try It Online")
Thanks to @ØrjanJohansen for helping me golf this!
### Explanation
This uses the [Faddeev–LeVerrier algorithm](https://en.wikipedia.org/wiki/Faddeev%E2%80%93LeVerrier_algorithm) to compute the coefficients. Here's an ungolfed version with more verbose names:
```
-- Transpose a matrix/list
transpose b = foldr (zipWith(:)) (replicate (length b) []) b
-- Matrix-matrix multiplication
(#) :: [[Int]] -> [[Int]] -> [[Int]]
a # b = [[sum $ zipWith (*) x y | y <- transpose b]|x<-a]
-- Faddeev-LeVerrier algorithm
faddeevLeVerrier :: [[Int]] -> [Int]
faddeevLeVerrier a = snd <$> scanl go (zero,1) [1..n]
where n = length a
zero = replicate n (replicate n 0)
trace m = sum [sum [b|(n,b)<-zip [1..n] a,n==m]|(m,a)<-zip [1..n] m]
diag d = [[sum[d|x==y]|y<-[1..n]]|x<-[1..n]]
add as bs = [[x+y | (x,y) <- zip a b] | (b,a) <- zip as bs]
go (u,d) k = (m, -trace (a#m) `div` k)
where m = add (diag d) (a#u)
```
**Note:** I took this straight from [this solution](https://codegolf.stackexchange.com/a/150695/48198)
[Answer]
# [Python 2](https://docs.python.org/2/) + [numpy](http://www.numpy.org), 23 bytes
```
from numpy import*
poly
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P60oP1chrzS3oFIhM7cgv6hEiyvNtiA/p/J/QVFmXolGmkZ0tIWBjoKFQayOQrSpuY6CuWFsrKbmfwA "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 4 bytes
```
1$Yn
```
[Try it online!](https://tio.run/##y00syfn/31AlMu///2gLAx0LA2tTcx1zw1gA "MATL – Try It Online")
This is merely a port of [flawr's Octave answer](https://codegolf.stackexchange.com/a/150615/67312), so it returns the coefficients in decreasing order, i.e., `[a_n, ..., a_1, a_0]`
```
1$Yn # 1 input Yn is "poly"
```
[Answer]
## CJam (48 bytes)
```
{[1\:A_,{1$_,,.=1b\~/A@zf{\f.*1fb}1$Aff*..+}/;]}
```
[Online test suite](http://cjam.aditsu.net/#code=qN%25%7B%22%20-%3E%20%22%25~~%3AE%3B%22%5B%5D%22-'%3B%25%7B%5B~%5D%7D%25%0A%0A%7B%5B1%5C%3AA_%2C%7B1%24_%2C%2C.%3D1b%5C~%2FA%40zf%7B%5Cf.*1fb%7D1%24Aff*..%2B%7D%2F%3B%5D%7D%0A%0A~E%3D%7D%2F&input=%5B0%5D%20-%3E%20%5B1%200%5D%0A%5B1%5D%20-%3E%20%5B1%20-1%5D%0A%5B1%201%3B%200%201%5D%20-%3E%20%5B1%20-2%201%5D%0A%5B80%2080%3B%2057%2071%5D%20-%3E%20%5B1%20-151%201120%5D%20%0A%5B1%202%200%3B%202%20-3%205%3B%200%201%201%5D%20-%3E%20%5B1%201%20-14%2012%5D%0A%5B4%202%201%203%3B%204%20-3%209%200%3B%20-1%201%200%203%3B%2020%20-4%205%2020%5D%20-%3E%20%5B1%20-21%20-83%20559%20-1987%5D%0A%5B0%205%200%2012%20-3%20-6%3B%206%203%207%2016%204%202%3B%204%200%205%201%2013%20-2%3B%2012%2010%2012%20-2%201%20-6%3B%2016%2013%2012%20-4%207%2010%3B%206%2017%200%203%203%20-1%5D%20-%3E%20%5B1%20-12%20-484%203249%20-7065%20-836601%20-44200%5D%0A%5B1%200%200%201%200%200%200%3B%201%201%200%200%201%200%201%3B%201%201%200%201%201%200%200%3B%201%201%200%201%201%200%200%3B%201%201%200%201%201%201%201%3B%201%201%201%200%201%201%201%3B%200%201%200%200%200%200%201%5D%20-%3E%20%5B1%20-6%2010%20-6%203%20-2%200%200%5D)
### Dissection
This is quite similar to [my answer to *Determinant of an integer matrix*](/a/174391/194). It has some tweaks because the signs are different, and because we want to keep all of the coefficients rather than just the last one.
```
{[ e# Start a block which will return an array
1\ e# Push the leading coefficient under the input
:A e# Store the input matrix in A
_, e# Take the length of a copy
{ e# for i = 0 to n-1
e# Stack: ... AM_{i+1} i
1$_,,.=1b e# Calculate tr(AM_{i+1})
\~/ e# Divide by -(i+1)
A@ e# Push a copy of A, bring AM_{i+1} to the top
zf{\f.*1fb} e# Matrix multiplication
1$ e# Get a copy of the coefficient
Aff* e# Multiply by A
..+ e# Matrix addition
}/
; e# Pop AM_{n+1} (which incidentally is 0)
]}
```
[Answer]
# [Python 3](https://docs.python.org/3) and my [dronery](https://github.com/DroneBetter/dronery/blob/main/dronery.py) library, 476 bytes
```
λ M: C(λ f: λ t,m: t if len(t)==len(M) else f(f)(t+[n:=-sum(map(λ i: m[i][i],range(len(M))))/len(t)],matmul(M,lap(laph(__add__),m,lap(λ i: i*[0]+(n,)+(len(M)+~i)*[0],range(len(M)))))))([1],deepcopy(M))
```
(also using the [Faddeev-LaVerrier algorithm](https://en.wikipedia.org/wiki/Faddeev%E2%80%93LeVerrier_algorithm))
[Answer]
# [Maple](https://www.maplesoft.com/support/help/maple/view.aspx?path=LinearAlgebra/Generic/CharacteristicPolynomial), 39 bytes
```
LinearAlgebra[CharacteristicPolynomial]
```
```
M := <<1, 0, 0, 1, 0, 0, 0> | <1, 1, 0, 0, 1, 0, 1> | <1, 1, 0, 1, 1, 0, 0> | <1, 1, 0, 1, 1, 0, 0> | <1, 1, 0, 1, 1, 1, 1> | <1, 1, 1, 0, 1, 1, 1> | <0, 1, 0, 0, 0, 0, 1>>;
LinearAlgebra[CharacteristicPolynomial](M, x);
```
[](https://i.stack.imgur.com/1I7lW.png)
[Answer]
# [GAP](https://www.gap-system.org/), 24 bytes
```
CharacteristicPolynomial
```
```
m := [[4,2,1,3],[4,-3,9,0],[-1,1,0,3],[20,-4,5,20]];;
chPolynomial := CharacteristicPolynomial(m);
coup := CoefficientsOfUnivariatePolynomial(chPolynomial);
Print(chPolynomial , "\n");
Print(coup , "\n");
```
[Try it online!](https://tio.run/##VYyxCsIwFEV3vyJ0UniBNK2DFic/wC5ONUMIiX3QJCWNgl8f04K0bpdzz71POaZkyflCuq4GDiVUAnKiFZyA5UjLzNhCOQNawxE4E6Jpdqpv/fBx3qIc5oNrL4NUUQecIqq129tDlv1rXCSvjUGF2sXpZu4O3zKgjHqjb3/zsg3o4h8kQIqHK9Zu/v6xlL4)
[Answer]
# [Maxima](http://maxima.sourceforge.net/), 8 bytes
```
charpoly
```
```
A : matrix( [0, 5, 0, 12, -3, -6], [6, 3, 7, 16, 4, 2], [4, 0, 5, 1, 13, -2], [12, 10, 12, -2, 1, -6], [16, 13, 12, -4, 7, 10], [ 6, 17, 0, 3, 3, -1] );
ans: expand (charpoly (A, lambda));
print(ans);
```
[Try it online!](https://tio.run/##NYzBCoNADETv/Yo5rhDBVaugJ79DPKS1UMG1i3rYfv02WSkkIcy8GcdhcRzjgA6Oz30JBmNBuBPk2pKQV7LNRBgbgvytyPLVhFLFOoGCWxlFk6pB@y8ok3l1aFSxZNRXW6EG1GhTWZUmtxOy/sbb0QGv4HmbYZ5v3v1n/cIMhJXdY@ZMIL8v22kEzfoYfw)
] |
[Question]
[
This challenge is similar to [this other](https://codegolf.stackexchange.com/questions/32381/convert-english-to-a-number), however I made a restriction (see bold text below) that I think would made it much diffent and (I hope) fun either.
# The Challenge
Write a program or a function in any programming language that takes as input the English name of a positive integer `n` not exceeding `100` and returns `n` as an integer.
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden and ***you cannot use any built-in function, external tool, or library that already does this job***.
Shortest source code in bytes wins.
# Test
Here all the `input->output` cases:
```
one -> 1
two -> 2
three -> 3
four -> 4
five -> 5
six -> 6
seven -> 7
eight -> 8
nine -> 9
ten -> 10
eleven -> 11
twelve -> 12
thirteen -> 13
fourteen -> 14
fifteen -> 15
sixteen -> 16
seventeen -> 17
eighteen -> 18
nineteen -> 19
twenty -> 20
twenty-one -> 21
twenty-two -> 22
twenty-three -> 23
twenty-four -> 24
twenty-five -> 25
twenty-six -> 26
twenty-seven -> 27
twenty-eight -> 28
twenty-nine -> 29
thirty -> 30
thirty-one -> 31
thirty-two -> 32
thirty-three -> 33
thirty-four -> 34
thirty-five -> 35
thirty-six -> 36
thirty-seven -> 37
thirty-eight -> 38
thirty-nine -> 39
forty -> 40
forty-one -> 41
forty-two -> 42
forty-three -> 43
forty-four -> 44
forty-five -> 45
forty-six -> 46
forty-seven -> 47
forty-eight -> 48
forty-nine -> 49
fifty -> 50
fifty-one -> 51
fifty-two -> 52
fifty-three -> 53
fifty-four -> 54
fifty-five -> 55
fifty-six -> 56
fifty-seven -> 57
fifty-eight -> 58
fifty-nine -> 59
sixty -> 60
sixty-one -> 61
sixty-two -> 62
sixty-three -> 63
sixty-four -> 64
sixty-five -> 65
sixty-six -> 66
sixty-seven -> 67
sixty-eight -> 68
sixty-nine -> 69
seventy -> 70
seventy-one -> 71
seventy-two -> 72
seventy-three -> 73
seventy-four -> 74
seventy-five -> 75
seventy-six -> 76
seventy-seven -> 77
seventy-eight -> 78
seventy-nine -> 79
eighty -> 80
eighty-one -> 81
eighty-two -> 82
eighty-three -> 83
eighty-four -> 84
eighty-five -> 85
eighty-six -> 86
eighty-seven -> 87
eighty-eight -> 88
eighty-nine -> 89
ninety -> 90
ninety-one -> 91
ninety-two -> 92
ninety-three -> 93
ninety-four -> 94
ninety-five -> 95
ninety-six -> 96
ninety-seven -> 97
ninety-eight -> 98
ninety-nine -> 99
one hundred -> 100
```
[Answer]
# C, 160 bytes
```
g(char*s){char i=1,r=0,*p="k^[#>Pcx.yI<7CZpVgmH:o]sYK$2";for(;*s^'-'&&*s;r+=*s++|9);r=r%45+77;for(;*p!=r;p++,i++);return((*s^'-')?0:g(s+1))+(i<21?i:10*(i-18));}
```
# Test it
```
int main ()
{
char* w[] = {"", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen", "twenty", "twenty-one", "twenty-two", "twenty-three", "twenty-four", "twenty-five", "twenty-six", "twenty-seven", "twenty-eight", "twenty-nine", "thirty", "thirty-one", "thirty-two", "thirty-three", "thirty-four", "thirty-five", "thirty-six", "thirty-seven", "thirty-eight", "thirty-nine", "forty", "forty-one", "forty-two", "forty-three", "forty-four", "forty-five", "forty-six", "forty-seven", "forty-eight", "forty-nine", "fifty", "fifty-one", "fifty-two", "fifty-three", "fifty-four", "fifty-five", "fifty-six", "fifty-seven", "fifty-eight", "fifty-nine", "sixty", "sixty-one", "sixty-two", "sixty-three", "sixty-four", "sixty-five", "sixty-six", "sixty-seven", "sixty-eight", "sixty-nine", "seventy", "seventy-one", "seventy-two", "seventy-three", "seventy-four", "seventy-five", "seventy-six", "seventy-seven", "seventy-eight", "seventy-nine", "eighty", "eighty-one", "eighty-two", "eighty-three", "eighty-four", "eighty-five", "eighty-six", "eighty-seven", "eighty-eight", "eighty-nine", "ninety", "ninety-one", "ninety-two", "ninety-three", "ninety-four", "ninety-five", "ninety-six", "ninety-seven", "ninety-eight", "ninety-nine", "one hundred"};
int n;
for (n = 1; n <= 100; n++)
{
printf ("%s -> %d\n", w[n], g(w[n]));
if (n != g(w[n]))
{
printf ("Error at n = %d", n);
return 1;
}
}
return 0;
}
```
# How it works
After some attempts, I found a function that maps the "exceptional" numbers `one`, `two`, `three`, `four`, `five`, `six`, `seven`, `eight`, `nine`, `ten`, `eleven`, `twelve`, `thirteen`, `fourteen`, `fifteen`, `sixteen`, `seventeen`, `eighteen`, `nineteen`, `twenty`, `thirty`, `forty`, `fifty`, `sixty`, `seventy`, `eighty`, `ninety`, `one hundred`, to the printable ASCII characters `k`, `.`, `[`, `<`, `*`, , `c`, `K`, `w`, `y`, `e`, `(`, `S`, `_`, `-`, `C`, `)`, `7`, `=`, `4`, `&`, `o`, `]`, `s`, `Y`, `g`, `m`, `N`, respectively.
This function is:
```
char hash (char* s)
{
char r = 0;
while (*s)
{
r += *s|9;
s++;
}
return r%45+77;
}
```
The golfed program computes the `hash` function of the input until it reaches the end of the string or the character `-`. Then it searches the hash in the string `k.[<* cKwye(S_-C)7=4&o]sYgmN` and determines the corresponding number. If the end of the input string was reached the number is returned, if instead a `-` was reached, then it is returned the number plus the result of the golfed program applied to the rest of the input string.
[Answer]
# JavaScript (ES6), ~~175~~ ~~166~~ ~~163~~ ~~156~~ ~~153~~ 147 bytes
*Saved 7 bytes thanks to @Neil*
```
a=>+a.replace(/.+te|.*el|y$/,x=>x[1]?'on-'+x:'-d').split(/ |-|dr/).map(x=>"un|d,on|le,w,th,fo,f,x,s,h,i,".split`,`.findIndex(y=>x.match(y))).join``
```
Verify it here:
```
f=a=>+a.replace(/.+te|.*el|y$/,x=>x[1]?'on-'+x:'-d').split(/ |-|dr/).map(x=>"un|d,on|le,w,th,fo,f,x,s,h,i,".split`,`.findIndex(y=>x.match(y))).join``;
document.body.innerHTML="<pre>"+["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen","fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","twenty-one","twenty-two","twenty-three","twenty-four","twenty-five","twenty-six","twenty-seven","twenty-eight","twenty-nine","thirty","thirty-one","thirty-two","thirty-three","thirty-four","thirty-five","thirty-six","thirty-seven","thirty-eight","thirty-nine","forty","forty-one","forty-two","forty-three","forty-four","forty-five","forty-six","forty-seven","forty-eight","forty-nine","fifty","fifty-one","fifty-two","fifty-three","fifty-four","fifty-five","fifty-six","fifty-seven","fifty-eight","fifty-nine","sixty","sixty-one","sixty-two","sixty-three","sixty-four","sixty-five","sixty-six","sixty-seven","sixty-eight","sixty-nine","seventy","seventy-one","seventy-two","seventy-three","seventy-four","seventy-five","seventy-six","seventy-seven","seventy-eight","seventy-nine","eighty","eighty-one","eighty-two","eighty-three","eighty-four","eighty-five","eighty-six","eighty-seven","eighty-eight","eighty-nine","ninety","ninety-one","ninety-two","ninety-three","ninety-four","ninety-five","ninety-six","ninety-seven","ninety-eight","ninety-nine","one hundred"].map((x,y)=>'f("'+x+'") === '+f(x)+"? "+(f(x)===y+1)).join("<br>")+"</pre>"
```
### How it works
The basic idea is to split each number into its digit-words, then map each word to the corresponding digit. *Almost* all of the words are set up to be matched properly with a simple regex, but there are a few anomalies:
* `eleven` through `nineteen`: if the word contains an `el`, or a `te` in the middle (to avoid `ten`), we add a `on-` to the beginning, changing these to `on-eleven` through `on-nineteen`.
* `twenty`, `thirty`, etc.: replacing a trailing `y` with `-d` changes these to `twent-d`, `thirt-d`, etc.
Now we split at hyphens, spaces, and `dr`s. This splits everything from 11 to 99 into its corresponding digit-words, and `"one hundred"` into `[one,hun,ed]`. Then we map each of these words through an array of regexes, and keep the index of the one that matches first.
```
0: /un|d/ - This matches the "hun" and "ed" in 100, as well as the "d" we placed on the end of 20, 30, etc.
1: /on|le/ - Matches "one" and the "on" we placed on the beginning of 11 through 19, along with "eleven".
2: /w/ - Matches "two", "twelve", and "twenty".
3: /th/ - Matches "three" and "thirty".
4: /fo/ - Matches "four" and "forty".
5: /f/ - "five" and "fifty" are the only words by now that contain an "f".
6: /x/ - "six" and "sixty" are the only words that contain an "x".
7: /s/ - "seven" and "seventy" are the only words by now that contain an "s".
8: /h/ - "eight" and "eighty" are the only words by now that contain an "h".
9: /i/ - "nine" and "ninety" are the only words by now that contain an "i".
10: /<empty>/ - "ten" is the only word left, but it still has to be matched.
```
By now, each and every input will be the array of the proper digits. All we have to do is join them with `join``` , convert to a number with unary `+`, and we're done.
[Answer]
# sh + coreutils, 112 bytes
Can be run on all testcases at once, one per line.
```
sed -r "`awk '$0="s/"$0"/+"NR"/g"'<<<"on
tw
th
fo
fi
si
se
ei
ni
te|lv
el"`
s/ /y0/
s/y/*10/
s/^\+|[a-z-]//g"|bc
```
## Explanation
The backticked `awk` evaluates to the `sed` script
```
s/on/+1/g # one, one hundred
s/tw/+2/g # two, twelve, twenty
s/th/+3/g # three, thirteen, thirty
s/fo/+4/g # ...
s/fi/+5/g
s/si/+6/g
s/se/+7/g
s/ei/+8/g
s/ni/+9/g
s/te|lv/+10/g # ten, -teen, twelve
s/el/+11/g # eleven
```
which transforms parts of numbers into their numeric representation.
```
fife -> +5ve
ten -> +10n
eleven -> +11even
twelve -> +2e+10e
sixteen -> +6x+10en
thirty-seven -> +3irty-+7ven
forty-four -> +4rty-+4ur
eighty -> +8ghty
one hundred -> +1e hundred
```
The additional lines of the sed script
```
s/ /y0/
s/y/*10/
```
take care of `-ty`s and `one hundred`.
```
+3irty-+7ven -> +3irt*10-+7ven
+4rty-+4ur -> +4rt*10-+4ur
+8ghty -> +8ght*10
+1e hundred -> +1ey0hundred -> +1e*100hundred
```
Finally, remove leading `+`s and everything that is not `+`, `*` or a digit.
```
s/^\+|[a-z-]//g"
```
Only math expressions remain
```
fife -> 5
sixteen -> 6+10
forty-four -> 4*10+4
eighty -> 8*10
one hundred -> 1*100
```
and can be piped into `bc`.
[Answer]
## Pyth, 79 76 75 68 bytes
Thank @ETHproductions for 7 bytes.
```
?}"hu"z100sm*+hxc."ewEСBu["2<d2?|}"een"d}"lv"dTZ?}"ty"dT1cz\-
```
Basically first checks the corner case of 100, then uses an array of the first two letters of the numbers 0 to 11 to determine the semantics of the input and modify the value according to suffix ("-ty" and "-teen"; "lv" in 12 is another corner case). First splits input into a list of words, then map each one to a value, and sum them up.
In pythonic pseudocode:
```
z = input() # raw, unevaluated
Z = 0
T = 10
?}"hu"z if "hu" in z: # checks if input is 100
100 print(100)
else:
sm sum(map( lambda d: # evaluates each word, then sum
* multiply(
+hxc."ewEСBu["2<d2 plusOne(chop("ontwth...niteel",2).index(d[:2])) + \
# chops string into ["on","tw",..."el"]
# ."ewEСBu[" is a packed string
?|}"een"d}"lv"dTZ (T if "een" in d or "lv" in d else Z),
# add 10 for numbers from 12 to 19
?}"ty"dT1 T if "ty" in d else 1), # times 10 if "-ty"
cz\- z.split("-")) # splits input into words
```
[Test suite](http://pyth.herokuapp.com/?code=%3F%7D%22hu%22z100sm%2a%2Bhxc.%22ew%18E%C3%90%01%C2%A1%02B%1Bu%C2%AD%5B%C2%91%222%3Cd2%3F%7C%7D%22een%22d%7D%22lv%22dTZ%3F%7D%22ty%22dT1cz%5C-&input=hundred&test_suite=1&test_suite_input=one%0Atwo%0Athree%0Afour%0Afive%0Asix%0Aseven%0Aeight%0Anine%0Aten%0Aeleven%0Atwelve%0Athirteen%0Afourteen%0Afifteen%0Asixteen%0Aseventeen%0Aeighteen%0Anineteen%0Atwenty%0Atwenty-one%0Atwenty-two%0Atwenty-three%0Atwenty-four%0Atwenty-five%0Atwenty-six%0Atwenty-seven%0Atwenty-eight%0Atwenty-nine%0Athirty%0Athirty-one%0Athirty-two%0Athirty-three%0Athirty-four%0Athirty-five%0Athirty-six%0Athirty-seven%0Athirty-eight%0Athirty-nine%0Aforty%0Aforty-one%0Aforty-two%0Aforty-three%0Aforty-four%0Aforty-five%0Aforty-six%0Aforty-seven%0Aforty-eight%0Aforty-nine%0Afifty%0Afifty-one%0Afifty-two%0Afifty-three%0Afifty-four%0Afifty-five%0Afifty-six%0Afifty-seven%0Afifty-eight%0Afifty-nine%0Asixty%0Asixty-one%0Asixty-two%0Asixty-three%0Asixty-four%0Asixty-five%0Asixty-six%0Asixty-seven%0Asixty-eight%0Asixty-nine%0Aseventy%0Aseventy-one%0Aseventy-two%0Aseventy-three%0Aseventy-four%0Aseventy-five%0Aseventy-six%0Aseventy-seven%0Aseventy-eight%0Aseventy-nine%0Aeighty%0Aeighty-one%0Aeighty-two%0Aeighty-three%0Aeighty-four%0Aeighty-five%0Aeighty-six%0Aeighty-seven%0Aeighty-eight%0Aeighty-nine%0Aninety%0Aninety-one%0Aninety-two%0Aninety-three%0Aninety-four%0Aninety-five%0Aninety-six%0Aninety-seven%0Aninety-eight%0Aninety-nine%0Aone+hundred&debug=0)
---
## Python 3, 218 bytes
```
z=input()
if "hu" in z:print(100);exit()
print(sum(map(lambda d:([0,"on","tw","th","fo","fi","si","se","ei","ni","te","el"].index(d[:2])+(10 if "een" in d or "lv" in d else 0))*(10 if "ty" in d else 1),z.split("-"))))
```
Basically identical to the Pyth answer.
---
Off-topic:
I just discovered a meaningful version of the answer to life, the universe and everything: it's tea-thirsty twigs. Wow, twigs that yearn for tea! I'm not sure how many other answers do this, but for my answer if the input is "tea-thirsty-twigs" the output is 42.
[Answer]
# Python 3, ~~365~~ ~~361~~ ~~310~~ 303 characters
## Golfed
```
def f(a):
y=0
for i in a.split("-"):
x="one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir;four;fif;six;seven;eigh;nine;twenty,thirty,forty,fifty,sixty,seventy,eighty,ninety,one hundred".replace(";","teen,").split(",").index(i)
y+=x+1 if x<20 else range(30,110,10)[x-20]
return y
```
## Ungolfed
```
def nameToNumber (numberName):
names = ["one","two","three","four","five","six","seven","eight","nine","ten","eleven","twelve","thirteen",
"fourteen","fifteen","sixteen","seventeen","eighteen","nineteen","twenty","thirty","forty","fifty",
"sixty","seventy","eighty","ninety","one hundred"]
numbers = range(30, 110, 10)
number = 0
for n in numberName.split("-"):
x = names.index(n)
number += x + 1 if x < 20 else numbers[x - 20]
return number
```
[Answer]
## Haskell, ~~252~~ 231 bytes
```
let l=words;k=l"six seven eight nine";w=l"one two three four five"++k++l"ten eleven twelve"++((++"teen")<$>l"thir four fif"++k)++[n++"ty"++s|n<-l"twen thir for fif"++k,s<-"":['-':x|x<-take 9w]]in maybe 100id.flip lookup(zip w[1..])
```
This creates a list of all English number names from "one" to "ninety-nine" and then looks the index of the input up. If it doesn't exist, we're in the edge case "one hundred", so it returns `100`, otherwise it's going to return the index.
### Ungolfed
```
-- k in the golfed variant
common = words "six seven eight nine"
-- w in the golfed variant
numbers = words "one two three four five" ++ common
++ words "ten eleven twelve" ++ [p ++ "teen" | p <- words "thir four fif" ++ common]
++ [p ++ "ty" ++ s| p <- words "twen thir for fif" ++ common
, s <- "" : map ('-':) (take 9 numbers)]
-- part of the expression in the golfed variant
convert :: String -> Int
convert s = maybe 100 id $ lookup s $ zip numbers [1..]
```
[Answer]
# Python 2, 275 characters
```
def x(n):a='one two three four five six seven eight nine ten eleven twelve'.split();t='twen thir four fif six seven eigh nine'.split();b=[i+'teen'for i in t[1:]];c=[i+'ty'for i in t];return(a+b+[i+j for i in c for j in ['']+['-'+k for k in a[:9]]]+['one hundred']).index(n)+1
```
It simple builds a list of every number and finds the index.
[Answer]
# Japt, 82 bytes
```
+Ur`(.+)¿``¿-$1` r"y$""-d" q$/ |-|dr/$ £`un|Üaiwo|ØÏ¿ifoifix¿iÊ¿¿e¿iv`qi b_XfZ}Ãq
```
Each `¿` represents an unprintable char. [Test it online!](http://ethproductions.github.io/japt?v=master&code=K1VyYCguKymSYGCNLSQxYCByInkkIiItZCIgcSQvIHwtfGRyLyQgo2B1bnzcYWl3b3zYz5BpZm9pZml4iWnKgopliGl2YHFpIGJfWGZafcNx&input=InNldmVudHktdHdvIg==)
Based on my JS answer. Subtract one byte if the output doesn't need to be an integer, since it would appear exactly the same as a string.
### How it works
```
+Ur`(.+)¿` `¿-$1` r"y$""-d" q/ |-|dr/ £ `un|Üaiwo|ØÏ¿ifoifix¿iÊ¿¿e¿iv` qi b_ XfZ}à q
+Ur"(.+)te""on-$1" r"y$""-d" q/ |-|dr/ mX{"un|dioniwo|wenithifoifixisihineiteiniv"qi bZ{XfZ}} q
Ur"(.+)te""on-$1" // Replace "thirteen", "fourteen", etc. with "on-thiren", "on-fouren", etc.
r"y$""-d" // Replace "twenty", "thirty", etc. with "twent-d", "thirt-d", etc.
q/ |-|dr/ // Split at occurances of a space, hyphen, or "dr". By now,
// "one", "thirteen", "twenty", "sixty-six", "one hundred" will have become:
// "one", "on" "thiren", "twent" "d", "sixty" "six", "one" "hun" "ed"
mX } // Map each item X in the resulting array to:
"..."qi // Take this string, split at "i"s,
b_XfZ} // and find the first item Z where X.match(RegExp(Z)) is not null.
// See my JS answer to learn exactly how this works.
// Our previous example is now
// "1", "1" "3", "2" "0", "6" "6", "1" "0" "0"
+ q // Join and convert to integer.
// 1, 13, 20, 66, 100
```
[Answer]
# JavaScript, ~~214~~ 199 bytes
As always: turns out this is too long to compete, but now that I'm done it'd be a waste not to post this.
Perhaps there's an obvious way to golf this further that I've overlooked?
```
e=s=>s.slice(-1)=='d'?100:' ontwthfofisiseeinite'.indexOf(s.slice(0,2))/2;f=s=>([t,u]=s.split('-'),~s.indexOf`le`?11:~s.indexOf`lv`?12:e(t)+(t.slice(-3)=='een')*10+''+(u?e(u):t.slice(-1)=='y'?0:''))
```
[JSFiddle for test cases](https://jsfiddle.net/7n10vn7j/1/)
[Answer]
## Perl, 158 bytes
```
@s=split/(\d+)/,'te1ten0l1le1on1tw2th3fo4fi5si6se7ei8ni9d00';foreach(split'-',$n=$ARGV[0]){for($i=0;$i<$#s;$i+=2){m/$s[$i]/&&print$s[$i+1]}}$n=~/ty$/&&print 0
```
Runs from the command line. `one hundred` must be entered as `"one hundred"` to stop it being interpreted as two inputs.
] |
[Question]
[
The ubiquitous 7-segment numerical display can unambiguously display all 16 hexadecimal digits as show in [this wikipedia .gif](http://en.wikipedia.org/wiki/Seven-segment_display#mediaviewer/File:7-segments_Indicator.gif)
Entries for this challenge will create a circuit diagram using NAND logic gates which transforms the four bits of a hex digit to the inputs for the seven segments. The inputs for the 7 segment display are typically labelled as follows: *(DP (decimal point) is ignored for this challenge)*

Thus your circuit will need to conform to the following truth table:
```
Hex | Hex Input Bit | Output to Segment line:
digit | 3 2 1 0 | A B C D E F G
------+---------------+-----------------------
0 | 0 0 0 0 | 1 1 1 1 1 1 0
1 | 0 0 0 1 | 0 1 1 0 0 0 0
2 | 0 0 1 0 | 1 1 0 1 1 0 1
3 | 0 0 1 1 | 1 1 1 1 0 0 1
4 | 0 1 0 0 | 0 1 1 0 0 1 1
5 | 0 1 0 1 | 1 0 1 1 0 1 1
6 | 0 1 1 0 | 1 0 1 1 1 1 1
7 | 0 1 1 1 | 1 1 1 0 0 0 0
8 | 1 0 0 0 | 1 1 1 1 1 1 1
9 | 1 0 0 1 | 1 1 1 1 0 1 1
A | 1 0 1 0 | 1 1 1 0 1 1 1
b | 1 0 1 1 | 0 0 1 1 1 1 1
C | 1 1 0 0 | 1 0 0 1 1 1 0
d | 1 1 0 1 | 0 1 1 1 1 0 1
E | 1 1 1 0 | 1 0 0 1 1 1 1
F | 1 1 1 1 | 1 0 0 0 1 1 1
```
*I think this table is accurate, but please let me know if you spot any errors.*
Your score is determined by the number of 2-input NAND gates you use (1 point per gate). To simplify things, you may use AND, OR, NOT, and XOR gates in your diagram, with the following corresponding scores:
* `NOT: 1`
* `AND: 2`
* `OR: 3`
* `XOR: 4`
[Answer]
# 30 NANDs
I am quite sure there are no simpler solutions to this problem,
except perhaps by changing the symbols on the display,
but that would be another and different problem.
Since this is actually something useful to do, for instance when
programming an FPGA to show output, I provide Verilog code.
As for the minimalism: Of course it was tricky to make.
It is not comprehensible, since a 7-segment display is
just a fairly random way that humans show numbers, resulting
in a circuit that is fairly random too.
And as is typical for these minimal circuits, its logical depth
is somewhat higher than for close solutions. I guess this is because serial is simpler than parallel.
Transmission delay is indicated by downward position of each NAND gate on the sheet.

Verilog code:
```
// Hexadecimal 7-segment display driver
// Minimal at 30 NANDs
//
// By Kim Øyhus 2018 (c) into (CC BY-SA 3.0)
// This work is licensed under the Creative Commons Attribution 3.0
// Unported License. To view a copy of this license, visit
// https://creativecommons.org/licenses/by-sa/3.0/
//
// This is my entry to win this Programming Puzzle & Code Golf
// at Stack Exchange:
// https://codegolf.stackexchange.com/questions/37648/drive-a-hexadecimal-7-segment-display-using-nand-logic-gates
//
// I am quite sure there are no simpler solutions to this problem,
// except perhaps by changing the symbols on the display,
// but that would be another and different problem.
//
// Since this is actually something useful to do, for instance when
// programming an FPGA to show output, I provide this Verilog code.
//
// As for the minimalism: Of course it was tricky to make.
// It is not comprehensible, since a 7-segment display is
// just a fairly random way of showing numbers, resulting
// in a circuit that is fairly random too.
// And as is typical for these minimal circuits, its logical depth
// is somewhat higher than for close solutions. I guess this is because
// serial is simpler than parallel.
//
// 4 bits of input "in_00?", and 7 bits of output,
// one bit per LED in the segment.
// A
// F B
// G
// E C
// D
module display7 ( in_000, in_001, in_002, in_003, G, F, E, D, C, B, A );
input in_000, in_001, in_002, in_003;
output G, F, E, D, C, B, A;
wire wir000, wir001, wir002, wir003, wir004, wir005, wir006, wir007, wir008, wir009, wir010, wir011, wir012, wir013, wir014, wir015, wir016, wir017, wir018, wir019, wir020, wir021, wir022 ;
nand gate000 ( wir000, in_000, in_002 );
nand gate001 ( wir001, in_000, in_000 );
nand gate002 ( wir002, wir000, in_001 );
nand gate003 ( wir003, in_001, wir002 );
nand gate004 ( wir004, wir000, wir002 );
nand gate005 ( wir005, in_002, wir003 );
nand gate006 ( wir006, in_003, wir001 );
nand gate007 ( wir007, wir006, wir004 );
nand gate008 ( wir008, in_003, wir005 );
nand gate009 ( wir009, wir005, wir008 );
nand gate010 ( wir010, in_003, wir008 );
nand gate011 ( wir011, wir010, wir009 );
nand gate012 ( wir012, wir010, wir007 );
nand gate013 ( wir013, wir001, wir011 );
nand gate014 ( wir014, wir003, wir004 );
nand gate015 ( G, wir011, wir014 );
nand gate016 ( wir015, in_003, wir014 );
nand gate017 ( wir016, wir015, wir013 );
nand gate018 ( C, wir016, wir012 );
nand gate019 ( wir017, wir016, wir007 );
nand gate020 ( wir018, wir003, wir012 );
nand gate021 ( wir019, wir017, in_003 );
nand gate022 ( F, wir011, wir017 );
nand gate023 ( D, wir018, wir017 );
nand gate024 ( B, wir012, F );
nand gate025 ( wir020, wir004, wir018 );
nand gate026 ( wir021, wir001, D );
nand gate027 ( E, wir019, wir021 );
nand gate028 ( wir022, D, wir019 );
nand gate029 ( A, wir020, wir022 );
endmodule
```
Kim Øyhus
---
I (@Digital Trauma) recently reviewed this answer and was so impressed with it, I drew it out in [Logic.ly](https://logic.ly/demo/) and captured this GIF - it really does work!
[](https://i.stack.imgur.com/AB0nS.gif)
[Answer]
# Dominoes - Total Score: 243 NANDs
* ORs used: 61 (3 NANDs each -> 183 NANDs)
* NOTs used: 60 (1 NANDs each -> 60 NANDs)
This solution is in [dominoes](https://codegolf.stackexchange.com/questions/34875/golfing-for-domino-day) and required a collection of pieces of software I wrote in the course of answering Martin Büttner's two Domino related questions to produce ([Golfing for Domino Day](https://codegolf.stackexchange.com/questions/34875/golfing-for-domino-day) and [Domino Circuits](https://codegolf.stackexchange.com/questions/36361/domino-circuits/36364#36364)).
By modifying my [Domino Circuit](https://codegolf.stackexchange.com/questions/36361/domino-circuits/36364#36364) solver, I was able to produce a [domino circuit](http://visualmelon.onl/7segalllf.txt) (this file also contains the solver output and circuit skeleton) consisting of ORs, and IFNOTs where the first input is always TRUE (so it's essentially a NOT). Because there isn't much that *will* fit in this answer, I present the OR and NOT solutions to the truth table:
```
A: 1011011111101011
((-1 ifnot (2 or (1 or (-1 ifnot 0)))) or ((-1 ifnot ((-1 ifnot 1) or (-1 ifnot 2))) or ((-1 ifnot (3 or (-1 ifnot (0 or (-1 ifnot 1))))) or (-1 ifnot (0 or ((-1 ifnot 3) or (-1 ifnot (2 or 1))))))))
B: 1111100111100100
((-1 ifnot (3 or 1)) or ((-1 ifnot (3 or (2 or 0))) or (-1 ifnot ((-1 ifnot 3) or ((-1 ifnot (2 or (0 or (-1 ifnot 1)))) or (-1 ifnot ((-1 ifnot 0) or (-1 ifnot 2))))))))
C: 1101111111110100
((-1 ifnot (2 or (-1 ifnot 3))) or ((-1 ifnot (1 or (-1 ifnot 0))) or (-1 ifnot (0 or (-1 ifnot (3 or (1 or (-1 ifnot 2))))))))
D: 1011011011011110
((-1 ifnot (3 or (1 or 0))) or ((-1 ifnot (2 or ((-1 ifnot (3 or 0)) or (-1 ifnot (1 or 0))))) or (-1 ifnot ((-1 ifnot 2) or ((-1 ifnot (3 or 1)) or (-1 ifnot ((-1 ifnot 1) or (-1 ifnot 3))))))))
E: 1010001010111111
((-1 ifnot (3 or (-1 ifnot (2 or (-1 ifnot 1))))) or (-1 ifnot ((-1 ifnot 0) or (-1 ifnot (2 or 1)))))
F: 1000111011111011
((-1 ifnot (3 or (-1 ifnot 1))) or ((-1 ifnot (2 or (0 or (-1 ifnot (1 or (-1 ifnot 3)))))) or (-1 ifnot ((-1 ifnot 0) or (-1 ifnot (2 or (-1 ifnot 1)))))))
G: 0011111011110111
((-1 ifnot (2 or (0 or (-1 ifnot 1)))) or ((-1 ifnot (1 or (-1 ifnot (2 or 0)))) or (-1 ifnot ((-1 ifnot (3 or 2)) or (-1 ifnot (0 or (-1 ifnot 3)))))))
```
*Note that the only binary operations used are OR and IFNOT, where I count each IFNOT as a NOT for scoring purposes*
I added a 7-segment display to the end of the circuit and fed it into a domino simulator/gif generator. The resulting gif (which shows 'A' being displayed) took about 2 hours to generate. Because the final circuit is 1141 \* 517 in size each "cell" is represented by a single pixel. A black cell is empty, a grey cell has a standing domino in it, and a white cell has a fallen domino in it. This means that you can't really tell what is going on, and it won't help if it's being squashed at all. *Sparr kindly provided a much smaller version of my original gif (650kB), so here it is!*

Below is the last frame of the animation for input 1010 ('A') as above. You can see the inputs on the far left, powerline at the top, the switchboard taking up most of the space, the 7 individual pieces of logic (these are domino representations of the functions above) to the left of the switch board, and to the far right is the 7-segment display itself. When this runs, the individual segments light up roughly at the same time, so you can't be looking at it for too long with some segments lit up waiting for others to light up.

*See the animation in it's full glory [here](http://visualmelon.onl/7segdisp.gif) (36MB) or [here](https://i.stack.imgur.com/YGxpw.gif) (650kB, courtesy of Sparr) (the smaller copy is much smaller, but my browser seemed to like skipping frames marring the beauty so I've left the original thusly)*
*The detail of the 7-segment display can be seen [here](http://visualmelon.onl/7segdisplaydetail1.png) ('1' is shown)*
[Answer]
Using ~ for NOT and N for NAND, a computer search (without sharing terms between outputs) finds a solution with 82 NANDs without sharing. Manually looking for sharing terms reduces it to 54 NANDs, and a computer search that includes sharing further reduces it to 37 NANDs. The minimum might be even lower, as the method is certainly not exhaustive.
Here's the program that recreates the above table. Each line is labeled with the NANDS for that output.
```
#include <stdio.h>
int N(int x, int y) { return 1 & ~(x & y); }
void main(void)
{
int i0, i1, i2, i3;
for (i3 = 0; i3 <= 1; i3++) {
for (i2 = 0; i2 <= 1; i2++) {
for (i1 = 0; i1 <= 1; i1++) {
for (i0 = 0; i0 <= 1; i0++) {
printf("%d %d %d %d : %d %d %d %d %d %d %d\n", i3, i2, i1, i0,
/* 14 */ N(N(N(i3, N(i2, i1)), N(N(i2, i0), ~i1)), N(N(i2, N(i3, N(i3, i0))), N(i0, N(i3, N(i3, i1))))),
/* 12 */ N(N(N(i3, i0), N(i2, N(i1, i0))), N(~i1, N(N(i3, i0), N(~i3, N(i2, i0))))),
/* 10 */ N(N(i0, N(i3, i1)), N(N(i3, i2), N(i1, N(i1, N(~i3, ~i2))))),
/* 16 */ N(N(N(i2, i1), N(N(i3, i0), N(i2, i0))), N(N(i0, N(i1, ~i2)), N(N(i3, i2), N(N(i3, i1), N(i2, N(i2, i1)))))),
/* 7 */ N(N(i3, i2), N(N(i2, N(i2, i1)), N(i0, N(i3, i1)))),
/* 11 */ N(N(i3, N(i2, N(i3, i1))), N(N(i1, N(i2, N(i2, i0))), N(i0, N(i2, ~i3)))),
/* 12 */ N(N(i3, i0), ~N(N(i1, N(i2, i0)), N(N(i3, i2), N(~i3, N(i2, N(i2, i1)))))) );
} } } }
}
```
And here's the output:
```
0 0 0 0 : 1 1 1 1 1 1 0
0 0 0 1 : 0 1 1 0 0 0 0
0 0 1 0 : 1 1 0 1 1 0 1
0 0 1 1 : 1 1 1 1 0 0 1
0 1 0 0 : 0 1 1 0 0 1 1
0 1 0 1 : 1 0 1 1 0 1 1
0 1 1 0 : 1 0 1 1 1 1 1
0 1 1 1 : 1 1 1 0 0 0 0
1 0 0 0 : 1 1 1 1 1 1 1
1 0 0 1 : 1 1 1 1 0 1 1
1 0 1 0 : 1 1 1 0 1 1 1
1 0 1 1 : 0 0 1 1 1 1 1
1 1 0 0 : 1 0 0 1 1 1 0
1 1 0 1 : 0 1 1 1 1 0 1
1 1 1 0 : 1 0 0 1 1 1 1
1 1 1 1 : 1 0 0 0 1 1 1
```
And here are the equivalent equations, sharing terms that get it down to 54 NANDs:
```
/* 1 */ int z1 = 1 - i1;
/* 1 */ int z2 = 1 - i2;
/* 1 */ int z3 = 1 - i3;
/* 1 */ int n_i2_i0 = N(i2, i0);
/* 1 */ int n_i2_i1 = N(i2, i1);
/* 1 */ int n_i3_i0 = N(i3, i0);
/* 1 */ int n_i3_i1 = N(i3, i1);
/* 1 */ int n_i3_i2 = N(i3, i2);
/* 1 */ int n_i0_n_i3_i1 = N(i0, n_i3_i1);
/* 1 */ int n_i2_n_i2_i1 = N(i2, n_i2_i1);
printf("%d %d %d %d : %d %d %d %d %d %d %d\n", i3, i2, i1, i0,
/* 9 */ N(N(N(i3, n_i2_i1), N(n_i2_i0, z1)), N(N(i2, N(i3, n_i3_i0)), N(i0, N(i3, n_i3_i1)))),
/* 7 */ N(N(n_i3_i0, N(i2, N(i1, i0))), N(z1, N(n_i3_i0, N(z3, n_i2_i0)))),
/* 5 */ N(n_i0_n_i3_i1, N(n_i3_i2, N(i1, N(i1, N(z3, z2))))),
/* 8 */ N(N(n_i2_i1, N(n_i3_i0, n_i2_i0)), N(N(i0, N(i1, z2)), N(n_i3_i2, N(n_i3_i1, n_i2_n_i2_i1)))),
/* 2 */ N(n_i3_i2, N(n_i2_n_i2_i1, n_i0_n_i3_i1)),
/* 8 */ N(N(i3, N(i2, n_i3_i1)), N(N(i1, N(i2, n_i2_i0)), N(i0, N(i2, z3)))),
/* 6 */ N(n_i3_i0, ~N(N(i1, n_i2_i0), N(n_i3_i2, N(z3, n_i2_n_i2_i1)))) );
```
And here's the 37 NAND solution:
```
x0fff = N(i3, i2);
x33ff = N(i3, i1);
x55ff = N(i3, i0);
x0f0f = not(i2);
x3f3f = N(i2, i1);
x5f5f = N(i2, i0);
xcfcf = N(i2, x3f3f);
xf3f3 = N(i1, x0f0f);
x5d5d = N(i0, xf3f3);
xaaa0 = N(x55ff, x5f5f);
xfc30 = N(x33ff, xcfcf);
xd5df = N(x3f3f, xaaa0);
xf3cf = N(x0fff, xfc30);
xaeb2 = N(x5d5d, xf3cf);
x7b6d = N(xd5df, xaeb2);
xb7b3 = N(i1, x7b6d);
xf55f = N(x0fff, xaaa0);
xcea0 = N(x33ff, xf55f);
x795f = N(xb7b3, xcea0);
xd7ed = N(xaeb2, x795f);
xfaf0 = N(x55ff, x0f0f);
xae92 = N(x55ff, x7b6d);
xdd6d = N(x33ff, xae92);
x279f = N(xfaf0, xdd6d);
xaf0f = N(i2, x55ff);
x50ff = N(i3, xaf0f);
xef4c = N(xb7b3, x50ff);
x1cb3 = N(xf3cf, xef4c);
xef7c = N(xf3cf, x1cb3);
xfb73 = N(i1, x279f);
x2c9e = N(xd7ed, xfb73);
xdf71 = N(xf3cf, x2c9e);
xdd55 = N(i0, x33ff);
xf08e = N(x0fff, xdf71);
x2ffb = N(xdd55, xf08e);
x32ba = N(xcfcf, xdd55);
xfd45 = N(x0fff, x32ba);
printf("%d %d %d %d : %d %d %d %d %d %d %d\n", i3, i2, i1, i0,
xd7ed, x279f, x2ffb, x7b6d, xfd45, xdf71, xef7c);
} } } }
```
[Answer]
# 197 NANDs
Since this is my first logic gates challenge. it is not golfed much, and may not be the smallest solution. I'm not using circuit split here.
```
A = OR(AND(d, NOT(AND(a, XOR(c, b)))), AND(NOT(d), NOT(AND(NOT(b), XOR(a, c)))))
B = AND(OR(OR(NOT(c), AND(NOT(d), NOT(XOR(b, a)))), AND(d, a)), NOT(AND(AND(d, b), a)))
C = OR(AND(NOT(c), NOT(AND(AND(NOT(d), b), NOT(a)))), AND(c, OR(NOT(d), AND(AND(d, NOT(b)), a))))
D = AND(OR(OR(OR(a, c), AND(AND(NOT(d), NOT(c)), NOT(a))), AND(AND(d, NOT(c)), NOT(b))), NOT(OR(AND(AND(NOT(d), NOT(b)), XOR(c, a)), AND(AND(c, b), a))))
E = OR(AND(NOT(a), NOT(AND(AND(NOT(d), c), NOT(b)))), AND(d, NOT(AND(AND(NOT(c), NOT(b)), a))))
F = AND(OR(OR(d, c), AND(NOT(b), NOT(a))), NOT(AND(AND(c, a), XOR(d, b))))
G = AND(OR(OR(d, c), b), NOT(OR(AND(AND(NOT(d), c), AND(b, a)), AND(AND(d, c), AND(NOT(b), NOT(a))))))
```
* 36 NOTs used, 36 NANDs
* 41 ANDs used, 84 NANDs
* 19 ORs used, 57 NANDs
* 5 XORs used, 20 NANDs
If I'm right, my score is **197**.
---
During this challenge, I made a simple JavaScript code to test my gate.
```
function NOT(a){return !a}function AND(a,b){return a&b}function OR(a,b){return a|b}function XOR(a,b){return a^b}
for(d=0;d<=1;d++){for(c=0;c<=1;c++){for(b=0;b<=1;b++){for(a=0;a<=1;a++){console.log(""+d+c+b+a,
// Enter your gate here
// OR(AND(d, NOT(AND(a, XOR(c, b)))), AND(NOT(d), NOT(AND(NOT(b), XOR(a, c)))))
)}}}}
```
Copy and modify gate, and paste it to your browser's console, or Node.js REPL.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/5810/edit).
Closed 2 years ago.
[Improve this question](/posts/5810/edit)
The obvious solution would be to just print them as a string, but is it possible to write a shorter code?
Requirements:
1. No input should be processed, and the output should be in the form of `2 3 5 7 11 13 ...` etc.
2. No reserved words in the language are used at all
3. The language should at least allow structured programming, and have reserved words (otherwise point 2 would be moot).
first I had exclusively C/C++ in mind, but extended the question while still trying to prevent cheating
[Answer]
## C, 60 chars
The "no keywords" limitation doesn't matter here. I'm pretty sure that improving it, if possible, won't be done by adding keywords.
```
n=2;main(m){n<720&&main(m<2?printf("%d ",n),n:n%m?m-1:n++);}
```
Alternate version:
The output isn't as nice, but I like the `printf` abuse.
```
n=2;main(m){n<720&&main(m<2?printf("%*d",n,n):n%m?m-1:n++);}
```
The trick in both solutions is to merge two loops (implemented by recursion) into one.
`n` is the next potential prime, `m` the next potential divisor.
In each recursive call, we either increment `n` (while setting `m` to its previous value) or decrement `m`.
[Answer]
## Python, 108 chars
Python was not made for this challenge. Wanna `print`? That's reserved. Well, how about we use `stdout`? Well, that's gonna cost an `import`... you guessed it, reserved. Well... I'm on unix, so I can open up the file descriptor 1, which happens to be stdout. Hack!
Man, and iteration? Nothing but `eval`. No loops, of course, but we can't even define a function with `def` or `lambda`. And to add insult to injury, we can't even use list comprehension! I always look for an excuse to use things like `map(p.__mod__,...)` in code golf... comprehension is always better. Until now, that is.
```
p=1
eval(compile("p+=1;open('/dev/fd/1','w').write('%s '%p*all(map(p.__mod__,range(2,p))));"*720,'','exec'))
```
Now, you might complain that `exec` is a keyword, even though I didn't use the keyword (I didn't even `eval` an `exec`). Well, here's a 117-character solution which doesn't use `'exec'`.
```
p=2
s="eval('('+s*(p<720)+')',open('/dev/fd/1','w').write('%s '%p*all(map(p.__mod__,range(2,p)))),{'p':p+1})";eval(s)
```
[Answer]
# JavaScript (80 chars)
```
eval((s=Array(719)).join("s[j=++n]?j:"+s.join("s[j+=n]=")+"r+=n+' ';"),r="",n=1)
```
Run in console of your webbrowser.
Used a prime sieve, which turned out to be very condensed.
[Answer]
## C, 87 chars
```
d;p(n){--d<2||n%d&&p(n);}r(n){p(d=n);d<2&&printf("%d\n",n);++n<720&&r(n);}main(){r(2);}
```
(I tried to write it in a more functional style, but my inability to use `return` kind of killed that plan.)
[Answer]
## C, 183 chars
```
#define q j*j<k?i%p[j++]||(i++,j=0):printf("%d\n",p[j=0,k++]=i++)
#define A q;q;q;q;q;q;q;q
#define B A;A;A;A;A;A;A;A
#define C B;B;B;B;B;B;B
main(){int i=2,j=0,k=0,p[999];C;C;C;C;C;}
```
Well, here's a quick first attempt. I believe this should satisfy the requirements. I'm using simple trial division to find the primes and an unrolled loop constructed using the preprocessor to iterate it until I've found enough of them. The number of repetitions has been tweaked so that exactly 128 primes are printed.
[Answer]
## C, 134 chars
Here's an alternate solution that tries to avoid using words as much as possible, reserved or otherwise:
```
main(i){i<9?main(2953216):i>4097?--i&4094?i/4096%(i%4096)?main(i):
main((i/4096-1)*4097):printf("%d\n",i>>12,main((i/4096-1)*4097)):0;}
```
All it uses is `printf` and `main` with a single argument.
[Answer]
### *Mathematica* 50 characters
I'm not sure how to interpret "reserved words" for *Mathematica* but I want to play so I'll take it to mean doing without built-in functions to generate primes or test for primality.
```
Fold[#2Cases[#/#2,1|_Rational]&,#,#]&@Range[2,719]
```
[Answer]
## Haskell, 72 characters
```
main=putStrLn.unwords$take 128[show p|p<-[2..],all((>0).mod p)[2..p-1]]
```
Admittedly, avoiding keywords isn't too difficult in Haskell.
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), 31 bytes
```
x,1_&&/720#'!'x:24\234925135391
```
[Try it online!](https://tio.run/##y9bNS8/7/79CxzBeTU3f3MhAWV1RvcLKyCTGyNjE0sjU0NjU2NLw/38A "K (ngn/k) – Try It Online")
] |
[Question]
[
Write 2 programs in the same language which count the number of shared subsequences of consecutive elements from 2 given sequences.
For example, given `"test"` and `"enter"`, there are 5 shared subsequences of consecutive elements:
```
t
t
e
e
te
```
One possible algorithm consists in counting, for each subsequence of consecutive elements of one sequence, the number of times it appears in the list of subsequences of the other one.
In our previous example, for `"test"`, `"t"` appears once in `"enter"`, `"e"` appears twice, `"t"` appears once, and `"te"` appears once; therefore we get 5 as output. (it does not matter if you pick `"test"` or `"enter"` as the "first" sequence).
### Scoring
Your score will be the result of one of your programs, when given your 2 programs as input. That is, the number of shared subsequences of consecutive elements between both programs.
Lowest score wins. In case of a tie, the lowest byte count of the sum of your 2 programs wins.
### Inputs
Both sequences will have at least 1 element.
The two input sequences can either be strings, or lists of chars, or lists of numbers, or any other fitting format for your language.
For example, if you take lists of numbers as inputs, your will transform your programs as lists of char codes according to your language’s code page.
### Test cases
```
a, b -> 0
test, enter -> 5
hello, hello -> 17
yes, yeyeyeah -> 9
```
[Answer]
# [Python](https://www.python.org), score 0, 520 bytes
-25 from @Grain Ghost
-78 from @Jonathan Allan
-61 from @RootTwo
-4 from @Grain Ghost
```
class l:__class_getitem__=len
class r:__class_getitem__=range
class s:__class_getitem__=sum
f=lambda a,b:s[[b[g:h]==a[i:j]for j in r[l[a]+True]for i in r[j]for h in r[l[b]+True]for g in r[h]]]
```
```
ùìÆùîÅùìÆùì¨("\x67\x3D\x6C\x61\x6D\x62\x64\x61\x20\x61\x2C\x62\x3A\x61\x3E\x27\x27\x61\x6E\x64\x20\x73\x75\x6D\x28\x62\x2E\x63\x6F\x75\x6E\x74\x28\x61\x5B\x3A\x70\x5B\x30\x5D\x2B\x31\x5D\x29\x66\x6F\x72\x20\x70\x20\x69\x6E\x20\x65\x6E\x75\x6D\x65\x72\x61\x74\x65\x28\x61\x29\x29\x2B\x66\x28\x61\x5B\x31\x3A\x5D\x2C\x62\x29")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bVPNToNAEI4eTLpPQfBAiTRpqS0tCQd_6hN4Q0KWugUaCs2yTdqjz1BvxsSLnowP5FP4CM4wi7FJ00znm--bmZ2F4eVjvVNZVb69vW_Uojf5Pj1fxLWSRmBYljUveF0bhR_HDYpToXIlVnEcFKJkpMojquRlKrReH9HrzYotgoKvkkducCfx6zBMwtTPoiDgYe4vo0UljaWRl4YMi5BHF_dyIxoyJ5IysjYj-ZeREplFUQRXYCzV95HWz-v-6-f1-Yn8_rNrPmzH3sN2eAv-BmwAhtgFu6TY7Wt_Q_zwiuLhDDiPrKmbUQ3me0OwEfVyJ1Tnog78-E5rEHuXWof60TX19voao8d6xAONp5A71j1cfVZfzzilng1u--sZMMZ8PAfPxLg9F3s2dk29D-YZ0EzN2fr-7tS0Lb0rJ2drmZeq22yMzShofXpIiq2Yt4kN1jo71z1IdIgGnmiz1-uZNlOiVvAKQ9bpmtx0DDOBv77tYIwaUqJUQgIYEZ2JoqiQb8HAI2EnaqR3An88AzwFIWK4O7CLToX7g0191vkbDgQYqvM_dFJylU2Po_2EfgE)
It was a team effort.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), score 0 (15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage))
**Program 1 (3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):**
```
΢O
```
[Try it online](https://tio.run/##yy9OTMpM/f//6KRDi/yhFNejhkXearWHe4G08eEth5d76YUBAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/6OTDi3y/6/zPzpaKVFJRylJKVYnWqkktbgEyEnNK0ktAgtkpObk5ANFIDRIpDK1GMivTAXBxAyl2FgA).
**Program 2 (12 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)):**
```
•K&}Í•3ôçJ.V
```
[Try it online](https://tio.run/##yy9OTMpM/f//UcMib7Xaw71A2vjwlsPLvfTC/v8/OunQIn8uLFIA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/0cNi4weNTUWPuroAjKPbT28/sKmw8u99ML@6/yPjlZKVNJRSlKK1YlWKkktLgFyUvNKUovAAhmpOTn5QBEIDRKpTC0G8itTQTAxQyk2FgA).
The second program is pretty unimpressive, so I'll see if I can find a more original shorter approach.
**Explanation:**
```
Œ # Get all substrings of the first (implicit) input-string
¢ # Count how many times each substring occurs in the second (implicit) input-string
O # Sum those counts together
# (after which the result is output implicitly)
•K&}Í• # Push compressed integer 388162079
3ô # Split it into parts of size 3: [338,162,079]
ç # Convert each to a character with this codepoint: ["Œ","¢","O"]
J # Join it to a string: "΢O"
.V # Evaluate and execute as 05AB1E code (basically the program above)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•K&}Í•` is `388162079`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes, score 0
##### 6 bytes
```
ẆċⱮẆ}S
```
**[Try it online!](https://tio.run/##y0rNyan8///hrrYj3Y82rgPStcH/vXUOL9fPetQwR8HWTuFRw1zNyP//o6OVEpV0lJKUYnWilUpSi0uAnNS8ktQisEAG0Jh8oAiEBolUphYD@ZWpIJiYARZ61Ljn8L6jk1wOLQ9yO7QcKItiq1JsLAA "Jelly – Try It Online")**
##### 8 bytes
```
⁼þŒD§RF§
```
**[Try it online!](https://tio.run/##y0rNyan8//9R457D@45Ocjm0PMjt0PL/3jqHl@tnPWqYo2Brp/CoYa5m5P//0dFKiUo6SklKsTrRSiWpxSVATmpeSWoRWCADaE4@UARCg0QqU4uB/MpUEEzMAAuh2gKUfbir7Uj3o43rgHRtsFJsLAA "Jelly – Try It Online")**
### How?
```
ẆċⱮẆ}S - Link a, b: e.g. "tent", "spent"
Ẇ - sublists (a) ["t","e","n","t","te","en","nt","ten","ent","tent"]
Ẇ} - sublists (b) ["s","p","e","n","t","sp","pe","en","nt","spe","pen","ent","spen","pent","spent"]
Ɱ - map with:
ċ - (left) count occurrences (of right)
[0,0,1,1,2,0,0,1,1,0,0,1,0,0,0]
S - sum 7
⁼þŒD§RF§ - Link a, b: e.g. 'tent', 'spent'
þ - table of:
⁼ - equals? [[0,0,0,0],[0,0,0,0],[0,1,0,0],[0,0,1,0],[1,0,0,1]]
ŒD - diagonals [[0,0,0,0],[0,0,0],[0,0],[0],[1],[0,0],[0,0,0],[0,1,1,1]]
§ - sums [0,0,0,0,1,0,0,3]
R - range [[],[],[],[],[1],[],[],[1,2,3]]
F - flatten [1,1,2,3]
§ - sums 7
```
[Answer]
# Java 8, score 0 (~~1287~~ ~~1263~~ ~~1248~~ 1243 bytes)
**Function 1 (~~261~~ ~~237~~ ~~234~~ 229 bytes):**
```
a->b->{int l=a.length,z=l-l,r=z,i=z,j,L=b.length,I,J,x;for(String s,t;i<l;i++)for(j=i;j++<l;)for(I=z;I<L;I++)for(J=I;J++<L;r+=s.contains(t)&j-i==J-I?1:0){for(s=t="",x=i;x<j;)s+=a[x++];for(x=I;x<J;)t+=b[x++];}System.err.print(r);}
```
Inputs as character-arrays. Outputs the result to STDERR.
-3 bytes thanks to *@ceilingcat*
-5 bytes thanks to *@l4m2*
[Try it online.](https://tio.run/##bZFPb@MgEMXv@RTIh5URGO1ei8lqVWklW9lTj1EOY5c0eAm2YFLZifLZU5xQ9a8sG/x@o@HNo4NnKLrH/5fWQgjkHxh3WhASENC0pItUHNBYsT24Fk3vxN@0Kdsd@PWGf1dz37tw2GufapZLsiWKXKBYNsXyZBwSq0BY7Z5wx4/KFpZ7deQmvh1fqeYVVbzmo9z2Pn9Ab9wTCRylKa00jNFZ7pSRHWNRuf5W6iirciWrhGtVyTrilfRMBdH2DuN8IUf6oyuMUnVR/f5195Oe5uKgUGUZH2PLsewkDUzBemRsczUwxlZjWUuKTDU3@fwwBdR7ob0XQ7SHuafyfJGLmN9waGzML8X43JtHso9HpznWG6BzyoSgDphnkPGsyah8J83fqGqH2n8kO21tH9Ft/YAmHSKY9PzA7sbOi7frvPq4lqY8gadNk/x8GQlYxknGGpbdkdfDtgKGwU45COzv4w3/8R6mnFIBbasHzJtPuvy2tXV5Mni@vAA)
**Function 2 (~~1026~~ 1014 bytes):**
```
\u0061\u002D\u003E\u0062\u002D\u003E\u007B\u0069\u006E\u0074\u0020\u0072\u003D\u0030\u002C\u006C\u003D\u0061\u002E\u006C\u0065\u006E\u0067\u0074\u0068\u0028\u0029\u002C\u0069\u003D\u0030\u002C\u006A\u002C\u004C\u003D\u0062\u002E\u006C\u0065\u006E\u0067\u0074\u0068\u0028\u0029\u002C\u0049\u002C\u004A\u003B\u0066\u006F\u0072\u0028\u003B\u0069\u003C\u006C\u003B\u0069\u002B\u002B\u0029\u0066\u006F\u0072\u0028\u006A\u003D\u0069\u003B\u006A\u002B\u002B\u003C\u006C\u003B\u0029\u0066\u006F\u0072\u0028\u0049\u003D\u0030\u003B\u0049\u003C\u004C\u003B\u0049\u002B\u002B\u0029\u0066\u006F\u0072\u0028\u004A\u003D\u0049\u003B\u004A\u002B\u002B\u003C\u004C\u003B\u0029\u0069\u0066\u0028\u0061\u002E\u0073\u0075\u0062\u0073\u0074\u0072\u0069\u006E\u0067\u0028\u0069\u002C\u006A\u0029\u002E\u0065\u0071\u0075\u0061\u006C\u0073\u0028\u0062\u002E\u0073\u0075\u0062\u0073\u0074\u0072\u0069\u006E\u0067\u0028\u0049\u002C\u004A\u0029\u0029\u0029\u0072\u002B\u002B\u003B\u0072\u0065\u0074\u0075\u0072\u006E\u0020\u0072\u003B\u007D
```
Inputs as Strings. Returns the integer-result.
-12 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##rVRNb4JAEL37KzacIFqisECprYlfTXroyWPbw6KrYhGILCak8bfTZXeTHSUakzYkw@TN7Ju3wzA7ciQPu9V3vUxIUaB3Eqc/HYQKRli8RDsetUsWJ/a6TJcszlL7VTnPC3aI003vrpy3lNENPYxGaI1eUP1Z9vv@oLHOrLHuXCDOJRJMBB4KKxEscvrCF/muzBeIMxWZU42rKnON@55m8wPN6T@KTGlDwBZeqTLWPoYVnb9WxNAXVVzZB1/YV313edYFXXJhBwDuTIANb7HJe6m7hIBnfMnTrnWbGbc6KU9hoBxPL/H7lWOgHAPl@Ipy3FYO@FU3wPwErrCe/soKwVoJnFX5rRVP2JqcEMyJ4AwGgH@geyurKB7nf/S0Z0zpAVb1FvZtApg9UMsD@Lz1h8pTs3rY4ZslL6OEbxa1YI5ZvEJ7vnRMuSo@vojV7B@EGC2YaRCjZ0SGNQRQYzlK@Uo5nEe2NEkyHpLvs1BFCx6oaPOQrYydOnrRCR0iVepApKecSOlZVAWjezsrmZ3zAEtSk3SNHjK6Udd44q@1TfI8qUxiKSeyVJlT/Qs)
**Explanation:**
The golfed function is this:
```
a->b->{int r=0,l=a.length(),i=0,j,L=b.length(),I,J;for(;i<l;i++)for(j=i;j++<l;)for(I=0;I<L;I++)for(J=I;J++<L;)if(a.substring(i,j).equals(b.substring(I,J)))r++;return r;}
```
This golfed version is also the direct translation of the second function above [using a simple converter](https://tio.run/##TY4/a8MwEMX3fAphKEhIFh46VVGGbjbulKWQZDgljitVtlP9MYTgz@7KbqGdjvd79@6egRFyc/mc57MF79Eb6P6xQegWldVn5AOENMZBX1CXLLwPTvft4QRk2ULoOjg8gkPqBQ7FibdNeL2HxmNCVhuh/d2HpuNDDPyWogFnx2PM6M8dnuIdJPZUPL9nTBEiUmzaTPM8Q75T@e6RIsjJglkJ3DZ9Gz4wYToBw2qp/lDJKrGUEXprhaaULMJILQyliayylIUot7Uof@1KlqJKdi2IvmLgPiq/9sKaGcKbrwjWY/WPpy@EEEepcE2IrkdOTN8).
In order to use the unicode escaped Java function, we'll have to prevent using the characters `\u0123456789ABCDEF` in the other function. We're currently using three `0` and four `u`:
* To get rid of the three `0`, I've added an additional `z=l-l` integer to reuse;
* To get rid of the two `u` in `substring`, I create the substrings manually using `,x ... String s,t; ... for(s=t="",x=i;x<j;)s+=a.split("")[x++];for(x=I;x<J;)t+=b.split("")[x++];` (minor note: I couldn't use `.charAt(x++)` instead of `.split("")[x++]` here, since it contains an `A`);
* To get rid of the `u` in `equals`, I've used `s.contains(t)&j-i==J-I`;
* And to get rid of the `u` in `return`, I've printed to STDERR with `System.err.print(r);`.
After that, both `.split("")` were removed and both `.length()` were golfed to `.length` by taking the arguments as character-arrays instead of Strings.
*Explanation of the golfed base function:*
```
a->b->{ // Method with two string arguments
int r=0, // Result-count integer, starting at 0
l=a.length(), // Length of the first input-String
i=0,j, // Index-integers for the substrings of the first input
L=b.length(), // Length of the second input-String
I,J; // Index-integers for the substrings of the second input
for(;i<l;i++) // Loop `i` in the range [0,l):
for(j=i;j++<l;) // Inner loop `j` in the range (i,l]:
for(I=0;I<L;I++) // Inner loop `I` in the range [0,L):
for(J=I;J++<L;) // Inner loop `J` in the range (J,L]:
if(a.substring(i,j) // If the [i,j)-substring of the first input
.equals(b.substring(I,J)))
// equals the [I,J)-substring of the second:
r++; // Increase the result-count by 1
return r;} // After the loops, return the result
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), score 0 (23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax))
### 12 bytes
```
:e{n:es|#m|+
:e all substrings of b
{ m map over them:
n:e all substrings of a
s|# count occurrences
|+ sum
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#c=%3Ae%7Bn%3Aes%7C%23m%7C%2B&i=a%0Ab%0A%0Atest%0Aenter%0A%0Ahello%0Ahello%0A%0Ayes%0Ayeyeyeah%0A%0Aaaa%0Aaaa%0A%0A%3Ae%7Bn%3Aes%7C%23m%7C%2B%0A%C3%BC%E2%95%AA+%C2%B7%C2%A7%E2%95%A2%E2%94%8C%C3%86%3Dgy&m=1)
### 11 bytes
```
ü╪ ·§╢┌Æ=gy
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=81d820fa15b6da923d6779&i=a%0Ab%0A%0Atest%0Aenter%0A%0Ahello%0Ahello%0A%0Ayes%0Ayeyeyeah%0A%0Aaaa%0Aaaa%0A%0A%3Ae%7Bn%3Aes%7C%23m%7C%2B%0A%C3%BC%E2%95%AA+%C2%B7%C2%A7%E2%95%A2%E2%94%8C%C3%86%3Dgy&m=1)
The second is the same as the first, but with a `$` (number to string) appended before packing to get rid of a pesky `m` that was trying to give me a positive score.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes, Score = 0
Program 1 (14 bytes):
```
wJƛfÞS;Π'÷⁼;żt
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwid0rGm2bDnlM7zqAnw7figbw7xbx0IiwiIiwiXCJhXCIsXCJiXCJcblwidGVzdFwiLFwiZW50ZXJcIlxuXCJoZWxsb1wiLFwiaGVsbG9cIlxuXCJ5ZXNcIixcInlleWV5ZWFoXCJcblwid0rGm2bDnlM7zqAnw7figbw7xbx0XCIsXCLHjiTHjuG6in7iiYhMXCIiXQ==)
Program 2 (7 bytes):
```
ǎ$ǎẊ~≈L
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwix44kx47huop+4omITCIsIiIsIlwiYVwiLFwiYlwiXG5cInRlc3RcIixcImVudGVyXCJcblwiaGVsbG9cIixcImhlbGxvXCJcblwieWVzXCIsXCJ5ZXlleWVhaFwiXG5cIndKxptmw55TO86gJ8O34oG8O8W8dFwiLFwix44kx47huop+4omITFwiIl0=)
I'm very good at golfing language design as you can tell by the fact that there's multiple built-ins to do the same thing.
Both programs take 2 strings.
## Explained
```
wJƛfÞS;Π'÷⁼;żt
wJ # Put the two inputs into a list
∆õf√ûS; # Get the sublists of each - returns a list of lists
Π # Cartesian product of the two lists
'÷⁼; # Keep only those where all the items are equal
żt # Length of list
```
```
ǎ$ǎẊ~≈L
«é # Get the substrings of the first input
$«é # and of the second input - leaves two strings on the stack
Ẋ # Cartesian product of the two lists
~≈ # Keep only those where all the items are equal
L # Length of list
```
[Answer]
# Python, ~~542~~ ~~533~~ 479
## A, 89 bytes
```
def g(a,b):h=range;return sum(b.count(a[c:][:1+d])for c in h(len(a))for d in h(len(a)-c))
```
## B, 80 bytes
```
lambda i,l:sum(l.count(i[j:k+1]) for j in range(len(i)) for k in range(j,len(i)))
```
Not really sure how to optimize this. Will play a bit more. Submitting the same program twice would give me a score of 3,160 bytes.
[Answer]
# [Haskell](https://www.haskell.org), ~~67~~, ~~58~~, 57 score
```
a((f,j):q)|(9>8)>(f>j)&&(9>8)>(j>f)=a(q)+1
a(f)=0
f!h=scanr(+)0(((a.).zip)<$>scanr(:)[]f<*>scanr(:)[]h)!!0
```
```
x%y|t:u<-x,w:e<-y,t==w=1:u%e;_%_=mempty;k t|_:m<-t=t:k m;k _=mempty;t?u= sum$do{x<-k t;e<-k u;x%e}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fZK9bsIwFIXVNU9xiQiyC0GwUSdOBHM7dQQUWa1DID8YxxEJDWtfogtL1Wdqn6YJAYqqqpPvuT7y8Xftt4-ApSGPosPhPVO-OfqMUsihKAWRtpn3doTbZtETlO7oVMwJQoJgu-2kIIFjKwUPPDqdWyGIMiWxbQoqSAhx1fBozGOhCku4kj6vX3LbrFwWrxdp1Sl832R-3bwKuV5IFo-BagA6Q8jvrTDZ4BLdOSPsIN9Z4U7nJFaOjylDG9wdzhKGKjGYJX4roOkTSyTq4gFCiPVxf7cUx8se2wRP5759e6UC3GoNdO2UPWmyc6MoFclq-G0Dryjd0iHJDG55xoUqBFV6NbGi6jexcjMKaRa3z9iqwc6s3OB7XdNitkyqmVR5Qi4TBW3QFU-VDi7oPFFc6ldbEU8WKqiKy5Dcczn5xzb5sY0rW8zEgwciU49K3id_n9Y8x_krfAM)
~~I really wanted to get this under 64. But it just seems like it is not going to happen.~~ Got it under 64!
The characters that cause overlap are:
```
,|1=p$<s:
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 56 bytes, score = 0
First program, 31 bytes:
```
IΣEθΣE⊕κ№EηΦη№…ξ⁻⊕κ⁻λξρΦθ№…λ⊕κξ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0V8M3sUCjUEcBxvTMSy5KzU3NK0lN0cjW1FFwzi8FqgbJZOgouGXmlKQWgVgQ4aDEvPRUjQodBd/MvNJiDL0Q0RwdhQpNIK8IREBNKEQ1AagEVa8mWA8MWP///37PynOL3@9Zem4HmHrUNfXcrkct00Ai288tO7cdyH7UsOzcvkeNuyFyjbvP7T6373wjUHIHVBIic24f1/s9m89tAxFbH61tO9/xfs8aIH1uG5B41Ljr0M5ze0Csnqnv9ywEqpjTdG7bub1QiUM7z3f81y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Generates all substrings of the first input in order of last character index followed by first character index, for each substring extracts all substrings of that length from the second input, counts the number of matches, then takes the grand total.
```
θ First input
E Map over characters
κ Current index
‚äï Incremented
E Map over implicit range
η Second input
E Map over characters
η Second input
Φ Filtered where
… Range from
ξ Inner index to
ξ Inner index
⁻ Subtracted from
λ Outer value
⁻ Subtracted from
κ Outermost index
‚äï Incremented
‚Ññ Contains
ρ Innermost index
‚Ññ Count matches of
θ First input
Φ Filtered where
… Range from
λ Inner value to
κ Outer index
‚äï Incremented
‚Ññ Contains
ξ Innermost index
Σ Take the sum
Σ Take the sum
I Cast to string
Implicitly print
```
Second program, 25 bytes:
```
SζSε⭆ψL⭆ζ⭆⁺¹μ⭆⌕Aε✂ζν⁺¹μ¹ψ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0JLikKDMvXaNK05oLmZ8K5AcAWSUaEAHfxAKNSh0Fn9S89JIMJLEqHQUEJyCntFjDUEchVxNZ1C0zL8UxJ0cjFSiYk5mcCtKTp6OArNgQiCs1IcD6///3e1aeW/x@z9JzO8DUo66p53Y9apkGEtl@btm57UD2o4Zl5/Y9atwNkWvcfW73uX3nG4GSO6CSEJlz@7je79l8bhuI2Ppobdv5jvd71gDpc9uAxKPGXYd2ntsDYvVMfb9nIVDFnKZz287thUoc2nm@479uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Generates all substrings of the first input as before, then maps the indices of overlapping matches in the second input to null bytes, concatenates everything and takes the total length.
```
Sζ Rename first input
Sε Rename second input
ψ Null byte
⭆ Map over characters and join
ζ First input
⭆ Map over characters and join
μ Current index
⁺ Plus
¬π Literal integer `1`
⭆ Map over implicit range and join
ε Second input
‚åïÔº° Find all matching indices of
ζ First input
‚úÇ ¬π Sliced from
ν Inner value to
μ Outer index
⁺ Plus
¬π Literal integer `1`
⭆ Map over indices and join
ψ Null byte
L Take the length
Implicitly print
```
Using `StringMap` to stringify the count has the added bonus of renaming the loop variables thereby reducing the number of shared substrings. Other techniques I used:
* The second program uses `StringMap` instead of `Map`. I can do this by representing integers in unary as the length of the resulting string.
* The second program uses `Plus(1, k)` instead of `Incremented(k)`, as it needs a `1` for `Slice()` anyway.
* The first program uses `Minus(Incremented(k), Minus(l, x))` to avoid having to add `k` and `x` (because the second program is now using `Plus`).
* The first program uses `Filter` to extract substrings to avoid using `Slice`.
[Answer]
# [Go](https://go.dev), 265 bytes, score 772
thanks golang for not giving you that many ways of doing things (reasonably)
## A, 113 bytes
```
import."strings"
func f(v,b string)(z int){for i:= range v{for j:=i+1;j<= len(v);j++{z+=Count(b,v[i:j])}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=vZFBboMwEEXVLaewWHkEicqiagthUUXqLlK7jiIFUkNMwRgzEEiUk3QTVcohepT2NMWQtskFKi_s__9o3th-e4_zw4cMVq9BzEgWcGHwTOYKx2aUoXmsMBrdfRY_XomKi7g0jagSKxLR2g7J4AHdEi4QdlGuCHd9ogLRdax7nbg-txwvmfgkZYLW4CWWtdta_jSvBNLQrufcTRaw3xuKYaXEfgB_XR17kJ6LAtkZTx0KU0EjagamTczQBJtcw7mPrEQdMYFM6fjmIl6zNM11Phy63Lm9KGhZqeOW6RWsdcU9GGcVy39_jKVt_EIVi1kjT8yYNnY7X4QtMqDFH3Lj-gOx6aV0fcfaeHLia2ADnuyARS9mVYnTPJM8ZfS5ypHNGAZ0uAVt5htXLgBg_MjFy0Oa0tYeOQBWcTYbgHH6rcNh2L8B)
## B, 152 bytes
```
import."regexp"
func g(x,y[]byte)(q int){for w:=range x{for p:=1+w;p<=len(x);p++{q=len(MustCompile(QuoteMeta(string(x[w:p]))).FindAll(y,-1))+q}}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=zVFBboMwEFSvvMLi5BVOVA5VWxIOVaTeIrXnKBImNcQUDAFDIIh_VOolqtRH9CnNa4pxoiQ_qHzwzs54NZ79_ArT_U9GV-80ZCihXBg8ydJcjs0gkeZ3KYPRw-_HqZezkNWZaQSlWKEQ16RZLP1GMsAbxIWENkhztHXcnIp-XD3AzHFtazvJpm7MBK5hkllWuxnAvCzkLE0yHjP8WqaSzZmkuJA5F_3wxdbJlgAwfubi7SmOcUNGNoC16TojZ7LMRaf9HW4OgyFlHwNqA8dVGFPiIz0MenOtftPb1p4xBXKsfIDOeOmFMhY4wCY1CTJ9Ewi6hcu-ZIVUFBOS5Yq-u6LXLI5Txeui5-37K0HDCkU3TB26VopHMC4U3ilobbs4Jh3g6vwVvDtHzR0X6ayrAUeOyy17Ek1dpPKtYBL1Ye8sd5aWQmKfVAvuREs4J-gRw_uv2_UAjOOK93t9_wE)
## Changelog
* A/B: Some changes (@Kevin Cruijssen)
* (footers): Make sure they use the same inputs (@Grain Ghost)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), Score: 0 (15 + 38 = 53 bytes)
```
tT⁰&hsᶠ{∋~sT⁰}ᶜ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/vyTkUeMGtYzih9sWVD/q6K4rBvFrH26b8/9/tFJJanGJko5Sal5JapFS7P8oAA "Brachylog – Try It Online")
```
↰₁ᵐẋ=ˢl
↰₂ᵇbᵐ²
l‚ü¶‚ÇÅ;?zZ‚àß[A,.,C]cZ‚àß.l>0‚àß
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HbhkdNjQ@3Tni4q9v29KIcLrBA08Ot7UlAwUObuHIezV8GVGFtXxX1qGN5tKOOno5zbDKIrZdjZwCk/v@PVipJLS5R0lFKzStJLVKK/R8FAA "Brachylog – Try It Online")
[Program 1 with programs as input](https://tio.run/##SypKTM6ozMlPN/r/vyTkUeMGtYzih9sWVD/q6K4rBvFrH26b8/9/tBJOSSUdpUdtGx41NT7cOuHhrm7b04tyuMACTQ@3ticBBQ9t4sp5NH8ZUIW1fVXUo47l0Y46ejrOsckgtl6OnQGQUor9HwUA).
[Program 2 with programs as input](https://tio.run/##SypKTM6ozMlPN/r//1HbhkdNjQ@3Tni4q9v29KIcLrBA08Ot7UlAwUObuHIezV8GVGFtXxX1qGN5tKOOno5zbDKIrZdjZwCk/v@PVioJedS4QS2j@OG2BdWPOrrrikH82ofb5ijpKFFug1Ls/ygA)
## Explanation
Brachylog doesn't actually have that many built-ins; in addition, certain control flow symbols are used all the time. This makes it harder to write 2 programs that don't share symbols, which means we have to do some plumbing for the second program.
The main difficulty is that the direct way to generate substrings of consecutive elements is `s`, and getting substrings with another method that also doesn't generate duplicates (but works for strings with duplicate symbols!) is not that obvious.
### Program 1
This is a fairly straightforward declarative implementation of the problem:
```
tT⁰ Call the second input T⁰
&hsᶠ Find all subsequences of consecutive elements of the first input
{ }·∂ú Count:
∋~sT⁰ The number of such subsequences which are also subsequences of T⁰
```
### Program 2
We use a more imperative approach, computing all subsequences of consecutive elements and checking how many equal couples we get after cartesian product.
We can't use brackets to declare predicates, so we have to declare them using linebreaks. Predicate 3 computes the subsequences. Predicate 2 cleans up some plumbing set up in Predicate 3 to avoid duplicate subsequences.
We can't use `ᶠ - findall` to generate stuff, so we use `ᵇ - bagof` which does the same in cases where we're not generating unbounded variables.
```
- Predicate 0
↰₁ᵐ Map predicate 1 on each of the 2 inputs
ẋ Cartesian product
=À¢ Select the couples of equal elements
l Output the length of this list
- Predicate 1
↰₂ᵇ Find all outputs of Predicate 2
bᵐ² Remove the indices
- Predicate 2
l‚ü¶‚ÇÅ;?zZ Zip the string with indices [1,...,N]; call it Z
‚àß[A,.,C]cZ‚àß [A, Output, C] concatenates into Z
We avoid duplicate situations with the zipped indices
.l>0‚àß This Output has length > 0
This avoids all cases where the output is the empty string
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), score 0, 322 bytes
# [JavaScript (Node.js)](https://nodejs.org), 129 bytes
```
x=>y=>[g=_=>j--?[h=_=>j%z-v-z?x[j%z-v]==y[j/z-v|0]?--v|--Z|h``:0:0][v=0][h``]|g``:-Z][Z=0][j=y[l='l\x65\x6Eg\x74h']*[z=x[l]]]|g``
```
[Try it online!](https://tio.run/##dY7dasMwDIXv9x7DSanSDPYDBSVX7SsUooo160y8YOLRhGCHvHumuLcdQjpH0idQW491f739/A7QuW@9HJ17wcVjEbCgBj@xaAFKMtE9TzDCVHqKjhEDtTtxc84liABUs7lc9vk@ZxpRinQ8NzKCiqlaJ60cWVT27N/fJA/N2X@8GsUbmtCTZY58/OOEid@GFIu1SSjLMs9p1MDp09V1vbM6s65JIp2oWm3Vl0of7gbdD7LW3aBv/yBGW@uEuetjJuheiKDXqI1Ayx8 "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 193 bytes
```
function(A,B){return A.reduce(function(M,K,I){return B.reduce(function(M,L,N){return A.reduce(function(M,K,J){return(I<++J)*Array(A.slice(I,J)+1).includes(B.slice(N,J+~I+1+N)+1)+M},M)},M)},!1)}
```
[Try it online!](https://tio.run/##hc9BS8MwFMDxu59CT30xz0A9W6E9CO1srx5kh5g@XSUkkqRjYWxfvaab7lSREB6P3z@HfMqt9MoNX@HO2J6mJ2vvi@l9NCoM1kCJFds7CqMz16Vw1I@K4KItrrC@eLXgz9j98775dagfOG/YbemcjFAKr4fU1ingORODUXrsyUP1Ax02/FjznHez8/aALTvfm5wdTv94KWCHkRWP8wKvQojdGucR1@xKWeOtJqHtB5xiyGSG2VvGFi2QD4nJBHJ/JBvS2qbmPJebSD4VkeYjNymavgE "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
**This question already has answers here**:
[Product over exclusive and inclusive ranges](/questions/66285/product-over-exclusive-and-inclusive-ranges)
(25 answers)
[Interpret Interval Notation](/questions/217297/interpret-interval-notation)
(18 answers)
Closed 2 years ago.
Inspired by [this](https://codegolf.stackexchange.com/questions/66202/product-over-a-range) challenge, and similar to [this](https://codegolf.stackexchange.com/questions/217297/interpret-interval-notation) and [this](https://codegolf.stackexchange.com/questions/66285/product-over-exclusive-and-inclusive-ranges).
After seeing these, I figured I would continue the trend as there was no inclusive/exclusive sum.
The goal here is to sum an interval of integers, either inclusive and exclusive, and output the total to stdout.
Input format: either a `(` or `[` followed by 2 comma separated integers followed by a `)` or `]`. Ex: `[a, b]` `(a, b]` `[a, b)` `(a, b)`
* Note: `b > a >= 0` and the range will always contain at least 1 value.
* Input regex: `[\(\[]\d+,\d+[\)\]]`
Examples:
```
Input -> Output
[2,6] -> 20
(15,25] -> 205
[0,16) -> 120
(15,20) -> 70
[1,2) -> 1
(2,12] -> 75
[11,16] -> 81
(15,29) -> 286
[14,15) -> 14
(2,16] -> 133
(12,18) -> 75
```
This is code-golf, so the shortest code in bytes wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ḊṖVr/ḟ×ɗċⱮØ($S
```
A monadic Link accepting a list of characters that yields the sum of the described range.
**[Try it online!](https://tio.run/##ASwA0/9qZWxsef//4biK4bmWVnIv4bifw5fJl8SL4rGuw5goJFP///8iKDIsMTIpIg "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8///hjq6HO6eFFek/3DH/8PST0490P9q47vAMDZXg/w93bznc/qhpzf//0UY6ZrFcGoamOkamsVzRBjqGZpoQroEmV7ShjhGQZ6RjaASUMzQESkLVWoIkTXQMTSHSYGEgbaEJAA "Jelly – Try It Online").
### How?
```
ḊṖVr/ḟ×ɗċⱮØ($S - Link: list of characters, R e.g. "[5,8)"
Ḋ - dequeue "5,8)"
Ṗ - pop "5,8"
V - evaluate as Jelly [5,8]
(call that X)
$ - last two links as a monad - f(R):
Ø( - list of characters = "()" "()"
Ɱ - map across these with:
ċ - count ocuurences (in R) [0,1]
(call that Y)
ɗ - last three links as a dyad - f(X,Y):
/ - reduce (X) with:
r - inclusive range [5,6,7,8]
× - (X) multiply (Y) (vectorises) [0,8]
ḟ - filter discard [5,6,7]
S - sum 18
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
ṙ1“(Ḋ)Ṗ,r”yḟØ[VS
```
[Try it online!](https://tio.run/##y0rNyan8///hzpmGjxrmaDzc0aX5cOc0naJHDXMrH@6Yf3hGdFjw/4e7tzzcselR05qHOxYBycPtQOLopIc7ZwDpyP//o410zGIVdO0UjAy4NAxNdYxMoTxTrmgDHUMzTRDPECZpAOaaG3BFG@oYQaS4NIx0DI3AmsyBegwNgZrAPAtDiB5LsDojCzOgpImOoSlEmwlYH0SlobExUCmQawEx3hQA "Jelly – Try It Online")
Very similar to [my answer](https://codegolf.stackexchange.com/a/217302/66833) to the [related challenge](https://codegolf.stackexchange.com/questions/217297/interpret-interval-notation)
## How it works
```
ṙ1“(Ḋ)Ṗ,r”yḟØ[VS - Main link. Takes a string S on the left
ṙ1 - Rotate the first character of S to the end
“(Ḋ)Ṗ,r” - String literal "(Ḋ)Ṗ,r"
y - Translate S according to this string
This splits the string into pairs of characters [["(", "Ḋ"], [")", "Ṗ"], [",", "r"]]
then for each pair, replaces all occurrences of the first character
with the second character e.g. ( -> Ḋ; ) -> Ṗ; , -> r
ḟØ[ - Remove all square brackets
V - Evaluate as Jelly
S - Sum
```
### Why `r`, `Ḋ` and `Ṗ`?
Consider the four possible examples with `[`, `]`, `(` and `)`:
```
[2,6] -> 2,6][ -> 2r6
[2,6) -> 2,6)[ -> 2r6Ṗ
(2,6] -> 2,6]( -> 2r6Ḋ
(2,6) -> 2,6)( -> 2r6ṖḊ
```
The first step is rotating the string and the second step is translating and filtering.
`r` takes a number on the left and a number of the right and yields an inclusive range between them
`Ṗ` takes a list and `Ṗ`ops the last element off. `rṖ` is a right-exclusive range
`Ḋ` takes a list and `Ḋ`equeues it, removing the first element. `rḊ` is a left-exclusive range
Therefore, `rṖḊ` is a fully exclusive range
[Answer]
# [Python 3](https://docs.python.org/3/), 67 bytes
```
lambda s:sum(eval("range"+s.translate({91:"(",40:"(1+",93:"+1)"})))
```
[Try it online!](https://tio.run/##NYxBbsMgEEXX4RSI1SDTiMHGsS2lp@jOyYKopLFEXMvgRlHVszsE0hXz9N9juofL91iu5/1hdeZ6@jTUd365gv0xDthsxi/LCr8N8fLOBAu/LXYMmKhkfLBgoi07ViBnf5zz9XYZnKUf82I7sjGCnuieDuO0BOBbP7khAKNv75RxspnmYQwQnTMYHk2@9krUx@esJAHUQukXadJLgTV/Ev6PMuFOkh6FyhMBJVClaBcbxBglajA3bfJUU8exEqhzVqUum1iWUY3Y5O/1Aw "Python 3 – Try It Online")
[Answer]
# JavaScript (ES6), ~~66 ... 60~~ 56 bytes
*Saved 3 bytes by borrowing `split(/\b/)` from [Redwolf Programs' answer](https://codegolf.stackexchange.com/a/224327/58563)*
```
s=>([,x,c,y,p]=s.split(/\b/),(y-=p<c,x-=s>c)-y)*~(x+y)/2
```
[Try it online!](https://tio.run/##dY/LDoIwEEX3fkXDqqMDZYoFTKw/giy0PqIhQCwxsPHXkRBhYXV9z5x75354Hqx53OrGL6vTub/o3uodz7BFgx3WubaBrYtbw8X@KAB55@t6a7D1td0Z8DtYvni76kDI3lSlrYpzUFRXfuFeJjHOPQDGmBBMhouvnJNCqUZizNU3kIVIMYyGAaA/hhA@hsTJM0IJ8wJyziWSzCd/4vYTDQOmgSn9rN9M9TKNXcEaSU0ArX8NiOcBFEVuw0Ck84OqfwM "JavaScript (Node.js) – Try It Online")
### How?
We extract the comma as `c` along with the other substrings so that it can be used to distinguish between parentheses and brackets.
The sum of the range \$[x..y]\$ is obtained with:
$$\frac{(y-x+1)(x+y)}{2}$$
implemented as:
```
((x - 1) - y) * ~((x - 1) + y) / 2
```
(Because `x` is a string, we do `x -= s > c` instead of `x += s < c` to force the coercion to a number at no cost. That's why \$x\$ is off by \$1\$ in the JS code.)
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
1#.[:-.&i./']('&e.+3 1".&>@{;:
```
[Try it online!](https://tio.run/##TY6xCsIwEIZ3n@KokLR4PXNpE2ukIghOTq6lk7Soiw/gw8eAJulwy8fH99/LFyRn6B1IQFDgwtUE59v14nlNg6tJPGkrx1KKiTYNcEHiePocnK9W0/3xBq2ghxnkoNGOEiI0P1qyQW0S52QrZFtFvFMLWyXMf5dRZzWGNbJO3S6pHLr5jc4uwvscbqPeIpuMmybHcyVNcsBdsP0X "J – Try It Online")
Explained using `(2,12]` as an example:
* `;:` Chop into words:
```
┌─┬─┬─┬──┬─┐
│(│2│,│12│]│
└─┴─┴─┴──┴─┘
```
* `3 1".&>@{` Pluck the 3rd and 1st elements, and convert them to ints:
```
12 2
```
* `']('&e.` Are `](` elements of the input? Returns boolean list:
```
1 1
```
* `+` Add the results of the previous 2 steps. This does the endpoint "adjustment" we'll need for the final step:
```
13 3
```
* `[:-.&i./` Convert each of the above numbers to lists `0..<n-1>`, and then set subtract. That is:
```
v set minus
0 1 2 3 4 5 6 7 8 9 10 11 12 -. 0 1 2
3 4 5 6 7 8 9 10 11 12
```
* `1#.` Sum
```
75
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 104 bytes
```
n=>[...Array(+(p=n.split(/\b/))[3]+(p[4]>"[")).keys(n=0)].filter(i=>i>=+p[1]+(p[0]<")")).map(i=>n+=i)&&n
```
[Try it online!](https://tio.run/##HcpBDsIgEEDRu7BoZoJSiC5cOCQ9B7JAU5LRSgiQJj09tm7/f@@whvoqnNt5vfVIPZF1SqmplLCBhExJ1bxwg/HxHBHdxe/RXb0VTiCqz7xVSKTRq8hLmwswWbYkszN/qf1d4CG/IR8vSWIchtRz4dQgggBzMtrvpP8A "JavaScript (V8) – Try It Online")
[Answer]
# [Python 3](https://python.org), ~~105~~ 88 bytes
```
def f(s):c,d=map(int,s[1:-1].split(','));return sum(range(c+(s[0]=="("),d+(s[-1]!=")")))
```
Ungolfed:
```
def sumOverRange(s):
a = s[0]=="("
b = s[-1]!=")"
c, d = map(int, s[1:-1].split(','))
return sum(range(c+a,d+b))
```
[Answer]
# [Add++](https://github.com/cairdcoinheringaahing/AddPlusPlus), 40 bytes
```
L,BPBp","$t€v-1A:")"=0$_0A:"("=b[z£+¦rb+
```
[Try it online!](https://tio.run/##S0xJKSj4/99HxynAqUBJR0ml5FHTmjJdQ0crJU0lWwOVeAMgS0PJNim66tBi7UPLipK0/6vkJOYmpSQqGNopRRvpmMUqKVgr6NopGBlw@XMhyWkYmuoYmSJkTVGlow10DM00obKGWDUbwKTN0WSjDXWM4FrRNBrpGBrBLDVHt9PQEGgpTNbCEIudljBzjSzM0DWb6Biawq01wbQXbrKhsTG60UBpC00kZ/0HAA "Add++ – Try It Online")
Add++ ain't great at golfing, but it's surprisingly not awful here
## How it works
```
L, ; Define a lambda that takes a string S
BPBp ; Remove the first and last characters of S
","$t ; Split on ","
€v ; Evaluate each; Call this R
-1A: ; Get the last character of S
")"= ; Is it equal to ")"?
0$_ ; Negate
0A:"("= ; Is the first character of S "("?
b[ ; Pair
z£+ ; Add to R
¦r ; Range
b+ ; Sum
```
[Answer]
# [Python 3.6+](https://docs.python.org/3.6/), 57 bytes
```
lambda x:eval(f"sum(range({x<'['}+{x[1:-1]}+{']'in x}))")
```
An unnamed function accepting a string, `x`, that returns the sum of the range described.
**[Try it online!](https://tio.run/##bU9LDoJADN17imY2M42DsaMQJepFRhYYQUkQCIwGQzg7FiGu7Kbv06TvVW93L4vNrqqH9Hge8vhxucbQhskrzlUqmudD1XFxS1TXHqSV/bJrLYUeRYxkJLMC2h5R4JCWNbikccCSsEYHESjytfEjsGtNAU50jWBJG2ZGk2GPiM35dj@aW03@ZH9l3jsUq6bKM6cwXABPVWeF43Td@LAH7wRdqkaMPSf5dRjDzz3mDlJNif@2EIgf "Python 3.8 (pre-release) – Try It Online")**
### How?
Evaluates code made with an f-string with the following three evaluated parts (as they are enclosed in `{}`s):
```
x<'[' - does x start with a character before ']'?
...effectively: does x start with a '('? -> True / False
x[1:-1] - x without its brackets
']'in x - does x contain a ']'?
...effectively: does x end with a ']' -> True / False
```
For example for `x="(5,9)"` the string will be:
```
sum(range(True+5,9+False))
```
In Python `True` and `False` are equivalent to `1` and `0` respectively, while the `range(a,b)` function is \$[a,b)\$ so `range(True+5,9+False)` is \$[1+5,9+0)=[6,9)\$ and evaluation sums this giving \$21\$.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
F⮌⪪S,⊞υ⁺Σι∨№ι(№ι]IΣ…⊟υ⊟υ
```
[Try it online!](https://tio.run/##RYyxDsIgGIR3n4IwHQkOOrg4dnKSlLkDabAlQWjg//v6iHVwutzddzevrszZxdZeuQiMfveletgtBsIjbUyWSkgLlBZSS6WUMFxXsBYmcoXlN0LvngVD5kQInYPsyd9O35m6n0w/Igyu0jEbXVo8TN7AHf/pAbaGq77cpnbe4wc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F⮌⪪S,
```
Split the input on `,` and loop over the parts (in reverse order, so that I can pop them off with one-byte instructions).
```
⊞υ⁺Σι∨№ι(№ι]
```
Extract the integer part from the string but increment it if the string contains a `(` or a `]`. This converts the range into the `[..)` form.
```
IΣ…⊟υ⊟υ
```
Create the range and take the sum.
[Answer]
# Scala, 89 bytes
```
{case s"$a,$b"=>val(c,d)=a.tail.toInt->b.init.toInt;d*(d-1+b.last/42)-c*(c+1-a(0)/42)>>1}
```
[Try it in Scastie!](https://scastie.scala-lang.org/tgVW6zgZTS66UJFdVabkYQ)
Looks like math didn't win this time, although this answer is also long because parsing isn't too straightforward.
This uses the formula \$\frac{d(d-1+j)-c(c+1-i)}{2}\$, where \$c\$ is the first number, \$d\$ is the second number, \$i\$ is 2 if the start is closed and 0 otherwise, and \$j\$ is 2 if the end is closed and 0 otherwise.
Since the characters `[` and `]` are 91 and 93 in ASCII, respectively, when divided by 42, they become 2. The characters `(` and `)` are 40 and 41, so they become 0.
```
{case s"$a,$b" => //a is the part before the comma, b is the part after (including brackets)
val (c, d) = a.tail.toInt -> b.init.toInt; //c is the first number, d is the second
d*(d-1+b.last/42) //d(d - 1 + j)
-c*(c+1-a(0)/42) //- c(c + 1 - i)
>>1} //divided by 2 (for operator precedence reasons)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes
```
\d+
$*
[](]
1
M&!`(?<=(1*),1+)1*\1
1
```
[Try it online!](https://tio.run/##LcqxCoNAEATQfv9CiLJ7buEsOVFQLK38gvPAQFKksQj5//OiqYaZN5/X970/UsnzltZnTTdHIXIk0FIVG0/DyHCiqAVuBSGlYNpGYng1Hyk0ilau2ggFqOVmCssGZPx/@x/eFf7ic87ZyQE "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert to unary.
```
[](]
1
```
Add 1 to ranges beginning `(` or ending `]`, so that the range is now of the form `[..)`.
```
M&!`(?<=(1*),1+)1*\1
```
List all of the integers in the range.
```
1
```
Sum them and convert to decimal.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), `s`, 22 bytes
```
ḢṪ⌐:h⌊⁰h\(=+^t⌊⁰t\)=-ṡ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=s&code=%E1%B8%A2%E1%B9%AA%E2%8C%90%3Ah%E2%8C%8A%E2%81%B0h%5C%28%3D%2B%5Et%E2%8C%8A%E2%81%B0t%5C%29%3D-%E1%B9%A1&inputs=%22%2815%2C%2025%5D%22&header=&footer=)
I don't really know Vyxal so I suppose this can be golfed more. But the idea here is to get both the numbers and take sum of all integers between them. If the first character is `(`, then increase the first number by 1, and if the last character is `)`, then decrease the second number by 1.
```
ḢṪ⌐ # Remove first and last characters, then split by ","
: # Duplicate
h⌊ # Take first element and convert to integer
⁰h\(=+ # Add 1 if the first character of input is equal to "("
^ # Reverse stack
t⌊ # Get last element and convert to integer
⁰t\)=- # Subtract 1 if the last character of input is equal to ")"
ṡ # Inclusive summation
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~82~~ ~~80~~ 79 bytes
Saved ~~2~~ 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
a;b;c;f(char*s){sscanf(s+1,"%d,%d%c",&a,&b,&c);a-=*s&1;b-=c<42;b=a*~a-b*~b>>1;}
```
[Try it online!](https://tio.run/##XVBbboMwEPzPKVZIIEyMip2QhxzyU/UUJB/GmAS1JRFGKmpEj166PELTWlp5dnb2qfyTUm0rRSKUyFx1lqVnyM0YJYvMNXNGLTuldmorizqSOgl1FBHSjzzjMJH4kdotuUgi6X1JP/G@kv2eiabNiwreZV64ZHabAb6@MFTaVCY@QgQ3K@Z0dbQoWC4LKQ97GAeUrchEBj2MGeUDxynjg44xFP5mb0fhkrJwkt7jCDfEakQ/RzeYrq9aVTodBuEBBR6EFFiH1mgMP/Q3@PPNCv0l2mLRsWOVYRt11upVl1gG@o0O9Qs/1NtntLBr/eAv7v2zSwluN0RepLrGtECMcAcm/9SXzL2PR55GwpsYAfN5ryYwnPXhtFhrOG8vOIop3nUzGM3civxlNbLTMf6nXUuUZK5l@2sD/h7sFGxzKHCxioKh0/Y6isxxLNzMmvZbZW/yZFr/4wc "C (gcc) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~74~~… 70 bytes
```
f(h:t)|(b,e)<-read$'(':init t++")"=sum$[b..e]++[-b|h<'[']++[-e|')'<-t]
```
[Try it online!](https://tio.run/##NY1RjoMgFEX/WQVpTID4bIRWaxvsCmYHxEw00krG6kRpxg/37iDM/L2Te899XT1/6b7ftgftbpattAHNZDLpuo0IJTczGIttHB/YoZzfr0g1x6Ou4lglzdpJooi/9UoYkYmttldthrIdEVYGPmGsZPIzTu0so/tT2w8zaIR7bfFS7h@w631PZrD0gU1ZLmBgYQjvG5sSkFc4uWORIsozENkfZUilwHO2E/8PU4@XFCkOIkSICuDCSxfncO4kTwUPztX3RJG78Aw8C9rZe6HJTydXdViE@ewX "Haskell – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 72 bytes
```
/(\()?(\d+),(\d+)(\))?/;$m=$3-!!$4;$n=$2+!!$1;$_=($m*($m+1)-$n*($n-1))/2
```
[Try it online!](https://tio.run/##LYrdjoIwEIXveYrR7UVHyuJUMe4S4v2@AhhTQ6NEaAmW7NtbZ3Uvzpyfb0Y79UWMuWwkHmTTpqheVzaIh7wUQyU22WIhtqVwldApRyrFqZJiWLFSwkw4Ti4jxFxHZp/VsnFL@ICf@R7AtG3nLmDA2d@@cxaCh8Hc2K8W/BzGOcDgJwuTNa059xa@MdZa7Y6JpELp4pjUa0U7fNc1JjUpzU0r0syIGP7/fv3BraLijV8z@x4ffgydd/eYjU8 "Perl 5 – Try It Online")
Another beautiful regular expression saves the day. This regex has four capture groups.
* `$1` is truthy iff we start with an open parenthesis
* `$2` is the lower bound
* `$3` is the upper bound
* `$4` is truthy iff we end with a close parenthesis
From there, we set up our lower and upper bounds, using the conditional parentheses to adjust so we always have an inclusive range, and then it's just a matter of arithmetic.
] |
[Question]
[
In any programming language, create a program that takes input and animates the text being typed on a keyboard.
The delay between each character should be varying to simulate true typing on a keyboard. The delay shall be `0.1, 0.1, 0.5, 0.1, 0.1, 0.5 ...` seconds, until the last character is printed. The final output shall be left on the screen.
You must overwrite the current line of text you can't have the text be printed on new rows.
Example, the input "Hello, PPCG! Goodbye Earth!" should result in the following animation (note that the sampling rate of the gif-maker was low, so the true result is slightly different):
[](https://i.stack.imgur.com/o27z4.gif)
Since this is code golf, the smallest amount of bytes win.
[Answer]
## C ~~108~~ ~~93~~ ~~89~~ ~~78~~ ~~73~~ 80 bytes
```
f(char *s){for(int i=0;s[i];fflush(0),usleep(100000*(i++%3?1:5)))putchar(s[i]);}
```
Ungolfed version:
```
void f(char *s)
{
for( int i=0;s[i];)
{
putchar(s[i]);
fflush(0);
usleep(100000*(i++%3?1:5));
}
}
```
@Kritixi Lithos @Metoniem Thanks for your input! saved some bytes.
Somehow, just `int i` gave me a segmentation error on running, so I initialized it with 0.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
115D÷⁵ṁȮœS¥@"
```
This is a monadic link/function. Due to implicit output, it doesn't work as a full program.
### Verification

### How it works
```
115D÷⁵ṁȮœS¥@" Monadic link. Argument: s (string)
115 Set the return value to 115.
D Decimal; yield [1, 1, 5].
÷⁵ Divide all three integers by 10.
ṁ Mold; repeat the items of [0.1, 0.1, 0.5] as many times as
necessary to match the length of s.
¥@" Combine the two links to the left into a dyadic chain and apply it
to each element in s and the corr. element of the last return value.
Ȯ Print the left argument of the chain (a character of s) and sleep
as many seconds as the right argument indicates (0.1 or 0.5).
```
[Answer]
# MATLAB, 74 bytes
```
c=input('');p=[1,1,5]/10;for i=c;fprintf('%s',i);p=p([2,3,1]);pause(p);end
```
### Explanation:
I used quite a while to make the `fprintf` version shorter than `disp()` with `clc`. The breakthrough was when I found out / remembered that `pause` can take a vector as argument, in which case it will just pick the first value. This makes it possible to leave out a counter.
```
c=input(''); % Take input as 'Hello'
p=[.1,.1,.5]; % The various pause times
for i=c; % For each of the characters in the input c
fprintf('%s',i); % Print the character i, without any trailing newline or whitespace
% No need to clear the screen, it will just append the new character
% after the existing ones
pause(p); % pause for p(1) seconds. If the input to pause is a vector,
% then it will choose the first value
p=p([2,3,1]); % Shift the pause times
end
```
The shortest I got using `disp` was 81 bytes:
```
c=input('');p=[1,1,5]/10;for i=1:nnz(c),clc;disp(c(1:i));pause(p(mod(i,3)+1));end
```
[Answer]
## JavaScript (ES6), 67 bytes
```
f=(i,o,n=0)=>i[n]&&(o.data+=i[n],setTimeout(f,++n%3?100:500,i,o,n))
```
```
<form><input id=i><button onclick=f(i.value,o.firstChild)>Go!</button><pre id=o>
```
[Answer]
# [V](https://github.com/DJMcMayhem/V/), ~~20~~ ~~19~~ 18 bytes
*1 byte saved thanks to @DJMcMayhem*
*saved 1 byte by removing `ò` at the end*
```
òD1gÓulD1gÓulDgÓul
```
Terribly ungolfy, I know, it's just that strict `u`ndo preventing me to use nested loops.
### Explanation
The cursor starts in the beginning of the buffer, which is the first character of the input.
```
ò " Start recursion
D " Deletes everything from the cursor's position to the end of line
1gÓ " Sleep for 100ms
u " Undo (now the deletion is reverted)
l " Move cursor one to the right
D1gÓul " Do it again
D " Same as before but...
gÓ " Sleep for 500ms this time
ul " Then undo and move right
" Implicit ò
```
Gif coming soon...
[Answer]
# [Noodel](https://tkellehe.github.io/noodel/), 18 [bytes](https://tkellehe.github.io/noodel/docs/code_page.html)
```
ʋ115ṡḶƙÞṡạḌ100.ṡ€ß
```
[Try it:)](https://tkellehe.github.io/noodel/editor.html?code=%CA%8B115%E1%B9%A1%E1%B8%B6%C6%99%C3%9E%E1%B9%A1%E1%BA%A1%E1%B8%8C100.%E1%B9%A1%E2%82%AC%C3%9F&input=%22Hello%2C%20PPCG!%20Goodbye%20Earth!%22&run=false)
---
### How it works
```
# Input is automatically pushed to the stack.
ʋ # Vectorize the string into an array of characters.
115 # Push on the string literal "115" to be used to create the delays.
ṡ # Swap the two items on the stack.
ḶƙÞṡạḌ100.ṡ€ # The main loop for the animation.
Ḷ # Loops the following code based off of the length of the string.
ƙ # Push on the current iteration's element of the character array (essentially a foreach).
Þ # Pop off of the stack and push to the screen.
ṡ # Swap the string "115" and he array of characters (this is done because need array of characters on the top for the loop to know how many times to loop)
ạ # Grab the next character in the string "115" (essentially a natural animation cmd that every time called on the same object will access the next item looping)
# Also, turns the string into an array of characters.
Ḍ100. # Pop the character off and convert to a number then multiply by 100 to get the correct delay. Then delay for that many ms.
ṡ # Swap the items again to compensate for the one earlier.
€ # The end of the loop.
ß # Clears the screen such that when implicit popping of the stack occurs it will display the correct output.
```
---
**19 byte** code snippet that loops endlessly.
```
<div id="noodel" cols="30" rows="2" code="ʋ115ṡḷḶƙÞṡạḌ100.ṡ€ß" input='"Hello, PPCG! Goodbye Earth!"'/>
<script src="https://tkellehe.github.io/noodel/release/noodel-2.5.js"></script>
<script src="https://tkellehe.github.io/noodel/ppcg.min.js"></script>
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 16 bytes
```
"@&htDTT5hX@)&Xx
```
[Try it at MATL Online!](https://matl.io/?code=%22%40%26htDTT5hX%40%29%26Xx&inputs=%27Hello%2C+PPCG%21+Goodbye+Earth%21%27&version=19.8.0)
### Explanation
```
" % Implicitly input string. For each char of it
@ % Push current char
&h % Concatenate everything so far into a string
tD % Duplicate and display
TT5h % Push array [1 1 5]
X@) % Get the k-th element modularly, where k is current iteration.
% So this gives 1, 1, 5 cyclically
&Xx % Pause for that many tenths of a second and clear screen
% Implicit end. Implicitly display the final string, again (screen
% was deleted at the end of the last iteration)
```
[Answer]
# APL, 23 bytes
```
⊢{⍞←⍺⊣⎕DL⍵÷10}¨1 1 5⍴⍨⍴
```
Explanation:
```
1 1 5⍴⍨⍴ ⍝ repeat the values [1,1,5] to match the input length
⊢ ⍝ the input itself
{ }¨ ⍝ pairwise map
⎕DL⍵÷10 ⍝ wait ⍵÷10 seconds, where ⍵ is the number
⊣ ⍝ ignore that value, and
⍞←⍺ ⍝ output the character
```
[Answer]
# C#, ~~131~~ bytes
Not much to explain. It just takes a string (wrapped in "") as argument and prints each character using the correct delay pattern. After the animation it exits with an `OutOfRangeException` because the loop doesn't stop after it looped over all characters. Since it's an infinite loop, that also means I can use `int Main` instead of `void Main` ;-)
## Golfed
```
class C{static int Main(string[]a){for(int i=0;){System.Console.Write(a[0][i]);System.Threading.Thread.Sleep(i++%3<1?500:100);}}}
```
# Ungolfed
```
class C
{
static int Main(string[] a)
{
for (int i = 0; ;)
{
System.Console.Write(a[0][i]);
System.Threading.Thread.Sleep(i++ % 3 < 1 ? 500 : 100);
}
}
}
```
## Edits
* Saved 1 byte by moving incrementing `i` inside of the `Sleep()` method instead of in the `for` loop. (Thanks [Maliafo](https://codegolf.stackexchange.com/users/56032/maliafo))
[Answer]
# SmileBASIC, 61 bytes
```
LINPUT S$FOR I=0TO LEN(S$)-1?S$[I];
WAIT 6+24*(I MOD 3>1)NEXT
```
I think the delay calculation could be a lot shorter.
[Answer]
# Clojure, 81 bytes
```
#(doseq[[c d](map vector %(cycle[100 100 500]))](Thread/sleep d)(print c)(flush))
```
Loops over the input string zipped with a infinite list of `[100 100 500]`.
```
(defn typer [input]
; (map vector... is generally how you zip lists in Clojure
(doseq [[chr delay] (map vector input (cycle [100 100 500]))]
(Thread/sleep delay)
(print chr) (flush)))
```
[Answer]
# Bash (+utilities), 32 byte
>
> Note, this will beep in the process, but who said submissions can not have fancy sound effects !
>
>
>
**Golfed**
```
sed 's/.../&\a\a\a\a/g'|pv -qL10
```
**Demo**
[](https://i.stack.imgur.com/Thspc.gif)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~83~~ 75 bytes
```
import time;i=0
for c in input():i+=1;print(end=c);time.sleep(i%3and.1or.5)
```
[Try it online!](https://repl.it/Fqlc/0)
[Answer]
# Powershell, ~~66~~ ~~65~~ 63 Bytes
```
[char[]]$args|%{sleep -m((1,1,5)[++$i%3]*100);Write-Host $_ -N}
```
[](https://i.stack.imgur.com/cOmPY.gif)
-1 removed unneeded white space after `-m`
-2 thanks to AdmBorkBork - used `1,1,5` and `*` end result by `100` instead of using `100,100,500`
takes `$args` as a char array, loops through sleeping as specified, `Write-Host` with the `-N`oNewline argument is used to write the chars out on the same line.
Improvements?
* use `[0..99]` instead of `[char[]]` to save 1 byte, but wont work on strings over 100 chars.
* use `100,500` and `[(++$i%3)-gt1]` but make it shorter somehow.
* combine it into a single string and clear between outputs, eliminating the long `Write-Host`
can't find any way to make the last two work, and the first one isn't valid by any particular rule.
[Answer]
# Perl, 63 bytes
```
foreach(split//,pop){$|=++$i;print;select('','','',$i%3?.1:.5)}
```
[Answer]
# Python 3, 88 Bytes
```
import time;s=''
for x in input():s+=x;time.sleep(.1+.4*(len(s)%3==0));print('\n'*25+s)
```
[Answer]
# Rebol, 65 bytes
```
s: input t:[.1 .1 .5]forall s[prin s/1 wait last append t take t]
```
Ungolfed:
```
s: input
t: [.1 .1 .5]
forall s [
prin s/1
wait last append t take t
]
```
[Answer]
# Bash + coreutils, 57 bytes
```
for((;k<${#1};k++)){ echo -n ${1:k:1};sleep .$[2&k%3|1];}
```
[Answer]
# Java 7, ~~151~~ 149 bytes
```
class M{public static void main(String[]a)throws Exception{int n=0;for(String c:a[0].split("")){System.out.print(c);Thread.sleep(n++%3>0?100:500);}}}
```
-2 bytes thanks to *@KritixiLithos* for something I always forget..
**Explanation:**
```
class M{
public static void main(String[] a) throws Exception{ // throws Exception is required due to the Thread.sleep
int n = 0; // Initialize counter (and set to 0)
for(String c : a[0].split("")){ // Loop over the characters of the input
System.out.print(c); // Print the character
Thread.sleep(n++ % 3 > 0 ? // if (n modulo 3 != 0)
100 // Use 100 ms
: // else (n modulo 3 == 0):
500); // Use 500 ms
}
}
}
```
**Usage:**
```
java -jar M.jar "Hello, PPCG! Goodbye Earth!"
```
[Answer]
# Processing, ~~133~~ 131 bytes
```
int i;void setup(){for(String c:String.join("",args).split(""))p{try{Thread.sleep(i++%3<1?500:100);}catch(Exception e){}print(c);}}
```
*I tried doing `args[0]` and wrapping the argument in `""` instead, but it does not work for some reason.*
Anyways... this is the first time I've written a Processing program that takes arguments. Unlike Java, you don't need to declare the arguments using `String[]args`, but the variable `args` will automatically be initialised to the arguments.
Put it in a file called `sketch_name.pde` under a folder called `sketch_name` (yes, same name for folder and sketch). Call it like:
```
processing-java --sketch=/full/path/to/sketch/folder --run input text here
```
[](https://i.stack.imgur.com/2SH37.gif)
] |
[Question]
[
## Introduction
You use Twitter (let's pretend, if not), where you are limited to 140 characters per individual tweet you care to share with the world. If you wanted to tweet to your followers Abraham Lincoln's [Gettysburg Address](http://en.wikisource.org/wiki/Gettysburg_Address_%28Lincoln_Memorial%29), then you would need to break up the text into multiple 140-character chunks in order to get the whole message out. However, those chunks should not always be exactly 140 characters long. Say for example, we broke the speech into 17-character chunks, we'd end up with these tweets:
* FOUR SCORE AND SE
* VEN YEARS AGO OUR
* FATHERS BROUGHT
* FORTH ON THIS CON
* TINENT A NEW NATI
* ON CONCEIVED IN L
* *(and so on)*
**That's no good!** When individual words are broken up, then it can get difficult to understand what you are trying to say. Also, in the twitterverse, one of your followers may come across a specific tweet and not realize that there's more to the message, so you'll want to number your tweets so they have some context to work with (still using 17-character chunks):
* (1/7) FOUR SCORE AND
* (2/7) SEVEN YEARS AGO
* (3/7) OUR FATHERS
* (4/7) BROUGHT FORTH ON
* (5/7) THIS CONTINENT A
* (6/7) NEW NATION
* (7/7) CONCEIVED IN...
You could manually figure out the best configuration for your tweets by hand, but that's what we have computers for!
## Challenge
In the shortest code possible, parse the Gettysburg Address (or any text, but we'll stick with this one as an example) into a set of tweets consisting of no more than 140 characters (assume ASCII, since our example text should not have any uncommon/unusual bits in it).
## Details
* Your function/program/etc should take in a single string argument and output one line of text for each tweet.
+ Assume this input will never result in more than 99 total tweets when parsed, regardless of how you choose to parse (so long as that choice still fits the other points of the challenge).
* Tweets need to include a `tweet number` of `total tweets` indicator in the format "`(x/y)`" preceding the body of the tweet.
+ **This count will take up part of your 140-character space!**
* Tweet chunks may only be split on newlines or spaces.
+ No hyphens, periods, commas or other punctuation is allowed, unless immediately preceded or followed by a space or newline.
* Tweets should consist of as many complete words as possible.
+ This constraint is a little flexible, e.g. when your final tweet only has one word
* This is code golf, so the shortest code wins.
## Full Text of Gettysburg Address
(Your code should still be able to handle any ASCII string passed to it.)
>
> FOUR SCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH ON THIS CONTINENT A NEW NATION CONCEIVED IN LIBERTY AND DEDICATED TO THE PROPOSITION THAT ALL MEN ARE CREATED EQUAL.
> NOW WE ARE ENGAGED IN A GREAT CIVIL WAR TESTING WHETHER THAT NATION OR ANY NATION SO CONCEIVED AND SO DEDICATED CAN LONG ENDURE. WE ARE MET ON A GREAT BATTLEFIELD OF THAT WAR. WE HAVE COME TO DEDICATE A PORTION OF THAT FIELD AS A FINAL RESTING PLACE FOR THOSE WHO HERE GAVE THEIR LIVES THAT THAT NATION MIGHT LIVE. IT IS ALTOGETHER FITTING AND PROPER THAT WE SHOULD DO THIS. BUT IN A LARGER SENSE WE CAN NOT DEDICATE, WE CAN NOT CONSECRATE, WE CAN NOT HALLOW, THIS GROUND. THE BRAVE MEN LIVING AND DEAD WHO STRUGGLED HERE HAVE CONSECRATED IT FAR ABOVE OUR POOR POWER TO ADD OR DETRACT. THE WORLD WILL LITTLE NOTE NOR LONG REMEMBER WHAT WE SAY HERE BUT IT CAN NEVER FORGET WHAT THEY DID HERE. IT IS FOR US THE LIVING RATHER TO BE DEDICATED HERE TO THE UNFINISHED WORK WHICH THEY WHO FOUGHT HERE HAVE THUS FAR SO NOBLY ADVANCED. IT IS RATHER FOR US TO BE HERE DEDICATED TO THE GREAT TASK REMAINING BEFORE US, THAT FROM THESE HONORED DEAD WE TAKE INCREASED DEVOTION TO THAT CAUSE FOR WHICH THEY GAVE THE LAST FULL MEASURE OF DEVOTION, THAT WE HERE HIGHLY RESOLVE THAT THESE DEAD SHALL NOT HAVE DIED IN VAIN, THAT THIS NATION UNDER GOD SHALL HAVE A NEW BIRTH OF FREEDOM, AND THAT GOVERNMENT OF THE PEOPLE BY THE PEOPLE FOR THE PEOPLE SHALL NOT PERISH FROM THE EARTH.
>
>
>
[Answer]
## Python, 140
^ 140 chars was actually a coincidence.
```
def f(s):
s=s.split();i=0;l=[]
while s:
i+=1;t='(%d/%%d)'%i
while s and len(t+s[0])<140:t+=' '+s.pop(0)
l+=[t]
for t in l:print t%i
```
While there are words left, the solution will create new tweets from the supply of words and append them to a list. For each tweet, it will keep trying to add words until the tweet's length reaches over 140 characters. Two characters are reserved for the `total tweets`, which are filled in later as each tweet in the list is printed.
Example output:
```
(1/11) FOUR SCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH ON THIS CONTINENT A NEW NATION CONCEIVED IN LIBERTY AND DEDICATED TO THE
(2/11) PROPOSITION THAT ALL MEN ARE CREATED EQUAL. NOW WE ARE ENGAGED IN A GREAT CIVIL WAR TESTING WHETHER THAT NATION OR ANY NATION SO
(3/11) CONCEIVED AND SO DEDICATED CAN LONG ENDURE. WE ARE MET ON A GREAT BATTLEFIELD OF THAT WAR. WE HAVE COME TO DEDICATE A PORTION OF THAT
(4/11) FIELD AS A FINAL RESTING PLACE FOR THOSE WHO HERE GAVE THEIR LIVES THAT THAT NATION MIGHT LIVE. IT IS ALTOGETHER FITTING AND PROPER
(5/11) THAT WE SHOULD DO THIS. BUT IN A LARGER SENSE WE CAN NOT DEDICATE, WE CAN NOT CONSECRATE, WE CAN NOT HALLOW, THIS GROUND. THE BRAVE
(6/11) MEN LIVING AND DEAD WHO STRUGGLED HERE HAVE CONSECRATED IT FAR ABOVE OUR POOR POWER TO ADD OR DETRACT. THE WORLD WILL LITTLE NOTE NOR
(7/11) LONG REMEMBER WHAT WE SAY HERE BUT IT CAN NEVER FORGET WHAT THEY DID HERE. IT IS FOR US THE LIVING RATHER TO BE DEDICATED HERE TO THE
(8/11) UNFINISHED WORK WHICH THEY WHO FOUGHT HERE HAVE THUS FAR SO NOBLY ADVANCED. IT IS RATHER FOR US TO BE HERE DEDICATED TO THE GREAT
(9/11) TASK REMAINING BEFORE US, THAT FROM THESE HONORED DEAD WE TAKE INCREASED DEVOTION TO THAT CAUSE FOR WHICH THEY GAVE THE LAST FULL
(10/11) MEASURE OF DEVOTION, THAT WE HERE HIGHLY RESOLVE THAT THESE DEAD SHALL NOT HAVE DIED IN VAIN, THAT THIS NATION UNDER GOD SHALL HAVE
(11/11) A NEW BIRTH OF FREEDOM, AND THAT GOVERNMENT OF THE PEOPLE BY THE PEOPLE FOR THE PEOPLE SHALL NOT PERISH FROM THE EARTH.
```
[Answer]
**Perl, 51 Characters**
```
s#\G(.{1,132})(\s+|$)#(${\++$a}/~) $1\n#g;s#~#$a#g
```
Requires -p command line prompt, 1 char included.
Explanation: insert the count portion before and newline after word groups of up to 132 characters. Insert a placeholder (`~`) for the total, which is then replaced by a second substitution. This breaks if the message contains `~`, but one could easily use an unprintable character instead.
It cheats slightly: it always allows seven characters for the count portion, `(nn/nn)`. Really, if it is `(n/n)` it should allow two extra characters. However, an arbitrary solution to this would greatly increase the complexity of the problem.
[Answer]
### Ruby, 77 characters
```
f=->t{i=0;$><<t.gsub(/(.{1,132})([ \n]|$)/m){"(#{i+=1}/%{i}) #{$1}\n"}%{i:i}}
```
Packed the logic into a single regular expression. Output of `f[text]`:
```
(1/11) FOUR SCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH ON THIS CONTINENT A NEW NATION CONCEIVED IN LIBERTY AND DEDICATED TO THE
(2/11) PROPOSITION THAT ALL MEN ARE CREATED EQUAL. NOW WE ARE ENGAGED IN A GREAT CIVIL WAR TESTING WHETHER THAT NATION OR ANY NATION SO
(3/11) CONCEIVED AND SO DEDICATED CAN LONG ENDURE. WE ARE MET ON A GREAT BATTLEFIELD OF THAT WAR. WE HAVE COME TO DEDICATE A PORTION OF
(4/11) THAT FIELD AS A FINAL RESTING PLACE FOR THOSE WHO HERE GAVE THEIR LIVES THAT THAT NATION MIGHT LIVE. IT IS ALTOGETHER FITTING AND
(5/11) PROPER THAT WE SHOULD DO THIS. BUT IN A LARGER SENSE WE CAN NOT DEDICATE, WE CAN NOT CONSECRATE, WE CAN NOT HALLOW, THIS GROUND. THE
(6/11) BRAVE MEN LIVING AND DEAD WHO STRUGGLED HERE HAVE CONSECRATED IT FAR ABOVE OUR POOR POWER TO ADD OR DETRACT. THE WORLD WILL LITTLE
(7/11) NOTE NOR LONG REMEMBER WHAT WE SAY HERE BUT IT CAN NEVER FORGET WHAT THEY DID HERE. IT IS FOR US THE LIVING RATHER TO BE DEDICATED
(8/11) HERE TO THE UNFINISHED WORK WHICH THEY WHO FOUGHT HERE HAVE THUS FAR SO NOBLY ADVANCED. IT IS RATHER FOR US TO BE HERE DEDICATED TO
(9/11) THE GREAT TASK REMAINING BEFORE US, THAT FROM THESE HONORED DEAD WE TAKE INCREASED DEVOTION TO THAT CAUSE FOR WHICH THEY GAVE THE
(10/11) LAST FULL MEASURE OF DEVOTION, THAT WE HERE HIGHLY RESOLVE THAT THESE DEAD SHALL NOT HAVE DIED IN VAIN, THAT THIS NATION UNDER GOD
(11/11) SHALL HAVE A NEW BIRTH OF FREEDOM, AND THAT GOVERNMENT OF THE PEOPLE BY THE PEOPLE FOR THE PEOPLE SHALL NOT PERISH FROM THE EARTH.
```
[Answer]
## Ruby, 75
Can't beat Perl, but at least it marginally beats the other Ruby solution. Note that it prints the tweets in reverse order (the problem does not specify one).
```
f=->t,i=1{t=~/\S.{,130}\S(?!\S)/?puts("(#{i}/%d) #$&"%n=f[$',i+1])||n :i-1}
```
[Answer]
## VBA, 251
Tried another method... Not quite as good as my original, but I'm still working on it...
```
Sub a(s)
Dim n(99)
m=1
r=Split(StrConv(s,64),Chr(0))
For i=0 To Len(s)
If i-g>132 Then n(m)=Mid(s,g+1,u-g):i=u:g=i:m=m+1
If r(i)=" " Or r(i)=vbCr Then i=i+1:u=i
Next
n(m)=Mid(s,g+1)
For o=1 To m
Debug.Print "(" & o & "/" & m & ") " & n(o)
Next
End Sub
```
Outputs:
```
(1/11) FOUR SCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH ON THIS CONTINENT A NEW NATION CONCEIVED IN LIBERTY AND DEDICATED TO THE
(2/11) PROPOSITION THAT ALL MEN ARE CREATED EQUAL. NOW WE ARE ENGAGED IN A GREAT CIVIL WAR TESTING WHETHER THAT NATION OR ANY NATION SO
(3/11) CONCEIVED AND SO DEDICATED CAN LONG ENDURE. WE ARE MET ON A GREAT BATTLEFIELD OF THAT WAR. WE HAVE COME TO DEDICATE A PORTION OF
(4/11) THAT FIELD AS A FINAL RESTING PLACE FOR THOSE WHO HERE GAVE THEIR LIVES THAT THAT NATION MIGHT LIVE. IT IS ALTOGETHER FITTING AND
(5/11) PROPER THAT WE SHOULD DO THIS. BUT IN A LARGER SENSE WE CAN NOT DEDICATE, WE CAN NOT CONSECRATE, WE CAN NOT HALLOW, THIS GROUND. THE
(6/11) BRAVE MEN LIVING AND DEAD WHO STRUGGLED HERE HAVE CONSECRATED IT FAR ABOVE OUR POOR POWER TO ADD OR DETRACT. THE WORLD WILL LITTLE
(7/11) NOTE NOR LONG REMEMBER WHAT WE SAY HERE BUT IT CAN NEVER FORGET WHAT THEY DID HERE. IT IS FOR US THE LIVING RATHER TO BE DEDICATED
(8/11) HERE TO THE UNFINISHED WORK WHICH THEY WHO FOUGHT HERE HAVE THUS FAR SO NOBLY ADVANCED. IT IS RATHER FOR US TO BE HERE DEDICATED TO
(9/11) THE GREAT TASK REMAINING BEFORE US, THAT FROM THESE HONORED DEAD WE TAKE INCREASED DEVOTION TO THAT CAUSE FOR WHICH THEY GAVE THE
(10/11) LAST FULL MEASURE OF DEVOTION, THAT WE HERE HIGHLY RESOLVE THAT THESE DEAD SHALL NOT HAVE DIED IN VAIN, THAT THIS NATION UNDER GOD
(11/11) SHALL HAVE A NEW BIRTH OF FREEDOM, AND THAT GOVERNMENT OF THE PEOPLE BY THE PEOPLE FOR THE PEOPLE SHALL NOT PERISH FROM THE EARTH.
```
[Answer]
# BASH (88 Chars)
```
fold -132 -s |tac|cat -n |tac|awk '{if(NR==1)a=$1;$1="";printf "(%d/%d) %s\n",NR,a,$0 }'
```
Fold the line at 132 characters (to allow for our tweet count), on spaces (`-s`), Read text backwards (tac), number the text (`cat -n`), re-reverse (`tac`). Inside Awk: First line (NR==1), assign the letter 'a' the value in the first . Blank the number column. Print (NR/'a') then the line.
Output:
```
(1/12) FOUR SCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH ON THIS CONTINENT A NEW NATION CONCEIVED IN LIBERTY AND DEDICATED TO THE
(2/12) PROPOSITION THAT ALL MEN ARE CREATED EQUAL. NOW WE ARE ENGAGED IN A GREAT CIVIL WAR TESTING WHETHER THAT NATION OR ANY NATION SO
(3/12) CONCEIVED AND SO DEDICATED CAN LONG ENDURE. WE ARE MET ON A GREAT BATTLEFIELD OF THAT WAR. WE HAVE COME TO DEDICATE A PORTION OF
(4/12) THAT FIELD AS A FINAL RESTING PLACE FOR THOSE WHO HERE GAVE THEIR LIVES THAT THAT NATION MIGHT LIVE. IT IS ALTOGETHER FITTING AND
(5/12) PROPER THAT WE SHOULD DO THIS. BUT IN A LARGER SENSE WE CAN NOT DEDICATE, WE CAN NOT CONSECRATE, WE CAN NOT HALLOW, THIS GROUND.
(6/12) THE BRAVE MEN LIVING AND DEAD WHO STRUGGLED HERE HAVE CONSECRATED IT FAR ABOVE OUR POOR POWER TO ADD OR DETRACT. THE WORLD WILL
(7/12) LITTLE NOTE NOR LONG REMEMBER WHAT WE SAY HERE BUT IT CAN NEVER FORGET WHAT THEY DID HERE. IT IS FOR US THE LIVING RATHER TO BE
(8/12) DEDICATED HERE TO THE UNFINISHED WORK WHICH THEY WHO FOUGHT HERE HAVE THUS FAR SO NOBLY ADVANCED. IT IS RATHER FOR US TO BE HERE
(9/12) DEDICATED TO THE GREAT TASK REMAINING BEFORE US, THAT FROM THESE HONORED DEAD WE TAKE INCREASED DEVOTION TO THAT CAUSE FOR WHICH
(10/12) THEY GAVE THE LAST FULL MEASURE OF DEVOTION, THAT WE HERE HIGHLY RESOLVE THAT THESE DEAD SHALL NOT HAVE DIED IN VAIN, THAT THIS
(11/12) NATION UNDER GOD SHALL HAVE A NEW BIRTH OF FREEDOM, AND THAT GOVERNMENT OF THE PEOPLE BY THE PEOPLE FOR THE PEOPLE SHALL NOT PERISH
(12/12) FROM THE EARTH.
```
[Answer]
## Javascript (FF only), 92 chars
```
r=(s)=>{s.match(/.{1,132}(\s|$)/gm).map((v,i,a)=>console.log(v,'('+(i+1)+'/'+a.length+')'))}
```
Formatted, that's a rip-off of the Perl script:
```
r=(s)=>{
s.match(/.{1,132}(\s|$)/gm).map((v,i,a) => console.log(v,'('+(i+1)+'/'+a.length+')'))
}
```
[Answer]
## VBA, 227
```
Sub a(s)
Dim n(99)
m=1
x=133
While Len(s)>x
t=Left(s,x):p=InStrRev(t," "):q=InStrRev(t,vbCr):i=IIf(p>q,p,q):t=Left(s,i):s=Mid(s,i+1):n(m)=t:m=m+1
Wend
n(m)=s
For o=1 To m
Debug.Print "(" & o & "/" & m & ") " & n(o)
Next
End Sub
```
Outputs:
```
(1/11) FOUR SCORE AND SEVEN YEARS AGO OUR FATHERS BROUGHT FORTH ON THIS CONTINENT A NEW NATION CONCEIVED IN LIBERTY AND DEDICATED TO THE
(2/11) PROPOSITION THAT ALL MEN ARE CREATED EQUAL. NOW WE ARE ENGAGED IN A GREAT CIVIL WAR TESTING WHETHER THAT NATION OR ANY NATION SO
(3/11) CONCEIVED AND SO DEDICATED CAN LONG ENDURE. WE ARE MET ON A GREAT BATTLEFIELD OF THAT WAR. WE HAVE COME TO DEDICATE A PORTION OF
(4/11) THAT FIELD AS A FINAL RESTING PLACE FOR THOSE WHO HERE GAVE THEIR LIVES THAT THAT NATION MIGHT LIVE. IT IS ALTOGETHER FITTING AND
(5/11) PROPER THAT WE SHOULD DO THIS. BUT IN A LARGER SENSE WE CAN NOT DEDICATE, WE CAN NOT CONSECRATE, WE CAN NOT HALLOW, THIS GROUND. THE
(6/11) BRAVE MEN LIVING AND DEAD WHO STRUGGLED HERE HAVE CONSECRATED IT FAR ABOVE OUR POOR POWER TO ADD OR DETRACT. THE WORLD WILL LITTLE
(7/11) NOTE NOR LONG REMEMBER WHAT WE SAY HERE BUT IT CAN NEVER FORGET WHAT THEY DID HERE. IT IS FOR US THE LIVING RATHER TO BE DEDICATED
(8/11) HERE TO THE UNFINISHED WORK WHICH THEY WHO FOUGHT HERE HAVE THUS FAR SO NOBLY ADVANCED. IT IS RATHER FOR US TO BE HERE DEDICATED TO
(9/11) THE GREAT TASK REMAINING BEFORE US, THAT FROM THESE HONORED DEAD WE TAKE INCREASED DEVOTION TO THAT CAUSE FOR WHICH THEY GAVE THE
(10/11) LAST FULL MEASURE OF DEVOTION, THAT WE HERE HIGHLY RESOLVE THAT THESE DEAD SHALL NOT HAVE DIED IN VAIN, THAT THIS NATION UNDER GOD
(11/11) SHALL HAVE A NEW BIRTH OF FREEDOM, AND THAT GOVERNMENT OF THE PEOPLE BY THE PEOPLE FOR THE PEOPLE SHALL NOT PERISH FROM THE EARTH.
```
[Answer]
## Javascript (FF only), 135 chars
```
n=(s)=>{for(g=[],i=1,a=s.split(/(\s)/),r='';c=a.shift();g[i]=r+=c)if((c+r)[132]&&i++)r='';g.map((v,k)=>console.log(v,'('+k+'/'+i+')'))}
```
Formatted, that's:
```
n=(s)=>{
for (g=[],i=1,a=s.split(/(\s)/),r=''; c=a.shift(); g[i]=r+=c) {
if((c+r)[132]&&i++) {
r='';
}
}
g.map((v,k)=>console.log(v,'('+k+'/'+i+')'))
}
```
[Answer]
# PHP, 233
Am I correct in assuming that this is the first answer that does not cheat on the count portion?
(It also works with more than 99 tweets; I could shave off two more bytes if I would allow an infinite loop in that case.)
```
function t($s,$e=1){$a=explode(' ',$s);while($a){$t=++$n;while($a&&strlen($t.$a[0])<137-$e)$t.=' '.array_shift($a);$r[]=$t;}if($n>=10**$e)t($s,$e+1);else foreach($r as$i=>$s)echo preg_replace('%(^\d+)%',"(\$1/$n)",$s),'
';}
```
ungolfed:
```
function t($s,$e=1)
{
$a=explode(' ',$s);
while($a)
{
$t=++$n;
while($a&&strlen($t.$a[0])<137-$e)$t.=' '.array_shift($a);
$r[]=$t;
}
if($n>=10**$e) // if tweet count has more than $e digits
t($s,ceil(log10($n+1))); // use correct length (golfed: try with length+1)
else
foreach($r as$i=>$s)
echo preg_replace('%(^\d+)%',"(\$1/$n)",$s),"\n";
}
```
] |
[Question]
[
I recently saw some questions on SO that asked if you could make a Hello World program without using any semi colons using C#. The challenge is to do this again, but in the shortest amount of code possible!
[Answer]
# C# 85 chars
```
class H{static void Main(){if(System.Console.Out.WriteAsync("Hello, world!")is H){}}}
```
[Answer]
# C#, 76
```
class X{static void Main(){if(System.Console.Write("Hello, World!")is X){}}}
```
I tried this in my VS2012 and it works just fine, even though it is quite a surprise that you can apply the `is` operator to `void`...
[Answer]
## C# (114)
```
class M{static void Main(){if(typeof(System.Console).GetMethods()[78].Invoke(null,new[]{"Hello, world!"})is M){}}}
```
Note that the proper index for `Write(string)`/`WriteLine(string)` may be different on your system. However, since there are only 106 methods total, I'm almost certain either `Write(string)` or `WriteLine(string)` will be a two-digit index number on every system, so the character count should be generally valid.
Demo: <http://ideone.com/5npky> (`Write` method is apparently index 23 here)
[Answer]
# 115 Bytes
```
class H{static void Main(){if(((System.Action)(()=>System.Console.Write("Hello, world!"))).DynamicInvoke()is H){}}}
```
It's likely possible to produce something a bit shorter, but I'm pretty sure that you're going to need make some sort of asynchronous call.
[Answer]
# C# ~~96~~ ~~95~~ 94 chars
A bit of a cheat, but works if you have IronRuby installed:
```
class P{static void Main(){if(IronRuby.Ruby.CreateEngine().Execute("puts'Hello World'")>1){}}}
```
] |
[Question]
[
**This question already has answers here**:
[Find the number in the Champernowne constant](/questions/66878/find-the-number-in-the-champernowne-constant)
(29 answers)
Closed last month.
Someone I know has no coding experience, but has proposed an algorithm\* to determine the character limit of text fields they find online. They copy a string containing the numbers from 1 to 1,000 inclusive, not separated in any way, and they read the last few digits it displays.
For example, after pasting, they might see
`...5645745845`
From here, they can figure out the character limit.
They've got two problems with this approach. One, it's a little hard to determine where the discrete numbers are in the string. (The last whole number displayed here is `458`, and the final two digits would have been followed by `9` if the text field allowed one more character.)
Two, the math is a little tricky even when that character has been identified. It's easy with single digits. For instance, if the last whole number were `5`, the limit would be `5` characters. With double digits it's a little harder. If the last whole number were `13` followed by the `1` of `14`, the full field would display `123456789101112131` for a limit of `18` characters.
They've managed to get a script that copies the last 10 digits the text field displays, or as many as the field holds if the field can hold less than 10. They'd like to feed that into another script that returns the field's length limit.
Additional test cases:
```
'' -> 0
'1' -> 1
'12' -> 2
'7891011121' -> 16
'1191201211' -> 256
'5645745845' -> 1268
```
Here are some examples of invalid inputs, incidentally:
```
'0'
'121'
'1211'
```
---
\* Possibly in jest :)
[Answer]
# Excel (ms365)
**1)** Recursion with `LAMBDA()`, **74 bytes**:
[](https://i.stack.imgur.com/CHMiF.gif)
Formula in `B1`:
```
=LET(x,LAMBDA(y,n,s,IFERROR(FIND(A1,s),y(y,n+1,s&n))),x(x,1,""))+LEN(A1)-1
```
**Note**: Due to the limitations within Excel this may return an error above a certain amount of recursive lambda calls.
---
**2)** Concatenating with `ROW()`, **39 bytes**:
I did explicitly want to stay away from using a concatenated string from any arbitrary range of numbers for this challenge. If one is okay with this concept then try:
```
=FIND(A1,CONCAT(ROW(1:8468)))+LEN(A1)-1
```
Here I found that concatenating `ROW(1:8468)` seems to be Excel's (or rather `CONCAT()`'s) limit.
---
**3)** Overcome Excel's limits using `PY()`, **87 bytes**:
To overcome these limits of function within Excel, we could use the new `PY()` function:
```
=PY(
''.join(map(str,range(1,int(xl("A1")+1)))).find(str(xl("A1")))++len(str(xl("A1")))
)
```
**Note**: Python is not my forté, so I'm sure this can be golfed down. However, more importantly. Since `PY()` is executed on an external server there is a high chance of this code error out due to a "time-limit".
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LJIkIg+
```
Times out for larger inputs. Add a leading `‚ÇÑ` (push 1000) to speed it up.
[Try it online](https://tio.run/##yy9OTMpM/f/fx8sz2zNd@/9/U3MTUwsTUwA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/H6/K7Mp07f86/6MNdZSUdEx1DI0NdUzNTUwtTExjAQ).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
J # Join it together to a single string
Ik # Pop and push the (0-based) index of the input
Ig+ # Add the length of the input
# (after which the result is output implicitly)
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 50 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 6.25 bytes
```
⌊ɾṅḟ?L+
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2&c=1#WyI9IiwiIiwi4oyKyb7huYXhuJ8/TCsiLCIiLCJcIjEwMTExMlwiIl0=)
Bitstring:
```
11001011010011010000000111000101111000110100000010
```
Times out for very large inputs because it needs to generate a range between 1 and whatever number represented by the input.
## Explained
```
⌊ɾṅḟ?L+­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏‏​⁡⁠⁡‌­
⌊ɾ # ‎⁡The range [1, input]
ṅ # ‎⁢Joined into a single string.
ḟ # ‎⁣Find the index of the input in that string
?L+ # ‎⁤And add the length of the input to that
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 43 bytes
```
x=>~(g=s=>~s.indexOf(x,1)||g(s+i++))(x,i=1)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/C1q5OI922GEgV62XmpaRW@KdpVOgYatbUpGsUa2dqa2tqAvmZtoaa/625kvPzivNzUvVy8tM10jTUzcwtLA0NDA0NjdQ1NTFk4ZKG2GRNzUxMzU1MLUxMscli1QIS@w8A "JavaScript (Node.js) – Try It Online")
Using range, fail `11` (expect 13, get 1)
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
x=>~(g=s=>~s.search(x)||g(s+ ++i))(i='')+x.length
```
[Try it online!](https://tio.run/##bcvBCgIhFIXhfU/RznuRJENnJsLeRcxxjEFj7hAuhl7datMmVwf@j3O3T0tuiY/1kPLN19HUYq4vCIY@Q4K8XdwEBbctAPE95xERomEMeRGzT2Gd6mXncqI8ezHnACOwrh/O8iilPDHEP/2hbKnulO6VHpRuafPybfUN "JavaScript (Node.js) – Try It Online")
-4 from Arnauld
Not using the 10
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~34~~ 30 bytes
```
->i{[*1..1e3]*''=~/(?<=#{i})/}
```
[Try it online!](https://tio.run/##Zc5LCoMwFIXheVZx0UFUasw1D3OhsQspHbRFISClSDsoYreejpOOv5/DWd@3T5x9bMewnRsUAid1aTj33646HX25hb3u9vhcw@MFs7hfl6UCjhzqQ8EKKKEdAVnGicpcjdVm0MZpk6701uUp9knS507kiAillGnnSP1PKW3s4Cj7LhnEHw "Ruby – Try It Online")
*Thanks to @Neil for saving 1 Byte by removing useless + in regexp*
Regexp /(?<=#{i})+/ finds index next to input in the constructed string `[*1..1e3]*''` by using a look behind.
[Answer]
# [Perl 5](https://www.perl.org/) (`-p`), 27 bytes
```
(join"",1..1e3)=~$_;$_="@+"
```
[Try it online!](https://tio.run/##K0gtyjH9/18jKz8zT0lJx1BPzzDVWNO2TiXeWiXeVslBW@n/fzNzC0tDA0NDQyMuOMuQy9TMxNTcxNTCxJTLkIvrX35BSWZ@XvF/3ZwCAA "Perl 5 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~65~~ 63 bytes
*-2 bytes thanks to [@AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)*
```
n%h|l<-length n,n==take l h=l
n%(_:h)=1+n%h
f=(%([1..]>>=show))
```
[Try it online!](https://tio.run/##PcvdCoIwGAbg813FiyBsZNHMmUVfNyISI2YT14w26KR7XxbS2cP7Y3UYjXMp@dy@3WntjL9FC194oqhHAwdLjvmcX45WkFzNO9YTz3krN5vufKZgp5cQ6a4HD8LjOfiItscAIkx4gw8FJoHTGtGEeNXBhI6xv@dPywCeyayAFMXPM7cLVV2pfaWaSn37sm6WXJa7StX75vD7bUXH0gc "Haskell – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 38 bytes
```
^
1001$*1¶
\G1
$.`
r`\B\1.*¶(.*)
$1
\B
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP47L0MDAUEXL8NA2rhh3Qy4VvQSuooQYpxhDPa1D2zT0tDS5VAy5Ypz@/@cy5DIEITA2BAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^
1001$*1¶
\G1
$.`
```
Create a string of all the numbers from `0` to `1000` concatenated.
```
r`\B\1.*¶(.*)
$1
```
Remove everything after the first copy of the input, but don't delete the leading `0`. The `r` reverses the direction of processing, so the `(.*)` is matched first and the `\B` last.
```
\B
```
Count the pairs of adjacent digits, which is the same as the length excluding the leading `0`.
Alternative 38-byte version that works for arbitrary numbers given enough memory and processing power but is slower for inputs of four or more digits.
```
^
$'$*111¶
\G1
$.`
r`\B\1.*¶(.*)
$1
\B
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP45LRV1Fy9DQ8NA2rhh3Qy4VvQSuooQYpxhDPa1D2zT0tDS5VAy5Ypz@/@cy5DIEITA2BAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
^
$'$*111¶
\G1
$.`
```
Create a string of all the numbers from `0` to the input plus `1` concatenated. (This is needed for the edge case of an empty input.)
```
r`\B\1.*¶(.*)
$1
```
Remove everything after the first copy of the input, but don't delete the leading `0`.
```
\B
```
Take the length excluding the leading `0`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
I⁺Lθ⌕⭆φ⊕ιθ
```
[Try it online!](https://tio.run/##DcrRCkAwFADQX/F4V9TUhvKolKKUL1izWM3FXH7/2nk@djfRniYwz9EjQWcegjm8D4wON9rhFnnWe1xhoRS2yVxQSinzbEAb3eGQ3ApepHWLpGXWldK10o3SXHzhBw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
φ Predefined variable `1000`
⭆ Map over implicit range and join
ι Current value
‚äï Incremented
‚åï Find index of
θ Input string
⁺ Plus
θ Input string
L Length
I Cast to string
Implicitly print
```
[Answer]
# APL+WIN, ~~35~~ 33 bytes
Two bytes saved thanks to Tbw
Prompts for string of digits:
```
↑(¯1+⍴s)+((s←,⎕)⍷n)/⍳⍴n←⊃,/⍕¨⍳1E3
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3t/6O2iRqH1htqP@rdUqypraFRDJTSAarRfNS7PU9T/1HvZqBMHlDwUVezDpA79dAKoJihq/F/oHau/2lc6obqXEASTJiamZiam5hamJiCuYZGxiamZuYWloYGhoaGRobGEKWGQIqLCwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 10 bytes
Semi-port of [lyxal's Vyxal answer](https://codegolf.stackexchange.com/a/267362)
```
J1,a~:Xa$)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuharvAx1EuusIhJVNCECUPFl0YYGhoaxUB4A)
```
J1,a~:Xa$)­⁡​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌­
J1,a # ‎⁡Range from 1 to input as string
~:Xa # ‎⁢Match input as regex in range
$) # ‎⁣Return last index of first match
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 22 bytes
```
≢-1-(⊃∘⍸⍷∘(⊃,/⍕¨⍳1E3))
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v8/TeFR2wSFR52LdA11NR51NT/qmPGod8ej3u1ABoivo/@od@qhFY96Nxu6Gmtq/v9fklpcUgzWpK6uoG4IwkbGJqZm5haWII6pmYmpuYmphYkpkGNpaGBoaGhkaAySsbS0sLQEihgYqHNxgU3RiTbUM41NO7QCYqbCo965Cmn5RbmJJSWZeekA)
```
≢-1-(⊃∘⍸⍷∘(⊃,/⍕¨⍳1E3)) # tacit function⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤⁡‏⁠‎⁡⁠⁤⁢‏‏​⁡⁠⁡‌⁤​‎‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁢⁡​‎‎⁡⁠⁤⁤‏⁠‎⁡⁠⁢⁡⁡‏⁠‎⁡⁠⁢⁡⁢‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁡‏‏​⁡⁠⁡‌­
⊃∘⍸⍷∘ # ‎⁡index of first subsequence equal to input in
1E3 # ‎⁢⁡1000
⍳ # ‎⁤range
⍕¨ # ‎⁣toString each
,/ # ‎⁢concat reduce
⊃,/⍕¨⍳1E3 # '12345678910...'
-1- # ‎⁢⁢minus 1 (because a-1-c = a-(1-c) = ¯1+a+c in APL)
≢ # ‎⁢⁣length of input (this is one character;
üíé # the code block does not display it correctly)
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# Python 3, 55 bytes
```
lambda s:"".join(map(str,range(1,1001))).find(s)+len(s)
```
This is a rather simple solution, but it works.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
+A³õ ¬
aN
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=K0Gz9SCsCmFO&input=IjU2NDU3NDU4NDUi)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 57 bytes
```
x=>[...Array(1000).keys()].join('').indexOf(x)-1+x.length
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NY5NDoIwEEb3nKJhQxtl0kEQCMHEhWsPYFwYbfGHtAnUBC7gJdyw0IVH8jZCwUwyk-9l5mWeL6VPovuUwhBJckLfdyP95Js2-WoHAOuqOrQUOecMbqKtKdvDVV8U9TwGF3USzVbShvk4a6AUqjDnSfBgmTNIjahN3Yt3boocEQNcoDsnbrQMoziMkjAakkUY2I4pBrzfsyxO_mfuPnOsDKSuNofjmVo3yVfkqFWtSwGlLiiRE2dDZeM3XTfOHw)
Constructs `"0123456789..."`, then finds the input in it.
[Answer]
# [Scala 3](https://www.scala-lang.org/), 41 bytes
```
s=>(1 to 1000).mkString.indexOf(s)+s.size
```
[Attempt This Online!](https://ato.pxeger.com/run?1=lZK7asMwFIaho5_i4EmixLETO7ENDnTs0Au0nUIKjiM7ah3JWMekF_IkXbK0S58ofZo6UaEemoImIfH93znS0duHytIyHX5O7Z6Q67QW9mx3L-cPLEO4SLmAVwtgwXJYtRuS1oWK4ayu0-fpDdZcFDMaw53gCMmB1GzOxeJaKo5cihiIJpPJuUDacu8N5r1wR1UyIR6gBM91XeqsHjXntGH2dJUTRU-Vo_gL04Gvk8u9v2oZLAXp1iC2Z1MK_T7cLhnIBqsGYc3LEuYMsD2qfkCQObQsVGWjgKOCkokCl9Zx8XGvC0RxkekC2nPQ28AVuPQfZzDyg7EfhH5g0HUnZNC-NzB5mIGJOorCKIr2szMo0QkZ3WLoB6NxGBmN-Tf0R6mNtdHfarvV6zc)
[Answer]
# [Uiua](https://www.uiua.org), 30 bytes
```
(⊏0+⧻:⊚⌕:/$"__"+1⇡1e3.|0;)=0⧻.
```
[Test suite](https://www.uiua.org/pad?src=0_7_1__RiDihpAgKOKKjzAr4qe7OuKKmuKMlTovJCJfXyIrMeKHoTFlMy58MDspPTDip7suCgpGICIiCkYgIjEiCkYgIjEyIgpGICI3ODkxMDExMTIxIgpGICIxMTkxMjAxMjExIgpGICI1NjQ1NzQ1ODQ1Igo=)
I felt like adding another answer
] |
[Question]
[
The [resultant](https://en.wikipedia.org/wiki/Resultant) of two polynomials is a polynomial in their coefficients that is zero if and only if \$p\$ and \$q\$ have a common root. It is a useful tool for eliminating variables from systems of polynomial equations. For example, it is used in [my answer](https://codegolf.stackexchange.com/a/120756/9288) to the code golf challenge [Add up two algebraic numbers](https://codegolf.stackexchange.com/q/120702/9288).
The resultant of two polynomials \$p(x)\$ and \$q(x)\$ is defined as the determinant of the Sylvester matrix. More precisely, if \$p(x) = a\_n x^n + a\_{n-1} x^{n-1} + \cdots + a\_0\$ and \$q(x) = b\_m x^m + b\_{m-1} x^{m-1} + \cdots + b\_0\$, then the Sylvester matrix is the following \$(n+m) \times (n+m)\$ matrix:
$$ \begin{bmatrix} a\_n & a\_{n-1} & \cdots & a\_0 & 0 & \cdots & 0 \\ 0 & a\_n & a\_{n-1} & \cdots & a\_0 & \cdots & 0 \\ \vdots & & & & & & \vdots \\ 0 & \cdots & 0 & a\_n & a\_{n-1} & \cdots & a\_0 \\ b\_m & b\_{m-1} & \cdots & b\_0 & 0 & \cdots & 0 \\ 0 & b\_m & b\_{m-1} & \cdots & b\_0 & \cdots & 0 \\ \vdots & & & & & & \vdots \\ 0 & \cdots & 0 & b\_m & b\_{m-1} & \cdots & b\_0 \end{bmatrix} $$
where the first \$m\$ rows are the coefficients of \$p(x)\$ and the last \$n\$ rows are the coefficients of \$q(x)\$. The resultant is the determinant of this matrix.
For example, the resultant of \$p(x) = x^3 + 2x^2 + 3x + 4\$ and \$q(x) = 5x^2 + 6x + 7\$ is
$$ \begin{vmatrix} 1 & 2 & 3 & 4 & 0 \\ 0 & 1 & 2 & 3 & 4 \\ 5 & 6 & 7 & 0 & 0 \\ 0 & 5 & 6 & 7 & 0 \\ 0 & 0 & 5 & 6 & 7 \end{vmatrix} = 832. $$
In particular, when \$m = n = 0\$, the Sylvester matrix is the empty matrix, whose determinant is \$1\$.
## Task
Given two nonzero polynomials \$p(x)\$ and \$q(x)\$, compute their resultant.
The coefficients of the polynomials are all integers.
You may take the polynomial in any reasonable format. For example, the polynomial \$x^4-4x^3+5x^2-2x\$ may be represented as:
* a list of coefficients, in descending order: `[1,-4,5,-2,0]`;
* a list of coefficients, in ascending order:`[0,-2,5,-4,1]`;
* a string representation of the polynomial, with a chosen variable, e.g., `x`: `"x^4-4*x^3+5*x^2-2*x"`;
* a built-in polynomial object, e.g., `x^4-4*x^3+5*x^2-2*x` in PARI/GP.
When you take input as a list of coefficients, the leading coefficient is guaranteed to be nonzero.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
Here I use coefficient lists in descending order:
```
[1] [2] -> 1
[3,3] [1,2,1] -> 0
[1,3,3,1] [1,0,-1] -> 0
[1,2,3,4] [5,6,7] -> 832
[1,2,3,4] [4,3,2,1] -> -2000
[1,-4,5,-2,0] [1,-4,5,-2,1] -> 1
[1,-4,5,-2,0] [1,-12,60,-160,240,-192,64,0] -> 0
```
[Answer]
# [Python](https://www.python.org) NumPy, 36 bytes (-19 thanks to @DanielSchepler)
```
lambda p,q:p.c[0]**q.o*q(p.r).prod()
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZY9NasMwEIX3PsUQupDMyFiyk6aB5CKuF24cU4FsyT8p-Cilm0Bpb9GD5DYd-QcKRSDmfe9JT_r4duPwapvbZ3V8_roOldjfH0xRv5QFOGwPLjpncR6GbWTDlrmo45HrbMn4kn2vOltDc63dCLp2thvAWTPKEnV_Nra_BJXtwIBuwLpLw2J-CECjhSOYqHdGD2wjThtOkJBeEMlwDtWFY5e3wiDzgJPhOt0Mk1orWMVCn1uLOffJ-YG3-08mc8hUDuIEMsgSTEhKVCgnFAckCHpJU4ziD1fEU-Jb3OHjhPeJ8oZIcYtCYTwdWpVcS_4FpMKdv5o2lfrhiUDq3bVKqKV_WZOTqPkXvw)
#### [Python](https://www.python.org) NumPy, 55 bytes
```
lambda p,q:(p.r-q.r[:,1>0]).prod()*(p**q.o*q**p.o).c[0]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZY5NasMwEIX3PsWQlSRGwlKcnwaSi7heuElMBbI1VpxCjlK6CS3tnXKbSk4MhW7EvO-90ZuPH7oMr767fjXb5-_z0Mj1beXq9uVQA2G_YaSC7FUoN6h3ecUVBX9gXDASolde9EKQ8lzty7x6rL83wbfQnVu6gG3JhwHIu4s-oD3tnT8ds8YHcGA78HTsWM43GVj0sAWnTuTswGZyN-MRRmQfKEpxD7U1seNb7ZAlwKNBwXbDqKYK1jCRclMx5yl5P_B6-yx1BaWpQO5AZ-Uc51FqNKhHlGdRRJhknHKUf7iJvIh8gUtcjXg9N8mQBS5QGszHpUnpqeRfQBtcpq_jY4o0PEVQJDdV3U_9BQ)
Takes two poly1d objects as input. Has floating point issues.
## Without poly1d
#### [Python](https://www.python.org) NumPy, 87 bytes
```
lambda p,q:prod(roots(p)-c_[roots(q)])*p[0]**~-len(q)*q[0]**~-len(p)
from numpy import*
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ZY7BasMwDIbveQrRUxzkETtp1xXa19ghCyNbG2ZwYsV1B73sRXYpG9s79W0mJy0UdhH6vl-W_PlLx_Dm-tN3u376OYRWLs-Ptuletg0QDivybpt658I-JSFfn6upH0QtMqryOss-pN31LLLhBkkkrXcd9IeOjmA6cj5kl_VN6zxYMD044tFcrBIw6GAN9m5P1oR0JjczwZKVuSjGbBrqGkp3743FNArBAXnTh0gtF8FuOnQ6f1WqhkrXIDegkqrAglGhRjWqPGFgGZG7HOWN1-xL9nNc4P2ol4WOgSxxjlJjPj66kroe-TegNC7iai66jM0DizKm8dT01T8)
Takes two sequences. Has floating point issues.
### How?
Uses the well-known (?) [formula](https://en.wikipedia.org/wiki/Resultant#Properties)
\$\mathrm{res}(p,q)=p\_m^nq\_n^m\prod(\lambda\_i-\mu\_j)\$
or its variant (thanks @DanielSchepler)
\$\mathrm{res}(p,q)=p\_m^n \prod q(\lambda\_i)=(-1)^{mn}q\_n^m \prod p(\mu\_j)\$
that expresses the resultant in terms of the roots \$\{\lambda\_i\}\$,\$\{\mu\_j\}\$ degrees \$m,n\$ and leading coefficients of the two polynomials \$p,q\$.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 176 bytes
```
float f(float*p,int n,float*q,int m){return n<=m?m?*p?({int i=1;for(;i<=n;++i)q[i]-=*q/ *p*p[i];}),*p*f(p,n,q+1,m-1):n?(m%2?-*q:*q)*f(p+1,n-1,q,m):0:1:(n*m%2?-1:1)*f(q,m,p,n);}
```
(Note that this uses the gcc extension for block expressions, in order to be able to avoid repeated `return` keywords and use `?:` instead of `if/else`.)
The idea of this submission is to perform an algorithm very reminiscent of the Euclidean algorithm on polynomials. In terms of the Sylvester matrix, you could view the reduction for example as: suppose you start with the matrix
\$\$\begin{bmatrix} 5 & 6 & 7 & 0 & 0 \\ 0 & 5 & 6 & 7 & 0 \\ 0 & 0 & 5 & 6 & 7 \\ 1 & 2 & 3 & 4 & 0 \\ 0 & 1 & 2 & 3 & 4\end{bmatrix}.\$\$
Then by subtracting one fifth of row 1 from row 4 and also subtracting one fifth of row 2 from row 5, you reduce to taking the determinant of:
\$\$\begin{bmatrix} 5 & 6 & 7 & 0 & 0 \\ 0 & 5 & 6 & 7 & 0 \\ 0 & 0 & 5 & 6 & 7 \\ 0 & 4/5 & 8/5 & 4 & 0 \\ 0 & 0 & 4/5 & 8/5 & 4 \end{bmatrix}.\$\$
Now, by expanding by minors along the first column, this is 5 times the resultant of \$5x^2 + 6x + 7\$ and \$(4/5) x^2 + (8/5) x + 4\$.
(Do note that in the intermediate steps, it is possible that it is considering a resultant of polynomials with one of the leading coefficients being 0. In this case, it is still calculating the determinant of a generalized Sylvester matrix.)
(It's also slightly amusing that in one place, I needed to insert a space in `*q/ *p` to avoid accidentally starting a comment.)
[Try it online!](https://tio.run/##jVTBbqMwFLzzFU@JKtlgWgwkq4VQPiTNIQ3QtRSMTWAPjfLtqW2KaqwcGqHgmTczeEyUU/hxOt3vzbk7DtAgc/cFYXwATiYkDWrxta@HsefAd0VbtqUvSnTVE1bQvOl6lLNdwfMgYFju2SEsfPkCvvCFAvkNE7VskCCcyICSNqQ44yVqn@Iy9GXmS6ynasJDSiRpcRZlNEPcNwqaUT1XPFEJOL/dvTXjp/NY1bC7DBXrnv@9et7/jlUw1Jdh6qGeTmBqAt@EnIgWw9UD9TH7z81S9Ao0aCWyFZ4YVQoQK6IcTDNgQYDNwJbD08eKAKq68f1cY10WL/PeuHyc2P4qUT5K7OvLeB6OfMiU@I1bcn3Euq8q2mLluxmnZ0ofGUe6@LqqG8Zr6EduDovj6dDEeq2cF/ZZd40BGF5suI8OGEKgKt1WyqVSWsqp3HT2gu4PUMAVKNxyi5czHy95EX/zCYHEscwjtZWYuIEi@Zkm5nKfaAkiAqHrTxfpyp86/lmwIbAl8Mexb37sYUq0KFQxkZPxWOVuZfurLFtF1XxrWunvODXLv5pMLeP86ile4tjBiYNTB28cvJ3x9FcR6R/g/Qs "C (gcc) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 9 bytes
```
Resultant
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pyi1uDSnJDGv5D@Xa3JGvkNatKFCRZyxgraCEZA2AtLGChVA0kRHwRQqYAYWMNdRqK6ojf0PAA "Wolfram Language (Mathematica) – Try It Online")
Obligatory. And hat tip to OP...
[Answer]
# [J](http://jsoftware.com/), 30 bytes
```
g~-/ .*@,g=.(+&-/}:@i.)&#{."{[
```
[Try it online!](https://tio.run/##dY8xa8MwEIV3/4pLAnGTnhTdWVZqQUqg0ClTV2M8lDhNliwZCiH96@6Ti0ugFCHx3vdOd9KpryZRmjCJVZ5nU5t3tImUE5OjiG0svbztXvvDl1mRXW75sLEPj3OzusXt0S7ms6udXut@ke3fP84k1JH@yAKrA1CSMUtIBuio/aUK6kFLCrQeYevhW0Vhd@fkn1iUQmqJQ30SFYAnl@0/jxd8SxqqtSHzjA51wQWssLIMyGUwgMlCOTZ3XME9eMmB1wN@KjQFxnPJRtkNl0Yn45A/BaIcUmsceCJEBeBTmkb13w "J – Try It Online")
Straightforward but non-trivial answer.
Constructs the matrix and calculates the det `-/ .*`.
[Answer]
# JavaScript (ES10), 171 bytes
Expects `[p, q]` where `p` and `q` are lists of coefficients, in descending order.
No built-in at all, so this is a bit lengthy.
```
a=>(D=m=>m+m?m.reduce((s,[v],i)=>s+v*(-1)**i*D(m.flatMap(([,...r])=>i--?[r]:[])),0):1)(a.flat().slice(2).map((_,y,v)=>v.map((_,x)=>~~a[i=1/a[1][y+1]?0:1][x-=i?y+~o:o=y])))
```
[Try it online!](https://tio.run/##fcxBboMwEAXQfU/Bcgxjg03SRkiGTbY9gWVVFoHKFY4jSFDYcHVqGtFFW3U3X/P@/zCjGereXq707E/N0srFyBKO0snSJa5yrG9Ot7oBGFCNGi2R5ZCMMVBO4tjGR3Cs7cz11VwAFDLGeh2IpbRSvS6UJgQzUnAC5ssBYUNnw54gzK2dN5xwDI1xi/cQ5tkoK3lqFNdqSriusiJcdyptNSWzL7ycwjJZan8efNewzr9DCypwjJTQ4RelacSffv5zzFfBUSDfVPZLcQwO@UNmSP@lItDdSvf4jC@bPOTiD0t3uEcqMHtMb/F7ny@f "JavaScript (Node.js) – Try It Online")
### Building the Sylvester matrix
```
a.flat() // build a vector whose length is the sum of the
.slice(2) // lengths of p and q, minus 2
.map((_, y, v) => // for each entry at index y in this vector v[]:
v.map((_, x) => // for each entry at index x in v[]:
~~a[ // coerce to 0 if undefined:
i = // define i:
1 / a[1][y + 1] ? // if a[1][y + 1] is defined:
0 // set i = 0
: // else:
1 // set i = 1
][ //
x -= // subtract from x:
i ? // if i is set:
y + ~o // subtract y - o - 1
: // else:
o = y // save y in o and subtract y
] // read a[i][x]
) // end of inner map()
) // end of outer map()
```
### Computing its determinant
The code is similar to the one used [in my answer](https://codegolf.stackexchange.com/a/260339/58563) to [this other challenge](https://codegolf.stackexchange.com/q/260324/58563), except we make sure to return \$1\$ for the empty matrix.
[Answer]
# Python3 + [`numpy`](https://numpy.org/), 155 bytes
```
from numpy import*
def f(p,q):P=len(p);Q=len(q);return linalg.det([[0]*i+p+[0]*(Q-2-i)for i in range(Q-1)]+[[0]*i+q+[0]*(P-2-i)for i in range(P-1)]or[[1]])
```
[Try it online!](https://ato.pxeger.com/run?1=bZBLbsMgEIb3OQVLJh4qQ5z0EfUOzhqxiBRIkWzACC9ylmyyaU_SS_Q2hdqpVKsbGP7vG17Xj3BJb97dbu9jMuzp62qi74kb-3Ahtg8-pvXqpA0xNOAAL-1rpx0NsD_8FAPso05jdKSz7tidH046USlrtbZVqMpMD0wwC8ZHYol1JB7dWeeQg6pmcZjE9j-xLaKPUnKlYL7iZ4jWJWpoDpFIoQBWv9EGNyXkKJD_ARwzQj7BGtmSikybQre4w8cFZA1ukQmsp_b7crnHUuMCd-WoPIimFM85aDKG-S33b_8G)
[Answer]
# Excel, 164 bytes
Expects coefficient lists in descending order in *vertical* spilled ranges `A1#` and `B1#`.
```
=LET(
a,A1#,
b,B1#,
c,ROWS(b),
d,ROWS(a),
f,LAMBDA(g,h,LET(i,SEQUENCE(,c+d-2)-SEQUENCE(h-1,,0),IFERROR(INDEX(g,IF(i,i,-1)),))),
IFERROR(MDETERM(VSTACK(f(a,c),f(b,d))),1)
)
```
[Answer]
# [Haskell](https://www.haskell.org/), 130 bytes
```
d=([]%);e%(f:g)=f!!0*d(tail<$>e++g)-(e++[f])%g;[]%_=1;_%_=0
x?[]=[x];x?(0:t)=[x++0:t]++(0:x)?t
u=drop 2.map(0*)
p#q=d$p?u q++q?u p
```
[Try it online!](https://tio.run/##DYrtCoMgGEb/dxVFBdrrhrUvyDkvRCQEq8WqWTPw7p1/nnMOPG/9@/TzHILhSKoSs75EQztiPmQZrQxyepqfxasHGPEJRchB4XJk8dvxmnVxaeKFVFx6xbxAtHU4OkAUBRDbY@GSg5v9a9PmvGiLaIUTm2/cFFYc6QawRdiw6Gnldp9WV8iaNORCriqXN3InDxX@ "Haskell – Try It Online")
Determinant code stolen from
xnor's <https://codegolf.stackexchange.com/a/147820>
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ 14 bytes
```
,&GnqXyY+]v&0|
```
Explanation
```
, % Do twice
&G % Push all inputs so far. The first time this implicitly takes p and
% pushes it. The second time this pushes p, then q
nq % Number of elements minus 1
Xy % Identity matrix of that size
Y+ % Two-dimensional convolution. The first time this implicitly takes q
% and uses it as first argument. The second time the first argument is p
] % End
v % Vertically concatenate the two matrices
&0| % Determinant. Implicit display
```
[Try it online!](https://tio.run/##y00syfn/X0fNPa8wojJSO7ZMzaDm//9oQx0jHWMdk1iuaFMdMx3zWAA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8F9HzT2vMKIyUju2TM2g5r9LVEXI/2jDWK5oIyA21jEGkoY6RjqGYBrIh7IMdHQNoVLGOiZAlqmOmY45WETXRMdUR9dIxwCFZxirgEXS0EjHDGQUkDAyATEsgQImQFkA).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~27~~ 25 bytes
```
@:∑2-:∇$-ʀ∇∆ZZƛ÷$¨VǓ;ÞfÞḊ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCJAOuKIkTItOuKIhyQtyoDiiIfiiIZaWsabw7ckwqhWx5M7w55mw57huIoiLCIiLCJbMSwyLDMsNF0sIFs0LDMsMiwxXSJd)
-2 Thanks @The Thonnu!
A weird combination of Vyxal commands that unexpectedly gives the right result.
Welcome to golf it more!
Explanation:
```
@ # Keep input and get lengths
:∑2-: # Size of matrix
∇$-ʀ∇ # Numbers of rotations
∆Z # Pad with zeros to size
Z # Zip with numbers of rotations
ƛ÷$¨VǓ; # For both polynomials rotate every row
Þf # Flatten
ÞḊ # Determinant
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 81 bytes
```
≔⁺EΦηκ⁺Eκ⁰θEΦθκ⁺Eκ⁰ηθ¿θ«≔⟦Eθ…⁺ιEθ⁰Lθ⟧θFθ¿⊖LιFE⊟ιEι×Φμ⁻πλ⎇ν¹×X±¹⁺Lιλκ⊞θκ⊞υ⊟⊟ιIΣυ»1
```
[Try it online!](https://tio.run/##bZBPa4QwEMXP66cY9pRACrV/D56Kpae2CN2beAjurAZj1ERbltLPbidRlx6aQyCT33tvZspa2rKTep6fnFOVYZmeHHuTPXtRekTLagENF3ApNwKu6T1wuv5gw/9YzXmAk0idgA0cvqPdGpR7jGTpudSY1l2/RKvFdvB6kr6iqcaalJwXi9Hu1Nlg5R2fsbTYohnxyFZUEQqB8T4Z@aq1VbI@qBbd1nNLZWUosxegfdgBrZH2zIyAeGOz7ovQd6zkiCzeRrxkrcqGhwPZ5OplFwmgdrgUJlJ1Wy/cz5BZZUaWSjeyj6llU6j@RIsk/O3jPU/mOc@pkxsBtwLuaAH5vYAHAY9FMV996l8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⁺EΦηκ⁺Eκ⁰θEΦθκ⁺Eκ⁰ηθ
```
Partly generate the Sylvester matrix.
```
¿θ«
```
If it's not empty then:
```
≔⟦Eθ…⁺ιEθ⁰Lθ⟧θ
```
Pad the matrix so that it is square and wrap it in a list of matrix determinants to calculate.
```
Fθ¿⊖LιFE⊟ιEι×Φμ⁻πλ⎇ν¹×X±¹⁺Lιλκ⊞θκ⊞υ⊟⊟ιIΣυ
```
Output the determinant as per my answer to [Hankel transform of an integer sequence](https://codegolf.stackexchange.com/questions/260324/).
```
»1
```
Otherwise output the literal `1`.
70 bytes by requiring the polynomials to be in ascending order of degree:
```
≔⊖EθLιζF⌈ζFθ⊞κ⁰≔…⁰Σζη⊞υ⟦⟧Fη≔ΣEυE⁻⎇﹪λ²⮌ηηκ⁺κ⟦μ⟧υI↨E⮌υΠEι§§θ÷λ⌈ζ⁻μ﹪λ⌈ζ±¹
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZDPTgIxEMbj1aeYcJomJQH_J5xQLiRiCHrb7KHuDruV3a70D0FexQsHjb6Db-LTOF3AcGim7fy-b772_Tsrlc0aVW23n8HPuze_Jy9D53RhcESZpZqMpxwn6hWXEu7JFL5ELYSQsBGD03ljgZtrXYcaN0JAe7EUMA2uxIWEHkN7v5kyBWFPwuOOlVByswWDhCQ92JUC9ooIxsncjmWiTXD4RNYo-4aTJg9Vg5WEM7aa0YqsIxZHWwkLXtOKcc6Q1KloE4c4z2rj8U45j7eKBdH4IA5RZNk38-29ljD0Y5PTGg-VP2Fs_EivdE5x9tHbWbxLWPPmP9wxEJEHKpQn7MfT4MM9Z27_8V9Jp7uqOulPkiSXEq4kXKecvc_vk3Au4SJN0x35Bw "Charcoal – Attempt This Online") Link is to verbose version of code. Takes input as a list of two polynomials in ascending order of degree. Explanation:
```
≔⊖EθLιζ
```
Get the degrees of the polynomials.
```
F⌈ζFθ⊞κ⁰
```
Pad them with zeros so that they can be readily cyclically indexed.
```
≔…⁰Σζη⊞υ⟦⟧Fη≔ΣEυE⁻⎇﹪λ²⮌ηηκ⁺κ⟦μ⟧υ
```
Generate all of the permutations of `[0..n+m)` as per my answer to [Hankel transform of an integer sequence](https://codegolf.stackexchange.com/questions/260324/).
```
I↨E⮌υΠEι§§θ÷λ⌈ζ⁻μ﹪λ⌈ζ±¹
```
For each permutation, use the index for each element to determine the polynomial and offset and get the respective coefficient, then take the alternating sum of products, which is the resultant as required.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Ẉ’Ḷ0ẋ;€"ṚẎz0ÆḊ
```
[Try it online!](https://tio.run/##y0rNyan8///hro5HDTMf7thm8HBXt/WjpjVKD3fOerirr8rgcNvDHV3/gbzD7ZqR//9Hc0VHG8bqKEQbxcbqANnGOgrGIK6hjoKRjoIhRBDIMQYjQ6iUgY6CLkLOCCxnApIz1VEw01Ewh0kZ6RjrgMVNgAwjHYQWXRMdBaBaXaBWA6iZSEL41RkCOWZgF4BIIxMw0xIkaAJSBdQaCwA "Jelly – Try It Online")
Feels clumsy but it's at least shorter than I started with. Monadic link taking a list `[q, p]` (i.e. backwards).
```
0ẋ Repeat 0 to the length of each of
’Ḷ the range from 0 to 2 less than
Ẉ the length of each coefficient list.
; Append
"Ṛ the other coefficient list to each
€ of the sublists.
Ẏ Concatenate the p rows and the q rows,
z0 transpose with 0-padding (no effect on determinant),
ÆḊ and take the determinant.
```
[Answer]
# [Python](https://www.python.org) + [`sympy`](https://www.sympy.org/en/index.html), 30 bytes
```
from sympy import*
f=resultant
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhb70orycxWKK3MLKhUycwvyi0q0uNJsi1KLS3NKEvNKIIpuNlYo2IIUJeXnFGuoV6hrcnEV5OdUGgJFA4C0hqFWhZaWsYK2ghGIYQRkGGtVAEkTHYUKTbBSI5hSU5gKM7AKc7AKLqCFQAVpGmBTdRTAOkCWFGXmlWgAJTUhDoG5GgA)
] |
[Question]
[
Given a volume level `V` in the range `1-10`. Your program should draw the following ASCII art.
When `V=1`:
```
\
|
/
```
When `V=2`:
```
\
\ |
| |
/ |
/
```
When `V=3`:
```
\
\ |
\ | |
| | |
/ | |
/ |
/
```
And etc. Trailing spaces are allowed.
This is a code-golf challenge so the shortest solution wins.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 17 bytes
```
ɾ\|*\\?ɾ꘍$YvøMøĊ§
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLJvlxcfCpcXFxcP8m+6piNJFl2w7hNw7jEisKnIiwiIiwiMyJd)
This was quite a nice approach that may have ended up a bit clunky due to lack of overloads.
The idea is simple: Create the rotated form:
```
\ /
|
\ /
|||
\ /
|||||
```
And rotate it 90° with the `§` builtin.
We can create the above by interleaving the following:
```
|
|||
|||||
\ /
\ /
\ /
```
And that's basically what this does, with a few convenient Vyxal builtins. So close to beating Charcoal...
```
* # Repeat...
\| # "|"
ɾ # By 1...n
?ɾ # 1...n
꘍ # Spaces appended to...
\\ # "\"
$Y # Interleave them
vøM # Mirror each line, leaving the middle alone and flipping slashes
øĊ # Align each line to the center
§ # Rotate the whole thing 90°
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~169~~ ~~157~~ ~~144~~ ~~131~~ ~~98~~ ~~92~~ ~~90~~ 87 bytes
*Thanks [@ophact](https://codegolf.stackexchange.com/users/106710/ophact) for helping me save ~~some~~ a lot of bytes*
*Thanks [@alephalpha](https://codegolf.stackexchange.com/users/9288/alephalpha) for helping me golf it down to under 100 bytes with a completely new strategy*
*Thanks [@
emanresu A](https://codegolf.stackexchange.com/users/100664/emanresu-a) for another -8 bytes*
```
lambda n:[print(*" "*~-abs(i)+(i!=0)*"\\/"[i>0],(n-abs(i))*" |")for i in range(-n,n+1)]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHPKrqgKDOvRENLSUFJq043MalYI1NTWyNT0dZAU0spJkZfKTrTziBWRyMPKgcUVahR0kzLL1LIVMjMUyhKzEtP1dDN08nTNtSM/Y8mbqhjaKhpxaUAsSRTk0shDUxC@Jr/AQ "Python 3.8 (pre-release) – Try It Online")
~~First time trying to golf in Python. There's probably tons of stuff to golf here :D~~
My answer has literally been golfed to death entirely by the efforts of other people (not me).
[Answer]
# [Python 2](https://docs.python.org/2/), 78 bytes
```
n=i=input()
while~n-i:x=abs(i);print(' '*x+'\/'[i<0]+' ')[2:],'| '*(n-x);i-=1
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8820zYzr6C0REOTqzwjMye1Lk8306rCNjGpWCNT07qgKDOvRENdQUFdq0JbPUZfPTrTxiBWW11BXTPayCpWR70GKKORp1uhaZ2pa2v4/78xAA "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 92 bytes
This builds the output character per character. (So it may be longer than generating the strings explicitly, but it's a little more fun. ^^)
```
n=>(y=n,g=x=>y<-n?'':` |\\/
`[d=y*y-x*x++/4,x>n*2?(y--,x=0,4):x&1?d-x?0:2^y<0:d<0|0]+g(x))``
```
[Try it online!](https://tio.run/##ZchLDoIwEADQPadwJR1opXxWDUMPIpoSCkRDWiPGTBPuXteGt3zP4Tts4/vx@gjn7RRnjA47FtDxBQm70Aqn01SZ0973RWKuFkMWBGWU50XDqXNZpVkQghNK3oCic6mtIC1VdQ@tVLaVu7zlCyMAY@Lo3ebX6bL6hc2sBEj@pzpMfZgGIP4A "JavaScript (Node.js) – Try It Online")
### How?
For each position \$(x,y)\$ with \$0\le x<2n\$ and \$-n\le y \le n\$, we compute:
$$d=y^2-x^2/4$$
For \$n=3\$, this gives:
$$\begin{array} {|c|c|}
\hline
& 0 & 1 & 2 & 3 & 4 & 5 \\ \hline
3 & 9 & 8.75 & 8 & 6.75 & \color{red}{5} & 2.75 \\ \hline
2 & 4 & 3.75 & \color{red}{3} & 1.75 & 0 & \color{blue}{-2.25} \\ \hline
1 & \color{red}{1} & 0.75 & 0 & \color{blue}{-1.25} & -3 & \color{blue}{-5.25} \\ \hline
0 & 0 & \color{blue}{-0.25} & -1 & \color{blue}{-2.25} & -4 & \color{blue}{-6.25} \\ \hline
-1 & \color{red}{1} & 0.75 & 0 & \color{blue}{-1.25} & -3 & \color{blue}{-5.25} \\ \hline
-2 & 4 & 3.75 & \color{red}{3} & 1.75 & 0 & \color{blue}{-2.25} \\ \hline
-3 & 9 & 8.75 & 8 & 6.75 & \color{red}{5} & 2.75 \\ \hline
\end{array}$$
We then apply the following rules:
* If \$x\$ is even:
+ If \$x=d-1\$, we insert either a `\` or a `/` according to the sign of \$y\$ (red cells)
+ Otherwise, we insert a space
* If \$x\$ is odd:
+ If \$d<0\$, we insert a `|` (blue cells)
+ Otherwise, we insert a space
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 85 bytes
```
n->for(i=-n,n,print(concat([if(j>l=abs(i)," |",j<l," ",i<0,"\\ ","/ ")|j<-[1..n]])))
```
[Try it online!](https://tio.run/##FcwxDoMwDEDRq1iebMmhoK4JFwGGFCnIETJRysjd03R7@sMvsao7SksQmrk5XZU0OBOTUtVu2i/b402LJsrzGeLnS8qC8KBkf3YAivpRcF278AXIT/ZumYbBto2Z239pEGASeAskst5@ "Pari/GP – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 69 bytes
```
->n{(-n..n).map{|c|((" "*2*z=c.abs)+(c>0?"/ ":"\\ ")+" |"*n)[2,2*n]}}
```
[Try it online!](https://tio.run/##BcFBCoAgEADAryx7UksLoUugPaQ8qOCtJbIOpb3dZs47PC2ZJi0VJkkp4mr3R6mxMoaAQovXROVD5h2LdlxwAJxx2wB5h1BREF91rwW572vHfWVI6@TaDw "Ruby – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
FN«P↖²P↓⊕ι→↗»‖B↓
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzOvoLTErzQ3KbVIQ1NToZqL07c0pySzoCgzr0TDKrTAJzWtREfBSNMaVcIlvzxPR8EzL7koNTc1ryQ1RSNTE6wmvyxVwyooMz2jBMENLYAJ1HIFpablpCaXOJWWlKQWpeVUQozStP7/3/i/blkOAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FN«
```
Loop `V` times.
```
P↖²
```
Draw each of the `\`s along the top as a line of two without moving the cursor, so that the second one gets overwritten by the vertical line below.
```
P↓⊕ι
```
Draw the top half of each vertical line without moving the cursor.
```
→↗
```
Move to the top of the next vertical line.
```
»‖B↓
```
Reflect to complete the art.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Ýx¨R'\ús„ |×ζ`θ».∊
```
[Try it online](https://tio.run/##ASgA1/9vc2FiaWX//8OdeMKoUidcw7pz4oCeIHzDl862YM64wrsu4oiK//8z) or [verify all test cases](https://tio.run/##yy9OTMpM/R/iquSZV1BaYqWgZO@nw6XkX1oC4en4/T88t@LQiiD1mMO7ih81zFOoOTz93LaEczsO7dZ71NH1X@fQNvv/AA).
**Explanation:**
```
# e.g. input=3
Ý # Push a list in the range [0, (implicit) input]
# STACK: [0,1,2,3]
x # Double each value (without popping)
# STACK: [0,1,2,3],[0,2,4,6]
¨ # Remove the last item
# STACK: [0,1,2,3],[0,2,4]
R # Reverse it
# STACK: [0,1,2,3],[4,2,0]
'\ '# Push string "\"
# STACK: [0,1,2,3],[4,2,0],"\"
ú # Pad it with leading spaces based on the integer-list
# STACK: [0,1,2,3],[" \"," \","\"]
s # Swap so the earlier list is at the top
# STACK: [" \"," \","\"],[0,1,2,3]
„ | # Push string " |"
# STACK: [" \"," \","\"],[0,1,2,3]," |"
× # Repeat it the integers amount of times
# STACK: [" \"," \","\"],[""," |"," | |"," | | |"]
ζ # Create pairs of the two lists, which uses a space as implicit filler
# since they're of unequal lengths
# STACK: [[" \",""],[" \"," |"],["\"," | |"],[" "," | | |"]]
` # Pop and push the pairs separated to the stack
# STACK: [" \",""],[" \"," |"],["\"," | |"],[" "," | | |"]
θ # Leave just the last/second item of the top pair
# STACK: [" \",""],[" \"," |"],["\"," | |"]," | | |"
» # Join the stack with newline delimiter, which will implicitly join
# lists by spaces first
# STACK: " \ \n \ |\n\ | |\n | | |"
.∊ # Vertically mirror with overlap
# STACK: " \ \n \ |\n\ | |\n | | |\n\ | |\n \ |\n \ "
# (which is output implicitly as result)
```
[Answer]
# Java, 241, 238 bytes
```
public class V{public static void main(String[]a){int V=new java.util.Scanner(System.in).nextInt(),d=-1,i=V;var s="";while(i<=V){if(i==0)d=1;else s+=(" ".repeat(i-1)+(d<0?"\\ ":"/ "));s+=" |".repeat(V-i)+'\n';i+=d;}System.out.print(s);}}
```
Obviously Java is a rather verbose language for code golf, but I like to see how well I can do with it anyway.
It isn't clear if "Given a value V" means to read it as an input, or if the value for V is allowed to be hard coded, so long as values in the range (1-10) work.
If the value for V can be set in the code, the answer can be reduced to 198 bytes.
If we go so far as to allow a line of code that can be entered into jshell, then we can get it to 145 or 146 bytes (depending on V being one or two digits):
```
int V=3,d=-1,i=V;var s="";while(i<=V){if(i==0)d=1;else s+=(" ".repeat(i-1)+(d<0?"\\ ":"/ "));s+=" |".repeat(V-i)+'\n';i+=d;}System.out.print(s);
```
In this case the input value for V is entered directly in the program. I suspect this violates [Default for Code Golf: Program, Function or Snippet?](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet) though.
[Answer]
# GNU APL, ~~43~~ 42 Chars, ~~67~~ 66 Bytes
```
{⍉(2/-⍵-⍳⍵)⌽⊃⊃,/{1(¯1+2×⍵)1/¨"\ /"" | "}¨⍳⍵}
```
`⊃⊃,/{1(¯1+2×⍵)1/¨'\ /' ' | '}¨⍳⍵` replicates characters according to the input and builds the matrix, for example V=3:
```
\ /
|
\ /
|||
\ /
|||||
```
`(2/-⍵-⍳⍵)⌽` rotates rows to their position, and finally `⍉` does a transpose:
```
\
\ |
\ | |
| | |
/ | |
/ |
/
```
Update:
Since GNU APL support double quote string, `'\ /' ' | '` can be rewritten as `"\ /"" | "`, with one space removed.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 65 bytes
```
.+
$*:¶$&$*:¶$&$*:
:
|
\G \|
¶$.%'$* \ $%`
r` \|\G
$.%`$* / $%'¶
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLRcvq0DYVNQTFZcWlUMMV464QU8MFFNJTVVfRUohRUFFN4CpKAArGuHMBBROAgvpAQfVD2/7/NwYA "Retina 0.8.2 – Try It Online") Explanation:
```
.+
$*:¶$&$*:¶$&$*:
```
Convert the input into three rows of `V` `:`s as placeholders for the `|`s (which cost an extra byte to match).
```
:
|
```
Replace the `:`s with `|`, so that the `|`s have the correct spacing.
```
\G \|
¶$.%'$* \ $%`
```
Turn the first row of `|`s into a "triangle", preceded with `\`s.
```
r` \|\G
$.%`$* / $%'¶
```
Turn the last row of `|`s into a "triangle", preceded with `/`s.
[Answer]
# APL+WIN, 59 bytes
Prompts for n. Index origin = 0
```
(∊2/¨⌽-i)⊖⍉⊃,('\',¨(-1+n)↑¨'/'),[0.1]' ',¨(n←1+2×i←⍳⎕)⍴¨'|'
```
[Try it online! Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv8ajji4j/UMrHvXs1c3UfNQ17VFv56OuZh0N9Rh1nUMrNHQNtfM0H7VNPLRCXV9dUyfaQM8wVl0BLJUHNMVQ2@jw9Ewg41HvZqDJmo96twBV1qj/BxrO9T@Ny5ALqJgrjcsIShtzAQA "APL (Dyalog Classic) – Try It Online")
] |
[Question]
[
Convert short date format into English long date in as few bytes as possible.
# Input
Input will be in the form of a string with format, `yyyy-mm-dd`, with zero padding optional for all values. You can assume that this is syntactically correct, but not necessarily a valid date. Negative year values do not need to be supported.
# Output
You must convert the date into the English long date format (e.g. `14th February 2017`). Zero padding here is not allowed.
If the date is invalid (e.g. `2011-02-29`), then this must be recognised in some way. Throwing an exception is allowed.
More examples can be seen below.
# Test Cases
```
"1980-05-12" -> 12th May 1980
"2005-12-3" -> 3rd December 2005
"150-4-21" -> 21st April 150
"2011-2-29" -> (error/invalid)
"1999-10-35" -> (error/invalid)
```
[Answer]
# Python 3.6, ~~137~~ 129 bytes
```
from datetime import*
def f(k):g=[*map(int,k.split('-'))];n=g[2];return f"{date(*g):%-d{'tsnrhtdd'[n%5*(n^15>4>n%10)::4]} %B %Y}"
```
[Try it online!](https://repl.it/JG24/8)
[Answer]
# PostgreSQL, 61 characters
```
prepare f(date)as select to_char($1,'fmDDth fmMonth fmYYYY');
```
Prepared statement, takes input as parameter.
Sample run:
```
Tuples only is on.
Output format is unaligned.
psql (9.6.3, server 9.4.8)
Type "help" for help.
psql=# prepare f(date)as select to_char($1,'fmDDth fmMonth fmYYYY');
PREPARE
psql=# execute f('1980-05-12');
12th May 1980
psql=# execute f('2005-12-3');
3rd December 2005
psql=# execute f('150-4-21');
21st April 150
psql=# execute f('2011-2-29');
ERROR: date/time field value out of range: "2011-2-29"
LINE 1: execute f('2011-2-29');
^
psql=# execute f('1999-10-35');
ERROR: date/time field value out of range: "1999-10-35"
LINE 1: execute f('1999-10-35');
^
HINT: Perhaps you need a different "datestyle" setting.
```
[Answer]
# JavaScript (ES6), ~~142~~ 140 bytes
Outputs `NaNth Invalid Date` for invalid dates.
The code for ordinal numbers was [adapted from this answer](https://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd).
```
d=>`${s=(D=new Date(d)).getDate()+''}${[,'st','nd','rd'][s.match`1?.$`]||'th'} `+D.toLocaleDateString('en-GB',{month:'long',year:'numeric'})
```
```
f=
d=>`${s=(D=new Date(d)).getDate()+''}${[,'st','nd','rd'][s.match`1?.$`]||'th'} `+D.toLocaleDateString('en-GB',{month:'long',year:'numeric'})
console.log(
f('2005-12-3'),
f('1980-05-12'),
f('2005-12-3'),
f('150-4-21'),
f('2011-2-29'),
f('1999-10-35')
)
```
[Answer]
# [Python 3.6](https://docs.python.org/3/), 154 bytes
```
from datetime import*
s=[*map(int,input().split('-'))]
b=s[2]
print(date(*s).strftime(f"%-d{'th'if(3<b<21)+(23<b<31)else('st','nd','rd')[b%10-1]} %B %Y"))
```
[Try it online!](https://repl.it/JG24/6) (Set input stream and then run.)
Thanks to good suggestions from commenters below.
[Answer]
# PHP, 87 bytes
```
<?=checkdate(($a=explode("-",$argn))[1],$a[2],$a[0])?date("jS F Y",strtotime($argn)):E;
```
Run as pipe with `-F` or [test it online](http://sandbox.onlinephpfunctions.com/code/31c2f34e2d5210f35c4f3764602b3d42b4d1f307). Always prints a 4 digit year; fails for years > 9999.
**no validity check, 35 bytes:**
```
<?=date("jS F Y",strtotime($argn));
```
[Answer]
# Bash + coreutils, 115 78
* 2 bytes saved thanks to @manatwork.
```
d="date -d$1 +%-e"
t=`$d`
f=thstndrd
$d"${f:t/10-1?t%10<4?t%10*2:0:0:2} %B %Y"
```
[Try it online](https://tio.run/##PY1BC4JAEEbv@ysGWS/F0Myk0FoSBN06RDdvGrNiEAq60CH67bZ4kO/w3uHB92ymbv50r7eH0Td6BB0MAEw@ACLYx/V@q2YtE22CB1TLsE3RJyaUtdXatGXoptDrqMZqYr9tEXZMyOeQMp2yBRspKE5@kF4grZJZh97P7A6ElCOxWVVWZTFCJEgZSgxywkWEmGOG4mLpHMarff4H).
[Answer]
# C#, ~~147~~ 143 bytes
```
s=>{var t=System.DateTime.Parse(s);int d=t.Day,o=d%10;return d+((d/10)%10==1?"th":o==1?"st":o==2?"nd":o==3?"rd":"th")+t.ToString(" MMMM yyy");}
```
*Saved 4 bytes thanks to @The\_Lone\_Devil.*
[Answer]
## mIRC version 7.49 (197 bytes)
```
//tokenize 45 2-2-2 | say $iif($3 isnum 1- $iif($2 = 2,$iif(4 // $1 && 25 \\ $1||16//$1,29,28),$iif($or($2,6) isin 615,30,31))&&$2 isnum1-12&&1//$1,$asctime($ctime($+($1,-,$2,-,$3)date), doo mmmm yyyy))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~104~~ ~~103~~ 102+8 = ~~112~~ ~~111~~ 110 bytes
Uses `-rdate -p` program flags.
-1 byte from manatwork.
```
sub(/.*-(\d*)/){Date.parse($&).strftime"%-d#{d=eval$1;(d<4||d>20)&&"..stndrd"[d%10*2,2]||:th} %B %-Y"}
```
[Try it online!](https://tio.run/##HYrRasIwFEDf8xVZbEtbvDU3Wljm9GFsHyGbSOuNWnBduUkHYv32ruzpwDmH@/o2zp54ggSmKjgJnRC1Ozft6Ps6XRQ5pF@UZ4vs/j7loqvYuzRKssIHPoXm26kYaHanjfutrhGuU3pdDQNtjc6SRBXT1hKT@qQYdW7mZj8ML@HykPGbjGGnHiM7f@yd6Prgpfpg/mElosOmba7CtTSifdagS0AjjP4nLAWWGlZgcFKIYMBYgdZaQA3L8g8 "Ruby – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 167 197 bytes
```
s=>s.Equals(DateTime.MinValue)?"":s.Day+((s.Day%10==1&s.Day!=11)?"st":(s.Day%10==2&s.Day!=12)?"nd":(s.Day%10==3&s.Day!=13)?"rd":"th")+" "+s.ToString("MMMM")+" "+s.Year
```
[Try it online!](https://tio.run/##VY9BS8NAEIXv@RXjgrIhJnTTk62pB6snA8UWxeOQTOtCsos7G6FIf3vcBJrqXGaY783wXsVpZR31HWtzgO2RPbXLqGqQGTbOHhy2PxEAe/S6gm@rayhRGxkPW4DnzlT3a/S00y3dsnfhywr2UEDPxYqzp68OG5ZnRVZq84ZNR/GDEAvO1nhMpBz7tZoVhboZ56tCqaBgLxZ/YD7BPEBT/4PzCc4DdAEK/yniRIBIONvZ7WhNijLUtP4gdP0QYzmGebSGbUPZu9Oe5P7ieoOOSZ7xK2H9og3JONRweYpOfT5TKp2n@d0v "C# (.NET Core) – Try It Online")
+30 bytes for
`using System;`
`DateTime.Parse()`
[Answer]
# Excel, 212 bytes
```
=ABS(RIGHT(A1,2))&IF(ABS(ABS(RIGHT(A1,2))-12)<2,"th",SWITCH(RIGHT(A1,1),"1","st","2","nd","3","rd","th"))&TEXT(MID(A1,FIND("-",A1)+1,FIND("-",REPLACE(A1,1,FIND("-",A1),""))-1)*30," mmmm ")&LEFT(A1,FIND("-",A1)-1)
```
If you break it into chunks at every ampersand, you get these pieces:
* `ABS()` pulls the day number from the last two characters in the string. Since that may include a hyphen, `ABS` converts it to positive.
* `IF((ABS-12)<2,"th",SWITCH())` adds the ordinal. The `-12` bit is because 11, 12, and 13 don't follow the normal rule and they all get `th` instead of `st`, `nd`, and `rd`. This corrects for that.
+ Note: The `SWITCH` function is only available in Excel 2016 and later. ([Source](https://support.office.com/en-us/article/SWITCH-function-47ab33c0-28ce-4530-8a45-d532ec4aa25e?ui=en-US&rs=en-US&ad=US&fromAR=1)) It's shorter than `CHOOSE` in this case because it can return a value if no match is found whereas `CHOOSE` requires numeric input and must have a corresponding return for each possible value.
* `TEXT(MID()*30," mmmm ")` extracts the month name. `MID()` pulls out the month number as a string and multiplying by 30 returns a number. Excel sees that number as a date (1900-01-30, 1900-02-29, 1900-03-30, etc.) and `TEXT()` formats it as a month name with a space on both ends. 28 and 29 would have also works but 30 looks "nicer".
* `LEFT()` extracts the year number.
---
Now, given all that, it would have been way easier if the test cases were all in a date range that Excel can handle as an actual date: 1900-01-01 to 9999-12-31. The big advantage is that the entire date is formatted at once. That solution is **133 bytes**:
```
=TEXT(DATEVALUE(A1),"d""" & IF(ABS(ABS(RIGHT(A1,2))-12)<2,"th",SWITCH(RIGHT(A1,1),"1","st","2","nd","3","rd","th")) & """ mmmm yyyy")
```
The other big hurdle was having to include the ordinal. Without that, the solution is just **34 bytes**:
```
=TEXT(DATEVALUE(A1),"d mmmm yyyy")
```
[Answer]
## Swift 3 : 298 bytes
```
let d=DateFormatter()
d.dateFormat="yyyy-MM-dd"
if let m=d.date(from:"1999-10-3"){let n=NumberFormatter()
n.numberStyle = .ordinal
let s=n.string(from:NSNumber(value:Calendar.current.component(.day, from:m)))
d.dateFormat="MMMM YYY"
print("\(s!) \(d.string(from:m))")}else{print("(error/invalid)")}
```
[Try it online!](https://iswift.org/playground)
[Answer]
# T-SQL, 194 bytes
```
DECLARE @ DATE;SELECT @=PARSE('00'+i AS DATE)FROM t;PRINT DATENAME(d,@)+CASE WHEN DAY(@)IN(1,21,31)THEN'st'WHEN DAY(@)IN(2,22)THEN'nd'WHEN DAY(@)IN(3,23)THEN'rd'ELSE'th'END+FORMAT(@,' MMMM yyy')
```
Input is via text column *i* in pre-existing table *t*, [per our IO standards](https://codegolf.meta.stackexchange.com/a/5341/70172).
Works for dates from Jan 1, 0001 to Dec 31, 9999. The year is output with at least 3 digits (per 150AD example).
Invalid dates will result in the following ugly error:
```
Error converting string value 'foo' into data type date using culture ''.
```
Different default language/culture settings might change this behavior. If you want a slightly more graceful error output (NULL), add 4 bytes by changing `PARSE()` to `TRY_PARSE()`.
Format and explanation:
```
DECLARE @ DATE;
SELECT @=PARSE('00'+i AS DATE)FROM t;
PRINT DATENAME(d,@) +
CASE WHEN DAY(@) IN (1,21,31) THEN 'st'
WHEN DAY(@) IN (2,22) THEN 'nd'
WHEN DAY(@) IN (3,23) THEN 'rd'
ELSE 'th' END
+ FORMAT(@, ' MMMM yyy')
```
The `DATE` data type introduced in SQL 2008 allows much wider range than `DATETIME`, from Jan 1, 0001 to Dec 31, 9999.
Some very early dates can be parsed wrong with my US locality settings ("01-02-03" becomes "Jan 2 2003"), so I pre-pended a couple extra zeros so it knows that first value is the year.
After that, its just a messy `CASE` statement to add the ordinal suffix to the day. Annoyingly, the SQL `FORMAT` command has no way to do that automatically.
[Answer]
# q/kdb+ 210 bytes, non-competing
**Solution:**
```
f:{a:"I"$"-"vs x;if[(12<a 1)|31<d:a 2;:0];" "sv(raze($)d,$[d in 1 21 31;`st;d in 2 22;`nd;d in 3 23;`rd;`th];$:[``January`February`March`April`May`June`July`August`September`October`November`December]a 1;($)a 0)};
```
**Examples:**
```
q)f "2017-08-03"
"3rd August 2017"
q)f "1980-05-12"
"12th May 1980"
q)f "2005-12-3"
"3rd December 2005"
q)f "150-4-21"
"21st April 150"
q)f "2011-2-29" / yes it's wrong :(
"29th February 2011"
q)f "1999-10-35"
0
```
**Explanation:**
This is a horrible challenge as there is no date formatting, so I have to create months from scratch (95 bytes) as well as generating the suffix.
Ungolfed solution is below, basically split the input string and then join back together after we've added the suffix and switched out the month.
```
f:{
// split input on "-", cast to integers, save as variable a
a:"I"$ "-" vs x;
// if a[1] (month) > 12 or a[2] (day) > 31 return 0; note: save day in variable d for later
if[(12<a 1) | 31<d:a 2;
:0];
// joins the list on " " (like " ".join(...) in python)
" " sv (
// the day with suffix
raze string d,$[d in 1 21 31;`st;d in 2 22;`nd;d in 3 23;`rd;`th];
// index into a of months, start with 0 as null, to mimic 1-indexing
string[``January`February`March`April`May`June`July`August`September`October`November`December]a 1;
// the year cast back to a string (removes any leading zeroes)
string a 0)
};
```
**Notes:**
Dates in **q** only go back to ~1709 so I don't have a trivial way of validating the date, hence this is a non-competing entry... The best I can do is check whether the day is > 31 or month is > 12 and return 0.
] |
[Question]
[
**Closed**. This question needs [details or clarity](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Add details and clarify the problem by [editing this post](/posts/10783/edit).
Closed 1 year ago.
[Improve this question](/posts/10783/edit)
Output the same length of [Lorem ipsum](https://web.archive.org/web/20171121024811/http://www.loremipsum.net/index.html) your code is!
Rules:
* Code can't be identical to output
* No compression libraries
* Shortest program in two weeks wins
* No network usage, file reading and other tricks which with one could easily solve any code golf problem (with `eval`, `exec`, etc)
Example
```
Your code with length 25.
```
Output
```
Lorem ipsum dolor sit ame
```
[Answer]
# rot13 (1)
i'm surprised nobody came up with this before :)
```
Y
```
and as a bonus, a very simple perl solution
# Perl (252)
```
s//LoremIpsumDolorSitAmet,ConsectetuerAdipiscingElit,SedDiamNonummyNibhEuismodTinciduntUtLaoreetDoloreMagnaAliquamEratVolutpat. UtWisiEnimAdMinimVeniam,QuisNostrudExerciTationUllamcorperSuscipitLobortisNislUtAliquipExE/;s,([^ ])([A-Z]),$1$"\l$2,g;print
```
[Answer]
## GolfScript (122 or 138 bytes)
There seems to be a very small ambiguity in the rules: what precisely does "output" mean? Many programs assume that the "output" of a program doesn't include a final newline, which is there to ensure that the next line of the shell input begins on a separate line.
```
00000000 27 80 38 6e df 07 55 f7 a7 8f c0 42 9d dc 1e e7 |'.8n..U....B....|
00000010 7d 48 9a 88 79 03 92 c1 fb ed 8a af 51 92 52 24 |}H..y.......Q.R$|
00000020 2c b7 0b 17 d4 eb dc b0 d8 ce 8c 82 0f 94 0d 18 |,...............|
00000030 42 71 58 8a dd e6 b9 70 9b 48 74 f5 f0 70 c2 bb |BqX....p.Ht..p..|
00000040 e0 5b 1d e1 f2 a7 29 3e 87 b4 f0 4d 3a 22 5c 71 |.[....)>...M:"\q|
00000050 55 3d d1 fd 77 12 e2 52 73 24 89 00 9b c3 e5 47 |U=..w..Rs$.....G|
00000060 0c b4 17 1a 27 32 35 36 62 61 73 65 20 39 30 62 |....'256base 90b|
00000070 61 73 65 7b 33 32 2b 7d 25 2b |ase{32+}%+|
0000007a
```
is 122 bytes and outputs 122 bytes of lorum ipsum and a trailing newline.
```
00000000 27 75 24 b6 ac 4e 36 10 aa 62 7f 2b 35 67 cc ee |'u$..N6..b.+5g..|
00000010 c2 fa d4 9a 7a 54 96 e9 f0 0b 38 58 63 79 97 f8 |....zT....8Xcy..|
00000020 d5 7e 8a bc 4e e6 9b ee 88 ed f0 87 b5 9e 78 8c |.~..N.........x.|
00000030 ff 4e ac 59 49 d5 71 f1 94 51 f5 4e 6a 58 57 24 |.N.YI.q..Q.NjXW$|
00000040 f6 4a 07 40 d6 06 bb a3 34 55 8d 83 aa ce d4 41 |[[email protected]](/cdn-cgi/l/email-protection)|
00000050 46 04 26 c7 ef e2 f7 00 a2 61 a9 d2 40 8c 00 d9 |F.&......a..@...|
00000060 78 9a a7 53 d6 ea 85 16 23 fd c6 2c 8d a6 cb 09 |x..S....#..,....|
00000070 0a 27 32 35 36 62 61 73 65 20 39 30 62 61 73 65 |.'256base 90base|
00000080 7b 33 32 2b 7d 25 2b 3a 6e 3b |{32+}%+:n;|
0000008a
```
is 138 bytes and produces 138 bytes of lorum ipsum with no trailing newline.
[Answer]
# Golfscript - 161
Edit: python solution output a different length than its own, so I did a better one with golfscript. This is also my first golfscript answer.
```
[' ,.LUabcdeghilmnopqrstuvwy''zä{~4ú›Úˆ2©JfÖØélq¤öäpDÎ;bÐô(;ÆXÔZo´dZ]e§B¥×ûba(šX†Cf½ÇUÃ0~3i‰d<Ú{¡º¯ŠÛ„å4B9W}˜$ûã–'{1-}%255base{.26%@.@=\@26/.}do;;]''+
```
I'm not sure how this is encoded here, so [here](https://dl.dropbox.com/u/79102187/lorem.gs) is a link to the file.
[Answer]
# Mathematica, 8
I make the assumption that *visually* identical output is acceptable. I therefore use [this character](http://www.unicodemap.org/details/0x0456/index.html) in place of ASCII "i" which causes the two Symbols to be automatically sorted in the correct order:
```
іp*Lorem
```
>
>
> ```
> Lorem іp
>
> ```
>
>
[Answer]
# Python 2 - 332
```
print''.join([x,'tmoi eiidoqa ua lde rsernponutsatmnci '[ord(x)%21::21]]['.'<x<'D']for x in'LAe@1su@2lA6i?9et,;3sectetu/7d1Bc0gC<t,6e=di9:3ummy:ibhCuBmo=t0cidun?8 laAee?2lA>magna7<49Cr5 vol8p5. U?wBiCni@a=m0i@veni9, 4B:ostru=ex/ci t5i3 ull9cAp/6usc1i?lobAtB:Bl 87<41CxCa;ommo2;3se45. DuB78e@velCu@iriur>2lA 0 hendr/i?0 vulp85>')
```
If anybody cares, here's a partial list of improvements:
1181 -> 630 -> 549 -> 510 -> 456 -> 416 -> 381 -> 332
[Answer]
## Bash, 156
Because using a real "compression library" is forbidden, I'll abuse `base64` from coreutils instead. (`xxd -r` to decode submission)
```
0000000: 7461 696c 202d 3120 2430 7c62 6173 6536 tail -1 $0|base6
0000010: 3420 2d77 307c 7472 2058 595a 205c 202c 4 -w0|tr XYZ \ ,
0000020: 2e0a 6578 6974 0a2e 8ade 9978 a9b2 e997 ..exit.....x....
0000030: 7689 68ad 7b22 b576 a67a d617 7289 ec79 v.h.{".v.z..r..y
0000040: cb5e b6e7 ab5d a762 a62b 1c8a 7817 7a58 .^...].b.+..x.zX
0000050: ad61 7b1e 7577 626a 65e7 a27b a69b 25e7 .a{.uwbje..{..%.
0000060: 89b8 577a e8ac 9a87 57b6 29dc 89db a7b5 ..Wz....W.).....
0000070: 7bad 5e56 a8ad e7ad 5dda 25a2 b797 99a8 {.^V....].%.....
0000080: 2769 76a5 8aab 9a99 77ab 6ad5 efa2 5bad 'iv.....w.j...[.
0000090: a5ab 595d 4b57 c22b 225d e9e2 ..Y]KW.+"]..
```
I generated the above code using this PHP program:
```
<?php
$lorem = '<text here>';
$enclorem = base64_decode( strtr( $lorem, ' ,.', 'XYZ' ) );
$prog = "tail -\$3 \$0|base64 -w0|tr XYZ \\ ,.\nexit\n$1";
for ( $i = 0, $n = strlen( $lorem ); $i < $n; $i++ ) {
$cutlorem = substr( $lorem, 0, $i );
for ( $j = 0, $o = strlen( $enclorem ); $j < $o; $j++ ) {
$cutenclorem = substr( $enclorem, 0, $j );
if ( substr( strtr( base64_encode( $cutenclorem ), 'XYZ', ' ,.' ), 0, $i ) === $cutlorem ) {
break;
}
}
$out = strtr( $prog, array(
'$1' => $cutenclorem,
'$2' => $i,
'$3' => substr_count( $cutenclorem, "\n" ) + 1,
) );
echo "\$i=$i strlen(\$out)=" . strlen( $out ) . "\n";
if ( $i === strlen( $out ) ) {
break;
}
}
echo "\nHexdump:\n";
$p = popen( 'xxd', 'w' );
fwrite( $p, $out );
pclose( $p );
echo "\nFinal output check: ";
$tmp = tmpfile();
fwrite( $tmp, $out );
$md = stream_get_meta_data( $tmp );
ob_start();
passthru( 'bash ' . escapeshellarg( $md['uri'] ) );
$buf = rtrim( ob_get_clean() );
echo $buf === substr( $lorem, 0, strlen( $out ) ) ? 'PASS' : 'FAIL', "\n$buf\n";
```
[Answer]
# Windows batch, 878 720
Tested on Windows XP and Windows 7, but should work for every cmd with extensions (IIRC, Windows NT and later).
Has to be run using `CMD /V:ON /C batchfile` to turn on delayed variable extension, but I prefer that to having non codegolf friendly `SETLOCAL EnableDelayedExpansion` inside the batch file.
```
@ECHO OFF
SET A=Lore2ipsu21 si0amet,6ctetu7 adip3cing4lit, sed dia2nonummy nibh4u3mod tincidun0u0laoree018magna aliqua27a0volutpat. U0w3i4ni2ad mini2veniam, qu3 nostrud4x7ci tation ullamcorp7 suscipi0lobort3 n3l u0aliquip4x4a commodo6quat. Du3 aute2vel4u2iriur81 in hendr7i0in vulputat8veli0ess8molestie6quat, vel illu21e4u feugia53 a0v7o4ros40accumsan40iusto odio dign3si2qui blandi0praesen0luptatu2zzril deleni0augu8du3 18t8feugai5i. Na2lib7 tempor cu2soluta nob34leifend option congu8nihil imp7die0doming id quod mazi2plac7a0fac7 possi2assum. Typi non haben0claritate2insitam;4s0usus legent3
FOR %%I IN ("8=e ","7=er","6= conse","5=0nulla facil3","4= e","3=is","2=m ","1=dolor","0=t ") do SET "A=!A:%%~I!"
ECHO %A%
```
[Answer]
## J (144)
Would've been 128 if I hadn't needed to make it a proper script so you can measure the output.
```
exit[stdout'utsrponmligfedcbaVLI., '{~#._5>\,#:a.i.'�F��$f����`kg�c������$NI�f!!��`�L�:����l���5l�0A����Fـ���T�X ��@g�I�`��'
```
How it works: there are only 23 unique characters in the text, so this can be represented in a 5-byte encoding. The characters in the encoded string are converted to their ASCII numbers (`a.i.`), then each of the numbers is turned into their base-2 representation (`#:`), then the bits are grouped in groups of five (`_5>\,`), then each of these groups is converted to its value (`#.`), and these are used as an index into the lookup table. (`{~`).
The lookup table actually needed some tinkering, because a J string literal cannot contain `\n`, `\r` or `\0`.
Hexdump:
```
0000000: 7865 7469 735b 6474 756f 2774 7475 7273
0000010: 6f70 6d6e 696c 6667 6465 6263 5661 494c
0000020: 2c2e 2720 7e7b 2e23 355f 5c3e 232c 613a
0000030: 692e 272e 4691 d9c3 1024 660f 0595 841d
0000040: da90 6007 676b c214 8263 81c0 b483 921a
0000050: 4e24 9549 2166 a521 60a6 4cb1 8c1d 3a03
0000060: 02d0 ca80 6cd9 9302 d800 35c5 c56c 4130
0000070: ac80 d600 00c3 0346 80d9 88ad 8001 b454
0000080: 2058 e0a5 0f40 1467 49cd 60d8 e080 0a27
```
[Answer]
# Mathematica 47 46 44
With 2 bytes saved thanks to Imanton1
Not sure if this is fair play. Mathematica has the 'full' text of Lorem ipsum in its example data. The following simply tells Mathematica to take a string of a particular length from the built-in example of Lorem Ipsum.
```
#@#["Text"][[19]]&@ExampleData~StringTake~44
```
>
> "Lorem ipsum dolor sit amet, consectetuer adi"
>
>
>
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 12 bytes
```
.•ÿ₆∊Ã̦R•.ª
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f71HDosP7HzW1PeroOtx8uOfQsiCgiN6hVf//AwA "05AB1E – Try It Online")
```
.•ÿ₆∊Ã̦R•.ª # full program
.•ÿ₆∊Ã̦R• # "lorem ipsum "...
.ª # in sentence case
# implicit output
```
[Answer]
# [LaTeX](https://www.latex-project.org/) + [lipsum](https://www.ctan.org/pkg/lipsum), 125 bytes
```
\documentclass[12pt]{article}
\usepackage{lipsum}
\pagenumbering{gobble}
\begin{document}
\lipsum[1][1-2]
\end{document}
```
Output:
>
> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Ut purus elit, vestibulum ut, placerat ac, adipiscing vitae, felis.
>
>
>
[Answer]
# [FEU](https://github.com/TryItOnline/feu), 545 bytes
```
a/Lorem ipsum dolor sit amet!consectetuer adipiscing elit. Integer nunc augue!feugiat non!egestas ut!rutrum eu!purus. Vestibulum condimentum commodo pede. Nam in metus eu justo commodo posuere. Nunc varius dui id nulla. Fusce porttitor pretium leo. Quisque in diam. Nulla pellentesque. Donec vitae urna et arcu lobortis varius. Aenean velit eros!varius ac!semper sit amet!lacinia eget!sem. Phasellus mollis nunc a pede cursus fermentum. Proin et odio. Nullam turpis. Fusce eget arcu. Mauris placerat ultricies lectus. Nullam pede nisl!u
s/!/, /g
```
[Try it online!](https://tio.run/##TZHNThwxEITvPEX7jrzPgIQiISUILtyN3Ttp5J@hf3j9Tc2yUXKbmSpXfa45c1wu5fRzKQ@S3WJQW30pmTiVwZ7qmsbV2YOVSpNdrMrciLt4pqfpvEGYMSuV2ILTmWOT4jTXTNDMi1F40nBFOkfaQ8MyvUGS9@j4iI4mg6dfn8dYbdHOjTM9F2BNAkgYztJHmK9/nmWgOmxH/VdRgauFkDQQ9V4y/QirDKO6i@Neu7ILajqvTK8h9hl8NDQp48jBIVT3Dhg@tEyPazLCxQtT6CzEWEZrUF/viBW7FWd64Mll0tcxDbEuSzekUpPx2Pm/WXvBioKwDS8QM738LoZi2MfqHbHfm16HoBpqUM6s3zPBrgvYYFlN1o18kIfiB/299hF@Zc30q4Qic0cvK/5OdFepwoYlqh/0t4Rr3RTrKe7slE73dNoulz8 "FEU – Try It Online")
It just so happened to work.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
`Lo≥›
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgTG/iiaXigLoiLCIiLCIiXQ==)
[Answer]
# [Perl 5](https://www.perl.org/) + `-M5.10.0`, 35 bytes
If anything that starts `Lorem ipsum` is acceptable this should work:
```
say"\u@{[<'{,do}lor{em ipsum,}'>]}"
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoic2F5XCJcXHVAe1s8J3ssZG99bG9ye2VtIGlwc3VtLH0nPl19XCIiLCJhcmdzIjoiLU01LjEwLjAifQ==)
---
# [Perl 5](https://www.perl.org/) + `-M5.10.0`, 42 bytes
However if it needs to start `Lorem ipsum dolor sit amet`, you'll need this:
```
$}=" dolor sit ame";say"Lorem ipsum$}t,$}"
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJH09XCIgZG9sb3Igc2l0IGFtZVwiO3NheVwiTG9yZW0gaXBzdW0kfXQsJH1cIiIsImFyZ3MiOiItTTUuMTAuMCJ9)
---
# [Perl 5](https://www.perl.org/) + `-M5.10.0`, 72 bytes
But, if it needs to start `Lorem ipsum dolor sit amet, consectetur adipiscing elit.`, then I think this is the shortest I can manage:
```
$}="Lorem ipsum do";say"$}lor sit amet, consectetur adipiscing elit. $}"
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoiJH09XCJMb3JlbSBpcHN1bSBkb1wiO3NheVwiJH1sb3Igc2l0IGFtZXQsIGNvbnNlY3RldHVyIGFkaXBpc2NpbmcgZWxpdC4gJH1cIiIsImFyZ3MiOiItTTUuMTAuMCJ9)
] |
[Question]
[
Write a program using the fewest bytes of source code which given a list of strings finds all elements which are still in the list when any character is deleted.
For example, given a list of all English words `boats` would be output because `oats`, `bats`, `bots`, `boas`, `boat` are all English words and thus would be in the list.
Simple Pyhon code example, assuming `words` is the input list:
```
for w in words:
has_all = True
for i in range(len(w)):
test = w[:i] + w[i+1:]
if test not in words:
has_all = False
break
if has_all
print(w)
```
Example input list with some strings:
```
aorn (+)
aor (+)
arn
aon
orn (+)
ao
ar
or
rn
on
```
The strings marked with `(+)` are the ones that should be the output.
`arn` and `aon` shouldn't be output because we can delete the middle character to get `an`, which is not in the input list.
You should test that aba is not present on the output of this list:
```
aba
ba
aa
b
```
[Answer]
# [J](http://jsoftware.com/), 11 bytes
```
*/@e.~1<\.]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/tfQdUvXqDG1i9GL/a3JxpWQml9jqKdhY68UbAlWn5Csk5SRmKCQllhQrJOWDiUQwUaKQDxKryixQ5@JKTc7IVwBpVUhTUAdJFqujilVUVKj/BwA "J – Try It Online")
J's "outfix" adverb `\.` does exactly what we need here.
Take the dictionary as the left arg (implicitly, via the overall dyadic hook), and the string to test as the right arg.
* `1<\.]` Returns the box of every length 1 outfix of our right arg, that is, every copy with exactly 1 char deleted.
* `e.~` Asks if each of those is an element of the dictionary given as the left arg. Returns a list of boolean zeros and ones.
* `*/@` Multiplies them all together, that is, are they all one?
[Answer]
# JavaScript (ES6), 74 bytes
```
a=>a.filter(w=>[...w].every((_,i)=>a.includes(w.slice(0,i)+w.slice(i+1))))
```
[Try it online!](https://tio.run/##NYxhCoMwDEaPY0QX5gHqRURGqenIKO1oncXTd2nR/PiS7z3IRx86mcjf/eHDRsWqotWs0bLbKUJW84KIeUU6KJ4Ar5H76tkb99soQcbk2BA8RQx34WHqZYoJPgVH6MIbLCydDtF3Y101r7vmzRtuXaIx0at8@gM "JavaScript (Node.js) – Try It Online")
---
### 75 bytes
A bit more fun, but 1 byte longer:
```
a=>a.filter(w=>w.replace(/./g,"$`$',").split`,`.every(w=>!w|a.includes(w)))
```
[Try it online!](https://tio.run/##NYxhCsMgDEbPslJQwaUnsBcZgwYbi0O0qKsUdvdOZfvzkrzvIy88MOlo93z3YaXLqAvVjGCsyxR5UXOBSLtDTXyCaZPDuIxMDgLS7mxe5AJ0UDxb81Y@CNZr914p8SKEuHTwKTgCFzZu@INhiJ7JNhp/e@Pfd93viu5q/Kyfvg "JavaScript (Node.js) – Try It Online")
or:
```
a=>a.filter(w=>!+w.replace(/./g,_=>+!a.includes(r["$`"]+r["$'"])),r=RegExp)
```
[Try it online!](https://tio.run/##NYxBDsIgEEXP0sakNEV6ArrzAm6bRid02qAIZKhWT49AdPP@/PeTucELgiLtt2PwekZ6OHvHT1xkBDmAWLTZkNguh6rbBaE3oJD1ol/5RQ5dBUJbZZ4zBkZjfbjWU5ezqae25STPuJ7evo3K2eAMCuNWtrCxAUe24Tkyf3fm3xddekJxaU4/4xc "JavaScript (SpiderMonkey) – Try It Online") (SpiderMonkey)
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
lambda L:[w for w in L if{w[:i]+w[i+1:]for i in range(len(w))}<={*L}]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUcHHKrpcIS2/SKFcITNPwUchM626PNoqM1a7PDpT29AqFiSVCZIqSsxLT9XISc3TKNfUrLWxrdbyqY397@MZHGIbrZ6Un1hSrK4DoqEUkISKASmIEJiCkRBlMEo9lqugKDOvRCNNA2SipuZ/AA "Python 3 – Try It Online")
# [Python 2](https://docs.python.org/2/), 71 bytes
```
lambda L:[w for w in L if{w[:i]+w[i+1:]for i in range(len(w))}<=set(L)]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUcHHKrpcIS2/SKFcITNPwUchM626PNoqM1a7PDpT29AqFiSVCZIqSsxLT9XISc3TKNfUrLWxLU4t0fDRjP3v4xkcYhutnpSfWFKsrgOioRSQhIoBKYgQmIKREGUwSj2Wq6AoM69EIU0DZKLmfwA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~7~~ 6 bytes
```
e-ƤẠ¥Ƈ
```
[Try it online!](https://tio.run/##y0rNyan8/z9V99iSh7sWHFp6rP3/w91bDrdH/v@fmF@UxwUkuBLBdB4XhA/kAllcQHZ@HgA "Jelly – Try It Online")
A monadic link taking a list of words and returning a list of words.
Thanks to @JonathanAllan for saving a byte!
## Explanation
```
¥Ƈ | Keep only those where the following is true:
e-Ƥ | - Check whether each outfix with sublists length 1 removed is in the original list
Ạ | - All
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~51~~ ~~48~~ 45 bytes
```
->a{a.reject{|i|i.gsub(/./m){[$`+$']-a}[?"]}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xOlGvKDUrNbmkuiazJlMvvbg0SUNfTz9XszpaJUFbRT1WN7E22l4ptrb2f4FCWnS0elJ@Ykmxug6IhlJAEioGpCBCYApGQpTBKPXY2P8A "Ruby – Try It Online")
For each character in a string, generate the string with it deleted, then replace the character with either that string, if it's not in `a`, or an empty array, using `-` for the set complement operation. Then check whether the result contains any string representations.
Edit: -3 bytes from Value Ink by not converting arrays to booleans.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
Φθ⬤ι№θΦι⁻ξμ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMtM6cktUijUEfBMSdHI1NHwTm/FCgM5ENlgEK@mXmlxRoVOgq5mmBg/f9/dLRSYn5RnpKOAogGUzAemILLQaQgQiASIg5UFBv7X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
Φ Filter where
ι Current word
⬤ All characters satisfy
№ (Non-zero) Count of
ι Current word
Φ Filtered where
ξ Character index
μ Inner index
⁻ Differ (i.e. filter out that character index)
θ In input array
Implicitly output each matching word on its own line
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 64 bytes
```
->l{l.select{|w|(1..w.size).all?{|a|l&[w[0,a-1]+w[a..-1]]!=[]}}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nOkevODUnNbmkuqa8RsNQT69crzizKlVTLzEnx766JrEmRy26PNpAJ1HXMFa7PDpRTw/IiFW0jY6tra39X6CQFh2tnpSfWFKsrgOioRSQhIoBKYgQmIKREGUwSj029j8A "Ruby – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 34 bytes
```
~:a{.,,{1$.2$<\@)>+a?)}%{and}*\;},
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/v84qsVpPR6faUEXPSMUmxkHTTjvRXrNWtToxL6VWK8a6Vud/bML/aKXE/KI8JQUQBSKhbBAJEwcLg/lAAiwGlI4FAA "GolfScript – Try It Online")
# Explanation
```
~ # Evaluate the inplicit list input
:a # Assign to the variable a w/o popping
# (To be golfed)
{ }, # Huge filter block
. # Copy the current string
,, # Generate a length list
{ }% # Map the length list:
1$.2$<\@)>+ # Remove the character at the index
a?) # Is this string still in the list?
{and}* # logical AND all of the results
\; # Discard the extra operand
```
[Answer]
# [PHP](https://php.net/), 112 bytes
```
for(;$s=$argv[++$i];$j=0){for($t=1;$s[$j];)$t&=in_array(substr($s,0,$j).substr($s,++$j),$argv);if($t)echo"$s,";}
```
[Try it online!](https://tio.run/##RYzRCsIwDEX/ZQRZWBnzuRY/ZAyJ4lz70Ja0CjL89pjNB19u7uGGk5csp3PWnBO3FooD4sdr7Drwk4XgBly3Bao76jpCmCxCPTgfL8RM77Y8r6XqQzGDgYD9n9UR0Ow@tH5WB95vS2p0auxHRChx3EJov1F@rKhNtKf4BQ "PHP – Try It Online")
That's still pretty ugly and throws a lot of notices, but it works..
Pretty straightforward:
```
for(;$s=$argv[++$i];$j=0){ //loops on arguments skipping the first (script name) and resetting $j each turn
for($t=1;$s[$j];) //loops on all chars indexes initializing $t to true
$t&=in_array(substr($s,0,$j).substr($s,++$j),$argv); //checks if in arguments array, with deleted char -> bitwise AND the result to $t
if($t)echo"$s,"; //if $t still true, displays argument with a coma
}
```
caveat: can lead to false positive if the name of the script is a word that can be a match in the list (".code.tio" in TIO, so OK here)
[Try it online!](https://tio.run/##RYzbCoMwEET/RRZxMRR93gY/RKSsxUvyUEMSBSn99u22L8IwMJzhhDXIvQva8xYrgmSB43L0dQ1uIPC2wfePQLat0h78QAi5tO714Bj5rNI@pqyHZBoDHm/XVodH8/chuVkdOD3XrVBU0EdEeGTRsPYX "PHP – Try It Online") for the added second test case `[aba, ba, aa, b]`
EDIT: saved 3 bytes using bitwise assign operator `&=in_array` instead of logical operator `=$t&&in_array`
EDIT2: saved another 3 by initializing `$j` to zero and moving `++` inside `substr`
EDIT3: saved another one by resetting `$j` to zero in first loop declaration, saving the `,` (it is undefined on first iteration, causing a bunch of new notices, but PHP is a smart guy)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 67 bytes
```
a=>a.Where(x=>x.Select((y,_)=>x.Remove(_,1)).All(y=>a.Contains(y)))
```
[Try it online!](https://tio.run/##TY3NCsIwEITP5ikWT7tQC55rCyIKggfRg8cSw9YG0hST@FNKn71ai@Jlh/lmd1b5mfK639ysWuy0DwsfnLaXLNqu7a1iJ8@Gvywr0l6mmYxPJTvGZ5o94yMbVgGxiXIa/IGr@s6YR3OieGkMNsPBqrZBauuxIaI@Ef@fwEAKlh/wD5HaqaydnUYw6Ee@7iO/bIxGNMyRv5e6RIiidixViWMrXEFbKNAQQSsm@zcLeKVEdP0L "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Java 10, ~~137~~ ~~130~~ 121 bytes
```
L->L.stream().filter(w->{var b=1>0;for(int i=0;i<w.length();)b&=L.contains(w.substring(0,i)+w.substring(++i));return b;})
```
-7 bytes thanks to *@ExpiredData*.
[Try it online.](https://tio.run/##dZHBbsIwDIbvPIXVw5SoELHrSivtOKljB47TDmlXWFhJUeJSIcSzd04axoBx8Z/Y1u8v8Vru5GT9@d2XtbQWXqXShxGA0liZpSwrmLsrwJr6RIuqFhZNJTdi4WVGovQqg5KdO3Jl8beQ84QMjiMKFiWqEuagIYU@n2R5MGNcLFVNE1k3yQ47aaBIH7NpsmwMIxJQ6TRRs07UlV7hF@MJLx7SXJSNRuK1rBO2LawfyKZjxeO/iThWnCemwtZoKJIj7xMHs22LmmAC065Rn7AhMzZwv3@A5MPLsbLIItkYHY2duBjOLp7yPu3vFHyOyv7tJ4uikWhdfpAiSBNEBsHo5sc8nTcZ6IQQtKFtiwFxsbdYbUTTothSHWvNohdXfwKI4vNino2ReyuwGWzY4BEgr9oulljThXamq@7ftozdzJDWVS4nXGOy6K1FTxnd6aCH3KfXomQOjFPK1xjn933Cpx77Hw)
**Explanation:**
```
L-> // Method with String-List parameter & String-Stream return-type
L.stream().filter(w-> // Filter the words in the input-Stream by:
var b=1>0; // Create a boolean, starting at true
for(int i=0;i<w.length();)
// Loop `i` in the range [0, word-length)
b&= // Check if all are truthy for:
L.contains(w.substring(0,i)+w.substring(++i)
// Remove the `i`th character from the word
); // and check if this is in the input-list
return b;}) // And return the resulting boolean
```
[Answer]
# Haskell 42 bytes
```
f l=[e|e<-l,all(\c->filter(/=c)e`elem`l)e]
```
In `f` I'm just literally asking for all elementes `e` in the list `l`, such that, for all characters `c` in that element, if I filter `c` from `e` (`filter(/=c)e`), the result is still in the list (`filter(/=c)e`elem`l`).
[Answer]
# [C++ (clang)](http://clang.llvm.org/), ~~216~~ \$\cdots\$ ~~164~~ 160 bytes
```
#import<string>
#import<set>
void f(std::set<std::string>d){for(auto w:d){int h=1,i=0;for(;w[i]*h;){auto t=w;h=d.find(t.erase(i++,1))!=end(d);}h&&puts(&w[0]);}}
```
[Try it online!](https://tio.run/##bY/LDoIwEEX3/YqqCWkFDW6p5UeMi8YWmURaUgZZEL4diw/QxK7OvXOaaS91vbvclL2O4waq2nk8NujBXnMyZ4M5uTvQtGAN6iwLxfEFL1PzvnCeqRYd7bKQwCIt5SEBmYppIroTnLel4P3TQdmJUup9AVYz3BuvGsMgjpMD5ytpQqm5GMooqltsWNSd0nPIw/h3OdW0JzSctXLerpOZZ/xuZ/xxF3UZf2jxwmUyCDJ9rlJgGX8vLqbnPskbbL2lqSADGR8 "C++ (clang) – Try It Online")
Saved 10 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
**Ungolfed:**
```
#include <iostream>
#include <set>
#include <string>
void f(const std::set<std::string>& words) {
for (auto word : words) {
bool hit = true;
for (size_t i = 0; i < word.size(); ++i) {
auto temp = word;
temp.erase(i, 1);
if (words.find(temp) == end(words)) {
hit = false;
break;
}
}
if (hit) {
std::cout << word << "\n";
}
}
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-f`](https://codegolf.meta.stackexchange.com/a/14339/), ~~11~~ ~~10~~ 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I am *horribly* out of practice; (now slightly less) convinced this can be shorter!
```
¬e@NÎøUjY
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWY&code=rGVATs74VWpZ&input=WyJhb3JuIiwiYW9yIiwiYXJuIiwiYW9uIiwib3JuIiwiYW8iLCJhciIsIm9yIiwicm4iLCJvbiJd)
[Answer]
# AWK, ~~101~~ 94 bytes
```
{a[$0]++}END{for(w in a){e=split(w,x,"");for(i in x){t=w;sub(x[i],"",t);e*=a[t]}if(e)print w}}
```
[Try it online!](https://tio.run/##JYmxCsMgFEV3v0JCB20cuotbu/YHxOEVDDxaNBjLE8RvNyZZ7j2HA/TtvYK9Pdw8t9f7WZeYBHEMHGT1Zlt/mAWpoqZJ6qPh0Yqs2ZDe/h9RLLoRVZba3w3Y7Bouwss1YcicWusdYgpsDIPzA7t86CA2OIYd "AWK – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~44~~ 42 bytes
*[crossed out 44 is still 44](https://codegolf.stackexchange.com/a/195414/76162)*
```
{@^a.grep:{m:ex/^(.*).(.*)$/>>.join⊂@a}}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv9ohLlEvvSi1wKo61yq1Qj9OQ09LUw9EqOjb2ell5WfmPepqckisrf1fnFipkKaQk5mXWvw/Mb8ojwtIcCWC6TwuCB/IBbK4gOz8PAA "Perl 6 – Try It Online")
Filter from the input list elements where the possible regex matches excluding one letter are a subset of the input.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
ʒæ¤g<ùåP
```
[Try it online!](https://tio.run/##yy9OTMpM/f//1KTDyw4tSbc5vPPw0oD//6OVEvOL8pR0FEA0mILxwBRcDiIFEQKREHGgolgA "05AB1E – Try It Online")
```
ʒ # filter the list of words by:
æ # powerset of the word
¤g< # length of the word - 1
ù # elements of the powerset that have this length
åP # are they all in the list of words?
```
[Answer]
# [Zsh](https://www.zsh.org/), 58 bytes
```
for x;(repeat $#x (($@[(I)$x[0,i]${x: ++i}]))||exit;<<<$x)
```
[Try it online!](https://tio.run/##JYcxDsIwDEX3nMISHmwVpM40AytnqDoYKVGzJCjNYEE5e3BB@nr/vde29khMbgsNLtpjqaAT1fAM0gBPCkR4m@nOqPN4Tgu@9QrDkD4L874HTW3y3qNyZ@ciyEPAJsajSs0HQH6f4d@WZmBecv8C "Zsh – Try It Online")
I abuse a `(subshell)` to remove the need to reset `i` on each iteration, and to use `exit` instead of `continue 2`.
```
for x;(repeat $#x (($@[(I)$x[0,i]${x: ++i}]))||exit;<<<$x)
for x; # for each element
(repeat $#x ; ) # repeat for the length
( $x[0,i]${x: ++i} ) # 1-indexed substring, zero-indexed substring
( $@[(I) ] ) # get smallest index of match
( (( ))||exit; ) # if zero, exit the subshell
( <<<$x) # if we didn't exit, print the string
( ) # exit subshell, which unsets i.
```
] |
[Question]
[
# Input
A nonnegative integer `n`, and a nonempty string `s` containing only alphanumeric characters and underscores `_`.
The first character of `s` is not `_`.
The underscores of `s` are interpreted as blank spaces that can be filled with other characters.
We define an infinite sequence of "infinite strings" as follows.
The string `s1 = s s s...` is just `s` repeated infinitely many times.
For all `k > 1`, the string `sk+1` is obtained from `sk` by filling its blank spaces with the characters of `s1`, so that the first `_` of `sk` is replaced with `s1[0]`, the second with `s1[1]`, and so on.
Since the first letter of `s` is not `_`, every blank space gets filled eventually, and we denote by `s∞` the infinite string where every `_` has been replaced by its eventual value.
# Output
The first `n` characters of `s∞` as a string.
# Example
Consider the inputs `n = 30` and `s = ab_c_`.
We have
```
s1 = ab_c_ab_c_ab_c_ab_c_ab_c_ab_c_ab_c_...
```
Substituting `s1` to the blanks of `s1`, we have
```
s2 = abacbab_ccab_caabbc_abcc_abacbab_cc...
```
We again substitute `s1` to the blanks, which results in
```
s3 = abacbabaccabbcaabbc_abcccabacbab_cc...
```
One more substitution:
```
s4 = abacbabaccabbcaabbcaabcccabacbabbcc...
```
From this we can already deduce the first 30 characters of `s∞`, which are
```
abacbabaccabbcaabbcaabcccabacb
```
This is the correct output.
# Rules
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
Crashing on incorrect input is acceptable.
# Test Cases
```
0 "ab__" -> ""
1 "ab__" -> "a"
3 "ab__" -> "aba"
20 "ab" -> "abababababababababab"
20 "ab__" -> "abababababababababab"
20 "ab_" -> "abaabbabaabaabbabbab"
30 "ab_c_" -> "abacbabaccabbcaabbcaabcccabacb"
50 "ab_a_cc" -> "abaabccabaaaccabbacccabcaaccabbaaccabaaaccabcaccca"
50 "abc____" -> "abcabcaabcbcaaabcbcbcabcaaababccbcbabccabcabcaaaba"
```
[Answer]
# APL ~~29~~ 28
```
{a⊣(b/a)←a↑⍨+/b←'_'=a←⍺⍴⍵}⍣≡
```
it's used like this:
```
fun←{a⊣(b/a)←a↑⍨+/b←'_'=a←⍺⍴⍵}⍣≡
20 fun 'ab_c_'
abacbabaccabbcaabbca
```
**Explanation:**
```
a←⍺⍴⍵ makes vector long as left argument using repeated chars in right argument
a↑⍨+/b←'_'=a takes a string from the beginning of string a (a↑⍨), long as the number of _'s in a (+/b←'_'=a)
(b/a)← puts those chars in place of the _'s in the original vector
a⊣ and returns a
{}⍣≡ repeats function ( {} ) until results doesn't change anymore
```
[Tryapl.org](http://tryapl.org/?a=fun%u2190%7Ba%u22A3%28b/a%29%u2190a%u2191%u2368+/b%u2190%27_%27%3Da%u2190%u237A%u2374%u2375%7D%u2363%u2261%u22C420%20fun%20%27ab_c_%27&run)
[Answer]
# CJam, ~~26~~ ~~24~~ 20 bytes
4 bytes saved thanks to Peter.
```
l~:I*{_'_/[\]zsI<}I*
```
[Test it here.](http://cjam.aditsu.net/) Takes the string first and `n` second on STDIN.
You can run all test cases by pasting them into the input as they are (include the `-> output` if you want), and using the following test harness (which reverses the order for the code):
```
qN/{"->"/0=S/W%S*
~:I*{_'_/[\]zsI<}I*
]oNo}/
```
## Explanation
```
l~:I*{_'_/[\]zsI<}I*
l~ "Read the input and evaluate.";
:I "Store n in I for future use.";
* "Repeat s n times to ensure it's long enough for the output.";
{ }I* "Repeat this block n times. This will always be enough passes.";
_ "Duplicate the string.";
'_/ "Split the string on underscores.";
[\] "Swap with the other copy, putting both in an array.";
z "Zip the two arrays together, interleaving substrings from the split
copy with characters from the unsplit copy. Extraneous
characters from the unsplit copy just go at the end and
can be ignored.";
s "Convert the result into a string, flattening the array in the
process. This basically joins the two interleaved strings together.";
I< "Truncate to n characters.";
```
The result is printed automatically at the end of the program.
**A note on `[\]`:** In principle, `[` remembers the current size of the stack and `]` collects everything down to the last remembered size in an array. However, if the array size falls below the remembered size in between, then the start of the array gets adjusted accordingly. Now you might think that swapping the top two array elements doesn't affect the array size at all, but `\` actually pops two value and then pushes them in reverse order. This is what pushes the start of the array down by two. Therefore, `[\]` is the shortest way to wrap the top two stack elements in an array. Sometimes, the side effect of collecting them in reverse order is quite annoying, but in this case, it's exactly what I need.
[Answer]
# Python 3, 110 bytes
```
n=int(input())
*b,=input()*n
a=b[:n]
while"_"in a:b,a=b[:],[x*(x!="_")or b.pop(0)for x in a]
print("".join(a))
```
Needs a fair bit more golfing, but here is some sheer insanity. Reads in `n` then `s` from STDIN.
The fun part is, in the loop's assignment we **copy `b`, then start popping from `b` during a list comprehension**. If the assignment was the other way around, it wouldn't work!
[Answer]
# Pyth, 17
```
<ussC,cG\_GUQ*zQQ
```
Input should be given with the string on the first line, and the length on the second, on STDIN. For example:
```
abc____
50
```
[Try it here.](http://pyth.herokuapp.com/)
**Explanation:**
```
Implicit:
z = input() z is the string.
Q = eval(input()) Q is the length.
< Q First Q characters of
u UQ*zQ Reduce, with an initial value of z repeated Q times,
on the list range(len(Q)).
Since the reduce function doesn't use the sequence variable H
this function amounts to applying the inner code Q times to
the initial value, where the working variable is G.
ss Sum from list of tuples of strings, to tuple of strings,
to string.
C, Zip together
cG\_ G split on underscores
G with G.
This inserts a character of G between every underscore
separated group of G, which amounts to replacing the
underscores with characters of G, after summation.
```
[Answer]
# k, 30
```
{{@[x;i;:;(#i:&"_"=x)#x]}/x#y}
```
[Answer]
# Java - 162 ~~174~~
It's not every day I get to use a do/while loop when golfing in Java :D
This just iterates and fills in blanks as they come. It just keeps going until there are no more `_` in the result.
```
char[]a(int n,char[]s){char[]o=new char[n];if(n>0)do for(int i=0,j=0;i<n;i++)if(o[i]==95|o[i]<1)o[i]=s[j++%s.length];while(new String(o).contains("_"));return o;}
```
With line breaks:
```
char[]a(int n,char[]s){
char[]o=new char[n];
if(n>0)
do
for(int i=0,j=0;i<n;i++)
if(o[i]==95|o[i]<1)
o[i]=s[j++%s.length];
while(new String(o).contains("_"));
return o;
}
```
[Answer]
# Java 8, 238
```
(n,s)->{int i=0,j=0;for(s=String.join("",java.util.Collections.nCopies(n,new String(s))).toCharArray();j<1;){for(i=0;i<n;i++){for(;s[++j]!=95&j<n;);if(j<n)s[j]=s[i];}for(j=1,i=0;i<n;)j=s[++i]==95?0:1;}return java.util.Arrays.copyOf(s,n);}
```
Less golfed:
```
(Integer n, char[] s) -> {
int i = 0, j = 0;
for (s = String.join("", java.util.Collections.nCopies(n, new String(s))).toCharArray(); j < 1;) {
for (i = 0; i < n; i++) {
for (; s[j] != 95 & j < n; j++);
if (j < n) {
s[j] = s[i];
}
}
for (j = 1, i = 0; i < n;) {
j = s[++i] == 95 ? 0 : 1;
}
}
return java.util.Arrays.copyOf(s, n);
}
```
[Answer]
# Ruby, 60
```
->n,s{eval"r=%1$p.chars;s.gsub!(?_){r.next};"*n%s*=n;s[0,n]}
```
Concatenates `s` to itself `n` times, then generates `n` copies of code that replaces underscores with `s`, evaluates those copies, and returns the first `n` characters of the result. Since at least one underscore is removed in each loop, this is guaranteed to give us `n` underscore-free characters.
[Answer]
# Python 2, 75
```
n,s=input()
S='';c=0
for x in s*n:b=x=='_';S+=S[c:c+b]or x;c+=b
print S[:n]
```
This expects input like `(30,"ab_c_")`.
In Python, strings don't allow assignment. So, replacing the blanks with the desired character is hard. One can get around this by converting to a list and back, but I found it shorter to just generate the output string from scratch, adding on the desired characters one at a time.
The output being constructed is `S`, which starts empty. We loop through the characters of the input `s` copied many times to simulate a circle. We check if it's a blank via the Boolean `b`. We check equality `x=='_'` rather than comparison because the underscore lies between capital and lowercase letters.
If the character is not a blank, we just add it onto `S`. If it is blank, we add the next unused letter of the output-so-far `S`. We track used letters by an index pointer `c` that starts at 0 and is incremented each time we encounter a blank.
At the end, we print the first `n` characters of the resulting string `S`.
We have to use `S[c:c+b]` in place of the shorter `b*S[c]` because the latter gives an out-of-bounds error when `S` starts empty and `c` is 0. It never matters because we're guaranteed the first character of `s` is non-blank, so this `S[c]` is never needed, but the code doesn't know it. Flipping the `or` to short-circuit could also solve this, but costs more characters.
---
# Python 2, 83
A Pyth-to-Python port of [isaacg's solution](https://codegolf.stackexchange.com/a/45276/20260), which uses `split` and `zip` to perform the replacement:
```
n,s=input()
s*=n
exec"s=''.join(a+b for a,b in zip(s.split('_'),s));"*n
print s[:n]
```
It turned out longer because, suprise, named methods are long in python. But it can perhaps be improved by riffling `s` and `s.split('_')` together in a shorter way.
[Answer]
## Haskell (93) 67
I haven't written any Haskell in a while, so this can probably be shortened by a lot. *but it was so good, we had to shorten it and make it better!*
```
('_':b)&(d:e)=d:b&e;(a:b)&c=a:b&c
f n s=take n$q where q=cycle s&q
```
Usage:
```
*Main> f 50 "ab_a_cc"
"abaabccabaaaccabbacccabcaaccabbaaccabaaaccabcaccca"
```
[Answer]
## Batch - 425
Do I lose?
```
@echo off&setLocal enableDelayedExpansion&set s=%2
if "%3"=="" (for /l %%a in (1,1,%1)do set o=!o!%s%)else set o=%3
set o=!o:~0,%1!&set l=0
:c
if defined s set/al+=1&set "s=%s:~1%"&goto c
set s=%2&set/ap=%1-1
set y=&set c=0&for /l %%a in (0,1,%p%)do set x=!o:~%%a,1!&if !x!==_ (for %%b in (!c!)do set y=!y!!s:~%%b,1!&set/ac+=1)else (set y=!y!!x!)&if !c!==%l% set c=0
if "!y:_=!"=="!y!" echo !y!&goto :EOF
%0 %1 %2 !y!
```
Batch has limitations - I accept this. For example; I had to use a for loop to get a single variable in a usable format due to limitations of variable parsing syntax. `for %%b in (!c!)do...` just exists so I can use `%%b` instead of `!c!` so I can actually do the string manipulation `!s:~%%b,1!` and have the variables expand at the correct time.
There are a couple of pretty basic things I could do to golf this further, but probably not below 400 bytes. I'll have another crack soon.
[Answer]
# ECMAScript 6, 78
```
f=(s,n,i=0)=>[...s.repeat(n)].reduce((s,x)=>s+(x=='_'?s[i++]:x),'').slice(0,n)
```
Starts off with an empty string and for every occurrence of underscore, replaces it with the character at the next index of the current string.
[Answer]
# Python 2 - ~~99~~ 97 bytes
---
Because 4 python-based submissions aren't enough...
```
n,s=input();S=s=s*n
while"_"in S:x=iter(s);S="".join(j>"_"and j or next(x)for j in S)
print S[:n]
```
Example:
```
$ python2 t.py
(50, "ab_a_cc")
abaabccabaaaccabbacccabcaaccabbaaccabaaaccabcaccca
```
[Answer]
# ECMAScript 6, ~~93~~ 91
```
(n,s)=>{for(x="_".repeat(n);n=0,/_/.test(x);)x=x.replace(/_/g,a=>s[n++%s.length]);return x}
```
Shaved off 2 characters from the first version.
```
(n,s)=>{x="_".repeat(n);while(/_/.test(x)){n=0,x=x.replace(/_/g,a=>s[n++%s.length])}return x}
```
[Answer]
# C# - 162
I stole Geobits solution and changed it to C#
```
char[]p(int n,string s){var r=new char[n];if(n>0)do for(int i=0,j=0;i<n;i++)if(r[i]=='_'||r[i]<1)r[i]=s[j++%s.Length];while(r.ToList().IndexOf('_')>=0);return r;}
```
1 char better, so you can improve Geobits ;)
] |
[Question]
[
A Bayer matrix is a threshold map used for [ordered dithering](https://en.wikipedia.org/wiki/Ordered_dithering) that gives the illusion of having more shades of color than actually present by using a crosshatch-like pattern.
Bayer matrices are square with a side length that is a power of 2. Here are some examples:
\$
\displaystyle\frac{1}{4}
\times
\begin{bmatrix}
0 & 2\\
3 & 1
\end{bmatrix}\$
\$
\displaystyle\frac{1}{16}
\times
\begin{bmatrix}
0 & 8 & 2 & 10\\
12 & 4 & 14 & 6\\
3 & 11 & 1 & 9\\
15 & 7 & 13 & 5
\end{bmatrix}\$
\$
\displaystyle\frac{1}{64}
\times
\begin{bmatrix}
0 & 32 & 8 & 40 & 2 & 34 & 10 & 42\\
48 & 16 & 56 & 24 & 50 & 18 & 58 & 26\\
12 & 44 & 4 & 36 & 14 & 46 & 6 & 38\\
60 & 28 & 52 & 20 & 62 & 30 & 54 & 22\\
3 & 35 & 11 & 43 & 1 & 33 & 9 & 41\\
51 & 19 & 59 & 27 & 49 & 17 & 57 & 25\\
15 & 47 & 7 & 39 & 13 & 45 & 5 & 37\\
63 & 31 & 55 & 23 & 61 & 29 & 53 & 21
\end{bmatrix}\$
The numbers in the matrix are arranged in such a way so that each number is placed as distant from the previous ones as possible, taking account that the edges wrap.
For example, in the second matrix shown above, the 0 is placed in the top left first, then the 1 is placed two to the right and two below the 0, which is the maximum distance away from the 0. Note that the 1 is not placed in the bottom right, because since the edges wrap, the bottom right would be one to the left and one above the 0. Next, the 2 is placed with a distance of 2 from both 0 and 1, and the 3 is placed similarly.
Note that measuring the distances to generate the matrix is not the simplest method.
# Challenge
Your task is to create a program or function, that when given an input side length \$s\$, outputs a Bayer matrix that has a side length of \$s\$.
# Rules
* For a side length of \$s\$, you may take the input as \$s\$ or \$log\_2(s)\$. You may assume that \$2\le s\le16\$ and that \$log\_2(s)\$ is an integer. This means you are allowed to hardcode outputs, but in most cases this is not the shortest method.
* The numbers in the output matrix may range from (inclusive) \$0\$ to \$s^2-1\$, \$1\$ to \$s^2\$, \$0\$ to \$\frac{s^2-1}{s^2}\$, or \$\frac{1}{s^2}\$ to \$1\$. For example, for \$s=2\$, all of these are acceptable:
\$
\begin{bmatrix}
0 & 2\\
3 & 1
\end{bmatrix}\$, \$
\begin{bmatrix}
1 & 3\\
4 & 2
\end{bmatrix}\$, \$
\begin{bmatrix}
0 & 0.5\\
0.75 & 0.25
\end{bmatrix}\$, \$
\begin{bmatrix}
0.25 & 0.75\\
1 & 0.5
\end{bmatrix}
\$
* The output matrix may be offsetted or transposed, reflected, rotated, etc. as long as the general pattern is the same. This means that when there is a tie for maximum distance, any of the tied options may be chosen. For example, for \$s=2\$, any matrix with 0 and 1 in opposite corners and 2 and 3 in opposite corners is acceptable.
* Input and output may be in any convenient format.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [Python](https://www.python.org) NumPy, 75 bytes
```
from numpy import*
f=lambda n:n and kron(c_[[0,3],[2,1]]-4j,1j-f(n-1)).imag
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3vdOK8nMV8kpzCyoVMnML8otKtLjSbHMSc5NSEhXyrPIUEvNSFLKL8vM0kuOjow10jGN1oo10DGNjdU2ydAyzdNM08nQNNTX1MnMT06FG6hcUZeaVaKRpGGhqcsHYhkhsIyS2saYmRBvMRQA)
### How?
Recursively expands the pattern by "Kroneckering" it with the 2x2 template. The Kronecker product knows which of the inputs must come together in each cell of the output. Only, it takes the product where we want the sum.
In principle we could address this by exponentiating but that would be numerically unsound.
Instead we use a bit of complex number trickery. Principle:
*Have* a,b,times
*Need* a+b
*Do* (1+ai)x(1+bi) = 1-ab + (a+b)i and use imaginary part of result
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
```
Nest[ArrayFlatten@{{4#,4#+2},{4#+3,4#+1}}&,0,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCTasagosdItJ7GkJDXPobraRFnHRFnbqFYHyNI2BrENa2vVdAx0lGPV/qdFG8f@/69bUJSZVwIA "Wolfram Language (Mathematica) – Try It Online")
Input is \$\log\_2s\$, output is an integer matrix with entries starting from 0. Modified from the recursive formula on [the Wikipedia page for ordered dithering](https://en.wikipedia.org/wiki/Ordered_dithering):
$$M\_{2s}=\begin{bmatrix}4M\_s&4M\_s+2\\
4M\_s+3&4M\_s+1
\end{bmatrix}$$
[Answer]
# JavaScript (ES6), 87 bytes
Based on the recursive formula already pointed out by [Parcly Taxel](https://codegolf.stackexchange.com/a/259635/58563), but using a bitwise construction.
```
n=>[...Array(1<<n)].map((_,y,a)=>a.map(g=(k=n,x)=>k--&&4*g(k,x)|2*(x>>k)+3*(y>>k&1)&3))
```
[Try it online!](https://tio.run/##ZcvRCsIgFMbx@x5EzjEV3Lqcwp4jIg5rk3LpcBETenez7qK77/@D70ZPWod0XR4yxMtYJlOCsUelVJ8SZdBdF/Ck7rQAnEUWhMbSN50Bb4LYKngpGTtwB77mq@GwWetx33LIdTCNrEUsQwxrnEc1RwcTaMTdrzR/8nm9AQ "JavaScript (Node.js) – Try It Online")
### How?
Given \$n\$, we build a square matrix of width \$2^n\$:
```
[...Array(1 << n)].map((_, y, a) =>
a.map(
...
)
)
```
We fill this matrix with a recursive callback function. Because the content of the array we iterate over is not initialized, \$k\$ is undefined on the first call and set to the default value \$n\$. The second argument \$x\$, on the other hand, is well defined right away.
```
g = (k = n, x) => // k = counter, x = horizontal position
k-- && // decrement k; if it was not 0:
4 * g(k, x) | // append 4 times the result of a recursive call
2 * (x >> k) + // set bit #1 if the k-th bit of x is set
3 * (y >> k & 1) // toggle bits #0 and #1 if the k-th bit of y is set
& 3 // ignore the other bits
```
[Answer]
# [Python 3](https://docs.python.org/3/), 93 bytes (@alephalpha)
```
lambda n:[[g(x)/4+g(x^y)/2for y in range(n)]for x in range(n)]
g=lambda n:n and n%2+g(n//2)/4
```
[Try it online!](https://tio.run/##VYxBCoMwFAX3nuJvhHwVQmNWgidRCykxUbBPCS7M6dO4aelqYGDmiOeyo02uH9Nm3i9rCN0weHGx1HXGM7JUbg8UaQUFAz8L8HSb688Uvv8OQAaWUKp8gJQqv9Jd4Fc8Gs1dQUdYcQonVFWBOX0A "Python 3 – Try It Online") Link includes test cases. Takes the size of the matrix as input and returns binary fractions. Explanation: `g` takes the bits of `n` from LSB to MSB and interprets them as base `4` digits starting at the quaternary point e.g. `6 = 110₂ => 0.11₄ = 0.3125 = 0.0101₂`. One set of alternate bits depends only on the row while the other set depends on the bitwise XOR of the row and column; this is the equivalent to the `3*` and `2*` approach of the previous versions.
Previous 104-byte [Python 3.8](https://docs.python.org/3.8/) answer (@xnor):
```
lambda n:[[2*(g:=lambda m:int(f"{m:0{n}b}"[::-1],4))(y)^3*g(x)for y in range(2**n)]for x in range(2**n)]
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPqfZhvzPycxNyklUSHPKjraSEsj3coWKpBrlZlXopGmVJ1rZVCdV5tUqxRtZaVrGKtjoqmpUakZZ6yVrlGhmZZfpFCpkJmnUJSYl56qYaSllacZCxKsQBf8DxLNQ4gaAg2y4lIoKAJbo5GnqfkfAA "Python 3.8 (pre-release) – Try It Online") Link includes test cases. Takes the power of `2` as input and outputs integers.
Previous ~~154~~ 116-byte [Python 3](https://docs.python.org/3/) answer:
```
lambda n:[[2*g(y,n)^3*g(x,n)for y in range(2**n)]for x in range(2**n)]
g=lambda m,n:int(bin(m)[2:].zfill(n)[::-1],4)
```
[Try it online!](https://tio.run/##XYzBCsMgEAXv@QqPrthCTE8L@RJjwdBqBd0EySH2561CodDbMLw3ezleG03VzUuNNq0Pywi1VsLzIgnuU4OzgdsyKywQy5b8kyshCEyX578c/PwNJUkY6OBrIJ5AKzTXtwsxcgKNeBmNvEHtDfo1xuZwYHvuR9eWUD8 "Python 3 – Try It Online") Link includes test cases. Takes the power of `2` as input and outputs integers. Explanation: Lots of bit twiddling.
First row of cells:
```
Col Bin Rev Val Binary
0 000 000 0 000000
1 001 100 32 100000
2 010 010 8 001000
3 011 110 40 101000
4 100 001 2 000010
5 101 101 34 100010
6 110 011 10 001010
7 111 111 42 101010
```
First column of cells:
```
Row Bin Rev Val Binary
0 000 000 0 000000
1 001 100 48 110000
2 010 010 12 001100
3 011 110 60 111100
4 100 001 3 000011
5 101 101 51 110011
6 110 011 15 001111
7 111 111 64 111111
```
Each cell is then the bitwise XOR of the first cell in its row and column.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~20~~ ~~18~~ 14 bytes
```
ḶBUz0Zµ+Ḥ^þḤḅ4
```
[Try it online!](https://tio.run/##y0rNyan8///hjm1OoVUGUYe2aj/csSTu8D4g@XBHq8n/w@1R7ppZjxr3cXH9/2@ko2Cio2Cho2BoBgA "Jelly – Try It Online")
*-4 porting [Neil's Python solution](https://codegolf.stackexchange.com/a/259645/85334)*
Thought something that generates it flat then cuts the rows up at the end might be shorter, but I haven't actually gotten anything like that to work.
```
ḶB Binary digits of each [0 .. n).
U Reverse each
z0Z and right-pad with zeroes to the same length.
µ+Ḥ Multiply each by 3,
Ḥ multiply each by 2,
^þ table XOR,
ḅ4 convert from base 4.
```
[Answer]
# MATLAB/Octave, 72 bytes
```
function B=f(n),if n,S=f(n-1);B=[4*S,4*S+2;4*S+3,4*S+1];else,B=0;end,end
```
[Try it online!](https://tio.run/##bcyxDoIwEAbgnae4xQSwRntlIGm69BVwM5oQbJMmWgytBp8erzBBHP67/274@i62HzNN9u276HoPWtncF8xZ8KxJ/cALqdWlKhtG2aNMU8ydX6V5BMO0Oknj74wy7eBsQoSuDQZsPwCOCLr9mgGebRzcmHkOCrjMdNrkE5/dXXjl/JhXNzqhBJ2e2ZaqxmpDIRFIFC4UrimcKfxH1WO9oQQRgiixUGJNiZlKz@kH)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 18 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ݨ2вí0ζøxs3*δ^εε4β
```
Port of [*@Neil*'s previous Python answer](https://codegolf.stackexchange.com/a/259645/52210).
Outputs the transposed result compared to the challenge description.
[Try it online](https://tio.run/##AScA2P9vc2FiaWX//8Odwqgy0LLDrTDOtsO4eHMzKs60Xs61zrU0zrL//zQ) or [verify all test cases](https://tio.run/##AUMAvP9vc2FiaWX/NcaSTm//w53CqDLQssOtMM62w7h4czMqzrRezrXOtTTOsv99fVpnVc61zrVYw7pYLsKjfX3CuyzCtj//) or [try it step-by-step](https://tio.run/##bY@9SgNREIV7n2LYTjGwaAoRZEFtrJRgIYjCbDLZHdidG@ZOXH0YexubYIJ10i@@0bq5F//A9sx85/A5jzlT1yUXMpvbMSTZyXqV7SRnTh5IDdjAHCDcpvsVSWHlLihKQROo2If/zfP65S9DOC6BxaggjXTOgvr0jRx8LCIxoh7wFIjQ9RrzK5xAw1aCKXLFUkDqt/e0XW3e48u5m@fVD/kY02vl2a/UH@7F/JStYU@Dm8sRGG5BNwUrqd@2xkGNpjymsNG@3f@rI6SD2nkLFjBVV0OOfeUwKMqXcKhYtsthu7jLuu7oEw).
**Explanation:**
```
Ý # Push a list in the range [0, (implicit) input]
¨ # Remove the last character to make the range [0,input)
2в # Convert each integer to binary as lists
í # Reverse each inner list
0ζø # Right-pad each inner list with 0s:
ζ # Zip/transpose; swapping rows/columns,
0 # using 0 as filler character for unequal length rows
ø # Then zip/transpose back
x # Double each inner 1 (without popping the matrix)
s # Swap so the matrix is at the top again
3* # Multiply each 1 by 3
δ # Apply double-vectorized using the two matrices:
^ # Bitwise-XOR them together
ε # Then map over the list of matrices:
ε # Map over each inner matrix:
4β # Convert the current row-list from base-4 to an integer
# (after which the resulting matrix is output implicitly)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~33~~ 29 bytes
```
NθI⊘EθEθ↨E⟦⁰λ⟧↨↨⁻|νι&νι²⊘⊘¹⊘¹
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMjMacsNUXDN7FAo1BHAUo5JRangoWiDXQUcmKhAhDRzLzSYg2nzJLyzOJU/yKNPB2FTE2gAoiAY14KRAQoZATEUNOhlKGmpiZCEMwDAev//03@65blAAA "Charcoal – Try It Online") Link is to verbose version of code. Takes the size of the matrix as input and outputs binary fractions. Explanation: Now uses @alephalpha's trick of converting from base `¼` to reverse the bit pattern.
```
Nθ First input as a number
θ Input number
E Map over implicit range
θ Input number
E Map over implicit range
⟦ ⟧ List of
⁰ Literal integer `0`
λ Inner value
E Map over list
⁻|νι&νι Bitwise XOR with outer value
↨ ² Convert to base `2`
↨ ⊘⊘¹ Interpret as base `¼`
↨ ⊘¹ Interpret as base `½`
⊘ Vectorised halved
I Cast to string
Implicitly print
```
Previous 33-byte version:
```
⊞υ⟦⁰⟧FN«≧×⁴υ≔⁺Eυ⁺κ⁺²κEυ⁺⁺³κ⊕κυ»Iυ
```
[Try it online!](https://tio.run/##TYw/C8IwFMTn9lO88T2IINWtkzh1qBRxE4dYYxuapiXJcxE/e@wfB5e7g9/d1a109SBNjBX7FlnAdXujPH0ODrCwI4cT93flkAjeaVLK8eC9buxZN23Ai@6VF7AXwNMmWRFWhj1Ozfltyd3PMwEdEQn4h4vsZiKgsLVTvbJBPXBu0nr8SSunbcCj9AGZKI8xi5uX@QI "Charcoal – Try It Online") Link is to verbose version of code. Takes the power of `2` as input and outputs integers. Explanation: Another port of @ParclyTaxel's recursive formula.
```
⊞υ⟦⁰⟧
```
Start with a `1×1` matrix for `s=0`.
```
FN«
```
Repeat `s` times.
```
≧×⁴υ
```
Multiply the matrix by `4`. (Fortunately this function fully vectorises on the version of Charcoal on TIO.)
```
≔⁺Eυ⁺κ⁺²κEυ⁺⁺³κ⊕κυ
```
Concatenate copies of the matrix with itself both horizontally and vertically, with each copy offset by a different integer from `0` to `3` appropriately.
```
»Iυ
```
Output the final matrix in Charcoal's default output format for matrices (each element on its own line and rows double-spaced from each other).
[Answer]
# [R](https://www.r-project.org/), ~~65~~ 63 bytes
```
f=function(n)"if"(n,kronecker(matrix(4:1%%4,2),4*f(n-1),"+"),0)
```
[Try it online!](https://tio.run/##FcTBCoAgDADQe58xELZakOYp6GNCHIg0YRj090bv8GwMOeXR1EtTVIIigMrVmuZUs@F9dSsvxsM7FzkQx1lQV08MCxBvNAQ9TYLhb6fxAQ "R – Try It Online")
-2 bytes thanks to pajonk.
Recursive function. Takes \$log\_2(s)\$ as an input and returns the corresponding \$s\times s\$ matrix as output. 4 bytes shorter than using `rbind` and `cbind`.
# [R](https://www.r-project.org/), 67 bytes
```
f=function(n)"if"(n,cbind(rbind(g<-4*f(n-1),g+3),rbind(g+2,g+1)),0)
```
[Try it online!](https://tio.run/##K/r/P802rTQvuSQzP08jT1MpM01JI08nOSkzL0WjCEym2@iaaKVp5Okaauqkaxtr6kCFtY2AXENNTR0Dzf9pGoaaXGkaRiDCWPM/AA "R – Try It Online")
[Answer]
# [PARI/GP](https://pari.math.u-bordeaux.fr), 65 bytes
```
f(n)=matrix(2^n,,i,j,if(n,f(n-1)[-i\-2,-j\-2]+(i%2+j%2*2+1)%4))/4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWNx3TNPI0bXMTS4oyKzSM4vJ0dDJ1snQygaI6QKxrqBmtmxmja6SjmwUkY7U1MlWNtLNUjbSMtA01VU00NfVNoAYpp-UXaeQp2CoY6CgY6ygUFGXmlQD5Sgq6dkACZIumJkQpzG4A)
Takes \$\log\_2(s)\$ and the output ranges from \$0\$ to \$\frac{s^2-1}{s^2}\$.
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 68 bytes
```
n->matrix(n,,i,j,g(i--,j--))
g(i,j)=if(k=i+j,i%2+k%2*2+g(i\2,j\2))/4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYzBCsIwEETvfsUiFLNmF2X14CU9-RlF6SVlU4wlRPBfvARE_Cb_xki9zMxjhnm8pz7peZjK04N73bLnw-cYub30OendRCKlQINRZgrMiIuaKaBTb0anNpA2YsdG1mJr0wmFThA3-__Xyl-TieBgS7AjmJLGbOQUYQncVvE_QMR5XsrsXw)
Takes \$s\$ and the output ranges from \$0\$ to \$\frac{s^2-1}{s^2}\$.
---
# [PARI/GP](https://pari.math.u-bordeaux.fr), 69 bytes
```
f(n)=if(n,matconcat([m=4*f(n--),m+2*o=matrix(2^n,,i,j,1);m+3*o,m+o]))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728ILEoMz69YMGCpaUlaboWN13TNPI0bTOBpE5uYklyfl5yYolGdK6tiRZQSFdXUydX20gr3xYoV5RZoWEUl6ejk6mTpWOoaZ2rbayVD5TOj9XUhBqmnJZfpJGnYKtgoKNgrKNQUJSZVwLkKyno2gEJkE0wpTD7AQ)
Takes \$\log\_2(s)\$ and the output ranges from \$0\$ to \$s^2-1\$.
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 18 bytes
```
r2B:ᵒ{ᵈ:-A2*+ç4£Ed
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FjuKjJysHm6dVP1wa4eVrqORlvbh5SaHFrumLClOSi6GKlqw3JDLiMuEywLCBQA)
Port of [@Neil's Python answer](https://codegolf.stackexchange.com/a/259645/9288). Takes \$s\$ and the output ranges from \$0\$ to \$\frac{s^2-1}{s^2}\$.
```
r2B:ᵒ{ᵈ:-A2*+ç4£Ed
r Range from 0 to s-1
2B Convert to base 2. The least significant digit comes first.
: Duplicate
ᵒ{ Make a table with the following function
ᵈ:- Take the difference between the two arguments
A Absolute value
2* Multiply by 2
+ Add the second argument
ç Prepend 0
4£Ed Convert from base 1/4
```
---
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 21 bytes
```
0UU$ᵑ{4*::3+,$→:→$,ᶻ,
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FnsNQkNVHm6dWG2iZWVlrK2j8qhtkhUQq-g83LZbZ0lxUnIxVOWC5QZchlxGXMYQLgA)
Port of [@Parcly Taxel's Mathematica answer](https://codegolf.stackexchange.com/a/259635/9288). Takes \$\log\_2(s)\$ and the output ranges from \$0\$ to \$s^2-1\$.
```
0UU$ᵑ{4*::3+,$→:→$,ᶻ,
0UU [[0]]
$ᵑ{ Apply the following function n times
4* Multiply by 4
: Duplicate
: Duplicate
3+ Add 3
, Join
$ Swap
→ Increment
: Duplicate
→ Increment
, Join
ᶻ, Zip with join
```
[Answer]
# Java, ~~131~~ 129 bytes
```
n->{int d=1<<n,m[][]=new int[d][d],i=d*d,g,k;for(;i-->0;m[i/d][i%d]=g)for(g=k=0;k<n;)g=4*g|2*(i%d>>k)+3*(i/d>>k++&1)&3;return m;}
```
Port of [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/259638/52210), so will also output a \$2^n\$ by \$2^n\$ sized matrix based on the given \$n\$.
-2 bytes thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##fVA7T8MwEN77K06RQHbTuC1lwnUkBgYGEBJsVQbTuMFN4lSO04cgv72c0yCoEEiWdb7v7nt4LbcyWqf5cVnIuoYHqc37AEAbp@xKLhU8@mfXWCSLBJYEKzCUY7cd4FU76fQSHsGAOJoofvd4KqbzuRmVfkUYtevW0wTPSIt0mI6yUc5XlSVcR1E84eVCjxHWF2kiMuqBTORiwvO54TQT18Ps42pIEI7jnIYzLMe@DMPLKb2ccatcYw2UvD1y72nTvBboqbe2rXQKJQYjz85qky0SSU@hvJC3q8WU67m45joMaYcgB5K6wxMuOGIYxqa/MnfEP@f6Tyol6ux7ja20KL4HAWv8atY4XbBba@WhZrWzSpakH2erQroHuXmp7pGqgij@c6OilCEnoayyd0WtyKTzdgrkBW21uzlz8Q1tZdGoGxz4CgrwfKidKlnVOLbpcgQQMKs2SjqC7vZhEFBWKJO5N0Ij0jGc9WjY9yDojfwmLQzpsXbwH94O2uMn)
**Explanation:**
```
n->{ // Method with integer parameter and int-matrix return-type
int d=1<<n, // Integer `d`, set to 2 to the power `n`
m[][]=new int[d][d], // Result-matrix, of size `d` by `d`
i=d*d, // Index-integer, starting at `d` squared
g,k; // Temp-integers, uninitialized
for(;i-->0 // Loop `i` in the range (d*d,0], over all cells:
; // After every iteration:
m[i/d][i%d]= // Set the [y,x]'th matrix-value to:
g) // Value `g`
for(g=k=0; // Reset both `g` and `k` to 0
k<n;) // Inner loop `k` in the range [0,n):
g= // Set `g` to:
4*g| // Append 4 times the previous `g`;
2*(i%d>>k)+ // Set bit #1 if the k'th bit of `x` is set
3*(i/d>>k++&1) // Toggle bits #0 and #1 if the k'th bit of `y` is set
// (and increase `k` by 1 afterwards with `k++`)
&3; // Ignore the other bits
return m;} // Return the resulting matrix after the loops
```
[Answer]
# TI-Basic, ~~68~~ 60 bytes
```
Input N
identity(1→[A]
0Ans
For(I,1,N
4Ans
augment(augment(Ans,Ans+3[A])ᵀ,augment(Ans+2[A],Ans+[A])ᵀ→[A]
Fill(1,[A]
End
Ans
```
Takes input as \$log\_2(s)\$.
-8 bytes thanks to [MarcMush](https://codegolf.stackexchange.com/users/98541/marcmush).
] |
[Question]
[
Inspired by this building (United States Air Force Academy Cadet Chapel, Colorado)
[](https://i.stack.imgur.com/sDxIp.png)
Your task is simple, given a positive integer `n`, output the spiked building to size `n`
# Testcases
```
1
->
^
/|\
/.|.\
/..|..\
_______
2
->
^ ^
/|\/|\
/.|..|.\
/..|..|..\
__________
7
->
^ ^ ^ ^ ^ ^ ^
/|\/|\/|\/|\/|\/|\/|\
/.|..|..|..|..|..|..|.\
/..|..|..|..|..|..|..|..\
_________________________
```
Trailing spaces are allowed
You are to output the string with newlines
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 80 bytes
```
n=>` ^
/|\\
/.|.\\
/..|..\\
___`.replace(/.[_|^]./g,'$&'.repeat(n))+'____'
```
[Try it online!](https://tio.run/##FYtBDsIgFAX3PcVbGIFUP7rWehGxlCBtaAg0beOKuyNdzeRl3mx@ZrOrX/ZrTF9Xxq7E7jUA6NEAMivVQFKmSkmVh2itB1rdEox1XNJb5/5Dcrqw05kduzM7j0K0rIaalTGt4B4d7g94PCtvVdpWwKa4peAopImP3NeHiioyUf4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 81 bytes
```
lambda n:f" {' ^'*n}\n "+'/|\\'*n+'\n /'+(d:='.|.'*n)+rf'\
/.{d}.\
_'+'_'*3*-~n
```
[Try it online!](https://tio.run/##DchBCoMwEAXQvacY3PwkQ5OFixbBmwwVSwgttNMQ3Ijaq6dZvpe39fnV4ZZLTZPU9/J5xIV0TD3tILrD6SlK1DPCIdLIaA5gE8cJ/vCtLJcE6YLf4@mlm8GY4QZ3@WnN5aWrSeZqbf0D "Python 3.8 (pre-release) – Try It Online")
Thanks @UnrelatedString for -3 bytes, by teaching me about the `rf` string literal.
Thanks @AidenChow for -1 byte, by adding another f-string.
Thanks @tsh for -1 byte.
Wow, looks like this has become a bit of a community effort.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 30 bytes
```
»ε¥»₄τ2?»øƒ≈»₇τẋṀf`|^/\.`τ\_+§
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCu861wqXCu+KChM+EMj/Cu8O4xpLiiYjCu+KCh8+E4bqL4bmAZmB8Xi9cXC5gz4RcXF8rwqciLCIiLCI1Il0=)
Modified port of the Jelly answer.
```
»ε¥»₄τ # [2, 14, 19, 3]
2 Ṁ # Insert at position 2...
»øƒ≈»₇τ # [74, 125, 99]
? ẋ # Repeated <input> times
f # Flatten the whole thing
`|^/\.`τ # Decompress each from base with the key "|^/\."
\_+ # Append an underscore to each
§ # Transpose, fill and join by newlines.
```
Old version below because I thought it was quite elegant.
# [Vyxal](https://github.com/Vyxal/Vyxal) `C`, 42 bytes
```
` ^
/|
.|
.|
__`øM↵*`
/
/.
__`øṀ↵½Zƛ÷$j
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJDIiwiIiwiYCBeXG4vfFxuLnxcbi58XG5fX2DDuE3ihrUqYCBcbiBcbi9cbi8uXG5fX2DDuOG5gOKGtcK9Wsabw7ckaiIsIiIsIjQiXQ==)
This is quite elegant but somewhat messy approach. I'm unsatisfied with the last bit, `vj` should work but it doesn't.
The first bit produces the string
```
^
/|\
.|.
.|.
___
```
Then repeats each row of that by the input.
Then, it creates
```
/\
/..\
____
```
by mirroring half of each line, and inserts the previous into that. Finally, the whole thing is centered.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“\ɓ^‘ẋ“£×“Œ¥‘jṃ“|/.\^””_;Ɱz⁶ṚY
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5yYk5PjHjXMeLirG8g5tPjwdCB1dNKhpUCxrIc7m4G8Gn29GKCSuUAUb/1o47qqR43bHu6cFfn//39DcwA "Jelly – Try It Online")**
### How?
```
“\ɓ^‘ẋ“£×“Œ¥‘jṃ“|/.\^””_;Ɱz⁶ṚY - Main Link: integer, N
“\ɓ^‘ - Code-page indices = [92, 155, 94]
ẋ - repeat N times
“£×“Œ¥‘ - Code-page indices = [[2, 17], [19, 4]]
j - join -> [2, 17, 92, 155, 94, ..., 92, 155, 94, 19, 4]
“|/.\^” - list of characters = "|/.\^"
ṃ - convert to base 5 using "|/.\^" in place of the digits 12340
Ɱ - map across these lists of characters with:
”_; - concatenate to an '_' character
z⁶ - transpose with space characters as filler
Ṛ - reverse
Y - join with newlines
- implicit print
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
_/¶_./¶×“ ∧σ¿⊘=8G℅H«⊙”N_.\¶_\⟲
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREMpXj8mL14PSChpWnNBxEIyc1OLgTJ6IOH4mpqaOJASvZgYoCIdBc@8gtISv9LcpNQiDU24HqBqkHx8TAzInKD8ksSSVA1N6///jf/rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
_/¶_./¶
```
Print the first two columns.
```
ד ∧σ¿⊘=8G℅H«⊙”N
```
Print the middle columns repeated the appropriate number of times.
```
_.\¶_\
```
Print the last two columns.
```
⟲
```
Rotate to orient the output correctly.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~124~~ ~~91~~ ~~90~~ 88 bytes
```
lambda n:[print((' /_ /._'+' /.._^|||_ \.._'*n+' \._ \_')[i::5])for i in range(5)]
```
[Try it online!](https://tio.run/##DYpBCoMwEEWv8neTVNBFkULAk5g4RGzagI4S3BRy93QWj//4vOt3f095tjT5tsdj3SLEzVfJchtDAAZWeqaOdHpeaq0Mr0YP0U9VA3gmO2fnxmDTWZCRBSXK521GG1oyL9v@ "Python 3 – Try It Online")
[Answer]
# APL+WIN, ~~88~~ 73 bytes
Prompts for spikes.
Original
```
l←5 2⍴¯10↑'//.__'⋄c←5 3⍴' ^ /|\.|..|.___'⋄r←5 2⍴¯10↑'\ .\__'⋄⊃⊂[2]⍎'l,',((2×⎕)⍴'c,'),'r'
```
A simpler iindexing solution
```
m←5 7⍴' ^ /|\ /.|.\ /..|..\_______'⋄m[;⍳2],m[;(3×⎕)⍴2+⍳3],m[;6 7]
```
[Try it online! Thanks to Dyalog APL Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tfy6Qaapg/qh3i7qCgkKcAgjo18SASL0avRggCaT0YuIhQP1Rd0tutPWj3s1GsTpAhobx4elAAzWB2o20gaLGYFEzBfPY/0DTuf6ncRlyqSuoc6VxGUFpcwA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 69 bytes
```
->n{' ^
/|\
/.|.\
/..|..\
_______'.lines.each{|l|l[2,3]*=n}*''}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6vWl1BQSFOgUtBQb8mhktBX69GL4ZLXw9IAel4CFDXy8nMSy3WS01MzqiuyanJiTbSMY7Vss2r1VJXr/1fUJSZV6KQFm0c@x8A "Ruby – Try It Online")
Lambda tacking *n* that multiplies inner substring *n* times for each line of the spike.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~42~~ ~~41~~ 35 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Y17•₅œ •₅вIи19Y·)˜"^|/.\"Åв'_δšζRJ»
```
-6 bytes porting [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/243977/52210)
[Try it online](https://tio.run/##yy9OTMpM/f8/0tD8UcOiR02tRycrQBgXNnle2GFoGXlou@bpOUpxNfp6MUqHgaLq8ee2HF14bluQ16Hd//@bAAA) or [verify the first 10 test cases](https://tio.run/##yy9OTMpM/R/iquSZV1BaYqWgZO@nw6XkX1oC4en8jzQ0f9Sw6FFT69HJChDGhU1@F3YYWkYe2q55eo5SXI2@XozSYaCoevy5LUcXntsW5HVo93@dQ9vs/wMA).
[See the previous revision for the original 42 and 41 bytes approaches.](https://codegolf.stackexchange.com/revisions/243931/2)
**Explanation:**
```
Y # Push 2
17 # Push 17
•₅œ • # Push compressed 6021919
₅в # Convert it to base-255 as list: [92,155,94]
Iи # Repeat this list the input amount of times
19 # Push 19
Y· # Push 4 (2 doubled)
) # Wrap the stack into a list
˜ # Flatten
"^|/.\"Åв "# Convert it to custom base-"^|/.\"
# (basically base-length, and then index into the string)
δ # Map over each inner list:
'_ š '# Prepend a "_" to each
ζ # Zip/transpose; swapping rows/columns, with a space " " as
# default filler
R # Reverse the list of lists
J # Join each inner list together to a string
» # Join by newlines
# (after which the result is output implicitly)
```
[See this 05AB1E tip of mine (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•₅œ •` is `6021919` and `•₅œ •₅в` is `[92,155,94]`.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~64~~ 63 bytes
```
.+
$&*$( ^)¶ $&*$(/|\)¶ /$&*$(.|.)\¶/.$&*$(.|.).\¶__$&*3*___
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS0FFTUtFQ0EhTvPQNgUIR78mBsTRB3P0avQ0Yw5t09eD8/SA3Ph4INdYKz4@/v9/Qy4jLnMA "Retina – Try It Online") Link includes test cases. Explanation: Just an application of Retina 1's string repetition operator. Note that repetition has higher precedence than concatenation so the string to be repeated has to be grouped (except in the case of repeating three `_`s which is achieved via a second repetition).
[Answer]
# [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate), 61 bytes
```
( ^ ){$~1}
(/\|\\){$~1}
/((.\|.){$~1})\\
/.$3.\\
_{#3+4}
```
[Attempt This Online!](https://staging.ato.pxeger.com/run?1=m72qKDU9NS-1KLEkdcGCpaUlaboWN20VFDQU4hQ0q1XqDGu5gBz9mJqYGBhXX0NDL6ZGD8LVjInh0tdTMdYD0vHVysbaJrUQQ6BmLY42joUyAQ)
### Explanation
`$~1` is the input number, and `{$~1}` repeats something that many times. So:
```
( ^ ){$~1}
```
Two spaces, followed by `^` N times.
```
(/\|\\){$~1}
```
Two spaces, followed by `/|\` N times.
```
/((.\|.){$~1})\\
```
`/`, followed by `.|.` N times (and capture that result as group 3), followed by `\`.
```
/.$3.\\
```
`/.`, followed by the contents of group 3 again, followed by `.\`.
```
_{#3+4}
```
`_` repeated len(group 3) + 4 times.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~76~~ 66 bytes
```
{`0:+?[4 4#" / /. \\. \\";2;,/(x,3 4)#" /..^||| \\.."],'"_"}
```
[Try it online!](https://ngn.codeberg.page/k/#eJxdTtsKwjAMfc9XlPqg4my0mww30A9xXrfuwnSbdIJg/Xcj4igNJycPOScnefQ6LaLZdhewYMQZY0gQjCUJETGPZezh5On5LJiSAIU4GGO+e8H33pgf+RsgZ0tqSR0CIJR93+kIMW0zVbTXXOj+nNbqmZbnplAibW94fyjdV22jUQb+Wq7w8qiuWdUUc91VtdKwhPkG6IUDEZoEKNmIBCjfCJrHXwGA/AsH7SC3HLbp5wstn4PhjIPhqgMrxIGd6dQHDOxkXA==)
* `?[a;2;b]` use [`splice`](https://k.miraheze.org/wiki/Splice) to insert `b` into `a` at position `2`
+ `4 4#" / /. \\. \\"` the initial array, representing the "sides" of the spiked building
+ `,/(x,3 4)#" /..^||| \\.."` `x` copies of the spikes
* `?[;;],"_"` append a `"_"` to each slice
* ``0:+` transpose the above, and print to stdout
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 46 bytes
```
FlRsX,4.:"/\"J'|WR'.X,3PE'^AE'_X7{(l2,5)X:aPl}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhY39dxygoojdEz0rJT0Y5S81GvCg9T1InSMA1zV4xxd1eMjzKs1cox0TDUjrBIDcmohuqCaF0ebxEKZAA)
### Explanation
First, we generate this list
```
[" ^"
" /|\"
" /.|.\"
"/..|..\"
"_______"]
```
as follows:
```
RsX,4.:"/\"J'|WR'.X,3PE'^AE'_X7
,3 ; Range(3): [0;1;2]
'.X ; Repeat . that many times: ["";".";".."]
'|WR ; Wrap | in each of those strings: ["|";".|.";"..|.."]
"/\"J ; Insert each of those strings between / and \:
; ["/|\";"/.|.\";"/..|..\"]
PE'^ ; Prepend "^" to the front of that list
AE'_X7 ; and append "_______" to the end:
; ["^";"/|\";"/.|.\";"/..|..\";"_______"]
,4 ; Range(4): [0;1;2;3]
sX ; Repeat space that many times: ["";" ";" ";" "]
R ; Reverse: [" ";" ";" ";""]
.: ; Concatenate those two lists itemwise:
; [" ^";" /|\";" /.|.\";"/..|..\";"_______"]
```
Then we loop over each line, repeat the center section, and print the result:
```
Fl...{(l2,5)X:aPl}
Fl { } ; For each line l
... ; in the above list:
(l ) ; The section of l
2,5 ; at indices range(2,5) i.e. [2;3;4] (modular 0-based indexing)
X: ; string-repeat in place
a ; (program argument) times
Pl ; Print (the modified version of) l with a trailing newline
```
[Answer]
# [Lua](https://www.lua.org), 92 bytes
```
print(([[ ^
/|\
/.|.\
/..|..\
]]):gsub(".[_|^].",("%1"):rep(...))..('_'):rep(4+3*...))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m704pzRxwYKlpSVpuhY3YwqKMvNKNDSioxUUFOIUuBQU9GtiuBT09Wr0Yrj09YAUkI6N1bRKLy5N0lDSi46viYvVU9LRUFI1VNK0Kkot0NDT09PU1NPTUI9XhwiYaBtrgQUhdkCtWhxtFAtlAgA) I feel like it can go a bit lower but don't want to play with it right now. Basically? a port of tsh's answer but with the underscores outside the initial string.
[](https://i.stack.imgur.com/Zlnk0.png)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 70 bytes
```
.+
$&$*1¶ $&$*2¶ /$&$*3\¶/.$&$*3.\¶__$&$*4__
1
^
2
/|\
3
.|.
4
___
```
[Try it online!](https://tio.run/##K0otycxL/P9fT5tLQUVNRcvw0DYFMMMIyNAHMYxjDm3T1wOz9IDM@HgQ0yQ@nsuQS0EhjsuIS78mhsuYS69Gj8uEKz4@/v9/Q6CgOQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Since Retina 0.8.2 can only repeat characters, placeholder digits are used for the four different building parts which are then substituted in afterwards.
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 66 bytes
```
ri:R;SSSa"^ "R*NSS"/|\\"R*NS'/".|.":QR*'\N"/."QR*".\\"N'_"___"R)*
```
[Try it online!](https://tio.run/#cjam) I haven't golfed for a while, and longer since CJam, so this probably has significant optimizations available, but I was in the mood to try something. It basically just constructs the result line by line, with a couple minor optimizations by saving the size as a variable, saving the `".|."` construction as a variable since we re-use it, and using 3(n+1)+1 instead of 3n+4 to construct the bottom row.
] |
[Question]
[
For a given number `n`, output an strictly decreasing array whose sum is `n` and its lexicographical order is the smallest for any possible outputs
Smallest lexicographical order means that for or sum `n=9` the following strictly decreasing arrays are possible: `[[9],[8,1],[7,2],[6,3],[5,4],[6,2,1],[5,3,1],[4,3,2]]`. Putting these in lexicographical order: `[[4,3,2],[5,3,1],[5,4],[6,2,1],[6,3],[7,2],[8,1],[9]]`, the first `[4,3,2]` will be the final output
## Testcases
```
4 -> [3,1]
9 -> [4,3,2]
10 -> [4,3,2,1]
20 -> [6,5,4,3,2]
```
You may assume that `n>0` and that you are allowed to output any human readable form of characters to represent the array of numbers
Note that a *strictly decreasing* array has *no* duplicates so the array cannot be `[1,1,1...]`
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 38 bytes
* -7 bytes by [att](https://codegolf.stackexchange.com/users/81203/att) and [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)
```
f=n=>n?[p=.5+(n+n)**.5|0,...f(n-p)]:[]
```
[Try it online!](https://tio.run/##BcHBDkRADADQX3FsDY1NuBjlQ8RBrJGKtJMhe/Lvs@@d62@9tyTxqdW@e86BlUed5sjUOVCnWJbUvU1FRAG0jrj085KDJRD@eBm4bbw4h5vpbddOlx0gVRFAEH3@Aw "JavaScript (Node.js) – Try It Online")
That is, find out the smallest \$x\$ where
$$ \sum\_{i=1}^{x}i= \frac{(x+1)\cdot x}{2}\ge n $$
which is
$$ x=\left\lceil\frac{\sqrt{8n+1}-1}{2}\right\rceil $$
As [att](https://codegolf.stackexchange.com/users/81203/att) and [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) suggested in the comments. This formula could be simplified into
$$ x=\left\lfloor\sqrt{2n}+\frac{1}{2}\right\rfloor $$
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~7~~ 6 bytes
```
Ṅ~Þush
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuYR+w551c2giLCIiLCI0Il0=)
-1 thanks to EmanresuA reminding me that `~` exists.
## Explained
```
Ṅ~Þush
Ṅ # From all integer partitions of the input,
~ # Keep only partitions where:
Þu # The uniqufied version equals the partition (this makes sure that only partitions without duplicates are kept)
sh # Sort the list and take the first item
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~39~~ 37 bytes
```
f@n_:=#<>f[n-#]&@Round@√(2n)
f@0=""
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78/z/NIS/eylbZxi4tOk9XOVbNISi/NC/F4VHHLA2jPE2uNAcDWyWl/wFFmXkl0cq6dmkOQDV1jkVFiZV1Rgb/AQ "Wolfram Language (Mathematica) – Try It Online")
Returns a `StringJoin` of integers.
---
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 37 bytes
```
Last@Pick[s=Subsets@Range@#,Tr/@s,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexuMQhIDM5O7rYNrg0qTi1pNghKDEvPdVBWSekSN@hWEc5Vu1/QFFmXkm0sq5dmgOQW@dYVJRYWWdk8B8A "Wolfram Language (Mathematica) – Try It Online")
Returns the partition in increasing order. For decreasing order, +4 bytes: [Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexuMQhIDM5O7rYVlnbUDe4NKk4taTYISgxLz3VQVknpEjfoVhHOVbtf0BRZl5JtLKuXZoDkFvnWFSUWFlnZPAfAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~19~~ ~~16~~ ~~13~~ ~~11~~ 10 bytes
```
hf{ITS_M./
```
[Try it online!](https://tio.run/##K6gsyfj/PyOt2jMkON5XT///fyMDAA "Pyth – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 107 bytes
```
x=>{var y=new List<int>();while(x!=0){y.Add((int)Math.Ceiling((Math.Sqrt(x*8+1)-1)/2));x-=y[^1];}return y;}
```
[Try it online!](https://tio.run/##XY5PS8NAEMXPzacY62XX2NT0JKQJSFEQ6smCh1IhbkYzsN21m22bUPLZ4ySCf3qaN7x5v3mqmqiKuoe9UXMy/hqWVPleZRnsIIWuTrPTIXfQpAaPv66QybEkjaK@SG/kqYnuikIIduRT7stogaTJfAgxbM8750V9dRvGchLL6UzKpJ6kzfo13iStQ793Bpqk7ZJgOi1wa4F8FLxbBz0Qcq4RJzzmKcxuWIShDE7B6MWRx76Q2ImckUHLcXUJhcUKjPXwyWjf8OgpymqNypM1VQS@pAqOpHUUHCwV8IOarzLxeG/2W3T5m0Ze/wSHrwsGWI3REBHj9Zgfj7gr5qoEseLquAUy/2Ijzp0HYQzh93HIcqC0Z/QlGT7c9F7bfQE "C# (Visual C# Interactive Compiler) – Try It Online")
I think i can save a few bytes somewhere here, but i can't quite figure it out. Haskell tricks with unrolling multiple arguments comes to mind but it's been too long since i golfed properly to remember it (Lost access to old account when school email expired feelsbad). feel free to improve this and take the points. Uses the same approach as the Javascript answer, but without the JS list comprehension tricks. In other words, find the lowest value such that the sum from 1 to n is greater than x, push that to the list, subtract n from x and repeat until x is 0.
From my early tests, using Floor and the third formula is the same number of characters in C#, though i couldn't really get it working.
This can save a bunch of characters by taking an empty list as a parameter and editing/filling it in place (removes the need for the "new" and the return, effectively making the outer function a one-liner. Further, it could be made recursive, which removes the while loop, though idk if that actually saves anything), but i'd guess that's blocked by loophole rules.
making the list a list of double will save 2 bytes but the results are then doubles, and this raises the possibility of floating point nonsense and potentially printing out 3.0000000004 or something similar.
**Edit:** Uses the new Index object and it's ^ operator, introduced in C# 8.0. Not normally a fan b/c it makes the code more obtuse, but it's perfect for code golf. ^1 is shorthand for the last element in the list.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Læí.ΔOQ
```
[Try it online](https://tio.run/##yy9OTMpM/f/f5/Cyw2v1zk3xD/z/3xIA) or [verify all test cases](https://tio.run/##ATEAzv9vc2FiaWX/dnk/IiDihpIgIj95wqn/TMOmw60uzpRPwq5R/30s/1s0LDksMTAsMjBd).
**Explanation:**
```
L # Push a sum in the range [1, (implicit) input]
æ # Pop and get the powerset of this
# (which is already in the correct order)
í # Reverse each inner list to make the inner lists in decreasing order
.Δ # Keep the first inner list that's truthy for:
O # Where the sum
Q # Equals the (implicit) input
# (after which this found result is output implicitly)
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
↔ḟo=¹ΣṖḣ
```
[Try it online!](https://tio.run/##ASoA1f9odXNr/23igoH/4oaU4bifbz3Cuc6j4bmW4bij////WzQsOSwxMCwyMF0 "Husk – Try It Online")
[Husk](https://github.com/barbuz/Husk) has no 'integer partitions' built-in, but since the array must be strictly decreasing (no duplicates) we can build it by selecting a subset of `n..1` that sums to `n`.
If we do it the other way around (selecting from `1..n`), then the first 'hit' is already the right set, and we just need to reverse the order of its elements to make it decreasing.
```
ḣ # start with range 1..input:
Ṗ # get all subsequences;
↔ḟo # now get the first element that satisfies:
Σ # its sum
=¹ # equals the input;
↔ # and finally reverse it.
```
[Answer]
# [Haskell](https://www.haskell.org/), 45 bytes
```
f 0=[]
f n=[a:f(n-a)|a<-[1..n],[a]>f(n-a)]!!0
```
[Try it online!](https://tio.run/##TcrBCsIwEATQe75iCx4UNmWTRqFi@iNhDwsaLNZV1KP/HtEczG3ezJzleTktSykZKCY2GTQm2ee1Wtm85WCT63tlTMJTLbnrqFxlVohwvBm4P2Z9wQoyhBZjC0etPJUAdoI0oGMz/mLAAT0bR399R1@9wy3Wxwc "Haskell – Try It Online")
*f(n)* searches, starting from *a* = 1 , a list to append to *a* :
* lexicographically less than *a*,
that sums to *n* (with *a*).
Such list is *f( n-a )*.
[Answer]
# [R](https://www.r-project.org/), 46 bytes
```
f=function(n)if(n)c(p<-round((2*n)^.5),f(n-p))
```
[Try it online!](https://tio.run/##DckxCoAwEATAr6TcEyMasBH9ik3k4JpNOJL3xzTTjA99hnbmZoWgmE4y6h29dH5AWijvdso6I1aRocVhwRiOK@1S3digsDk/ "R – Try It Online")
Reproducing [tsh](https://codegolf.stackexchange.com/users/44718/tsh) resolution in R.
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics math.unicode`, 56 bytes
```
[ dup 1 [a,b] all-subsets [ Σ = ] with filter infimum ]
```
[Try it online!](https://tio.run/##LcoxCsIwFIfxvaf4H0BLKy4qzuLiIk6lQ5q@2kebNCYviIin8T5eKRZ0@/j4dUrL5NPlfDwdthjIWxphlPS5V/ZK4dd6Mg1bNUvW/xUt66klBLpFsnqWzpPIw3m2gl2WPbHGBmWBVYFXqtBGhxKVWjQ11DguQ2wCSUCFzxt71Liz9Oh4FPJg27GJBnUyyiGI0kOevg "Factor – Try It Online")
* `1 [a,b] all-subsets` Powerset of *n..1*
* `dup ... [ Σ = ] with filter` Select the subsets that sum to the input
* `infimum` Get the smallest one
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 30 bytes
```
.+
$*
(?=(\G1|1\1)*1)1\1?
$.&¶
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLS8PeViPG3bDGMMZQU8tQE0jZc6noqR3a9v@/CZcll6EBl5EBAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
(?=(\G1|1\1)*1)1\1?
```
Repeatedly match the smallest number whose triangular number exceeds the remainder, calculated as one more than the largest number whose triangular number is strictly less than the input.
```
$.&¶
```
Convert to decimal and list each number on its own line.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 45 bytes
Inspired by the [answer](https://codegolf.stackexchange.com/questions/243754/lexicographically-smallest-decreasing-integer-partition/243759#243759) of user `tsh`. -9 bytes thanks to user `att`.
```
lambda n:n*[p:=round((2*n)**.5)]and[p]+f(n-p)
```
[Try it online!](https://tio.run/##DcpBCsIwEAXQvaeYXTMxLbUqaKBeJGYRCcGC/RlCXUjp2WPf@slveWecb1JqGp/1E@ZXDAQL7cSOJX8RlRo0WOvuyj4gOvHHpNAK15QLgSaQu5i7OfVm6L09EEmZsKjUrNiofdC6d94arn8 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ŒṗUQƑƇṂ
```
[Try it online!](https://tio.run/##ASYA2f9qZWxsef//xZLhuZdVUcaRxofhuYL/w4dLKVn//zQsOSwxMCwyMA "Jelly – Try It Online")
The only real difference from lyxal's Vyxal solution is that Jelly's integer partitions builtin generates them in nondecreasing order, requiring them to be reversed before finding the minimum.
```
ŒṗU Nonincreasing integer partitions.
Ƈ Filter to those which
Ƒ are unchanged by
Q uniquification.
Ṃ Take the minimum.
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
NθWLΦθ‹Σ…·⁰κθ«≧⁻ιθ⟦Iι
```
[Try it online!](https://tio.run/##FYo9C8IwFADn5ldkfIEIIm6dRBAKrUgdxSGWkDxMXz9eUgfxt8f2xrvrvJm7wYScKxpTvKb@ZWeYVCk@HoOVUFty0cMFQ9yClrVlhnvqoaIuJMbFtoachb2Wb6W0nNSK/IqiMeOJGR216HyEBimxlrgdpShuM1KEx9lwBFTPVf1yPh7ybgl/ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `n`.
```
WLΦθ‹Σ…·⁰κθ«
```
Count how many triangular numbers starting from `0` are less than `n` and repeat until this becomes zero.
```
≧⁻ιθ
```
Subtract that number from `n`.
```
⟦Iι
```
Output that number on its own line.
] |
[Question]
[
For the context of this challenge, a *matched group* is a digit \$n\$, followed by \$n\$ more matched groups. In the case of \$n = 0\$, that's the whole matched group. Digits only go up to 9.
For example, 3010200 is a valid matched group, as:
```
3 # 3, capturing three elements...
0 # a 0 (group 1)
1 # a 1 (group 2), capturing...
0 # a 0
2 # And a 2 (group 3), capturing...
0 # a 0
0 # and another 0.
```
A *fully matched number* is simply any valid matched group.
The list begins:
```
0, 10, 110, 200, 1110, 1200, 2010, 2100, 3000, 11110, 11200, 12010, 12100, 13000, 20110, 20200, 21010, 21100, 22000, 30010, 30100, 31000, 40000
```
(As usual, these are hand-generated :P)
Your task is to implement this sequence.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") and [sequence](/questions/tagged/sequence "show questions tagged 'sequence'") rules apply.
## Testcases
These are zero-indexed. Last testcase thanks to tjjfvi.
```
0 -> 0
1 -> 10
4 -> 1110
6 -> 2010
9 -> 11110
13 -> 13000
18 -> 22000
22 -> 40000
64 -> 500000
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~29~~ 25 [bytes](https://github.com/abrudz/SBCS)
```
1+⍣{1∧.=⌊\⌽+\1-⌽⍎¨⍕⍺}⍣⎕⊢0
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@h9qPexdWGjzqW69k@6umKedSzVzvGUBdIPertO7TiUe/UR727aoFqHvVNfdS1yACk638alwFXGpchEJsAsRkQW4L4xiDCAkgYGYGETQA "APL (Dyalog Unicode) – Try It Online")
`⍣⎕⊢0`: Starting at 0, iterate input times:
`1+⍣{ ... }`: Increment until the new value is fully matched.
The number `⍺` is fully matched if:
`⍎¨⍕⍺`: base-10 digit list
`1-⌽`: 1 minus each digit in the reversed list
`+\`: cumulative sums of this list
`⌊\⌽`: minimum of each suffix
`1∧.=`: All minima are equal to `1`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
DCSÐƤ«\ỊƑø#
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//RENTw5DGpMKrXOG7isaRw7gj////NjU "Jelly – Try It Online")
Port of ovs's APL solution. Full program.
```
ø# Starting from 0, collect the first [input] integers satisfying:
DC Subtract each decimal digit from 1.
SÐƤ Take the sum of each suffix.
«\ Are the cumulative minima
ỊƑ all equal to 1?
```
`ø#` works by placing `#` in a niladic chain with no leading nilad, supplying it `0` as a starting value (note that it takes the number of values to gather from the last argument to the program, rather than anything within the link). The condition that the cumulative minima of the suffix sums are all 1 is equivalent to that the sum of the entire list is 1 and no suffix sum is less than 1.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 31 bytes
```
W1i:SNUQ$AL:{aRA_1+B.0MEa}M P*i
```
Outputs fully matched numbers indefinitely. [Try it online!](https://tio.run/##K8gs@P8/3DDTKtgvNFDF0ceqOjHIMd5Q20nPwNc1sdZXIUAr8/9/AA "Pip – Try It Online")
### Explanation
Observe that every fully matched number (other than 0) can be generated from a shorter fully matched number by taking a digit from the shorter number, incrementing it, and inserting a 0 after it: for example, `1**0** -> 1**10**`; `**1**0 -> **20**0`. If we apply this procedure to every f.m. number of length N, we generate a list of all f.m. numbers of length N+1; but the list will contain some duplicates.
```
W1i:SNUQ$AL:{aRA_1+B.0MEa}M P*i
i is 0 (implicit); we're going to use it to store
the list of all f.m. numbers of a given length
W1 While 1 (infinite loop):
P*i Print each element of i
{ }M Map this function to each f.m number in i:
MEa Map this function to each index and corresponding
digit of the number:
a The number
RA_ Replace at the current index
1+B with 1 plus the digit
.0 concatenated to 0
$AL: Flatten the resulting list
UQ Uniquify
SN Sort in numeric order
i: Assign back to i
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 53 bytes
```
0.step{|x|i=0;x.digits.all?{|d|0<i+=1-d}&&i==1&&p(x)}
```
[Try it online!](https://tio.run/##KypNqvz/30CvuCS1oLqmoibT1sC6Qi8lMz2zpFgvMSfHvrompcbAJlPb1lA3pVZNLdPW1lBNrUCjQrP2/38A "Ruby – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 76 bytes
Inspired by [ovs's Ruby answer](https://codegolf.stackexchange.com/a/238399/16766).
```
n=0
while 1:
i=t=1
for d in`n`:t*=i>0;i+=int(d)-1
if t>0==i:print n
n+=1
```
[Try it online!](https://tio.run/##DcnBCoAgDADQ@75ix0oC7WjMb/Fg4iCmyCD6@tX1vfFq63KYCXl4Gt8XhgjIpBQAa59YkCVLjroRJ3@yIxZdyrr/zxU1eSKOY/6KAiiOgtkH "Python 2 – Try It Online")
### Explanation
For each number `n`, we loop over each digit `d` in its string representation. Let `i` begin at 1; at each digit, add that digit to `i` and subtract 1. Then for a number to be fully matched, `i` should never drop below 1 until after the last digit, when it should be exactly 0.
```
d: 2 0 1 0
i: 1 2 1 1 0
```
The `for` loop on the fourth line performs these calculations, tracking whether `i` is always greater than 0 in `t`. After the loop, if `t` is still 1 and `i` is 0, we print the number.
[Answer]
# TypeScript Types, 295 bytes
```
//@ts-ignore
type a<T,N=[]>=T extends`${N["length"]}`?N:a<T,[...N,0]>;type b<T,N="1",M=[]>=N extends`${M["length"]}`?T:b<T extends`${infer C}${infer T}`?b<T,C>:0,N,[...M,0]>;type M<I,J=[],N=[]>=b<`${N["length"]}`>extends""?I extends J["length"]?N["length"]:M<I,[...J,0],[...N,0]>:M<I,J,[...N,0]>
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgDkBeAbQF0A+W8w9AD3HUQBNIAAwAkAb2r0ARABte8cAAtJjAL6CA-NQBcZKvQB0h6pQAMLANy4ChAEYUatSQEZJlALIMWtah268BIqJuUrKI8kqqGuRaduxcPPxCYrCIAGboqIQAwirJaRmE5GrqsZRZzFomNJQGhm6mFlZEbqQAkpQAUp4OTKx2gRIycorKaszx-pCSkuqtvgkChB0hwxGaK2EjjFot7bX6HQ01hvrGZhW7ncdGDcyY2PhE5CaEtIQtJszmmCCEfwB66ge1nITle71ITi+P2Af0IgOBTwATOCWkjob8AUCmoUAMyo0i4jGwrGYIA)
Works for 0, 1, 2, and 3, and hits the recursion limit after that.
---
# TypeScript Types, 319 bytes
```
//@ts-ignore
type a<T,N=[]>=T extends`${N["length"]}`?N:a<T,[...N,0]>;type b<T,N="1",M=[]>=N extends`${M["length"]}`?T:b<T extends`${infer C}${infer T}`?b<T,C>:0,N,[...M,0]>;type M<I,J=[0],N=[]>=I extends 0?"0":b<`${N["length"]}0`>extends""?I extends J["length"]?`${N["length"]}0`:M<I,[...J,0],[...N,0]>:M<I,J,[...N,0]>
```
[Try It Online!](https://www.typescriptlang.org/play?#code/PTACBcGcFoEsHMB2B7ATgUwFDgJ4Ad0ACAQwB4AVAGgDkBeAbQF0A+W8w9AD3HUQBNIAAwAkAb2r0ARABte8cAAtJjAL6CA-NQBcZKvQB0h6pQAMLANy4ChAEYUatSQEZJlALIMWtah268BIqJuUrKI8kqqGuRaduxcPPxCYrCIAGboqIQAwirJaRmE5GrqsZRZzFomNJQGhm6mFlZEbqQAkpQAUgxmDkysrb4JAoQm6pImkjGkgRIycorKKiaCzPH+kJKS6gNriYQdIfMR6jOHYQuqy1ot7bX6HQ01hvrGZhU3nU9GDcyY2PhEcgmQi0QgtEzMcyYECEWEAPXU-2s5CcILBpCckOhwFhhARSMBACY0S1CViYfDEU1CgBmEmkGnknGUgmFAAs9LZTNx+Op5AArPT+dyWXyAGz0sUivFUgGFADs9Pl0t5cvIAA56eqVYigA)
Works for 0-8.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 14 bytes
```
λfḂ⌐¦ḂKv↓1=Π;ȯ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu2bhuILijJDCpuG4gkt24oaTMT3OoDvIryIsIiIsIjEwIl0=)
Takes an integer `n` and returns first `n` elements of the sequence.
-1 thanks to @lyxal
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 62 bytes
```
K`0
"$+"{`$
¶
/¶/{s`.+
2*$($.(*__)¶
+T`d`_d`[1-9]0(?=.*$)
¶0¶
```
[Try it online!](https://tio.run/##K0otycxLNPz/3zvBgEtJRVupOkGF69A2Lv1D2/SrixP0tLmMtFQ0VPQ0tOLjNYHi2iEJKQnxKQnRhrqWsQYa9rZ6WiqaQA0GQLn//w2NAQ "Retina – Try It Online") No test suite due to the way the program uses history. Outputs the `n`th fully matched number. Explanation:
```
K`0
```
Replace the input with zero.
```
"$+"{`
```
Repeat the script `n` times.
```
$
¶
```
Append a newline to make a working area to verify fully matched numbers.
```
/¶/{`
```
Repeat while the working area contains a newline.
```
s`.+
2*$($.(*__)¶
```
Increment the current value and duplicate it into the working area, deleting any previous content.
```
+T`d`_d`[1-9]0(?=.*$)
```
Attempt to reduce the working area to a single `0`; any zero after a non-zero digit can be removed and the preceding digit decremented.
```
¶0¶
```
If the current value was fully matched then delete the working area, needed to avoid cluttering up the output, but also causing the inner loop to terminate.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 13 bytes
```
¥1mödm¬Go←+dN
```
[Try it online!](https://tio.run/##ASIA3f9odXNr/@KGkTIw4oKB/8KlMW3DtmRtwqxHb@KGkCtkTv// "Husk – Try It Online")
Inspired by [DLosc's](https://codegolf.stackexchange.com/a/238405/95126) and [ovs's](https://codegolf.stackexchange.com/a/238399/95126) answers.
```
mö N # for all natural numbers:
d # get the decimal digits,
Go←+ # subtract one, & get the cumulativ sum;
# now we want those with a final zero, and
# no preceding zero:
m¬ # logical not of all elements (zeros become 1s)
d # convert digits to decimal number;
¥1 # finally output whenever the answer is 1.
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~70~~ 69 bytes
```
filter(0#)[0..]
a#x=a!divMod x 10
a!(d,m)|d<1=a==m|c<-a-m+1=m<=a&&c#d
```
[Try it online!](https://tio.run/##BcFBCoMwEADAu69YCYjSRpJ79gm@oC2yZLUNydqgUjz49saZD21xSqlEfJY5pH1aW6O6h@n7V0XqQKo5/IYvwwHWVFS3fJfuZGeREOX0TpOWm0VxSE3jFRehsACCUB5GyGtYdojl7@dE761on/MF "Haskell – Try It Online")
* Thanks to @Unrelated String for saving 1 by using filter instead of list comprehension.
* *k* is an infinite sequence
We start from the end checking if the last digit(m) doesn't consume more groups than available `a` *a-m>=0*
Then we remove `m` groups and add 1 *a=a-m+1* and move backwards.
At the end we must have exactly one group *a-m+1==1*
```
3010200
m a a=a-m+1
0 0 1
0 1 2
2 2 1
0 1 2
1 2 2
0 2 3
3 3 1
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
µ1NS-.sO.s€ßΘP
```
Given \$n\$, it outputs the 0-based \$n^{th}\$ value.
Uses the legacy version of 05AB1E, which outputs `N` implicitly after a while-loop. In the new version of 05AB1E, this program required an additional trailing `}N` to work.
Port of [*@ovs*' APL answer](https://codegolf.stackexchange.com/a/238398/52210).
[Try it online](https://tio.run/##MzBNTDJM/f//0FZDv2BdvWJ/veJHTWsOzz83I@D/fzMA) or [verify outputs until it times out on TIO](https://tio.run/##yy9OTMpM/f8/2tAvWFev2F@v@FHTmsPzz80IeNQw@f9/AA).
**Explanation:**
```
µ # While the counter_variable is not equal to the (implicit)
# input-integer (the counter_variable is 0 by default):
N # Push the current 0-based loop-index
S # Convert it to a list of digits
1 - # Subtract each from 1
.s # Get the suffices of this list
O # Sum each inner suffix-list
.s # Get the suffices of this list again
ۧ # Get the minimum of each inner suffix-list
Θ # Check for each that they're equal to 1
P # And check if this is truthy for all of them
# (if this is 1: implicitly increase the counter_variable by 1)
# (after the while-loop, the resulting index is output implicitly)
```
[Answer]
# JavaScript (ES6), 71 bytes
Returns the n-th term, 1-indexed.
Based on [ovs' Ruby answer](https://codegolf.stackexchange.com/a/238399/58563).
```
n=>eval("for(k=-1;n-=!(i=g=n=>n?(i=-~i-n%10)<1|g(n/10|0):i-1)(k);)++k")
```
[Try it online!](https://tio.run/##FYtBDoIwEADvvGIlmOymqVITL8LqV2gQSC3ZGjBcAL9e622SmXnZxc7t5N4fLeHZxZ6j8L1b7Ih5Hyb0rE0lmg/oeOCk5JFIf52WoympNtuAcjblVtLNaUPoqSKlfE7xvwswmAoEaobLNYFSBGsG0AaZw9idxjBgY7FYZafUFmuPQntD2R5/ "JavaScript (Node.js) – Try It Online")
[Answer]
# Python3, 182 bytes:
```
f,n=lambda x,c=[1]:f(x,c[:-2]+[c[-2]-1])if c[-1]==0 and len(c)>1 else(len(c)==1 and c[0]==0if not x else f(x[1:],c+[x[0]])),0
while(n:=n+1):
if f(list(map(int,str(n-1)))):print(n-1)
```
[Try it online!](https://tio.run/##JUxBDsMgDLv3FTkGlUplu0xI7COIA6OgItG0apHWvZ5lnS@2Yzvbp84r3R/b3lqSZIpfXpOHUwZjldMJWVk93Fxvg2UalBM5AWvljBnB0wQlEgbxVBDLEfHvjFFXFuz46/GE1grnVQH@apV2MvT25NwJIcfuPecSkbShXgndAU8SlnxUXPyGmao86o40KMHQ286Xy7X2BQ)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
≔⁰ηFN«⟦Iη⟧≦⊕ηW∨⁻Ση⊖Lη⊙Iη‹Σ…Iημμ≦⊕η
```
[Try it online!](https://tio.run/##fY0/C8IwFMTn9lNkfIEKdXYqdSlYFRzFIcZnU0heS/4oRfzsMdCim8sNd/e7k0pYOQgdY@Vc3xGUBVN8k98Hy6ChMfh9MFe0wDl75dnR9uThXAvnQfFLKmatGBe0IWnRIHm8zSPZU/UaGRwstD0FB6dgElawLX6bsEPqvEo2T0FFEyzjBduhm5F6khprNYy/zPBZOPvz/45xXcbVQ38A "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` numbers (could be trivially modified to output the 0-indexed `n`th number for the same byte count). Explanation:
```
≔⁰η
```
Start with `0`.
```
FN«
```
Loop `n` times.
```
⟦Iη⟧
```
Output the found fully matched number.
```
≦⊕η
```
Try the next number.
```
W∨⁻Ση⊖Lη⊙Iη‹Σ…Iημμ≦⊕η
```
Keep trying the next number until a fully matched number is found. This is identified as a number having a digit sum of one less than its length but none of whose prefixes are a fully matched number.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 15 bytes
```
λf⌐ṘKṠ₍tg1=A;ȯt
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLOu2bijJDhuZhL4bmg4oKNdGcxPUE7yK90IiwiIiwiMCJd)
Mmm yes apl porting. Outputs nth fully matched number 0 indexed
] |
[Question]
[
**Challenge**
Giving a valid arithmetic sum with some missing numbers, output the full expression.
Example:
```
1#3 123
+ 45# => + 456
-------- --------
579 579
```
**Input**
* Expression format can be an array `["1#3", "45#", "579"]`, a string `"1#3+45#=579"`, or 3 inputs `f("1#3","45#","579")`
**Output**
* Same as input
* You don't need to output the result
**Notes**
* The missing numbers are going to be represented using `#` or any other constant non-numeric character you want
* Assume result wont have a missing number
* Assume Input/Output consist in 2 terms and a final result
* Assume both term > 0 and result >= 2
* There might be multiple solutions. You can output anyone as long as the sum result match
**Test Cases with possibly outputs (pretty format)**
```
#79 879
+ 44# => + 444
-------- --------
1323 1323
5#5 555
+ 3#3 => + 343
-------- --------
898 898
# 1
+ # => + 1
-------- --------
2 2
### 998
+ ### => + 1 PD: there are a lot of possible outputs for this one
-------- --------
999 999
123 123
+ # => + 1
-------- --------
124 124
9 9
+ #6 => + 46
-------- --------
55 55
#123651 1123651
+ #98# => + 7981
------------ -----------
1131632 1131632
```
---
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~22~~ 16 bytes
```
{Ṣ∧Ị∋|}ᵐ²ịᵐ.k+~t
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/rhzkWPOpY/3N31qKO7pvbh1gmHNj3c3Q2k9bK160r@/49WMlQwVtJRUDIxVQBRpuaWSrH/owA "Brachylog – Try It Online")
-6 bytes thanks to @Fatelize
## Explanation
```
{Ṣ∧Ị∋|}ᵐ²ịᵐ.k+~t
{ }ᵐ² # for each letter in each string
Ṣ∧Ị∋ # if " " return a digit; else input
| #
ịᵐ # cast each string to number
k+ # the sum of all but the last one
~t # is equal to the last one
. # output that list
```
[Answer]
# JavaScript (ES6), ~~74~~ 57 bytes
Takes input as `(a)(b)(result)`, where ***a*** and ***b*** are strings with `.` for unknown digits and ***result*** is an integer. Returns an array of 2 integers.
```
a=>b=>F=(c,n)=>`${r=[c,n]}`.match(`^`+[a,b])?r:F(c-1,-~n)
```
[Try it online!](https://tio.run/##bY7NDoIwEITvPgbx0EbYpBSQmhRvvATBtFTwJ9gaIF6MvnotjSfxsrPJfjOzV/mQoxou9ynS5tjajlvJi4YXJUcq1JgXYv0ceOX2@iXgJid1RuIgNpUMmxrvh12JVETC6K2xVUaPpm@hNyfUoQC2LMAoSBJwQmhMMV79ICmkM0KBOslZviQAZvdXGGNLgsTUE3NJnCzv/gnI3EzSP/nOnqXEMyz3IYSSjMYY2w8 "JavaScript (Node.js) – Try It Online")
### Commented
```
a => b => // a, b = term patterns (e.g. a = ".79", b = "44.")
F = (c, // c = expected result (e.g. 1323)
n) => // n = guessed value of b, initially undefined
`${r = [c, n]}` // we coerce r = [c, n] to a string (e.g. "879,444")
// if n is still undefined, this gives just c followed by a comma
.match(`^` + [a, b]) // we coerce [a, b] to a string, prefixed with "^" (e.g. "^.79,44.")
? // this is implicitly turned into a regular expression; if matching:
r // return r
: // else:
F(c - 1, -~n) // decrement c, increment n and do a recursive call
```
[Answer]
## Matlab, 143 134 132 119 115 bytes
```
function[m]=f(x,y,r),p=@(v)str2num(strrep(v,'#',char(randi([48,57]))));m=[1,1];while sum(m)-r,m=[p(x),p(y)];end;end
```
-4 bytes thanks to @Luismendo
[Try it Online](https://tio.run/##FYzBCoMwEER/RfCQXdgebBVbJND/kBxCjCg0UVZN9evT7cAw8GDe4nabfM7jEd0@L7EPRo9w0kWMtOo3JNx2vscjgCz7FRKpUpGbLAPbOMzQ109qWoOSLui@osp032n@@GKTV8Abk@AVThHChabzcfg3j6Cq8qGoUHUjyqJpX5h/)
---
Pretty big and pretty stupid. It simply replaces all `#` with random digits until it finds the correct ones.
[Answer]
# [R](https://www.r-project.org/), ~~67~~ 51 bytes
Rock simple and scales horribly, just grep all the sum combinations. Use "." for unknown digits. It won't find the same answer as test case number 4, but it will give **a** possible answer, which follows the letter of the rules as given.
-16 bytes by grepping after forming the output and replacing `paste` with the `?` operator.
```
function(x,y,z,`?`=paste)grep(x?y,1:z?z:1-1,v=T)[1]
```
[Try it online!](https://tio.run/##PYzBCoMwDIbve4rRk4VYSGOdkUlfYrcxcAwdu6g4N9SX72oru/w/@fIlo2vPqWs/3WN69V0ywwIr1Lauhvt7auRzbIZktgtgudq1xBThW13kFW@uTYQ6sQCRZconkiYhD54aZQQcBSnaquAiYrVNIfQOVEShmDlA1PT3UGfR5IDyLY3Zj72YGwwLLqKOhDn55@4H "R – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 32 bytes
```
F²⊞υ0W⁻ζΣIυ≔E⟦θη⟧⭆κ⎇⁼μ#‽χμυ←Eυ⮌ι
```
[Try it online!](https://tio.run/##FY7BCoJAEIbvPsWglxE2sESwPEV0SxDrFh0WW90lXXPXNerlt3FOw/D93/yN5KYZee99OxrAXQyVsxIdgzAJ4yL4SNULwFJpZ/HH4OoGPHE7o4tp4Git6jSW/I33iYF8EDEbpbv18mJwE0Zz88Xz5HhvcSBtFMYMaq6f44DbhPaBRAwcPasoOePhItqZwWqgGrVYhLECFVGF91mUBWmUBvk@95ul/wM "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
F²⊞υ0
```
Push two string `0`s to the predefined empty list `u` to get the while loop going.
```
W⁻ζΣIυ
```
Repeat while the sum of casting the values in `u` to integer is not equal to the desired result.
```
≔E⟦θη⟧
```
Create an array of the two inputs and map over it.
```
⭆κ⎇⁼μ#‽χμυ
```
Replace each `#` with a random digit and assign the result back to `u`.
```
←Eυ⮌ι
```
Print the result right justified. (Left justified would be just `υ` for a 4-byte saving.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 bytes
```
ØDṛċ¡V€)ŒpḌð€ŒpS⁼¥ƇḢ
```
[Try it online!](https://tio.run/##y0rNyan8///wDJeHO2cf6T60MOxR0xrNo5MKHu7oObwByAYygx817jm09Fj7wx2L/v//H62ubGhkbGZqqK6joK5saaGsHvvf0NDY0MzYCAA "Jelly – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands) (legacy), ~~23~~ 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[²³«εð9ÝΩ:}²gôJDO¹Q#
```
-3 bytes thanks to *@Emigna*.
Unknown digits are spaces (). Input order should be: expected result; longest string; shortest string.
[Try it online](https://tio.run/##ATwAw/8wNWFiMWX//1vCssKzwqvOtcOwOcOdzqk6fcKyZ8O0SkRPwrlRI///MTEzMTYzMgogMTIzNjUxCiA5OCA).
**Explanation:**
```
[ # Start an infinite loop
²³« # Take the second and third inputs, and merge them together
# i.e. " 79" and " 4 " → " 79 4 "
ε } # Map each character to:
ð : # Replace a space with:
9ÝΩ # A random digit in the range [0,9]
# i.e. " 79 4 " → ['3','7','9','2','4','3']
# i.e. " 79 4 " → ['5','7','9','7','4','4']
²g # Get the length of the second input
# i.e. " 79" → 3
ô # And split it into two numbers again
# i.e. ['3','7','9','2','4','3'] and 3 → [['3','7','9'],['2','4','3']]
# i.e. ['5','7','9','7','4','4'] and 3 → [['5','7','9'],['7','4','4']]
J # Join each list together to a single number
# i.e. [['3','7','9'],['2','4','3']] → [379,243]
# i.e. [['5','7','9'],['7','4','4']] → [579,744]
D # Duplicate this list
O # Sum the list
# i.e. [379,243] → 622
# i.e. [579,744] → 1323
¹Q# # If it's equal to the first input: stop the infinite loop
# (and output the duplicate list implicitly)
# i.e. 1323 and 622 → 0 (falsey) → continue the loop
# i.e. 1323 and 1323 → 1 (truthy) → stop the loop and output [579,744]
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~81~~ 74 bytes
*-7 bytes thanks to nwellnhof!*
```
{first {try S/\=/==/.EVAL},map {$^a;S:g[\#]=$a[$++]},[X] ^10 xx.comb('#')}
```
[Try it online!](https://tio.run/##JcfLCoJAFIDh/TzFwSOpjGhH0zKZRYt27YQIvMAUGYGSjAWK@OzT7Vv9f3dVTazbERY1CNBTfVf9E6anGiHzC@EL4Xv74@4wu63sYDIrmWbbW15gKUyZm5yXs5ufSqhoCcPgXR7t2bbQcmbdyxFqu29eqnNS9j@DAuSrCEW0TgxHwwdSEMYRMQ4/mGyQCfZNopDiMHgD "Perl 6 – Try It Online")
Anonymous code block that takes input as a string containing an arithmetical expression e.g. "12#+45#=579". Substitutes each `#` with possible permutations of digits, substitutes the`=` with `==` and finds the first valid result.
### Explanation:
```
{ # Anonymous code block }
first # Find the first of:
^10 # The range of 0 to 9
xx.comb('#') # Multiplied by the number #s in the code
,[X] # The cross-product of these lists
map # Map each crossproduct to:
{$^a;.trans: "#"=>{$a[$++]}} # The given string with each # translated to each element in the list
{try S/\=/==/.EVAL}, # Find which of these is true when = are changed to == and it is eval'd
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 bytes
```
{'#'⎕R{⍕?10}t}⍣{⍎⍺}t∘←
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pdWf1R39Sg6ke9U@0NDWpLah/1LgZy@h717qotedQx41HbhP//gSo8/YEsA640IEmMHq40BXVTc0tbQ2VjbRNTZXUQ39DQ2NDM2MhW2dDI2MzUUFvZ0gIiYWlpaausrKwNxGA@UAmIow4A "APL (Dyalog Unicode) – Try It Online")
[Answer]
# Java 10, ~~203~~ ~~198~~ 193 bytes
```
(a,b,c)->{int A=0,B=0,l=a.length();for(a+=b,b="";A+B!=c;A=c.valueOf(b.substring(0,l)),B=c.valueOf(b.substring(l)),b="")for(var t:a.getBytes())b+=t<36?(t*=Math.random())%10:t-48;return A+"+"+B;}
```
[Try it online.](https://tio.run/##fZJBT4NAEIXv/opxicmubEkppRZxNe3Ng3rwaDws221F6dbA0MSY/vY6i3ggGkPYLPnmvckM71Xv9eh19XY0lW4auNOl@zwBKB3aeq2NhXv/CfCIdek2YHh/0bK/FPKWaje2BiNyKj2c0NGgxtLAPThQcORaFtKI0fUn2cJCjeWS3krpqLJugy9c5OtdzXWoClkoxvJFuDxVJl8oE@111dqHNS@ipi2ariUnrRDk8Tf1zLsI77nXNeCljjYWlx9oGy5EESq8SmY3HM/VncaXqNZutdsSOYvHlziazvPaYls7WISMnmV@OOZ@qPe2qGiofrb9rlzBltbVb@TpGbT43hX1Qc6Ci4xJNp0GTMbJJOmWM2TBnywNUmJJkDA5z@ZDWRB4mT@zLBugeJJ4RH6T6QB0jWZMpunQigSzNPYwm3tZnMSzZDKsIRqPiWW//mw3fVf1Xx766Hw0aLfRrsXonUqwctxFpg9FyCghLPzJzuH4BQ)
**Explanation:**
```
(a,b,c)->{ // Method with 2 Strings & integer parameters and String return-type
int A=0,B=0, // Result-integers, starting both at 0
l=a.length(); // Length of the first String-input
for(a+=b, // Concat the second String-input to the first
b=""; // Reuse `b`, and start it as an empty String
A+B!=c // Loop as long as `A+B` isn't equal to the integer-input
; // After every iteration:
A=c.valueOf(b.substring(0,l)),
// Set `A` to the first String-part as integer
B=c.valueOf(n.substring(l)),
// Set `B` to the second String-part as integer
b="") // Reset `b` to an empty String
for(var t:a.getBytes())
// Inner loop over the characters of the concatted String inputs
b+=t<36? // If the current character is a '#':
(t*=Math.random())%10
// Append a random digit to `b`
: // Else (it already is a digit):
t-48; // Append this digit to `b`
return A+"+"+B;} // After the loop, return `A` and `B` as result
```
[Answer]
# C# .NET, ~~225~~ ~~220~~ 196 bytes
```
(a,b,c)=>{int A=0,B=0,l=a.Length;for(a+=b,b="";A+B!=c;A=int.Parse(b.Substring(0,l)),B=int.Parse(b.Substring(l)),b="")foreach(var t in a)b+=(t<36?new System.Random().Next(10):t-48)+"";return(A,B);}
```
Port of [my Java 10 answer](https://codegolf.stackexchange.com/a/171486/52210).
(I'm very rusty in C# .NET golfing, so can defintely be golfed..)
-3 bytes implicitly thanks to *@user82593* and [this new C# tip he added](https://codegolf.stackexchange.com/a/171513/52210).
-29 bytes thanks to *@hvd*.
[Try it online.](https://tio.run/##bZFRb8IgEMff/RQ3@gIpNtbazq7iokv25BYzl@yZImoTpQmg22L87A60ZnHzgYPwu///uEOYtqi1PIo1Nwamul5qvtm3AIzlthIw@zZWbqLnrRIDY3WllhQue6UsBeyjW2QIC2BHzGlJBWHDvbuDEevQsVtrxqOJVEu7Kha1xjxkJS0ZQsUoHN8xUYyYy46mXBuJy2i2Lc8lsFMS4hxuU8@8C3GekosV3nEN1j0LOClDhu0gyR6V/Lw08cbVvN5gEr3KL4vjDnmw7V6fhO4dWtqtVnhEx6Q4HAGK1u8IdnU1hxdeKUz8YADepbEYBfc5oqjXCxCNk25Cin8suMnSIHUsCRJE@3n/WhYEXuZjnudXKO4mHjm/bu8KnApliKbptZUTZGnsYd73sjiJs6R7yjn8be4kOQ8VOG0Opf9VEE3PzQifamXqtYw@dGXlpFISL5ofDxEwQKFoKhyOPw)
**Explanation:**
```
(a,b,c)=>{ // Method with 2 string & int parameters and int-tuple return-type
int A=0,B=0, // Result-integers, starting both at 0
l=a.Length; // Length of the first string-input
for(a+=b, // Concat the second string-input to the first
b=""; // Reuse `b`, and start it as an empty string
A+B!=c // Loop as long as `A+B` isn't equal to the integer-input
; // After every iteration:
A=int.Parse(b.Substring(0,l)),
// Set `A` to the first string-part as integer
B=int.Parse(b.Substring(l)),
// Set `B` to the second string-part as integer
b="") // Reset `b` to an empty string
foreach(var t in a)
// Inner loop over the characters of the concatted string inputs
b+=(t<36? // If the current character is a '#':
new System.Random().Next(10)
// Use a random digit
: // Else (it already is a digit):
t-48) // Use this digit as is
+""; // And convert it to a string so it can be appended to the string
return(A,B);} // After the loop, return `A` and `B` in a tuple as result
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~121~~ ~~155~~ ~~152~~ 149 bytes
```
import re
def f(i,k=0,S=re.sub):s=S('#','%s',i)%(*list('%0*d'%(i.count('#'),k)),);print(s)if eval(S('=','==',S('\\b0*([1-9])','\\1',s)))else f(i,k+1)
```
[Try it online!](https://tio.run/##JY3dboMwDIXv@xSRIpSYZBUhoEEnP0V3N3bRn6BFpQXhdNKenhlqyZb1nXPs6S/9jA@/LPE@jXMSc9hdQy96He0NC3vEOezpeYYD4VErqazKSNkImc6HSEmrrMivKtNxfxmfj7RawN4ALHxMc2RAEHsRfk@D5jxyHnnw2nXnItdf7q39BqZd55QlAAgDhdd742CR4jNQEpcTBdr1fP29NVUl0fnSKxBSNBuoNrAaalkbLz02bcM6G@qaQeVRMBHbCSOxXLVXSW5nuJGXcvkH "Python 3 – Try It Online")
*+34 New solution with regex to circumvent the fact that python doesn't support numbers with leading zeroes.*
*-3 thanks to @Jonathan Frech*
---
**The old solution doesn't work if # is the first character in any number (because eval doesn't accept leading zeroes) and is therefore invalid :(**
```
def f(i,k=0):
s=i.replace('#','%s')%(*list('%0*d'%(i.count('#'),k)),)
print(s)if eval(s.replace('=','=='))else f(i,k+1)
```
[Try it online!](https://tio.run/##RY3LCoMwEADvfkUghN3VINonLezHiCZ0MWgwaaFfn1p66HUYZuI7P9blWMrkvPIoduaO7pVKLO3mYhhGh6DBgklABusgKSOYrp7AoLTj@lzyVyA7E1mqVNxkJ4nEK/caAqZ/hvcMMxC5kNxv1vRUPEJ/0M1JX/h8vQGVDw "Python 3 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~228~~ ~~213~~ ~~203~~ ~~172~~ 170 bytes
**-15** Bytes thanks to *@ceilingcat*. I've never used `index` before.
**-10** Bytes thanks to *@Logem*. Preprocessor magic
refactored call to `exit(0)` with puts as parameter.
```
char*c,*p[9],k;main(i,v)int**v;{for(i=X[1],35))||X[2],35))?p[k++]=c,main(*c=57,v):k;!c*i--;)47==--*p[i]?*p[i]=57:Y[1])+Y[2])^Y[3])?main(i,v):exit(puts(v[2],puts(v[1])));}
```
[Try it online!](https://tio.run/##PY3LbsIwFES/BWXj69gLx4RHLCubfkQiy5Wiy@sqECJILaTSX8d1KWIzOouZMyj3iDHiobtwFHx0ay96c@poYCQC0DBxHsz37nxhZBunvNAlwP3euOIf69H1ee4tiueIoy2XaVj1ZoacpDQwX1orZVKTr5@ZGlWbVJC3yQKfrdMe6vdntb3RxMav6crC38uLUh/A/MQYM1XoRalitl5lUSmtFrp44O7Y7a9RfrS2m87EQsLGMrQ0bLY3Fn4B "C (gcc) – Try It Online")
[Answer]
# PHP, 112 bytes
lame brute force solution
```
for(;$s=$argn;eval(strtr($s,['='=>'==','#'=>0]).'&&die($s);'))for($k=$n++;$k;$k=$k/10|0)$s[strpos($s,35)]=$k%10;
```
takes string as input, stops at first solution. Run as pipe with `-nR` or [try it online](http://sandbox.onlinephpfunctions.com/code/b89fdcd901365dc04bf9c90ad46ef25a7aa6553b).
[Answer]
# Powershell, 91 byte
The script finds all solutions. The total number of iterations is 10 power the number of characters `#`. The recursion depth is equal to the number of characters `#`.
```
filter f{$h,$t=$_-split'#',2
if($t){0..9|%{"$h$_$t"}|f}elseif($h-replace'=','-eq'|iex){$h}}
```
Test script:
```
filter f{$h,$t=$_-split'#',2
if($t){0..9|%{"$h$_$t"}|f}elseif($h-replace'=','-eq'|iex){$h}}
@(
,('1#3+45#=579','123+456=579')
,('#79+44#=1323','879+444=1323')
,('5#5+3#3=898','505+393=898 515+383=898 525+373=898 535+363=898 545+353=898 555+343=898 565+333=898 575+323=898 585+313=898 595+303=898')
,('#+#=2','0+2=2 1+1=2 2+0=2')
,('9+#6=55','9+46=55')
,('123+##=124','123+01=124')
,('#123651+#98#=1131632','1123651+7981=1131632')
,('##+##=2','00+02=2 01+01=2 02+00=2')
,('##+##=99','00+99=99 01+98=99 02+97=99 03+96=99 04+95=99 05+94=99 06+93=99 07+92=99 08+91=99 09+90=99 10+89=99 11+88=99 12+87=99 13+86=99 14+85=99 15+84=99 16+83=99 17+82=99 18+81=99 19+80=99 20+79=99 21+78=99 22+77=99 23+76=99 24+75=99 25+74=99 26+73=99 27+72=99 28+71=99 29+70=99 30+69=99 31+68=99 32+67=99 33+66=99 34+65=99 35+64=99 36+63=99 37+62=99 38+61=99 39+60=99 40+59=99 41+58=99 42+57=99 43+56=99 44+55=99 45+54=99 46+53=99 47+52=99 48+51=99 49+50=99 50+49=99 51+48=99 52+47=99 53+46=99 54+45=99 55+44=99 56+43=99 57+42=99 58+41=99 59+40=99 60+39=99 61+38=99 62+37=99 63+36=99 64+35=99 65+34=99 66+33=99 67+32=99 68+31=99 69+30=99 70+29=99 71+28=99 72+27=99 73+26=99 74+25=99 75+24=99 76+23=99 77+22=99 78+21=99 79+20=99 80+19=99 81+18=99 82+17=99 83+16=99 84+15=99 85+14=99 86+13=99 87+12=99 88+11=99 89+10=99 90+09=99 91+08=99 92+07=99 93+06=99 94+05=99 95+04=99 96+03=99 97+02=99 98+01=99 99+00=99')
) | % {
$s,$e = $_
$r = $s|f
"$($e-eq$r): $r"
}
```
## Powershell, 'Assume both term > 0' is mandatory, 110 bytes
```
filter f{$h,$t=$_-split'#',2
if($t){0..9|%{"$h$_$t"}|f}else{$a,$b,$c=$_-split'\D'
$_|?{+$a*+$b*!(+$a+$b-$c)}}}
```
] |
[Question]
[
Your challenge is to write a program, function, etc. that calculates if the passed string is "in order". That means that the characters of the string have character codes that are in order from smallest to largest. The smallest char code must be the first. By that I mean lowest unicode codepoints to highest. It doesn't matter what code page you language uses.
You must return one value if the input is "in order" and another if it is not. The values must be distinct, but there is no other restriction on the output values. For example, you may print/return/output `true` for `!1AQaq¡±` (in order) and `false` for `aq!QA`. The two distinct values don't need to be truthy or falsy or anything like that, just two distinct values. Repeated strings (eg. `aa`) are in order.
You only need to support up to unicode `U+007E` (`~`) (ascii 126)
However, the characters of your program must itself be in order. Good luck and happy [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")ing!
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
.o
```
[Try it online!](https://tio.run/nexus/brachylog2#@6@X//@/UmJqZn6pEgA "Brachylog – TIO Nexus")
## Explanation
```
.o
. Assert that {the input} equals the output of the last command in the program
o Sort {the input}
```
As a full program, an assertion failure gives `false.`, any successful run that doesn't violate any assertions gives `true.`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
Ṣ⁼
```
[Try it online!](https://tio.run/nexus/jelly#@/9w56JHjXv@//@vlJiamV@qBAA "Jelly – TIO Nexus")
## Explanation
```
Ṣ⁼
Ṣ Sort {the input}
⁼ Compare that to {the input} for equality of the whole structure
```
`⁼Ṣ` also has the right functionality ("compare the input to the sorted input"), so it was just a case of running the two programs on themselves to figure out which was in order (I certainly don't have the Unicode codepoints of this part of Jelly's weird character set memorized).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
GGS\a
```
Outputs `0` if input is in order, `1` otherwise.
[Try it online!](https://tio.run/nexus/matl#@@/uHhyT@P@/ekhGZrFCcUlRZl66ApCVl1@ikJmnkF@UklqkDgA "MATL – TIO Nexus")
### Explanation
This computes the modulus of (the code points of) each char from the input with that at the same index in the sorted input. The input is in order if and only if all results are `0`.
For example, consider the input string `BCD!`. Sorting it gives `'!BCD`. The arrays of code points are respectively `[66 67 68 33]` and `[33 66 67 68]`. Computing the moduli gives `[0 1 1 33]`, so the input is not in order. Note how some results can be `0` even if the values were not the same (here that happens at the first position), but that cannot happen in *all* entries unless the input is in order.
```
G % Push input string
GS % Push input string and sort it
\ % Modulus, element-wise. This gives all zeros iff the input was in order
a % Any: gives 1 if any entry is non-zero. Implicitly display
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~3~~ 2 bytes
```
{å
```
Thanks to Kevin for cutting out 33% of my source code!
[Try it online!](https://tio.run/##MzBNTDJM/f@/@vDS//9dgCQA "05AB1E – TIO Nexus")
Explanation:
```
There used to be a D here for 'Duplicate stack'
but we now use the same input twice implicitly
{ Sort the copy
å Check if the sorted copy is a substring of the original
This will only return 1 if the original input is sorted, 0 otherwise.
```
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 2 bytes
```
Sq
```
[Try it online!](https://tio.run/nexus/pyke#@x9c@P9/cCEA "Pyke – TIO Nexus")
```
S - sorted(input)
q - ^ == input
```
[Answer]
# [2sable](https://github.com/Adriandmen/2sable), 2 bytes
```
{Ê
```
[Try it online!](https://tio.run/nexus/2sable#@199uOv/fyPbQ4sPLT@85PDSw9sA "2sable – TIO Nexus")
**Explanation**
```
{ # sorted input
Ê # not equals (implicit input)
```
Outputs **0** if it is order, else **1**.
[Answer]
# Pyth, 2 bytes
```
<S
```
`False` means sorted, `True` means unsorted.
[Test suite](https://pyth.herokuapp.com/?code=%3CS&test_suite=1&test_suite_input=%22%3CS%22%0A%22%211AQaq%22%0A%22blah%22%0A%22aq%21QA%22&debug=0)
This was fairly nontrivial to come up with. The most obvious solution to this problem, without the restricted source, is `SI`, invariant under sorting. But that's not sorted. Then I thought of `qS`, which implicitly uses the input variable twice, checking if it's equal to its sorted self. But while `q < s`, `q > S`, so this didn't work either. But `<` comes before `S`, and the only way that the sorted version can not be less than the original is if the original was sorted, since the sorted version is the lexicographically minimal permutation of the elements.
[Answer]
# [CGL (CGL Golfing Language)](https://codepen.io/programmer5000/pen/zwYrVd), 4 bytes
```
-:Sc
```
Explanation:
```
- Decrement the stack counter so the current stack is where input is put
: Split the first element of the current stack (input) into an array of single strings, make that the next stack, and increment the stack counter
S Sort the current stack
c Compare the current stack and the one before, push that to the next stack and increment the stack counter
(implicit) Output the first element of the current stack, true if in order, false if not.
```
] |
[Question]
[
Using you language of choice, write the shortest function/script/program you can that will identify the word with the highest number of *unique* letters in a text.
* Unique letters should include any distinct character using [UTF-8 encoding](https://en.wikipedia.org/wiki/UTF-8).
+ Upper and lower case versions of the same character are different and distinct; `'a' != 'A'`
* Words are bound by any whitespace character.
* 'Letters' are any symbol which can be represented by a single unicode character.
* The text document must be read in by your code -- no preloading/hard-coding of the text allowed.
* The output should be the word, followed by the count of unique letters.
+ `llanfairpwllgwyngyllgogerychwyrndrobwllllantysiliogogogoch - 18`
+ Any delimiter/spacing between the two values is up to you, so long as there is at least one character to separate them.
* In the event more than one word exists with the highest count, print all words for that count, with one new line delimiting.
```
superacknowledgement - 16
pseudolamellibranchiate - 16
```
* This is code golf, so shortest code wins.
[This answer on English.SE](https://english.stackexchange.com/a/14786/19451) inspired me to create this challenge. The example uses just a [word list](http://wordlist.sourceforge.net/), but any text should be able to be processed.
[Answer]
## APL (56)
```
{⎕ML←3⋄⊃{⍵,⍴∪⍵}¨W[⍙]⍴⍨↑+/∆∘.=∆←∆[⍙←⍒∆←↑∘⍴∘∪¨W←⍵⊂⍨⍵≠' ']}
```
This is a function (question says that's allowed) that takes a string and returns a matrix of words and unique lengths.
Usage:
```
{⎕ML←3⋄⊃{⍵,⍴∪⍵}¨W[⍙]⍴⍨↑+/∆∘.=∆←∆[⍙←⍒∆←↑∘⍴∘∪¨W←⍵⊂⍨⍵≠' ']}'The quick brown fox jumps over the lazy dog.'
quick 5
brown 5
jumps 5
```
Explanation:
* `⎕ML←3`: set migration level to 3 (so that `⊂` is partition instead of enclose)
* `W←⍵⊂⍨⍵≠' '`: store in `W` the given string, where each partition consists of non-whitespace characters.
* `⍙←⍒∆←↑∘⍴∘∪¨W`: get the amount (`⍴`) of unique (`∪`) elements in each part (`¨`) of `W`, and store these in `∆`, then get the sort order when sorted downwards on this (`⍒`) and store that in `⍙`.
* `∆[⍙`...`]`: sort `∆` by `⍙`, so now we have the unique lengths in order.
* `∆∘.=∆←∆`: store the sorted `∆` back in `∆`, and see which elements of `∆` are equal.
* `↑+/`: sum the rows (now we know how many elements are equal to each element) and then take the first item (now we know how many elements are equal to the first element, i.e. how many of the words are tied for first place.)
* `W[⍙]⍴⍨`: sort `W` by `⍙`, and take the first N, where N is the number we just calculated.
* `{⍵,⍴∪⍵}¨`: for each of these, get the word itself and the amount of unique characters in the word
* `⊃`: format as matrix
[Answer]
## Perl 78 bytes
```
map{push$_[keys{map{$_,1}/./g}]||=[],$_}split for<>;print"$_ $#_
"for@{$_[-1]}
```
Interpretting the restriction *"The text document must be read in by your code"* to mean that command line options that read and parse the input are not allowed. As with the PHP solution below, only characters 10 and 32 are considered to be word delimiters. Input and output are also taken in the same manner.
---
## PHP 128 bytes
```
<?foreach(split(~߃õ,fread(STDIN,1e6))as$s){$w[count(count_chars($s,1))][]=$s;}krsort($w)?><?=join($f=~ß.key($w).~õ,pos($w)),$f;
```
The only characters considered to be word delimiters are characer 10, and character 32. The rest, including puncuation, are considered to be part of the word.
This contains a few binary characters, which saves quotation marks, but as a result needs to be saved with an ANSI encoding in order to function properly. Alternatively, this version can be used, which is 3 bytes heavier:
```
<?foreach(split(' |
',fread(STDIN,1e6))as$s){$w[count(count_chars($s,1))][]=$s;}krsort($w)?><?=join($f=' '.key($w).'
',pos($w)),$f;
```
Sample I/O:
input 1:
```
It was the best of times, it was the worst of times, it was the age of wisdom,
it was the age of foolishness, it was the epoch of belief, it was the epoch of
incredulity, it was the season of Light, it was the season of Darkness, it was
the spring of hope, it was the winter of despair, we had everything before us,
we had nothing before us, we were all going direct to Heaven, we were all going
direct the other way - in short, the period was so far like the present period,
that some of its noisiest authorities insisted on its being received, for good
or for evil, in the superlative degree of comparison only.
```
output 1:
```
$ php most-unique.php < input1.dat
incredulity, 11
```
input 2:
```
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit
amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus
ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae
ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus.
Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia
Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu,
venenatis nec hendrerit a, molestie vitae augue.
```
output 2:
```
$ php most-unique.php < input2.dat
consequat 9
ullamcorper 9
Vestibulum 9
```
[Answer]
# Mathematica 96 115
*Edit*: code now finds all words of the maximum number of characters. I refuse to treat commas as word characters.
```
f@t := With[{r = {#, Length@Union@Characters@#} & /@
StringSplit[t,RegularExpression@"\\W+"]}, Cases[r, {_, Max[r[[All, 2]]]}]]
```
**Examples**
```
f@"It was the best of times,...of comparison only."
```
or
```
f@Import["t1.txt"]
```
>
> {{"incredulity", 10}, {"superlative", 10}}
>
>
>
---
```
f@"Lorem ipsum... vitae augue."
```
or
```
f@Import["t2.txt"]
```
>
> {"Vestibulum", 9}
>
>
>
---
[Answer]
## Python 2 (110 (98 using file input))
```
import sys
f=lambda x:len(set(x))
a=sys.stdin.read().split()
c=max(map(f,a))
for i in a:
if f(i)==c:print i,c
```
.
```
f=lambda x:len(set(x))
a=file('a').read().split()
c=max(map(f,a))
for i in a:
if f(i)==c:print i,c
```
Things to improve: printing (33 characters)
Punctuation is considered letters.
[Answer]
This is my first codegolf, I'm so excited :) Also that means it is probably not any good.
**Groovy 127 117 112 105**
Edit: Since functions seem to be allowed here is one in 105. I also renamed the variables to make the first column read ACDC, because that is important in any kind of source code:
```
A={e={it.toSet().size()}
C=it.text.tokenize()
D=e(C.max{e(it)})
C.grep{e(it)==D}.each{println"$it $D"}}
```
You would call it like that:
```
A(new File("words.txt"))
```
Without function using standard input in **112**:
```
a={it.toSet().size()}
b=System.in.getText().tokenize()
c=a(b.max{a(it)})
b.grep{a(it)==c}.each{println "$it $c"}
```
```
a={it.toSet().size()}
b=System.in.getText().tokenize().sort{-a(it)}
c=a(b[0])
b.grep{a(it)==c}.each{println "$it $c"}
```
```
a={it.toSet().size()}
System.in.getText().tokenize().sort({-a(it)}).groupBy{a(it)}.take(1).each{k,v->v.each{println "$it $k"}}
```
Input: Lorem Ipsum Text from primo
All scripts output:
```
consequat 9
ullamcorper 9
Vestibulum 9
```
Anyone got an idea how to make them more groovy?
[Answer]
## GoRuby 2.0.0 – 66 chars
The solutions below didn't actually find all matches but only one. Here's my final version:
```
a=$<.r.sp.m{|x|[x,x.ch.u.sz]};a.m{|x|s x*' - 'if x.l==a.m_(&:l).l}
```
Examples:
>
> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis,
> nisl sit amet consequat fringilla, justo risus iaculis justo, vel
> ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed
> volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue
> pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis
> in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a
> lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis
> nec hendrerit a, molestie vitae augue.
>
>
>
produces:
```
$ ruby golf.rb < input.txt
consequat - 9
ullamcorper - 9
Vestibulum - 9
```
## GoRuby 2.0.0 – 29 chars (not exact output format)
```
s$<.sp.m{|x|[x.ch.u.sz,x]}.mx
```
Expects input from stdin. The output format is a little bit different, though. For example:
```
$ ruby golf.rb < british.1
14
manoeuvrability
```
## GoRuby 2.0.0 – 42 40 chars
```
s$<.r.sp.m{|x|[x.ch.u.sz,x]}.mx.rv*' - '
```
expects input from stdin
## Ruby 1.9.3 - 69 65 chars
```
puts$<.read.split.map{|x|[x.chars.uniq.size,x]}.max.reverse*' - '
```
expects input from stdin (same as above, but without GoRuby abbreviations)
[Answer]
**R - 106 characters**
As a function with the input text as parameter:
```
f=function(t){
s=strsplit
a=sapply
t=s(t," ")[[1]]
w=a(a(s(t,""),unique),length)
n=(w==max(w))
cbind(t[n],w[n])
}
```
And a few examples:
```
f("It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.")
[,1] [,2]
[1,] "incredulity," "11"
f("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis nec hendrerit a, molestie vitae augue.")
[,1] [,2]
[1,] "consequat" "9"
[2,] "ullamcorper" "9"
[3,] "Vestibulum" "9"
```
Or **R - 100 characters**
As a function with the path to the text file as parameter:
```
f=function(t){
t=scan(t,"")
a=sapply
w=a(a(strsplit(t,""),unique),length)
n=(w==max(w))
cbind(t[n],w[n])
}
```
Usage:
```
f("t1.txt")
Read 120 items
[,1] [,2]
[1,] "incredulity," "11"
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~19~~ ~~13~~ ~~16~~ ~~15~~ 14 bytes
*Edit: -6 bytes by taking inspiration from Shaggy's Japt answer, but then ~~+3~~ ~~+2~~ +1 byte to scrupulously adhere to the output format (without surrounding parentheses and/or quotation marks)*
```
mS+ȯΘs₁→k₁w
Lu
```
[Try it online!](https://tio.run/##yygtzv7/PzdY@8T6czOKHzU1PmqblA2kyrl8Sv8DJRIrFErzMgtLUxVyUktKUouKFTLzFHLzi1IVSjIS8xTy81IVyvOLUhQUAA "Husk – Try It Online")
```
Lu # helper function: get the number of unique letters
¶m§,I₁→k₁w # main program
¶ # split result by newlines
m # for each element of list
§,I₁ # combine itself (I) with result of helper function
→k₁w # list:
→ # last element of
k w # groups of words of input, grouped & sorted by
₁ # results of helper function
```
[Answer]
## Javascript 163 155 152 162 bytes
This is about as short as I can get it:
```
prompt(x=[]).split(/\s/).forEach(function(a){b={};c=0;a.split('').forEach(function(d){b[d]?1:b[d]=++c});x[c]?x[c].push(a):x[c]=[a]});alert((l=x.length-1)+':'+x[l])
prompt(x=[]).split(/\b/).map(function(a){b={};c=0;a.split('').map(function(d){b[d]?1:b[d]=++c});x[c]?x[c].push(a):x[c]=[a]});alert((l=x.length-1)+':'+x[l])
prompt(x=[]).split(/\s/).map(function(a){b=[c=0];a.split('').map(function(d){b[d]?1:b[d]=++c});x[c]=(x[c]||[]).concat(a)});alert((l=x.length-1)+':'+x[l])
```
```
prompt(x=[]).split(/\s/).map(function(a){b=[c=0];a.split('').map(function(d){b[d]?1:b[d]=++c});x[c]=(x[c]||[]).concat(a)});alert((l=x.length-1)+':'+x[l].join('\n'))
```
In this version `/\s/` separates words based on whitespace, so it includes punctuation, commas, periods, etc as part of words. This is easily changed to `/\b/` to not included them.
I'll see what I can do with for-loops instead of forEaches in a bit.
## I/O:
>
> It was the best of times, it was the worst of times, it was the age of
> wisdom, it was the age of foolishness, it was the epoch of belief, it
> was the epoch of incredulity, it was the season of Light, it was the
> season of Darkness, it was the spring of hope, it was the winter of
> despair, we had everything before us, we had nothing before us, we
> were all going direct to Heaven, we were all going direct the other
> way - in short, the period was so far like the present period, that
> some of its noisiest authorities insisted on its being received, for
> good or for evil, in the superlative degree of comparison only.
>
>
>
```
11:incredulity,
```
>
> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis,
> nisl sit amet consequat fringilla, justo risus iaculis justo, vel
> ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed
> volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue
> pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis
> in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a
> lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis
> nec hendrerit a, molestie vitae augue.
>
>
>
```
9:consequat
ullamcorper
Vestibulum
```
>
> A little tired, perhaps. But I feel peaceful. Your success in the ring
> this morning was, to a small degree, my success. Your future is
> assured. You will live, secure and safe, Wilbur. Nothing can harm you
> now. These autumn days will shorten and grow cold. The leaves will
> shake loose from the trees and fall. Christmas will come, and the
> snows of winter. You will live to enjoy the beauty of the frozen
> world, for you mean a great deal to Zuckerman and he will not harm
> you, ever. Winter will pass, the days will lengthen, the ice will melt
> in the pasture pond. The song sparrow will return and sing, the frogs
> will awake, the warm wind will blow again. All these sights and sounds
> and smells will be yours to enjoy, Wilbur—this lovely world, these
> precious days…
>
>
>
```
10:Wilbur—this
```
>
> Nearly all children nowadays were horrible. What was worst of all was
> that by means of such organizations as the Spies they were
> systematically turned into ungovernable little savages, and yet this
> produced in them no tendency whatever to rebel against the discipline
> of the Party. On the contrary, they adored the Party and everything
> connected with it... All their ferocity was turned outwards, against
> the enemies of the State, against foreigners, traitors, saboteurs,
> thought-criminals. It was almost normal for people over thirty to be
> frightened of their own children.
>
>
>
```
15:thought-criminals.
```
[Answer]
### Scala 129 chars:
```
def f{
val l=readLine.split(" ").map(s=>(s,s.distinct.length)).sortBy(_._2)
println(l.filter(x=>x._2==l.last._2).mkString)}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
QL
ḲÇÐṀ,ÇKƊ€Y
```
[Try it online!](https://tio.run/##JY6xTsMwEIZn8hS3Zal4DIQECxISQojBsa@O04svdWxcdwKWSEw8CBNDBQtDI/Ee7YsEk@qGX6f/@/@7BonSNN1cF4evz3EY3w/fz4txuPp9O75@3E/jkKU5vvzsd/vdND0UZ@VtjbAORq6gchwtLHkDTWi7HvgJHfhsk9gmUKzPy0UOXOYTDHfsSM37hbHKWD2TLfcegjXrgBDZnYCIJLlF8AxEwi6FcV0k0jFZnbKyRpdkHZOzynGVrX/Mp96QYT2PrOemPnTohFxZjoRKY4vWAzvoegyKSbT5NVM5YWVthMeyePwD "Jelly – Try It Online")
Just returning the number of unique characters is [6 bytes](https://tio.run/##JY4xTgQxDEVr9hQukKZBHANR0CAhIYQoMok3k12PPeskhFAhGi5DRQU1J1kuEsIgF/7Wf//LOySqrR0/P66vTn9e349fL@37rYu71u43J8PNhHDIwe5hVCkMW3mCXZ6XCPKICqnbZJ4rOPHnw1kPXPZCgVtRcut9EdgF9is5S0yQORwyQhH9BwqSlRkhCRAZ3pqgSyHypbKvfYtHrXYqVdmpjN36w1KNgYL4dey0NsW8oBq7ZymEzuOMnEAUlojZCZm5vxZGNWynYBIOm4df) and just returning the words (no count), is [7 bytes](https://tio.run/##JY4xTgMxEEVrcoopkLZBHANR0CAhIYRSeO2J15tZz2ZsY0wFNLQchIoigoYiOUlykcUs@sXo67/5@j0SlWk6fH1eX53u3w/fz3fT/u34@tEfX3522912mu4XJ81Nh7BJTq@hFc4eVvwIfRrGAPyAArHGpJ4KGLbnzVl9uKy9DLcsZGZ/4bxx3s7kwCFC8m6TEDLLP5CRNA8IkYFI@ZVyMmYim4u3pV62KEV3uYg3wm2N/rBYgiPHdpbu5qaQRhSl154zobE4oI/AAmPAZJjUUKe5VpTXnVMRm8XyFw).
## How it works
```
QL - Helper link. Takes a string W on the left
Q - Deduplicate W
L - Length
This returns the number of unique characters in W
ḲÇÐṀ,ÇKƊ€Y - Main link. Takes a string S on the left
Ḳ - Split S on spaces
ÐṀ - Find the words for which the following is maximal:
Ç - The number of unique characters
Ɗ€ - Over each maximal word:
Ç - Yield the number of unique characters
, - Pair with the word
K - Join by spaces
Y - Join by newlines
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0 [`-hR`](https://codegolf.meta.stackexchange.com/a/14339/), 11 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Uses a comma as the delimiter.
```
¸®¸pZâ lÃüÌ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LWhS&code=uK64cFriIGzD/Mw&input=IkZpbmRpbmcgdGhlIG1vc3QgdW5pcXVlIHdvcmQi)
```
¸®¸pZâ lÃüÌ :Implicit input of string > "Finding the most unique word"
¸ :Split on spaces > ["Finding","the","most","unique","word"]
® :Map each Z
¸ : Split on spaces > [["Finding"],["the"],["most"],["unique"],["word"]]
p : Push
Zâ : Z deduplicated > ["Findg","the","most","uniqe","word"]
l : Length > [5,3,4,5,4]
à :End map > [["Finding",5],["the",3],["most",4],["unique",5],["word",4]]
ü :Group & sort by
Ì : Last element > [[["the",3]],[["most",4],["word",4]],[["Finding",5],["unique",5]]]
:Implicit output of last element > [["Finding",5],["unique",5]]
: joined with newlines > "Finding,5\nunique,5"
```
[Answer]
**Python 176 168**
```
w = "".join((open('c')).readlines()).replace("\n", " ").split(" ")
l = sorted(zip([len(set(w[i])) for i in range(len(w))],w,))
print([x for x in l if l[-1][0] == x[0]])
```
[Answer]
# Python3 119
Reads from a file called `a`.
```
r={w:len(set(w))for w in open("a").read().split()};print("\n".join(str((k,v))for k,v in r.items()if v==max(r.values())))
```
Tested with the input texts from @primo:
```
Input 1:
('incredulity,', 11)
Input 2:
('Vestibulum', 9)
('consequat', 9)
('ullamcorper', 9)
```
[Answer]
# [Haskell](https://www.haskell.org/), 85 bytes
```
k(a:b)=k(filter(/=a)b)-1
k[]=0
f x=unlines[y++show(k y)|y<-x,all((>=k y).k)x]
f.words
```
[Try it online!](https://tio.run/##Fc2xDsIgFEDRna8gjcMjtVVX4/MnHJsONIVCeBYDNIXEf8e63jNcI6NTRLU6kPdJoANtKakAF5RiEt2NuWHEK9M847aSXVUcSttG43dwvIhveXT5LIkAnvgPvRN5ZAvqfvdhjvUt7YqfLb1SOC2NOV6eH0IzVzIk09Qf "Haskell – Try It Online")
This employs one clever trick. Instead of counting up the number of unique characters in each word, it counts down. So `hello` yeilds \$-4\$ rather than \$4\$. This allows us to use `-` as the delimter later which saves us a tiny bit.
# With more lenient IO, 65 bytes
```
k(a:b)=1+k(filter(/=a)b)
k[]=0
f x=[(y,k y)|y<-x,all((<=k y).k)x]
```
[Try it online!](https://tio.run/##FcxNCoMwEEDhvacYxMWE2r9tcU4iLkZMSJiplhgwgd49tcv3LZ7nXaxqrYL8mg09L4IuaLIR78RmNo2MEz0aB5lGLL1AMd8yXHPPqogD/eEmJk/1zWGlTwxr6lx3bHHZofXne4MzdAHLMfm2/gA "Haskell – Try It Online")
20 bytes were spent just conforming to the archaic IO restrictions. This takes a list of input words and outputs a list of tuples containing the word and the count.
[Answer]
# [Zsh](https://www.zsh.org/), 77 bytes
```
for x;z=`fold -1<<<$x|sort|uniq|wc -l` m=$[z>m?z:m]&&echo $z $x>>p
grep ^$m p
```
[Try it Online!](https://tio.run/##fVbbjtxEEH3fr6iHVQRodiReyQWF5IFIUQgKAnFVyu2y3dl2t9OX8XoIEh/BF/Ijy6m2ZzcLCZqH8biqq06dOlU9xzRcd598@vtZ8UkyzXRFCx1pPIsjfXbdhUhX948PX3fBtXTx@YMHD86v3qUQ87vi7dt3s6EL95rGh@c/Hx@NXx6/GH@9d0/MEOj8SOdXjx5NZ32UiX47H2m6VsMfZ2cdOce@Yxun2bl@Xny/4Dv0EhczzEv0bQwNTOqWl2SdDX39mIFSmSSyufRhdtL2MorPNCUpbXA8inO2iezNYDmLpnqGmjhRHoQaSZlCR9mOknZkby1ziB8zcS9qmG1qw/ghSxeCs2nwku4elEnhwqERZ6X7sM16E6UtzubljkMSTsGrx3PbD/kjtqccL/@TN03R@l7NQ5jkbpnWZ4lqaiVN4H9Hs9DALckB3OdBDzaCpguVdGP04UOWWfDMzlEf1NjaKCZTDvS18EH8//kACkICycwLXYAESgMktasWtNeGtmJOgTqO5OylrKYoqba7uqg7ZziNtQ82JyC1yWqXuWREtBk/ED7ZlKUlkKZOjSgWIBF7EERRjfcBKfGtz3KwbqegKpsqN8cZriANWq65TBgnjra2wbtlr0J7Dm5GslMqI0GLCJRAPSSJukzAcJksuUTi1k42GcUAYeQ9PQ1eDI0B0gWz3iZ3c3I9@LagzE67ajERO3pTEmhG@oLi2EA9aX23o4M4KnAaTYgATm2xlDEU8CyZxNtxT69KmsS3NiUhB1Sw1Vg7xQDyrEqspUNwJU/IDHQ7QBXb4RQdbGacs31xvKcXmowmNC/brNyhogqCS19qw7IFH6ZEJDiVqtSWCBK29Hv6XtM2xcEVEy8bixDyaLV/UEExsCe0yFhypYIGPcXlaA16PIVUVGumNNgWTE9KZPnlPn1bbHoLIEyutkfKKfUBHY2RIZ@WUfWeXoImiEuq/0oxR1OUUy8eCkjKBA0gIUJ/aNB7hK2s1KKrGB6DoZwdZAvJQ2PoxcATsnyFNjyjTkDRJGykK25PPwboIhWDStJJeHWIMXcJSaLXH5iInc4XMI86U6scAWI5nd0idQU1gsREnBKe2voe049DDmXv0F@jHox@Ju7w4gfrmhLRz23UDXuMPq6ABQexavf03YDZ07kqo6eWl7TGq4MrvobqY5ihWNdWbzQXe@DGjTHDLgTE6GIYa4kZ8FM92aGePT0ZoMM88nYGQwZkaq6DCBRp3cS6xP5VkvIi/k1YtkUPnEvd50PNdwRC7Hi3TbsWNQpKZGAWSLwVdhrip2IuJY681lM3JhJg/92Qsaurcg/C6iqt9ol1BWuqW14gpR5v/PoeGl1f44LKpw7jWO3TFPzGGPZJj/3NUYms/lFXxoomoS@7U0H9loZn8Lq@nRUhyGlXS@MQg3u2fk@P8TvX/iW9TVbOUyi@3R713twiNqJlxnTD6Ekcf//5V5WjC5jv5UTnGhZzbmzATCoB@30dgRfCEX6qVNzGDkPjVUm8cqTDCulE2zgBm7rIdePfXMR6bL22YGmW2q7afkgdN2fs2dsjhhL7kbbb7dWk2x5Pyxo@Ldj6I3wMgi069x5rDX0LVHyPKqJnZD9NauIDbvS0Km6RvA7fFENbTD2noUeUgIXqW/EGaQBO5aBcRWl07Snhab3iWt3yk7NeTkp8yTEve/pm7T92e44cl92KmVtsqPbWr@J4716Gu9c7RPubB9xk4PnUWYuhlxgM/kasrK21hpKhilZreg8X1tmoTG2gXmUUceuhV7ztvUSVdGTd6nhK3IQspb4cQoGILoxuZ88OW2f7j8VuDIjgAybI1UGbJEygNlSOBqtVgapGJaxClAqy2yoIs79Ryv76Hw)
`$z` is a count of the unique letters in each word. `$m` is the maximum `$z`. We write each word and its count to file `p`, then grep for `$m`.
OG: [119 bytes](https://tio.run/##fVZdbxVHDH3Pr/BDhBL15kp9LaQVhYciIdqKqlULSHhnvbtDZmeW@bibvYDUH9Ff2D@SHs/em0ALVR6yGXvs4@NjT/ZpuOnOzt@dFJ8k00zXtNCexpu8TKInFw9pPulCpOv7@8vXXXAtXXz94MGD0@v3KcT8vnj79v1s6MK9pvmry7PTazrdn9N4efpi/@343f6b8VW9vtDZ6buzq/P5w/nZ2fzidHl1eTmen9@7p7GWl3Raz@hGzBA@nHTkHPuObZxm5/p58f2C36GXuJhhXqJvY2hgUre8JOts6OuPGSiVSSKbKx9mJ20vo/hMU5LSBsejOGebyN4MlrOcINUT1M2J8iDUSMoUOsp2lLQhe2eZQ/ySiXtRw2xTG8bPWboQnE2Dl/TpRZkULhwacVa6z9usN1Ha4mxePnFIwil49Xhq@yF/wfaY49V/8qYpWt@reQiTfFqm9VmimlpJE/jf0Cw0cEuyA/d50IuNoKNCJd0afficZRZ8s3PUBzW2NorJlAP9ILwT/38@gIKQQDLzQhcggdIAuW2qBe21oa2YU6COIzl7JaspQrXa7uqi7pzhNNY@2JyA1CarXeaSEdFm/IHwyaYsLYE0dWpEsQCJ2J0gigq4D0iJ3/otO@s2CqqyqXJznOEK0vooNZcJ48TR1jZ4t2xVaE/BzUh2SmUkaBGBEqiHJFGXCRhAkyWXSNzaySajGCCMvKXHwYuhMUC6YNbb5G5vrhffFpTZaVctJmJDb0oCzUhfUBwbqCetZxvaiaMCp9GECODUFksZQwHPkkm8Hbf0vKRJfGtTEnJABVuNtVEMIM@qxFraBVfyhMxAtwFUsR1u0c5mxj3bF8dbeqbJaELzss3KHSqqILj0pTYsW/BhSkSCY6lKbYkg4ZB@S79q2qY4uGLi5cAihDxa7R9UUAzsCS0yllypoEFPcTlagx5PIRXVmikNtgXToxJZXt6nn4tNbwGEydX2SDmm3qGjMTLk0zKq3tJPoAnikuq/UszRFOXUi4cCkjJBA0iI0B8a9BFhKyu16CqGh2AoZwfZQvLQGHox8IQs36MNT6gTUDQJG@mK29LvAbpIxaCSdBReHWLMXUKS6PUPTMRG5wuYR52pVY4AsRzvHiJ1BTWCxEScEr7aeo7pxyWHsjfor1EPRj8Tdzj4zbqmRPTzMOqGPUY/jrTgIlbtln4ZMHs6V2X01PKS1nh1cMXXUH0MMxTr2uqN5mIP3LoxZtiFgBhdDGMtMQN@qjc71LOlRwN0mEc@3MGQAZma6yACRVo3sS6xf5WkvIh/E5bDogfOpe7zoebbAyF2vDtMuxY1CkpkYBZIvBV2GuKPYq4kjrzWUzcmEmD/3ZKxqatyC8LqKq32iXUFa6o7XiClHid@PYdG12M8UPnYYVyrfZqCPzCGfdJjf3NUIqt/1JWxoknoy@ZYUH9IwzN4XU9nRQhy2tXSOMTgnq3f0kP8nWv/kr4mK@cpFN8ePvXdPERsRMuM6ZbRozj@/vOvKkcXMN/Lkc41LObc2ICZVAK22zoCz4Qj/FSpeI0dhsarknjlSIcV0om2cQI2dZHrxr99iPXa@mzB0iy1XbX9kDpeztizt3sMJfYjHV6355Nue3wta/i0YOuP8DEItujce6w19C1Q8T2qiJ6R/TipiXd40dOquEXyOnxTDG0x9Z6GHlECFqpvxRukATiVg3IVpdG1p4Sn9YlrdctPzno5KvEnjnnZ0o9r/7Hbc@S4bFbM3GJDtXd@FcdH7zLcvb4h2t884CUDz8fOWgy9xGDwb8TK2lprKBmqaLWmj3BhnY3K1AHU84wi7jz0ibe9l6iSjqxbHV@Jm5Cl1MMhFIjowuh29uywdQ7/Y7EbAyL4gAlyddAmCROoDZWjwWpVoKpRCasQpYLsDhWE2d8qZXvzDw "Zsh – Try It Online") using associative array.
[Answer]
# JavaScript, 147 bytes
With map:
```
t=>(s='',m=new Map(),t.split(' ').map(w=>m.set(w,new Set(w).size)),d=[...m].sort((a,b)=>b[1]-a[1]),d.map(x=>x[1]==d[0][1]&&(s+=x.join('-')+`
`)),s)
```
With plain object
```
t=>(s='',m={},t.split(' ').map(w=>m[w]=new Set(w).size),d=Object.entries(m).sort((a,b)=>b[1]-a[1]),d.map(x=>x[1]==d[0][1]&&(s+=x.join('-')+`
`)),s)
```
Try it:
```
f=t=>(s='',m=new Map(),t.split(' ').map(w=>m.set(w,new Set(w).size)),d=[...m].sort((a,b)=>b[1]-a[1]),d.map(x=>x[1]==d[0][1]&&(s+=x.join('-')+`
`)),s)
console.log(f('It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way - in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.'));
console.log(f('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec mollis, nisl sit amet consequat fringilla, justo risus iaculis justo, vel ullamcorper dui tellus ut enim. Suspendisse lectus risus, molestie sed volutpat nec, eleifend vitae ligula. Nulla porttitor elit vel augue pretium cursus. Donec in turpis lectus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Quisque a lorem eu turpis viverra sodales. Pellentesque justo arcu, venenatis nec hendrerit a, molestie vitae augue.'));
console.log(f('A little tired, perhaps. But I feel peaceful. Your success in the ring this morning was, to a small degree, my success. Your future is assured. You will live, secure and safe, Wilbur. Nothing can harm you now. These autumn days will shorten and grow cold. The leaves will shake loose from the trees and fall. Christmas will come, and the snows of winter. You will live to enjoy the beauty of the frozen world, for you mean a great deal to Zuckerman and he will not harm you, ever. Winter will pass, the days will lengthen, the ice will melt in the pasture pond. The song sparrow will return and sing, the frogs will awake, the warm wind will blow again. All these sights and sounds and smells will be yours to enjoy, Wilbur—this lovely world, these precious days…'));
console.log(f('Nearly all children nowadays were horrible. What was worst of all was that by means of such organizations as the Spies they were systematically turned into ungovernable little savages, and yet this produced in them no tendency whatever to rebel against the discipline of the Party. On the contrary, they adored the Party and everything connected with it... All their ferocity was turned outwards, against the enemies of the State, against foreigners, traitors, saboteurs, thought-criminals. It was almost normal for people over thirty to be frightened of their own children.'));
```
[Answer]
# JavaScript, ~~76~~ 71 bytes
```
s=>s.split` `.map(w=>(n=new Set(w).size)<s||[w,s=n]).filter(x=>x[1]==s)
```
[Try it online!](https://tio.run/##DcexDoIwEADQX@nYJtrEzcFjdHDQgZGQlECLZ8oVe4Wi4d@rb3uvbu24jzin43ouDgpDxZpnj8kIo6dulhkqSUA2i9ommZVm/Fp14X1v8oGBWqUd@mSj3KDamlMLwKr0gTh4q30Y5a1@3DWniDSi@0gnzRVp@E@kpxVT4CQWwvdiRQ5xMEqp8gM)
[Answer]
# [Thunno](https://github.com/Thunno/Thunno) `N`, \$ 29 \log\_{256}(96) \approx \$ 23.87 bytes
```
A_ZiDedZULEZZz:zGAJzHAKerA_sj
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSn1LsgqWlJWm6Fnsd46MyXVJTokJ9XKOiqqyq3B29qjwcvVOLHOOLsyBqoEoX7HHLzEvJzEtXKMlIVcjNLy5RKM3LLCxNVSjPL0qBqAEA)
We can save a character if joining by a digit is allowed: [Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_abSSn1LsgqWlJWm6Fnsc46MyXVJTokJ9XKOiqqyq3B29qjwcvVOLDIqzIEqgKhfsccvMS8nMS1coyUhVyM0vLlEozcssLE1VKM8vSoGoAQA)
#### Explanation
```
A_Zi # Split the (implicit) input by spaces ["Finding", "the", "most", "unique", "word"]
D # Duplicate this list ["Finding", "the", "most", "unique", "word"], ["Finding", "the", "most", "unique", "word"]
e # Map over it: ["Finding", "the", "most", "unique", "word"]
dZU # Uniquify the string ["Findg", "the", "most", "uniqe", "word"]
L # And get the length [5, 3, 4, 5, 4]
E # (End map) ["Finding", "the", "most", "unique", "word"], [5, 3, 4, 5, 4]
ZZ # Zip this with the split list [[5, "Finding"], [3, "the"], [4, "most"], [5, "unique"], [4, "word"]]
z:zG # Sort and group by: [[3, "the"], [4, "most"], [4, "word"], [5, "Finding"], [5, "unique"]]
AJ # First element of each [3, 4, 4, 5, 5]
zH # (End group) [[[3, "the']], [[4, "most"], [4, "word"]], [[5, "Finding"], [5, "unique"]]]
AK # Get the last element [[5, "Finding"], [5, "unique"]]
e # Map over it: [[5, "Finding"], [5, "unique"]]
r # Reverse [["Finding", 5], ["unique", 5]]
A_sj # And join by spaces ["Finding 5", "unique 5"]
# (N flag joins by newlines) "Finding 5", "unique 5"
# Implicit output
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip) `-p`, ~~24~~ 23 bytes
```
(a^:s(Y#*UQ*a)@*My)ZDNy
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhXjpzKGEoWSMqVVEqYSlAKk15KVpETnkiLCIiLCIiLCJcIkxvcmVtIGlwc3VtIGRvbG9yIHNpdCBhbWV0LCBjb25zZWN0ZXR1ciBhZGlwaXNjaW5nIGVsaXQuIERvbmVjIG1vbGxpcywgbmlzbCBzaXQgYW1ldCBjb25zZXF1YXQgZnJpbmdpbGxhLCBqdXN0byByaXN1cyBpYWN1bGlzIGp1c3RvLCB2ZWwgdWxsYW1jb3JwZXIgZHVpIHRlbGx1cyB1dCBlbmltLiBTdXNwZW5kaXNzZSBsZWN0dXMgcmlzdXMsIG1vbGVzdGllIHNlZCB2b2x1dHBhdCBuZWMsIGVsZWlmZW5kIHZpdGFlIGxpZ3VsYS4gTnVsbGEgcG9ydHRpdG9yIGVsaXQgdmVsIGF1Z3VlIHByZXRpdW0gY3Vyc3VzLiBEb25lYyBpbiB0dXJwaXMgbGVjdHVzLiBWZXN0aWJ1bHVtIGFudGUgaXBzdW0gcHJpbWlzIGluIGZhdWNpYnVzIG9yY2kgbHVjdHVzIGV0IHVsdHJpY2VzIHBvc3VlcmUgY3ViaWxpYSBDdXJhZTsgUXVpc3F1ZSBhIGxvcmVtIGV1IHR1cnBpcyB2aXZlcnJhIHNvZGFsZXMuIFBlbGxlbnRlc3F1ZSBqdXN0byBhcmN1LCB2ZW5lbmF0aXMgbmVjIGhlbmRyZXJpdCBhLCBtb2xlc3RpZSB2aXRhZSBhdWd1ZS5cIiAtcCJd)
[Answer]
## VBScript - 430 / VBA - 420
**VBScript:**
```
Function r(t)
d="Scripting.Dictionary"
Set w=CreateObject(d)
c=1
Do Until c>Len(t)
p=InStr(c,t," ")
i=InStr(c,t,vbCr)
If p<i Then s=i Else s=p
If s=0 Then s=Len(t)+1
f=Mid(t,c,s-c)
If Not w.Exists(f) Then
Set x=CreateObject(d)
For l=1 To Len(f)
n=Mid(f,l,1)
If Not x.Exists(n) Then x.Add n,n
Next
w.Add f,f
y=x.Count
If m=y Then z=f &vbCr &z
If m<y Then m=y:z=f
End If
c=s+1
Loop
r=z &" " &m
End Function
```
**VBA:**
```
Function r(t)
d="Scripting.Dictionary"
Set w=CreateObject(d)
c=1
Do Until c>Len(t)
p=InStr(c,t," ")
i=InStr(c,t,vbCr)
s=IIf(p<i,i,p)
If s=0 Then s=Len(t)+1
f=Mid(t,c,s-c)
If Not w.Exists(f) Then
Set x=CreateObject(d)
For l=1 To Len(f)
n=Mid(f,l,1)
If Not x.Exists(n) Then x.Add n,n
Next
w.Add f,f
y=x.Count
If m=y Then z=f &vbCr &z
If m<y Then m=y:z=f
End If
c=s+1
Loop
r=z &" " &m
End Function
```
[Answer]
# [Python 3](https://docs.python.org/3/), 88 bytes
```
lambda s:[(w,len({*w}))for w in s.split()if len({*w})==max(map(len,map(set,s.split())))]
```
[Try it online!](https://tio.run/##PY3BCsIwEER/ZW/dSPHiTeiXqIdtu7HBZBOSLamI3x7rpXMZePNg0luXKJdmh3vzFMaZoFxvWHvPgp9T/RpjY4YKTqCcS/JO0TgLxzwMgTYMlHBH/b8La3@oex4tZSeKFruyJs40vSRWz/OTA4tCKrzOcT9n792YSabFkTKkqKSxM6b9AA "Python 3 – Try It Online")
] |
[Question]
[
In this task you will be given A (less than 10000 digits long) and B (less than 2^64), and you will need to compute the last digit of (A · A · A · ... · A (B times)).
The inputs A and B are given in a single line separated by a blank; the inputs are terminated by EOF.
**Input**
```
34543232321323243242434544533445343432434311112223454323232132324324243454453344534343243431111222345432323213232432424345445334453434324343111122234543232321323243242434544533445343432434311112223454323232132324324243454453344534343243431111222345432323213232432424345445334453434324343111122234543232321323243242434544533445343432434311112223454323232132324324243454453344534343243431111222 22337254775808
38758436543765743875437656358764347568437658743658743454354645645543532487548758475847684756897548758457843758437584758478574857438758436587436587436587643875643856783478743658743658764387564387564378658437658743658743687564387564387564765746576475647564756475465746574675647654765476547534587545689475689748574385743765874585743857843765893748643587438957458754376543265874387564384764367584375874758943267632487564357 54545454123
6777744348435743587643756438765436574587564354375674365645643675 23232
3875843654376574357 54545454
```
**Output**
```
6
3
5
9
```
**Constraints**
* Don't use any **inbuilt function or overloaded operators** to compute AB (you don't really need to compute that at all).
* Shortest solution wins!
[Answer]
# J - 52 characters
```
wd,.10|(^12+12&|)/"1(".@{:`".;._2@,&'x ');._2(1!:1)3
```
Passes all tests given, though only if the trailing spaces on the third input are removed (I'm guessing this was unintentional).
Solution will work in j602 in console mode (e.g. in terminal, emacs j-shell, etc.). It will not work in j701 (no `wd`).
Explanation & Mathiness:
The 'magic number' 12 is the LCM of the lengths of the "last digit" tables found in the other answers. All digits repeat with periods 1,2,3 or 4 so they will also repeat with period 12. Adding twelve to that fixes cases where b mod 12 = 0. My solution computes (Last digit of A)^(12+(B mod 12)), giving a number with the same last digit. (I considered a sneaky broken solution eliminating the three characters '12+' by using e.g. B mod 96 where no examples were likely to collide...)
[Answer]
**Python ~~125~~ 107 Chars**
O(1) solution
```
while 1:a,b=map(int,raw_input().split());d=1;exec"d*=a;"*(b%4);c=a%5and d%5;print b/~b+1or c+[0,5][c%2-a%2]
```
[Answer]
# GolfScript 21
```
~]2/{~.(4%)and?10%n}/
```
This basically calculate `A^C mod 10` where C is in the range `[1,4]` and `C mod 4 = B mod 4`, except if B is 0, then C is also 0.
This shortcut is possible because `A^(B+4) mod 10 = A^B mod 10` for any non-negative integer A and positive integer B.
[Answer]
## J, 79
```
,._2(4 :'10|x^(+y&(|~))x{10$1 1 4 4 2')/\x:".(]_1&{.`];._2~(' ',LF)e.~])(1!:1)3
```
[Answer]
## Ruby, 97 93 72 71 67 61 60
Also handles the case where b == 0.
```
#!ruby -nl
~/ /
p eval"#$`%10*"*($'>?0?($'.to_i-1)%4+1:0)+?1
```
Guess it's actually worse to use a lookup table.
[Answer]
## Windows PowerShell, 85
O(1) solution. Taken a hint from Lowjacker's Ruby solution ;-)
```
$input|%{$a,$b=-split$_
'0000111162481397646455556666179368421919'[4*$a[-1]%48+$b%4]}
```
[Answer]
**Python 149 Chars**
```
p=[[0],[1],[6,2,4,8],[1,3,9],[6,4],[5],[6],[1,7,9,3],[6,8,4,2],[1,9]]
while 1:a,b=map(int,raw_input().split());print b/~b+1or p[a%10][b%len(p[a%10])]
```
[Answer]
## Python (119 134 109)
I trust the prohibition against built-in functions doesn't apply to I/O.
```
import sys
p=lambda b,e:e and p(b*b%10,e/2)*(~e&1or b)%10or 1
for l in sys.stdin:print p(*map(int,l.split()))
```
**Edit:** remove use of Python's exponentiation operator.
**Edit:** Replaced ternary operators with short-circuited boolean operators.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
t$et
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=t%24et&inputs=12345%0A12&header=&footer=)
No one said it had to be efficient, and the rules forbid only calculating \$A^B\$, not \$A[-1]^B\$.
```
t # Last digit of...
t # Last digit of A
e # To the power of
? # B
```
[More efficient version](https://lyxal.pythonanywhere.com?flags=&code=t%244%25et&inputs=12345%0A12&header=&footer=)
[Answer]
## Python 3k
**121 Chars**
```
def p(a,b):
if b<1:return 1
return p(a*a%10,b//2)*[1,a][b%2]%10
while 1:
a,b=map(int,input().split())
print(p(a%10,b))
```
The `(a*a)%10` is not necessary but it speeds it up, so decided to keep it.
Edit: Apparently, the parentheses are not required.
Meanwhile, thinking about the `O(1)` Solution. :)
[Answer]
# Javascript ( 117 84 79 60 chars)
Reached 60 chars with the suggested improvements from @JiminP and @NoOneIsHere. Thank you!
d=function(s,n){a=Math.pow(s[s.length-1],n%4==0?1:n%4)+'';return a[a.length-1]}
```
d=(s,n)=>{return(Math.pow(s.slice(-1),n%4||1)+'').slice(-1)}
```
To test:
```
console.log(d('243242434544533445343432434311112223454323232132324324243454453344534343243431111222345432323213232432424345445334453434324343111122234543232321323243242434544533445343432434311112223454323232132324324243454453344534343243431111222345432323213232432424345445334453434324343111122234543232321323243242434544533445343432434311112223454323232132324324243454453344534343243431111222', 22337254775808));
console.log(d('38758436543765743875437656358764347568437658743658743454354645645543532487548758475847684756897548758457843758437584758478574857438758436587436587436587643875643856783478743658743658764387564387564378658437658743658743687564387564387564765746576475647564756475465746574675647654765476547534587545689475689748574385743765874585743857843765893748643587438957458754376543265874387564384764367584375874758943267632487564357', 54545454123));
console.log(d('6777744348435743587643756438765436574587564354375674365645643675', 23232));
console.log(d('3875843654376574357', 54545454));
```
Results:
```
2
3
5
9
```
] |
[Question]
[
Though challenges involving magic squares abound on this site, none I can find so far ask the golfer to print / output all normal magic squares of a certain size. To be clear, a normal magic square of order \$n\$ is:
1. An \$n\times n\$ array of numbers.
2. Each positive integer up to and including \$n^2\$ appears in exactly one position in the array, and
3. Each row, column, and both main- and anti-diagonals of the array sum to the same "magic number".
Your challenge is to write the shortest program that prints all normal magic squares of order 3. There are 8 such squares. For the purposes of this challenge, the characters surrounding the output array, such as braces or brackets that accompany arrays in many languages, are allowed. For a non-optimized example in python, see [here](https://math.stackexchange.com/questions/636633/how-to-prove-that-a-3-times-3-magic-square-must-have-5-in-its-middle-cell/4236803#4236803). Happy golfing!
[Answer]
# [Python 3](https://docs.python.org/3/), 61 bytes
Outputs every magic square, each as three comma-separated rows in the form: `XXX,XXX,XXX`.
```
for c in'
\zÁßİĺ':print(f'{ord(c)*1780218+275171220:,}')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/Py2/SCFZITNPnZE7pupw4@H5RzYc2aVuVVCUmVeikaZenV@UopGsqWVobmFgZGihbWRuamhuaGRkYKVTq675/z8A "Python 3 – Try It Online")
### Explanation
There are only eight magic squares, each of which are rotations/reflections of each other. In their flattened decimal representation, they are:
```
276951438, 294753618, 438951276, 492357816, 618753294, 672159834, 816357492, 834159672
```
What's remarkable about these numbers is that they are all congruent to `1017648 (mod 1780218)`, meaning they can be expressed in the form `x*1780218+1017648`. In the code, we actually use `x*1780218+275171220` as the formula instead, since it takes up less bytes to represent in our string. The number is then comma-formatted with `f'{x:,}'` to show the separation of the rows.
### [Python 3](https://docs.python.org/3/), 61 bytes
The same method but does not contain unicode characters, is (annoyingly) the same length.
```
n=50863752
for c in b'~ P
F
P ':n-=~c*1780218;print(f'{n:,}')
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P8/W1MDCzNjc1IgrLb9IIVkhM08hSb2OM0DWTTaAU90qT9e2LlnL0NzCwMjQwrqgKDOvRCNNvTrPSqdWXfP/fwA "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~15~~ 12 bytes
```
4:"3tYL@X!tP
```
[Try it online!](https://tio.run/##y00syfn/38RKybgk0schQrEk4P9/AA) Outputs all matrices without separation. Note that the output is unambiguous.
Alternatively, [this version](https://tio.run/##y00syfn/38RKybgk0schQtEguTKg8v9/AA) uses a line as separator, for 15 bytes.
### How it works
```
4: % Range [1 2 3 4]
" % For each k in that range
3tYL % Magic square of size 3 (gives one of the 8 possible squares)
@ % Push k
X! % Rotate matrix 90 degrees k times
t % Duplicate
P % Flip vertically
% End (implicit)
% Display stack, bottom to top (implicit)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
“ÑṆ6Ẉ’Ds3ZU$Ƭ;U$
```
A niladic Link that yields a list of eight lists of lists of digits, the eight magic squares.
**[Try it online!](https://tio.run/##AS8A0P9qZWxsef//4oCcw5HhuYY24bqI4oCZRHMzWlUkxqw7VST/w4dH4oKsauKBvgoK/w "Jelly – Try It Online")**
### How?
Builds one then constructs the other seven using rotations and reflections.
```
“ÑṆ6Ẉ’Ds3ZU$Ƭ;U$ - Link: no arguments
“ÑṆ6Ẉ’ - base 250 literal = 276951438
D - decimal digits -> [2,7,6,9,5,1,4,3,8]
s3 - split into threes -> [[2,7,6],[9,5,1],[4,3,8]]
Ƭ - collect up until a fixed point is found under:
$ - last two links as a monad - f=rotate(current):
Z - transpose - i.e. swap rows with columns
U - upend - i.e. reverse each row
$ - last two links as a monad - f=add_reflections(four_rotations):
U - upend - i.e. revese each row of each rotation
; - (four_rotations) concatenate (upended)
```
---
#### Alternatives
```
⁽Xð×3Œ?s3ZU$Ƭ;U$
```
```
“=ẹʋ‘×3D‘ZU$Ƭ;U$
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 201 bytes
```
_=>(h=S=>S[1]?S.flatMap(e=>h(S.filter(a=>a!=e)).map(a=>[e,...a])):[S])([1,2,3,4,5,6,7,8,9]).filter(e=>[[0,3],[0,1],[3,1],[6,1],[1,3],[2,3],[0,4],[2,2]].every(l=>e[l[0]]+e[l[0]+=l[1]]+e[l[0]+l[1]]==15))
```
[Try it online!](https://tio.run/##VY7NbsIwEITveYrtCa/YWoQU@iNt@gS9NEfLqqzUgSCDIXapqopnT00CrXoZe3Z2Pu3GHE2ou3Yfb3f@3fYN929cijVXXFYq18@VbJyJL2YvLJdrkWzrou2E4dLcsEWU25QlpyxJKY1GfFKVRqFymlNBd7SgJd3TAz1qvJYTSqkZFZqS5kmLQZeD5sN8fknvhv9ca2mPtvsSjkurnJppPR3fKbt0568bDHO@QOy3ZtXW1SEAQyMwa3wHwtkI4fBhOgu@gesGwncGUPtdiLCy8dV/pk6IpovA5WVfBtfWVgxTuoRTKDAV/8hnaLoaCoKlHqkj1zsrnV@JkS4Cyo1vd2ICEzwTTtn/NcxO/Q8 "JavaScript (Node.js) – Try It Online")
# Explanation
The integers 1 thru 9 should appear once each in the magic square, so the sum of all elements is \$\frac{9(9+1)}{2}=45\$ using a relatively simple formula.
Therefore, since each row forms one-third of the magic square, the sum of each row should equal 15 (and, by definition, the sums of columns and three-length diagonals must also equal 15).
The first thing my code does is that it creates all permutations of `[1,2,3,4,5,6,7,8,9]` (362880 of them to be exact) and checks for the ones which follow specifications. This is done using a special procedure I used in the [Parker square](https://codegolf.stackexchange.com/questions/229545/is-it-a-valid-parker-square?rq=1) challenge.
Rows, columns and diagonals are encoded in a format `[b, i]`:
* `b` is the starting index
* `i` is the number of indexes to add
The obtained subarray for such an array `[b, i]` would be (if the original array was `l`) `l[b], l[b+i], l[b+i+i]`. This is done using a slightly golfier method.
We check if, for each array, the corresponding sub-array (obtained via simple indexing methods) has a sum of 15.
As it turns out there are only eight magic squares of order 3. Right after writing my solution (and golfing it), I returned to this question and clicked the `math.se` link to find that someone had come up with a very simple formula. This notwithstanding, I am posting my answer because I think it offers a more creative approach than simple hard-coding. I am open to suggestions for reducing length.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~89~~ 83 bytes
The 8 magic squares of order 3 are all just rotations / reflections of each other, so this stores one of them and calculates the remaining ones.
```
exec("x='672','159','834'"+(';*map(print,*x),print();x=[*zip(*x)][::-1]'*4)[:-6]*2)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P7UiNVlDqcJW3czcSF1H3dDUEkhaGJuoK2lrqFtr5SYWaBQUZeaV6GhVaOqAWRqa1hW20VpVmQUaQLHYaCsrXcNYdS0TzWgrXbNYLSPN//8B "Python 3 – Try It Online")
A few bytes can be saved by using an uglier output format: [Try it online!](https://tio.run/##K6gsycjPM/7/v8JW3czcSF1H3dDUEkhaGJuoc6XlFymUK2TmKVToVERbWekaxlqlVqQma6hrlevYVmUWaGiVQ4Q1rQuKMvNKNMo1rdW1TDT//wcA "Python 3 – Try It Online")
---
Here are two programs with numpy that don't use hardcoding. The first one is quite slow, 157 bytes:
```
import itertools as I,numpy as N
for p in I.permutations(N.r_[1:10]):d=N.r_[p].reshape(3,3);{*d.sum(0),*d.sum(1),d.trace(),d[:,::-1].trace()}-{15}or print(d)
```
[Try it online!](https://tio.run/##Nc1BCsMgEIXhfU/hUouRSOjG0gNkkwuEUKRaIlQdxskihJzdNqXdff/bPFhpzqmrNUTISCyQR8r5VZgtrJdpibAeHE7PjAxYSKxX4DEuZCnkVPig8D5qo9tJGHf7FkwKfZkteN7JTly3s1NlibwV8ictpFOE9uH5R6ORxjR6@i97s@nLfvxhSMSdqPUN "Python 3 – Try It Online")
And the second one is decently fast, 175 bytes:
```
from numpy import*
from itertools import*
d=r_[[*permutations(r_[1:10])]].reshape(-1,3,3)
print(d[all(c_[sum(d,1),sum(d,2),trace(d,0,1,2),trace(flip(d,2),0,1,2)]==15,axis=1)])
```
[Try it online!](https://tio.run/##RclLCsMgFIXheVaRoQZbYkMnBVciEiQxRPBxuV6hWb0NDbSz/3wHDtpzmlrbMMc@1QhH7yNkpKH7kieHlHMoP14VzloP4DBWsuRzKuwU@ZKj4cbc0ZXdgmM3KSYx8Q7QJ2KrtiGwZdalRrYKycUVDy4I7eLOHIX8zy14uO6LjVLyKezbFyW54a19AA "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~22~~ 18 bytes
```
9Œ!i⁼ṛɗƇ5s€3§;SEƲƇ
```
[Try it online!](https://tio.run/##ATUAyv9qZWxsef//OcWSIWnigbzhuZvJl8aHNXPigqwzwqc7U0XGssaH/8OHR@KCrGrigb7CtsK2/w "Jelly – Try It Online")
The Footer simply formats the output into a nice column of grids, remove it to see the list of matrices
-4 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748/jonathan-allan)
## How it works
```
9Œ!i⁼ṛɗƇ5s€3§;SEƲƇ - Main link. Takes no arguments
9 - Set the left argument to 9
Œ! - All permutations of [1,2,3,4,5,6,7,8,9]
ɗ 5 - Group the previous 3 links into a dyad f(p, 5):
i - Index of 5 in p
ṛ - Yield 5
⁼ - Does the index of 5 equal 5?
Ƈ - Keep those permutations for which f(p, 5) is true
s€3 - Split each into a 3x3 matrix
ƲƇ - Keep those matrices for which the following is true:
§ - Sums of the rows
S - Sums of the columns
; - Concatenate
E - Are all equal?
```
[Answer]
# [R](https://www.r-project.org/), ~~79~~ ~~78~~ ~~76~~ ~~75~~ 70 bytes
*Edit: -6 bytes thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
m=matrix(c(2,7,6,9,5,1,4,3,8),3)
while(print(m<-t(print(m[3:1,])))-2)1
```
[Try it online!](https://tio.run/##K/r/P9c2N7GkKLNCI1nDSMdcx0zHUsdUx1DHRMdYx0JTx1iTqzwjMydVo6AoM69EI9dGtwTGjDa2MtSJ1dTU1DXSNPz/HwA "R – Try It Online")
Hardcodes one square and loops though its rotations, displaying also a transposition with every iteration.
Abuses the fact that `while` takes only the first element in a vector/matrix to check the looping condition.
[Answer]
# [Haskell](https://www.haskell.org/), ~~102~~ 91 bytes
```
r=reverse
m=map
[id,r,m r,r.m r]<*>m(m$m((+0).read.pure).show)[[276,951,438],[294,753,618]]
```
[Try it online!](https://tio.run/##FcZLCoMwEADQvadw4SKxQ/D/gdobeIKQRcABQx0Nk7YeP9rN4602vHHbYuSJ8YccMKGJrE/Iuv2fOfXs9k@m3QIMlDKwujXP/EWCMhLiUUjFaBflv4xShfU4pdZV38HYltDUgwFdjQ30bQ1dORgT4wU "Haskell – Try It Online")
Doesn't actually bother calculating anything, just compresses a hard-coded output.
There are some tactics used for compression
1. We encode each row as a base 10 number and use `m((+0).read.pure).show` to turn it into a list of intergers.
2. We only encode 2 of the squares and use flips to get the remaining squares.
I tried also other methods
* Only encoding the first two rows / columns and calculating the remainder
* Encoding each starting square only as a single number and splitting it into pieces
Plus some specific optimizations that only make sense with the above (e.g. multiply by 33 or 66).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
```
9Lœε3ô}ʒ4.DÅ\ªsÅ/ªsÅ|ªO˜Ë
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f0ufo5HNbjQ9vqT01yUTP5XBrzKFVxYdb9cFkzaFV/qfnHO7@/x8A "05AB1E – Try It Online")
Brute force, takes ~42 seconds to run on TIO.
**Attempted explanation**
```
9Lœε3ô} # All possible 3×3 squares (1..9 permutations, chunk in 3 pieces)
ʒ4.D # Filter by (Create 4 copies of the current square first to get the parts)
Å\ªsÅ/ªsÅ|ª # Take the rows, cols and diagonals in a list (Through builtins and appending into one another)
O˜Ë # Flattened sums are equal? Determines magic square (filter)
```
Or, 23 bytes if flat lists of magic squares are acceptable:
```
9Lœʒ3ô4.DÅ\ªsÅ/ªsÅ|ªO˜Ë
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f0ufo5FOTjA9vMdFzOdwac2hV8eFWfTBZc2iV/@k5h7v//wcA "05AB1E – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 59 bytes
```
l="276","951","438"
exec"r=zip(*l);l=r[::-1];print r,l,;"*4
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P8dWycjcTElHydLUEEiaGFsocaVWpCYrFdlWZRZoaOVoWufYFkVbWekaxloXFGXmlSgU6eToWCtpmfz/DwA "Python 2 – Try It Online")
Prints the eight arrays space-separated.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 67 bytes
```
r=259149258
"
Q\x1EG\x1EQ
".bytes{|x|p (r+=x*1780218).digits 1000}
```
[Try it online!](https://tio.run/##KypNqvz/v8jWyNTS0MTSyNSCS4mLKzCmwtDVHUQEcinpJVWWpBZX11TUFChoFGnbVmgZmlsYGBlaaOqlZKZnlhQrGBoYGNT@/w8A "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•G´dI•S3ô4F=í=ø
```
This hard-coded approach is 4 bytes shorter than [the brute-force generator approach](https://codegolf.stackexchange.com/questions/233921/generate-all-3-times-3-magic-squares#comment534860_233936).
[Try it online.](https://tio.run/##yy9OTMpM/f//UcMi90NbUjyBdLDx4S0mbraH19oe3vH/PwA)
**Explanation:**
```
•G´dI• # Push compressed integer 276951438
S # Convert it to a list of digits: [2,7,6,9,5,1,4,3,8]
3ô # Split it into triplets to a 3x3 matrix: [[2,7,6],[9,5,1],[4,3,8]]
4F # Loop 4 times:
= # Print the current matrix with trailing newline (without popping the matrix)
í # Reverse each row
= # Print that matrix without popping as well
ø # Zip/transpose; swapping rows/columns
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•G´dI•` is `276951438`.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~29~~ 21 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Well, this is ~~pretty damned~~ *slightly* less hideous! Outputs a 3D-array.
```
4o!z49#ë7816ì ò3
cUmy
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=NG8hejQ5I%2bs3ODE27CDyMwpjVW15&footer=VvEgrm24t8NxUrI) (footer formats output into squares)
```
4o!z49#ë7816ì ò3\ncUmy
4o :Range [0,4)
!z :For each rotate the following that many times
49#ë7816 : 492357816
ì : To digit array
ò3 : Partitions of length 3
\n :Assign to variable U
c :Concat
Um : Map U
y : Transpose
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 15 bytes (30 nibbles)
```
:;`.`/3`D10`'.$\$.$\$ 1081f18e
```
```
`D10 # get base-10 digits of
1081f18e # data in hex: 1081f18e
# (digits are 2,7,6,9,5,1,4,3,8);
`/3 # split into chunks of 3
`. # and iterate over this while unique:
.$ # map over each group of 3 digits
\$ # reversing them
`' # and transpose the result;
; # now save these 4 magic squares
: # and join them to
.$ # each of themselves
\$ # reversed
```
[](https://i.stack.imgur.com/77HOY.png)
Using the decimal number `276951438` directly (instead of encoding it as data in hex) also comes-out at 15 bytes (`:;`.`/3`p276951438`'.$\$.$\`), since the final argument `$` of program code can be omitted & added implicitly by Nibbles.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 317 bytes
```
++++++>++>-[----->+>+>+>+>+>+>+>+>+>+>+>+<<<<<<<<<<<<]++++++++++>->++++>+++>----->++++++>++>-->----->+>>+++++>-----<<<<<<<<<<<<
<[->>.>.>.>.<.<.<.<.>>>>>.>.>.>.<.<.<.<<<<<.>>>>>>>>>.>.>.>.<.<.<.<<<<<<<<<..>>>>>>>>>.>.>.>.<.<.<.<<<<<<<<<.>>>>>.>.>.>.<.<.<.<<<<<.>.>.>.>.<.<.<.<..<<[->>>+>->>>->>+>>>+>-<<<<<<<<<<<<<]>]
```
Score includes one unnecessary newline for "clarity."
Line 1 sets the code up.
Line 2 prints a vertically mirrored pair (separated by `.`) on three rows, then the horizontal mirrors of the first pair (Slightly odd but more user readable than some other answers!)
Then, internally, the six values off the `4 5 6` diagonal are adjusted (by +/-6 each) to flip the square diagonally, and line 2 is run again to print the other four squares.
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGwzsgEg3WhcE7LSxQxskEKsNB3ZADRADgEyIfoSJujAhOzuoYhBANonLJlrXzk4PAm2g0A4EUMVAACKOXQ4sT1ABToPRHAAUBjnLDuQ7OxDWhnBsUALBLvb/fwA "brainfuck – Try It Online")
**Commented code**
```
++++++>++>- FIll cells 0 1 and 2 with 6 2 and 255 respectively for looping
[----->+>+>+>+>+>+>+>+>+>+>+>+<<<<<<<<<<<<] Iterate 255/5=51 times to fill cells 3 to 14 with ASCII "2"
++++++++++> Cell 2 = 10 for linefeed
->++++>+++>----->++++++>++>-->----->+>>+++++>-----<<<<<<<<<<<< Adjust cells 3 to 14 to 276/951/438/ (cannot include period in comments so used slash instead)
<[-> Iterate twice (counter in cell 1)
>.>.>.>.<.<.<.<.>>>>>.>.>.>.<.<.<.<<<<<.>>>>>>>>>.>.>.>.<.<.<.<<<<<<<<<.. Output characters for 1st pair of squares (each row needs more arrows to get away from cell 2 linefeed)
>>>>>>>>>.>.>.>.<.<.<.<<<<<<<<<.>>>>>.>.>.>.<.<.<.<<<<<.>.>.>.>.<.<.<.<.. Output characters for 2nd pair of squares (basically the reverse of the first)
<<[->>>+>->>>->>+>>>+>-<<<<<<<<<<<<<]> Flip diagonal by ajusting the 6 values off the 4 5 6 diagonal plus or minus 6
] And loop to output 3rd and 4th pairs of squares
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
”)‴vv»!C”F⁴«F²«D‖»⟲»⎚
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREPJwtAsJs/Y1Dwmz8TSSEnTmistv0hBw0RToZqLE8w0AjM5XUpzCzSA0pycQalpOanJJWBOLRdnUH5JYkkqiFfL5ZyTmlgEZP7//1@3LAcA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
”)‴vv»!C”
```
Write a compressed magic square of digits to the canvas.
```
F⁴«F²«D‖»⟲»
```
Output all the rotations and reflections of the canvas.
```
⎚
```
Clear the canvas so that there's no implicit output.
The squares can be padded for easier viewing at a cost of 3 bytes:
```
←&!↶⸿⦃3εⅉ‽”F⁴«F²«D‖»⟲»⎚
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREMpJk/BwtAMSBqbmgNJE0sjhZg8JU1rrrT8IgUNE02Fai5OMNMIzOR0Kc0t0ABKc3IGpablpCaXgDm1XJxB@SWJJakgXi2Xc05qYhGQ@f//f92yHAA "Charcoal – Try It Online") Link is to verbose version of code.
If two columns of four squares is acceptable output, then for 17 bytes:
```
”←&!↶⸿⦃3εⅉ‽”⟲C‖C¬
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREMpJk/BwtAMSBqbmgNJE0sjhZg8JU1rrqD8ksSSVOf8gkoNEC81LSc1uQTMtTq0RtP6////umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
”←&!↶⸿⦃3εⅉ‽”
```
Output a padded magic square. (An unpadded square would save 3 bytes, but it would make the output format unreadable.)
```
⟲C
```
Make a 90° rotated copy.
```
‖C¬
```
Make four reflected copies of each copy. (One of these is reflected both horizontally and vertically, which is equivalent to a 180° rotation. Also the horizontal and vertical reflections are simply 180° rotations of each other. This therefore produces all of the rotations and their reflections.)
[Answer]
# [Perl 5](https://www.perl.org/), 70 bytes
```
map{say for/.../g,''}map$_*1780218+275171220,unpack"W*",'
\zÁßİĺ'
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saC6OLFSIS2/SF9PT08/XUddvRYoqBKvZWhuYWBkaKFtZG5qaG5oZGSgU5pXkJicrRSupaSjzsgdU3W48fD8IxuO7FL///9ffkFJZn5e8X9d39KSNAsgVWaqZ2gAAA "Perl 5 – Try It Online")
Borrowed method from @dingledooper's python3 answer.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 47 bytes
```
⎕←(3 3⍴⍕)¨1↓+\50863752,1780218×1+⎕UCS'~ P
F
P '
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtEzSMFYwf9W551DtV89AKw0dtk7VjTA0szIzNTY10DM0tDIwMLQ5PN9QGKg51Dlav4wyQdZMN4FT//x8A "APL (Dyalog Unicode) – Try It Online")
nice, my sixth APL answer
fast hardcoding (fork of dingledooper method)
`'`...`'` magic string
`⎕UCS` cast to unicode codepoints
`1+` increment
...`×` multiply by magic
...`,` prepend by magic
`+\` cumulative sum
`1↓` decapitate
`(`...`)¨` for each
`⍕` stringify
`3 3⍴` mold to 3×3 matrix
`⎕←` to stdout
[Answer]
# [Haskell](https://www.haskell.org/), 215 bytes, intractable for n>3
```
import Data.List
m n|let g=sum[1..n^2]`div`n=filter(\s->and[all((g==).sum)(m++[d])|
m<-[s,reverse.transpose$s],let d=map(\i->m!!i!!i)[0..n-1]]).
map(takeWhile(>[]).map(take n).iterate(drop n))$permutations[1..n^2]
```
[Try it online!](https://tio.run/##NY4xbwIxDIV3fkWQbkgEF5V2bW5i7N4hpMLSuWAR56LYMPHfr@mA5MXf8/N7V5Ab5ryuxHVpao6g4L9IdMOmPDOquQS5czx4X37e03mmx7mEX8qKzZ5knKDMEXK29hKC8/3UWd7t4pzcc2P4c4yyb/jAJui1QZG6CA6S9v@v58BQ7YnGibdb6uPiW88ZDyk5391dVLjh95Uy2il2@EKmOE@9AijauS21726o2PiuoLQUeRVeGaiE2qjowOZj/QM "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 361 bytes, intractable for n>4
```
import Data.List
s 0 l=[[]]
s n[]=[]
s n(a:b)=map(a:)(s(n-1)b)++s n b
m n|let g=sum[1..n^2]`div`n=
filter(\m->g==sum(map(\i->m!!(n-i-1)!!i)[0..n-1]))$
filter(\m->g==sum(map(\i->m!!i!!i)[0..n-1]))$concatMap permutations$
filter(all((g==).sum).transpose)$concatMap(sequence.map permutations)$
filter(([1..n^2]==).sort.concat)$s n$filter((g==).sum)$s n[1..n^2]
```
[Try it online!](https://tio.run/##hZDBTsQgEIbvfQpIeoBsSlrjyYQ9edQnYGt2WnF3IkwRqCffvdI11c1evP2B//sY5gzp3Tq3LOjDFDN7hAzqCVOuEmuZ08b0fYlkem0uQcDDILWHUIIUSVDTyUHuduWKDZVn9OVsZiedZm86pejlrj@@4ueRdMXe0GUbxcE3@5NeG2L1HLDZe86LCYuLc5SmLWDT9VLW/0B4Ux8nGiE/Q2DBRj9nyDhR@rOAc0IUjVRFJFWOQClMyV6RItmP2dJolb/RXE0jtr9dVGVx6oeXddlDvZV@H1pPN2LxgKRDRMq1Z/ect8s3 "Haskell – Try It Online")
# [Haskell](https://www.haskell.org/), 472 bytes, intractable for n>5
```
import Data.List
m n=let
g=sum[1..n^2]`div`n
t 1 _ s x l=[[x]|sum x==s]
t i 0 0 r l=map([]:)(t(i-1)n g(l++r)[])
t i j s (a:b) l|i>0&&j>0&&s>0=map(\(e:f)->(a:e):f)(t i(j-1)(s-a)b l)++t i j s b(l++[a])
t _ _ _ _ _=[]
u s[c]=[[s]|elem s c]
u s(a:b)=[e:f|e<-a,f<-u(s-e)b]
v m@([c]:_)=[transpose$m]
v m=[x:y|x<-u g m,y<-v(map(\\x)m)]
in
filter(\m->g==sum(map(\i->m!!(n-i-1)!!i)[0..n-1])).
filter(\m->g==sum(map(\i->m!!i!!i)[0..n-1])).
concatMap v$t n n g[1..n^2][]
```
[Try it online!](https://tio.run/##hZFBasMwEEX3OcUYQpBwZOxCNyYyXXTZnkBRU8VVXKWSYizFOOC7u@OYrLooA0Lov/9nGH2r8KOtnSbj2ksX4VVFlb2ZEFcOPLc6rqDh4epEkWX@40l@fpn@068gQgEHCDCA5UIMckQGBs6DnDUDOVaHmlMtEbKkJBLDCuqhITZNOyokXcAzhhBVHinY0VT5ZnOej1Dld@ue6PJEWYWEpngjaCFnDCKBKXoES9P0kXKck4Vagg@P4gInukIQtcRBgxy11Q7penm@t@YCu4x6x9T2tGNXzNb0iHoP7oWgsTwgEjvlQ3sJeu0WiYuhvI0DGqABt73tWE/uM@8H6igyBvd0Mjbqjuwdqxo@L3JBDKtckhDP5qUkiaEix/2yQlKa/WMyf/D64msV31UL/TqCx2oe3yXk5JTxvO2Mj2sHz0mST78 "Haskell – Try It Online")
[Answer]
# [MATLAB](https://www.mathworks.com/products/matlab.html)/[Octave](https://www.gnu.org/software/octave/), ~~165~~ ~~163~~ ~~155~~ 153 bytes
Using the `magic` function directly in MATLAB/Octave for a \$3\times3\$ magic square would only generate a single solution, not all \$8\$ possible solutions.
\$\textbf{Saved 12 bytes thanks to the comment of @ceilingcat} \$
---
Golfed version. [Try it online!](https://tio.run/##XY5BCsMgFESv4ir9n0qJEUui/MNINa0QG9G017cm2XUxMPNmMbM@Nvv1tSZKPscCQk9oEmiukJSZ18wCCS3vwzj2PMzMLguUT4RM2ZeXTR4SBK6RSy4RiYTquqO/Xc60BxfsEzL@g3Wb@h0fHFlsq5r7t7sKpGyaYU3VhZLg7IZ2Dk39AQ)
```
p=perms(1:9);p(:,5)=5;for i=1:362880,if all(sum(r=reshape(p(i,:),3,3))==15&&sum(r.')==15&sum(diag(r))==15&sum(diag(rot90(r)))==15) m(:,:,end+1)=r;end end
```
---
Ungolfed version. [Try it online!](https://tio.run/##fY9NCsIwEIX3PcWsNIFBGttqf@hJQhehTTVgTExaF718TYoILnSYgWG@x2Oe6SfxlOtqoQUrnfaEMzhCBjmc4AwlVB1tEh3oIp3xJEMInYbbaByoltVeLZJYZDSBUC4ouSUKWZ1TLDCuRV3SrvlgJ/1VWEkc8gyzaB@JGkF5@ZjFjfhZE0eRswK27ijsdt/0sP/LByUuwYIiK34wM1VpVGyS7YFYMWcvppBSo3s/Ju9DEmdQ3hIdjuv6Ag)
```
p = perms([1 2 3 4 6 7 8 9]);
m = zeros(3, 3, 0);
for i=1:size(p,1)
r = [p(i,1:4),5,p(i,5:8)];
r = reshape(r,[3,3]);
if isequal(sum(r),[15 15 15]) && isequal(sum(r.'),[15 15 15]) && isequal(sum(diag(r)),15) && isequal(sum(diag(rot90(r))),15)
m = cat(3,m,r);
end
end
disp(m);
```
] |
[Question]
[
The task is simple. You are given a string with **alphabetical words** (say `"Hello world, this are tests"`). You have to return the [**mode**](https://en.wikipedia.org/wiki/Mode_(statistics)) of the lengths of words in the string. In this case, output is `5`, as it's the *most often length* of words in the string.
Definition of an alphabetical word (for this challenge): a string that consists of `a-zA-Z` only.
### Sample I/O:
**Constraints:** Input has *atleast* one word, and a *unique* mode. Max. length is provided in last test case. Also, the string would be a single line, no newline chars.
(`In = Out` format)
```
"Hello world, this are tests" = 5
"Hello world, this... are tests" = 5
"I" = 1
"Let's box (ง︡'-'︠)ง" = 3
"Writing some ✍(◔◡◔) program" = 7
"the-the-the-then" = 3
"Gooooooooogle is an app" = 2
"()<>a+/sentence$#@(@with::many---_symbols{}|~~" = 4
"anot_her test actually" = 4
```
The unicode tests are *optional*.
[1000 words string](https://www.protectedtext.com/lorem-ipsum) = 5 (Password: `PXuCdMj5u65vwst`)
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes will win!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~10~~ ~~9~~ 7 bytes
-1 byte inspired by [Jonathan Allans Jelly answer](https://codegolf.stackexchange.com/a/209328/64121).
-2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!
Input is a list of characters.
```
aγO0K.M
```
[Try it online!](https://tio.run/##yy9OTMpM/f8/8dxmfwNvPd///6OVNJR0lDSB2AaI7YA4EYi1gVgfiIuBOBWI84C4BImdDGWrALEyEDsAsQaULgfiTKj6DCC2guJcqNkg/ZVArIuE46F2VULVJQFxPhDnQMWrgbgWiGuAuA6MYwE "05AB1E – Try It Online")
### Commented:
```
aγO0K.M implicit input ["a","b"," ","c","d"," ","e","."]
a is_alpha (vectorizes)[1, 1, 0, 0, 1, 1, 0, 1, 0]
γ split into chunks of equal elements
[[1, 1], [0, 0], [1, 1], [0], [1], [0]]
O sum the lists [2, 0, 2, 0, 1, 0]
0K remove 0's
.M mode 2
implicit output 2
```
`a` is implemented as `Regex.match?(~r/^[a-zA-Z]+$/, to_string(x))`, which should be equivalent to the challenge specification.
~~I feel like there has to be a shorter way to remove `0`s from a list than `ʒĀ}`.~~
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 30 [bytes](https://codegolf.meta.stackexchange.com/questions/9428/when-can-apl-characters-be-counted-as-1-byte-each/)
```
{⍵[⊃⍒+/∘.=⍨⍵]}≢¨⊆⍨⎕A∊⍨1(819⌶)⎕
```
[Try it online!](https://tio.run/##bY/BSsNAEIbvfYoFhU2oSclNi0o9qeDdg0jZttsksNkN2ZUaansR2liMFFHqwYP11AdQydknkXmBPkLcCMIi/jDDzD/fDAyJmdNLCRN@Cdm0Xw4hfz@D2TXk9/UGZE/uHuQr7Z2P4Ob1cwWzSdXfPR5ANtOVZ217O3D7YWurOlD2a7qCyRwfUcYEGoiE9baQCkKJSEKRolJJXPtDaRmg67r/sR7kb/jY2D2hCmOJOuISWV/FdF0sMXYwXhcvtm4N8DQJVch9JEVEETznFiweYLHU2UZxIvyERAatAuoYwY3RofiVzyiqXuKIxLFBWPbuPqk3JOWK8i7d3GhZrUGogmYzIjx1HKct06gjmByOrsZjY5FwodoBTX6@RqSrLghjKf4G "APL (Dyalog Unicode) – Try It Online")
```
{⍵[⊃⍒+/∘.=⍨⍵]}≢¨⊆⍨⎕A∊⍨1(819⌶)⎕ ⍝ Full program
1(819⌶)⎕ ⍝ Uppercase the input
⎕A∊⍨ ⍝ Test if each character is a capital letter
⊆⍨ ⍝ Group the letters together
≢¨ ⍝ Length of each word
{⍵[⊃⍒+/∘.=⍨⍵]} ⍝ Mode
```
The mode dfn is by [ngn](https://codegolf.stackexchange.com/a/43008/68261). My approach was similar but one byte longer: `{⊃⍵[⍒+/¨⍵⍷¨⊂⍵]}`.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 70 ~~68~~ 58 bytes
```
->s{(s=s.scan(/[a-z]+/i).map &:size).max_by{|y|s.count y}}
```
[Try it online!](https://tio.run/##VU7BasJAEL37FYMtNUF3vYcq3tpC7z0EkU26msBmN@yM6JrEa0@9Fbz0UP/Czyn@gJ8Q3YJgH8xjZt578Owyce181LIxVgGOkGMqdDCMBdtM@8M85IUo4SHCfCP9vp4lrqpdjTw1S03gmqaNO91nqZSBlbHqfQCU5QjCSiCJhN3BVb7gxsE5/2968fQqqYeQmDUEv4eP02HfY73T4Se8HF5@sznlegFoCgnH78/guPs67vYXDqG0ZmFF4W2USXYz2v@ezBULJcE31CDK0ktB@DgW/SFKTVKn8v5uEkxWOWVRVAjtGGMzdEViFFZNvd36hNCGZpm0f@1BpLQUSrluZ8qlSLMKaqqhhHlMU2jaMw "Ruby – Try It Online")
-20 bytes from Dingus.
-2 bytes from Rahul Verma.
-10 bytes from Dingus(again) by removing a variable.
# [Ruby](https://www.ruby-lang.org/), 90 bytes
```
->a{a.split(/\W+/).map(&:size).inject(Hash.new(0)){|h,v|h[v]+=1;h}.sort_by{|k,v|v}[-1][0]}
```
[Try it online!](https://tio.run/##tVnLrhy3EV1HX0EoQXQvxDuyt3JsOMjLAhLHgSB7cSMYnG7ODJV@qUmOrqIrb7PKLoA3WcR/oc8J9AP@BKWeJFtJgCCABWjkme4mq06dOnXYXvP@5bvDx@@uPnGv3C4uQ0gXD/741f0Hl7vRLRc/fRjDn/3lLkzPfJcuPnPxtJv8i4sPLi9f3Z7s@fZ0fX56/@MPPzq93sV5TV/vX766/RP8fn59ffXh0@sPnr5@d333Mz8Ms3kxr0NvTTqFaNzqTfIxxbv2jlyGP80du91ue9Mj/PitT/ei2c835uKfb/7y/Zvv7l3d@/7NPy7hC17@ag0pTEcT59Gbt3//68Xbb//29tvv4PPSLOt8XN2It6WTv2r@Tvjbb2b9cxy8wQgn45YFL11c/uwTd/9B9FPyU@d/8uNPLz59EdLp4cPRTS@vrq6@ji/H/TzEV69vv/mGwpxXP5qwxDyafh7m1cSQjBt9sqabpwhQ@pRX4/qwhNhhyB6A35nfzes@wC3jOPezcblL8Kyfwrgzn@dhcObgujCEGPQ7RN@vHtLGdc9ugGvm4PHT53arnfm5nzzk5A@H0AXcfHBdBizDHpaAOId5D/WDB@Pcu8FH2MGN5nmGX0aXV0QkGb/ChxvC8wzXoh8Xv5rJd/L3efY78wUUE5GK8M2c3D4kNyUzUmIJlkkBLwCYEBns7xM8KP8x4r7Z9Zjm6GHDzkCgCyZzBBq4qACFCe5NGOwA4a/zznwJ18M@D5AIMKALfYZNOUNKwa1dhmduwohbDT4cIGsARVJxzVPRLcFPtqR5hlAnlwiH4@QE@dEcwgQ7RjPlqTNLXnO0GFgeIMsuQPgDsWCZY/ZA5DDtzK9z7LwCTKANjMIZUIILcBkIkfRGirzWlba3AF0PJc7HAKXAAJUK0R0DYmKVcnCfhxWASiVjq4AybiZgBfsA2M99mC2WuOXnGVlZapAUgC9W57EblGnrDJu6rstjBIblZM5uDZgV/WOh@AOWxwPMg5@b59fTPGGJyrNTiIOZZi3vzvxidXDZjIHR3Jnfr13Q9aEqM5Jpofrsc4kRgurh7@JWiD144h9S0sIjACymtoY@dMAXgDVHBVzh0kJIgk7xVv4BLmY5gTyl1UH9AX1MaobqB9hmxXYCbpwgbCulPazQ5AHLRBg2VIe1YFnuMNnfinQA/895WHJyycN9JwwYCODyEZIGZUBxgHLhN@S3ZcIkaEu4QLQcwhEewbJK6R4TKRhnKMuAdIEl@jACSkWtHOjUAtmFLCqGEfoOYI7l9y6vEdFzMUJMXDNpr5taUGT9I8DkCEKxQD@SgMC3wp1U9eZxjlBJKFz0jUwxXvxIAVGaSuuh9bIsQhSNxEd0hjaBaxAX0LA0JFaIOlb7UXkO99TtKUzGDfuVBRDYBQJQOz0iknh/j/lyTNhKHAJpwza9pskstV7p0I0IstYjbbGYnJviz6Wllu1BsYj9GJyUnKjgb4CXJxdBkhmKWmd5ZKZ2AjoD/QeYI5E0/HPcDvqYruroQr1XckHv4CoiW4BNoi2a1q7gLHk4h8mBmoSzX1dXp1yDASsNFnZNDsHgOC1V41mOaZZLyFyoWq8jQRibVyBJYV30LWMbhPocRFNKVrXUFINlStZ68hRpcXRlaMBkQ1GTkpQZW9bmTiXNQwIxXHXSTDTIm9FF63HvL2sYoYKw/wFsQK3VkHVsMsIIsBC6y3vgi0PaOf@RSBoxFXaw6iZKuEQRW3UMy4gBtKnmVBtIwn00NRNRxhc/9ssZO0S0mWuGP5BCqILinGj6WMZQkddfJWqsRMVOAePF7qBdhXPFsHC7woKG5nE3r@hGCEIdj7A9hCVTtHB/U12eoBy6Lm0lekREvZiibZlqOPMaHKjQlFu1OEzMouQjuhzmAfjQc@gdNRTkSlfqKLaNdFBHrzmtyK6Ns9LRyQ@XwUXehRmKK5FsaqewH2HXVkZOtRfCrBnSQ2V9klpN@DdBLhw/@JVx3SqcdJwlY4v9WmRAjablKQTrI9GaEqLftf@pQWmmkloCnq31gYmmhqYvMi6QaOF0xrsyFeFeqqVYSdYXnOE96W11h@d5yGlB4U/ST6n2/Jfh7HDqcR70aat0Y2iVJlgOW5eDvUiQilLpBNV/afcCcJPKhgoQr@ob9yNNteJE@PhQ9ijTrhD1vyxbxvWy2UxpqtjL4YBckG38Spj0gJAh55pErSu0EPdDlSCmbwDFHcjDtemz8y0az@ZeqiwjC1e9qdNDY6sS1prbEkj14SIWZRaL/yWn1Zh7r9XeDw7ojpOx5@OSdjbxikYwiqYeFRpS1ynPDVy@q5FUu8fAYrawRkG7wGwp@hIWjYhaT5lHaIeKpcXQtq1aG5LEs1U9rqDl4xN/8BSR8w6uXCqCo5paFDiPgZBqn6Df@BSIWwGnknci5TG9xzhZuxwCCP2CDBWglIZu2hxwWcPZ1IpX2sifxlkPkdIgLPYgxNgpon8b0rcTUU99qN044RGTMqzem24cRCNtjRdGsbHY/kyrqn56aCKEVcxaJUZR4LJXXvOs4UlbPCA3V7Ub1MxyoEcJr@OOcFJbQKNt62jlxFtPi2zeea3iSZRH71WVUdBTdZtqlYIbzMc2Sok@M0d130W81ANI3wF8TU/pAZhHRPEJuUjVRsjKPJKT0ZNUGVGusa1l5RFisO7UsYnYKfnQlsYkivtD@Tr2SAJQff@DZ02qo4LDbGjc5jwxI0K/sUNkT/@QmVxFeolQXpkl1l3sfx169T1EYRVkxrEpKEXd8ZjBQQU9nhUbwtaYDzB80OeHpeBtvDJiWzWm57QzXXl/wsZJOgmy1tcSKp5bGZS7K2DlCKPBNK8pUOWOXkGWQbdtGsWoMdDEQjxSsAGRx8TKNX6jtAGd@/hUz8f9@iKHftWx0JyQSrfS@x9UUMRdmrCREUkXTVDzYgdHz6ZNWPSbJNQWkLrXwYMtJ5X7Yd8ACv2bdfribPt622bACUr81rJiYBtvSXqebWE6sQzOitBze7qhquWknrMP@KophiYcK/OctpLDspwrAelqC/k61xTwl91kXkPW2sT@phG4tpPwLaHypby6bbSetnRKeSGciAw1GxsWXKvIFElIruqH/ku5z7lYDpy7tYTTdKfVrcSoCMXVQvGD29d9tCLqIWs9S3XNBEekHK@aIYW/qulFgX9M1lBVEQPnVOT2MbQznF/i0BszNv1ObYOjF/Ry4lPn97/4mEbsqTFVR0n02ScVPy0vyp9UyapWW08VjEIxgUxwfQGsfJAWFqir7aVjb2Uu@1AmLcbatoZQVMOFcpGyKrSsK80MwZXbwdaJE@bxXl9klr7CechjGo1@eQOIulRfEdUR7XTMCnCh9Zd0YGA6Uk6FqPz@ob7wQc3it9KaiCspQilsozNZx7XYbiLoxkbrS44yr4uzEDZLn0jzVu/A3U2nCypfPQNJd@/M//0/itoaVltGsNKcv/t05113gkXN7bPbOz9azOH62dM78Mi7fwE "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~79~~ 67 bytes
*Edit: -9 and then -3 more bytes thanks to Giuseppe*
```
names(sort(-table(nchar(el(strsplit(scan(,''),"[^a-zA-Z]+"))))))[1]
```
[Try it online!](https://tio.run/##HcHhCoJADADgd7HAHTqivxJhr5FYzGOgcDfjNgi1fPUL@r6Us1BkBZ2TARoNgUH8SAk4gFrSV5gM1JNAXZauLroH4XrDe18V7q879xnc5UrVSVmMxfPx0EL7nmxsmkiyIOJTlzjMQbfvZ9/zDw "R – Try It Online")
Commented:
```
names( # Get the names (=values) of...
sort(- # the descending (-) frequencies of...
table( # the table of values of...
(w=nchar( # the number of characters of...
strsplit(scan(,''),
# the input, grouped by splitting on...
"[^a-zA-Z0-9]")[[1]]))
# non-alphanumeric characters...
[w>0] # ignoring zero-length groups.
)
)
)[1] # Output the first name, which is
# the most-frequent number of characters
# per group.
```
[Answer]
# JavaScript (ES6), 66 bytes
```
s=>s.replace(o=/[a-z]+/gi,w=>o[s]>(o[n=w.length]=-~o[n])?0:s=n)&&s
```
[Try it online!](https://tio.run/##jdHNSsNAEAfwu0@xVGl3aTfxE6GY2JsK3j2UINt0mkQ2uyGzGOtHr568Cb14sG@Rx5G@QB8hJoJQQlr9ww7M5Tcz7J24F@inUWK40mMoJk6BjotWCokUPlDt2EPBH72uHUS9zHH1ED2X6qFyMkuCCkzoOXxW9h473@@jo1i7jYWvFWoJltQBndDWJUipSaZTOe4RE0ZIRArEABpsMUaaYtuEnOw0OmXWKMuytmmNztWmqZtTOQd15xpMB8lIPxD6lb@u8kWHd1b5JyubvydU4lFdvEkjE6mAoI6BLD/e6HL@vpwvyspIkuogFXGzXGmndc2EwNee@sfZjVtd6N8EEkj1fYqIJNnGVc5h3aHszBVdG0EZUD7s7Q7oIItM2O/HQk0557c4jUda4tPL82z2w1fOcfEN "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 43 bytes
```
M!i`[a-z]+
%M`.
O#`
O#^$`(.+)(¶\1)*
$#2
1G`
```
[Try it online!](https://tio.run/##TY7NSsNAHMTv@xR/SUo2xl2pxyLSWxUsHj340WzrnySw2Q27KzV@9OrJm9CLB/sSkrNPInmBPkJcFSEDMzDMHH4GXaFEN6CTtJvuFOmFYPdXCRlMU07OgtT7OkwpT2L6@XE5jHdJGByQoT93xyilhqU28mYPXF5YEAbBoXWW/G1evZlz3nuckFN0kYW5vgP61Txvm03Eom3zHvtCzk3hsTKwukRo315ou35t1xufMVRGZ0aUxOXIelZkov@VSYQfHgWiqgiND49Esm9ROVQLDIMxHS8Ll49GpVA1Y2xm63KupX14elytiFDazXI0v6AgFu5WSFl/Aw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
M!i`[a-z]+
```
List only the words.
```
%M`.
```
Take the length of each word.
```
O#`
```
Sort the lengths numerically.
```
O#^$`(.+)(¶\1)*
$#2
```
Sort in reverse order of frequency.
```
1G`
```
Take the mode.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
e€ØẠŒg§ḟ0Æṃ
```
A monadic Link accepting a list of characters which yields an integer.
**[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzMe7lpwdFL6oeUPd8w3ONz2cGfz////lRLz8kviM1KLFEpSi0sUEpNLShOBWpQA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/z/1UdOawzMe7lpwdFL6oeUPd8w3ONz2cGfz/8PtQIn//6O5lDyACvMVyvOLclJ0FEoyMosVEotSFUpSi0uKlXRg0kCApEJPTw9VkSeI8EktUS9WSMqvUNB4sKP9/Y6F6rrq73cs0ARyQNLhRZklmXnpCsX5uakKj@b0ajyaPuXR9IVAUlOhoCg/vSgxF6SsJCNVFwnngcTc82EgPSdVAeTCPIXEggKQlIamjV2itn5xal5Jal5yqoqyg4ZDeWZJhpVVbmJepa6ubnxxZW5Sfk5xdW1NXR1IR2Jefkl8RmoR2PUKicklpYnAkALKxAIA "Jelly – Try It Online").
### How?
```
e€ØẠŒg§ḟ0Æṃ - Link: S
ØẠ - alphabetic characters
€ - for each (c in S)
e - (c) exists in (S)?
Œg - group runs of equal elements (1s or 0s)
§ - sums
0 - zero
ḟ - filter discard
Æṃ - mode
```
[Answer]
# [Perl 5](https://www.perl.org/) `-pF'[^A-Za-z]+'`, 51 bytes
```
map$k{y///c}++,@F;$_=(sort{$k{$b}-$k{$a}}keys%k)[0]
```
[Try it online!](https://tio.run/##FcjdCoIwGADQh2nhZH3NLryxH@zGu14gMZkyUHQ/uEGsNR@9VVcHjubLnMcomEaTd5TSPhCyK6sjas/YqMX636MuwB8WwsSd2U5pnTUx4vR0YYQaLi2XPUebEpfP0Q5FIZh0ANAaJzo1Gx/e6/pR2o5Kmgi3fJ8dsgh6rpL6cYU7g1dDki8 "Perl 5 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
3Y4XXzXM
```
Supports ASCII characters only. [Try it online!](https://tio.run/##y00syfn/3zjSJCKiKsL3/3/1xLz8kviM1CKFktTiEoXE5JLSxJycSnUA) Or [verify all ASCII test cases](https://tio.run/##VU27CsIwFN39ioBCK5o66FREOgjq4OZQp3rViyncJqW5Uuqjvx6jKNQDZznPApjcwU33szS9pVu33LlgjURG1Kai81iwyq2ACgWjZRv0vq5HJxBF0V9m48kKZYfaSyvzw4VQvHe1gLL0TjicL2A0sagZ9QkH/SRM6pxVHBegGyllZpviaMjen4@29QXQhjOF1edSwImvQNQELw).
### How it works
```
3Y4 % Push predefined literal '[A-Za-z]+'
XX % Implicit input. Regexp. Gives cell array of matched substrings
z % Number of nonzero chars of each substring
XM % Mode. Implicit display
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 18 bytes
```
aMR:+XA#_(_NaSKav)
```
[Try it online!](https://tio.run/##K8gs@P8/0TfISjvCUTleI94vMdg7sUzz////Gpo2dona@sWpeSWpecmpKsoOGg7lmSUZVla5iXmVurq68cWVuUn5OcXVtTV1dQA "Pip – Try It Online")
### Explanation
```
aMR:+XA#_(_NaSKav)
a is 1st cmdline arg; v is -1 (implicit)
aMR: Map a function to each regex match in a and assign the result back to a
+XA Regex: a letter (XA) repeated one or more times (+)
#_ The function: length of the match
Now we just need to get the mode:
SKa Sort a using this key function:
_Na Count of each element in the full list a
( v) Since it's now sorted from least common to most, get the last element
```
If Pip had a two-byte builtin for getting the mode of a list, I could do this in 10 bytes: `MO#*Ya@+XA` (with `MO` being the mode builtin). Ah well.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~148~~ ~~143~~ ~~140~~ ~~132~~ ~~100~~ 99 bytes
```
n,*c=0,
for x in input()+'1':
if'`'<x.lower()<'{':n+=1
elif n:c+=n,;n=0
print(max(c,key=c.count))
```
[Try it online!](https://tio.run/##DcvRCoMgFADQd79C2ECd1oq9uRz9ydbESGbXKKOkrV93wXk9Qwydh1tKIC5aFQK1fsQrtnAY5kAZJyWRCNuWvEi15s4vZqSsIhuRwFWJsHG2xSA1VyDuoAo0jBYC7ZuVavExUelc@xkCYykd8dHw62QgGNDmfKppvdjQSdk3ELMse06xf3s3bb/vvv8B "Python 3 – Try It Online")
Uses regex to check if character is a letter of the English alphabet and adds the count of all consecutive alphabets to a list and finds the mode of that list.
*-3 bytes thanks to Rahul Verma*
*-32 bytes thanks to ovs*
*-1 byte thanks to DLosc*
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12~~ 8 bytes
```
►=mLmf√w
```
[Try it online!](https://tio.run/##yygtzv7//9G0Xba5Prlpjzpmlf///98jNScnX6E8vygnRUehJCOzWCGxKFWhJLW4pBgA "Husk – Try It Online")
Previous answer was badly optimized.(-4 bytes)
From Zgarb:
>
> ► has a second mode. If you give it a binary function f, it returns an element x that maximizes the number of elements y for which fxy holds.
>
>
>
>
> So ►= is a 2-byte max by frequency.
>
>
>
## Explanation
```
►=fImLmf√ġK√
ġK√ group string on non alphabet-characters.
f√ filter out non-alphabet characters
m map that to each word ↑
mL Length of each word
fI filter out zeroes (empty string length)
►= max by frequency
```
[Answer]
# Scala, 66 bytes
```
"[a-zA-Z]+".r.findAllIn(_).toSeq.groupBy(_.size)maxBy(_._2.size)_1
```
[Try it in Scastie](https://scastie.scala-lang.org/JBEhqkOXTjSKfbRejhGaOg)
Unfortunately, finding the mode in Scala is a bit clumsy
[Answer]
# [Io](http://iolanguage.org/), 141 bytes
A really awful solution... just 2 bytes shorter than the Python one. 3
```
method(x,x asUppercase asList map(i,if(if(i at(0),i at(0),0)isLetter,1,0))join split("0")map(size)remove(0)uniqueCount map(reverse)max at(1))
```
[Try it online!](https://tio.run/##dZBLTgJBEIb3nqIymtAdZxC3RA2JCzVha9yYkAYKpk0/xu4aGHywdeXOhI0LuQXHMVyAI4w9GpRZWKl@/Knvr1S3tOUI2qdwW2qk1A5ZERcg/HWWoRsIj@HelZ5Ai4zJWI5YlSCItXi8PVtc@i4SoYuPg@B3VhrwmZLEolbEK6uXD8gdajvB4MiNvM/x3Obmp7HDCTqPgSyqlseclyMWXaJSFqbWqWEMlEoPwiEQevIRh8xJQ8rs/YIhdthms/kfflWXYfKGh74tgH2uXjarZSNpbFYfPIg6eOMkSTMGbzXC@v2VrRdv68Uy7BVmx07ouoFSTHaWqVcv7DbGCqF6nQGRZXWI8ZMzcXjk0RCaAR7sd1hnKiltt7UwsyRJen6m@1b5x@en@bzuFcZSL0X3/QcgBpQLpWZ/TPkF "Io – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 129 bytes
*Saved 10 bytes thanks to @ceilingcat!*
```
s->{int m=0,z=s.length()+1,a[]=new int[z];for(var x:s.split("[^a-zA-Z]+"))a[x.length()]++;for(;z-->0;m=a[z]>a[m]?z:m);return m;};
```
[Try it online!](https://tio.run/##fZHNbtNAEMfvPMUqIMWWs0u5xrUpF6ASB6QekGqZauJs7A37Ye2Ok9ghvXLihtQLB/oWeRyUF@gjhI0LiIsZab/0//9mRrNLWAFdzj8dCwnOkffbuplJURCHgP5YGTEnCoQOrtAKXWZ5GW5XYIlJrlqHXDHTYLz0SViDQrJFowsURrPXvy/nj9zkUiMvuU0XydHRdCs0EpWcTbrEMcl1iVUQRi8mkOWJ5mvi5azL44WxwanYZuqYq6XAYJR9BNq9otd5NApDyDZ/6TyKen/cUZqexSoBnyGFTOUvu6kKY8uxsZqoeBcfDat9Uyh1sGBQ17INRm@5lIasjZVzgpVwBCwnzihOkDt0vlj8ZBDz0ZOTHmWM9fR/wcsh4R3HsSMzsyHBz/2Xh/39mI4f9j9C/xhCPliBfsaP7R6@fw0Od98Od/d@D0ltTWlBDaFYcfrP0kO@N@ZPlJKT03g08dKQPQjPU4ieO@5/XRf82dOL4GItsJpOFeiWUnrjWjUz0m13n29vh7KANnhTcdtPkkCBDUjZnty73fEX "Java (JDK) – Try It Online")
---
Explanation:
```
s -> {
int m=0, //m is the index of the max element in a
z=s.length()+1, //z is to avoid using a.length twice
a[]=new int[z]; //Each index corresponds to a length, and the element at that index its frequency
for(var x : s.split("[^a-zA-Z]+")) //Fill up the pigeonholes
a[x.length()]++;
for(; //Find the index of the max element/highest frequency/mode
z-->0; //For every index from a.length to 0,
m=a[z]>a[m]?z:m); //If the current element is greater than the current max frequency, change the mode length
return m; //Return the length with the highest frequency
};
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 113 bytes
```
s->{int m=0,l=s.length(),t,L=0;for(;l>0;L=t>m?(m=t)-m+l:L)t=s.split("\\b[a-zA-Z]{"+l--+"}\\b").length;return-~L;}
```
[Try it online!](https://tio.run/##VZDNbhMxEMfveYrRQhQvWS@5cMl2l/YCVAqnIiHRVpWTOLsO/ljZsylpSK6ceqvUCwf6FnkclBfoIxhnEyQYaWzNzM9/z8ycLRidT796oWpjEeYhThsUMp01eoLC6PRV1plI5hx8ZELDqgNQN2MpJuCQYbgWRkxBhRq5QCt0eXkNzJYublGAT@Zc47uj2MkBKWAGuXe0WAmNoPJBInOXSq5LrEicYDLKB9nMWJLJYpCNcizUW6JyjKnqy@EoxkC7Wgok0dXV@JLRuzP65XoV9SWl/WgdclF8lMssx8Zquhlla5@1HQVhIAtmAbnD4X/NAlwsHXKVmgbTOrSKMxJ16ZuBA1pAd9rVUdI@S2CWsrqWyzMXxiP7VBwf5Nedva@9/8ClNHBrrJwCVsKFnzg4o3ir4I71YC2StEyapi12IM79iGPPwdh8A/J7@@N5@9SjveftrzgE/rMVGJZ5kNz9vCe7x4fd41M4Y6itKS1THitO/3Ht35u/VkoO@6Y0hEE8iU8K1n/tuEauJ/zli1NyeiuwGg4V00tK6Y1bqrGRbrX@vtl4pg3eVPywQ2ATbJiUyz8 "Java (JDK) – Try It Online")
## Explanation
This basically splits the String on ascii words of all possible lengths to count them, and returns the max value of the count.
```
s->{
int m=0, // The maximum number of
l=s.length(), // The length of ASCII letters, going from high to low
t, // Declare a temp variable.
L=0; // Initialize the most present length to 0.
for( // Loop
;
l>0; // On each length, going down
L=t>m?(m=t)-m+l:L // If a count is higher than the max count, the new count becomes the max count and the most present length becomes the current length
)
t=
s.split("\\b[a-zA-Z]{"+l--+"}\\b") // Count the number of parts between or around words of length l
// Also, decrement l
.length; // Store the count into t
return-~L; // Return L + 1
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~115~~ ~~113~~ 112 bytes
-1 byte ceilingcat
```
m;n;w;c;l;i;f(char*s){for(m=n=l=0;s[l++];m=c>n?n=c,l:m)for(i=w=c=0;w=isalpha(s[i])?1+w:w-l?0:!++c,s[i++];);n=m;}
```
[Try it online!](https://tio.run/##tVlrjxu3Ff3uX8GqDaDtctWkjy@rKk7Rp4E2TWE4X@IgoGYoie085CGpXcN1/rp7nyTl2m1RIAt4H5oheXnuuece0t3dsevevRu30/Zh222Hbdge1t3JLT@NN28O87Ied9Nu2H26jd8Mt7ffbsdd9/n0dNp1drgfb/CFsHvYdfDCwy5EN5xPbh2/Cd/ePP3s9uH@4W54@un9j25vOwsf4vib7bQbt2/fJR@TrJMWa8KUTHfy3T9uzJsnhv5cfDQ7c1jD85utfHZ2ET@kRzsegI/OCzw8rFefxHvzSW/WL@G3lysLv9@8nOAnDnu6wu@r@9XBhQE@gzmsobV53e2Tt0@ejC5MawyBwlv9yQ/DbB7mZeitSacQjVu8wWdxZT7wZc2vYJ52LHw1wzebzUdnaMc@@@DsH/@y5rMyNp38XfNvWv3Xsb8oY/8469dx8Aa3Oxl3Pq8@PvbnZez65tefu9ufRT8lP3X@Jz/@Yv3FQ0in@/vRTa/v7u6@i6/H/TzEN2//@f33Kxj7yzLWTXP67uQXAsa4LmU3DK9X/yHmOvbP8@JHE84xj6afh3kxMcAco0@Q2XmKvks@5cW4PpxD7MJ0NH4IaWP@Mi/7AK@M49zPxuUuwVg/hXFjvszD4MzBdWEIMejfAGa/@AVmh3kvECEAdPD43ed2qY35jZ88QOcPh9AFXHxwXY5mH/YwBcQ5zPt5STAwzr0bfIQV3GheZfhkdHlB4JPxC3xzQ3iV4Vn04xnwmXwn/15lvzFfAccQ7wh/mZPbh@SgSEbaWIJpUsAHkBKIDNb3CQbKLyOum12P2xyhnFxnINAzbuYIuLqoAIUJ3k0Y7ADhL/PGfA3Pwz4PsJEUpi70GRblHdIW3NJlGPMYRlxq8OEAuwZQZCuuGRXdOfjJlm1eINTJJcLhODlBfjSHMMGK0Ux56sw5LzmiZJg8wC67AOEPxILzHLOH@grTxvwhx84rwATawChcACV4AI@BEElfpMhrXml50AffQ4rzMUAqMEClQnTHgJhYpRy852EGoFLZsVVAGTcTMIN9AOznPswWU9zy84KsLDlICsBXi/NYU8q0ZYZFXdflMQLDcjIXtwTcFf2wkPwB0@MB5sHPzfjlNE@YojJ2CnEw06zp3ZjfLg4emzEwmhvz16ULOj9kZUYynSk/@1xihKB6@Hd2C8QePPEPKWlhCACLW1tCHzrgC8CaowKucGkiZINO8Vb@AS4Gmsri0@Ig/4A@bmqG7IPmA6DAQuDGCcK2ktoDdINjwDQRhg3VYS6YlitM1rciHcD/Sx7OObnk4b0TBgwEcPkImwZlQHGAdOFfyG/LhElQlvCAaDmEIwzBtErqnhMpGGdIy4B0gSn6MAJKRa0c6NQZdheyqBhG6DuAOZbPu7xERA8aGMTEOZPyeqwJRdY/A0yOIBRnqEcSEPircCdVvXmeI2QSEhd9I1OMFw8pIEpRaT40X5ZFiKKR@IjOUCbwDOJCKdeCxAxRxWo9Ks/hnbo8hcm4Yb2yAAK7QABqpUdEEt/vcb8cE5YSh0DacL29psgslV6p0CsRZK1H2mIyeW@KP6eWSrYHxSL2Y3CScqKCfwRenlwESWYoap5lyEzlBHQG@g/QRyJp@Je4HNQxPdXWhXqv5ILawVlEtgCbREs0pV3BOefhEiYHahIufllc7XINBqw0mNglOQSD47SUjb/nmGZ5hMyFrPXaEoSxeQGSFNZF3zK2QajPQTSl7KqmmmKwTMmaT@4iLY6uNA3obChqkpLSY8vcXKmkeUgghqt2mokaedO6aD6ufbCPI2QQ1j@ADai5GrK2TUYYARZCd3kPfHFIO@e3ImnEVFjBqpso4RJFbNUxTCMG0G41p1pAEu6zqemI0r542O9mrBDRZs4ZfkAKoQqKfaKpY2lDRV5/n6iwEiU7BYwXq4NWFc4Vw8LlChMa6sfdvKAbIQi1PcLyEJZ00cL9q@xyB@XQdWor0SMi6sUUbctUw57X4ECJpr1Vi8PELEo@osthHhwXdwm9o4KCvdKT2optIx1U0UtOC7Lryllp6@TBpXGRd2GG4kwkm1op7EfYtZWWU@2FMGuG7aGyvkitJvybIBeOH/zCuF4rnFScJWOL9VpkQI2m5S4E8yPRmhSi37UfKlDqqaSWgGdrfaCjqaHpi4wLJJo47fGudEV4l3IpVpL1BXt4T3pb3eFlHnI6o/AnqadUa/7rcHHY9Xgf9N1W6cbQKk0wHbZOB2uRIBWl0g6qP2n1AnCzlSsqQLyqb1yP1NWKE@HjQ1mjdLtC1I9MW9r1@WoxpaliL4cDckG28Sth0gNChj3XTdS8QglxPVQJYvoGUNyBPFy7fXa@RePZ3EuWpWXhrI@1e2hsVcJac1sCqT5cxKL0YvG/5LQac@812/vBAd2xM/Z8XNLKJl5RC0bR1KNCQ@ra5bmAy99qJNXuMbC4W5ijoF1gthR9CYtaRM2n9CO0Q8XSYmjXpVoLksSzVT3OoOXjE3/jLiLnHZy5ZARbNZUocB4DIdU@Qb3xKRCXAk4l70TKY3qPcTJ3OQQQ@gUZSkBJDb10dcBlDWdTK17pSv40znqIlAJhsQchxkoR/bsifdsR9dSH2o0dHjEpzeq97sZBNNLWeGEUG4vlz7Sq6qeHJkJYxaxVYhQFTnvlNfca7rTFA3JxVbtBxSwHepTw2u4IJ7UF1NquHa2ceOtpkc07z1U8ifLovawyCnqqbrdapeAR92MbpUSfmaO67yJe6gGk7gC@pqb0AMwtoviEXKTqSshKP5KT0YtUGVGesa1l5RFisO7UtonYKfnQlsYkivtD@Tr2SAJQvf/BsyblUcFhNjRuc56YEaG/skNkT/@WmVxFeolQXpkl1l3sf2169R6isAp2xrEpKEXd8ZjBQQU9nhUbwtaYDzB80OfBkvA2XmmxrRrTOK1MV@5P2DhJJcGu9VpCxfNaBuXtClg5wmgwzTUFqtzRK8jS6K6LRjFqDDSxEI8UbEBkmFi5xm@UMqBzH5/q@bhfL3LoU20LzQmpVCvd/6CCIu5ShI2MyHbRBDUXO9h6rsqERb/ZhNoCUvfaeLDkJHM/7A2g0L@Zpy/Otq@vXTU4QYlvLSsGtvGWpOfZFqYTy@CsCDW3pxeqWk7qOfuAV00xNOFY6ee0lByW5VwJSFdbyM85p4C/rCb9GnatRewfG4FrKwlvCZUv5eq20Xpa0inlhXAiMlRsbFhwriJTJCG5qh/6L@U@78Vy4FytJZymOq0uJUZFKK4WigdeX/fRjKiHrPUs1XUn2CLleNU0KfxUTS8K/HOyhqqKGDhvRV4fQ9vD@RKHbszY9Du1DY4u6OXEp87vf/ExjdhTYaqOkuizTyp@Wi7KX1TJqlZbTxWMQjGBTHC9AFY@SAkL1NX20rG3Mpd9KJMWY21LQyiq4UK6SFkVWtaVpofgzG1j68QJc3uvF5mlrrAfcptGo19uAFGX6hVRbdFO26wAF1p/SQcGpiPtqRCV7x/qhQ9qFt9K60Zc2SKkwjY6k7Vdi@0mgl7ZaL3kKP26OAths9SJFG/1DlzddLqg9NUzkFT3xvzf/1HU5rDaMoKV@vyK/@vu7bt/AQ "C (gcc) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 13 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
q\L f üÊñÊÌÌÊ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=cVxMIGYg/MrxyszMyg&input=IigpPD5hKy9zZW50ZW5jZSQjQChAd2l0aDo6bWFueS0tLV9zeW1ib2xze318fn4i)
```
q\L f üÊñÊÌÌÊ :Implicit input of string U e.g., "()<>a+/sentence$#@(@with::many---_symbols{}|~~"
q :Split on
\L : Regex /[^a-z]/i ["","","","","a","","sentence","","","","","with","","many","","","","symbols","","","","",""]
f :Filter (remove empty strings) ["a","sentence","with","many","symbols"]
ü :Group & sort by
Ê : Length [["a"],["with","many"],["symbols"],["sentence"]]
ñ :Sort by
Ê : Length [["a"],["symbols"],["sentence"],["with","many"]]
Ì :Last element ["with","many"]
Ì :Last element "many"
Ê :Length 4
```
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~81~~ 75 bytes
*Thanks to [Mukundan314](https://codegolf.stackexchange.com/users/91267/) for 5 bytes and [ovs](https://codegolf.stackexchange.com/users/64121/) for another 1 byte*
```
lambda S:max(L:=[*map(len,re.findall("[a-z]+",S,2))],key=L.count)
import re
```
[Try it online!](https://tio.run/##Dc3PDoIgHADge0/BrAMk2FaX5rJ5bfNmN3ONFKcLfjDEFf3x1anvBT7jXa9htzc2dChDlyC5urUclaniT1ykWbVW3GApgFqRdAO0XEocVZy96jiiJd0SUtO78FmRNHoCRxaDMto6ZEUwdgCHOzyAmRwmhARMDkceb0oBTkAjVssc54/TuU//HXjG2HX06qbl@P5@5vkH "Python 3.8 (pre-release) – Try It Online")
Anonymous function: Finds all runs of letters using regex, collects a list of the lengths of those runs, and prints the item with the maximum frequency in the list.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 48 bytes
```
Commonest@*StringLength@*StringCases[__?LetterQ]
```
[Try it online!](https://tio.run/##TY/fS8NADMff/StCKzK1171PnYWBOtiDom@llFizXuF@lLuMUeb2r9dzetBACEk@yTfRyJI0ctfguIWHcWW1toY8Fzfv7DrTbsi0LGO2Qk@@rOvHDTGTe6vG11Dm8sP@9cs0g7Xpd/xkna4ySEAsIclgW6ZVBVcwL@BwAQDJCyllYW@d@sqAZecBHQEHYR/wCRJsQuV5PgXP3Po/hkfExE3c82yjtYrgV8kA9n1sz67vl3g792SYTEOXaTEr9h3LxUKjGYQQtR/0p1X@cPw@neIUGsu1JHe@BLDhHSo1JMe78Qc "Wolfram Language (Mathematica) – Try It Online") Function. Takes a string as input and returns a list of most common lengths as output. The list should only have a single number if the mode length is unique. It gives incorrect output on one of the Unicode examples, presumably due to `ง` counting as a letter.
[Answer]
# [PHP](https://php.net/), 101 bytes
```
$a=array_count_values(array_map(strlen,preg_split('/[^A-Za-z]/',$argn,0,1)));arsort($a);echo key($a);
```
[Try it online!](https://tio.run/##TY7NSsNAFIX3eYoBA5lgptVtW7Uu1AoFuxMUDbfxkgQnM8PMrTX@dOvKndCNC/sWfRzJC/QNjLFF6IF74DvnLo7JTN07Mo37cADWQhkneqIofgA5Qcc3UQGGO7ISVWQsprEzMicetK9vj8UViKebdhD5YFMV7UX7YRh2wTptifsQdjHJNLvHcg31mkaDUXxyMezWA5RSs6m28i5ilOWOgUVG6Mh5m67RVt1qtbY@zr0hUuDYWD8y/r18Wy0XgQhWy6@wAe/S5pSrlDldIKs@33k1/6jmi8ZDZqxOLRQeZSi2Tnln@l@pRPa3RzEwxuNh7xB22w4VoUrQ3@nz/jSnrNMpQJVCiNiVxVhL9/z6Mpt5oDTFGdr1UAYJTUDK8kcbyrVytTj9BQ "PHP – Try It Online")
Drat PHP and it's super long function names again...
[Answer]
# [Factor](https://factorcode.org/) + `math.unicode`, 57 bytes
```
[ [ Letter? ¬ ] split-when harvest [ length ] map mode ]
```
[Try it online!](https://tio.run/##ZVG9SgNBEO7vKYYo5ILe2UfRdDEgNiIWIYTNZbxb2J9zZ2I8YtJa2Qk2Fqb3AVL7JJIXyCOce8kJAT@Y3Z2db@D7Zu5FwtaVtze9624bBCVSghacxcSCJbFMaJdPjEzsGCF3yFzkThoGwocJmgQJKFeSWZoUToNgFoBH4xKVsjC1To2PgTNJIBwCIzE19hkee6Q4jv/xevV9hdwkGNknCH9WL5vVshk1N6vPlk9qxp2TWxVkNcL64zVcv7@t35f@bHnlNnVC10zOMNoLU3937R9ShVBpNiDyvK6GrbNzcXRCaLjyfXjQCTtTyVm7rYUpoigaUqFHVtFs/rxY1E3CWB5m6LaWwM97IpQqGsE8KPvQB2@K0V3A9xcMdnOMpl4PZMI9Vg19UGhSznxVixx0tYRBWT3j8hc "Factor – Try It Online")
Split on non-letters, harvest (remove) any vestigial empty strings, get the length of each word, and take the mode.
] |
[Question]
[
A [Quine](https://en.wikipedia.org/wiki/Quine_(computing) "Wikipedia") is a program which outputs its source when run.
In this challenge, You should make a Fibonacci-quine, a variant of the quine.
---
## What is a Fibonacci-quine?
A Fibonacci-quine is a program, which outputs a modification of the source by the following rule:
The initial source should be `...2...`. In other words, the source should contain `2`. (Why 2? If it was 1, Nobody would know if it was the first 1 or the second, Even the program itself)
When run, You should output the source, but *only* the specific number (In this stage, `2`) changed to the next number of the fibonacci sequence. For example, `...3...`. Same goes for the output, and the output of the output, etc. You may support integers for up to 2^32-1. For integers over that limit, the next output is on your choice.
>
> ### OP's note
>
>
> I would really like to see a creative solution for this. I couldn't think of a single solution for this, since Both of the two important aspects of the challenge, fibonacci and quine, is not easy. I'll be waiting then!
>
>
>
[Answer]
## Mathematica, 61 bytes
```
ToString[#0 /. v:2 :> RuleCondition[Round[GoldenRatio v]]] &
```
Note that there is a trailing space. This is a function quine, i.e. the above code evaluates to an unnamed function which, if called returns the code itself as a string (with `2` changed to the next Fibonacci number).
This was suprisingly tricky to get to work. The basic idea is to take the function itself (with `#0`) and replace a number in that function with the next one using `/. v:2 :> nextFib[v]`. However, `nextFib` wouldn't get evaluated at this stage so we wouldn't really end up with the new number in the source code. After searching around for a while to figure out how to force immediate evaluation, I found [this great post on Mathematica.SE](https://mathematica.stackexchange.com/q/29317/2305). The "standard" technique uses a `With` block which forces evaluation, but the second answer by WReach contains a shorter alternative using the undocumented built-in `RuleCondition` which also forces evaluation.
The way we compute the next Fibonacci number is by making use of the fact that the ratio of consecutive numbers is roughly the golden ratio **1.618...** and this is accurate up to rounding. So we don't need to keep track of the last two numbers and can simply do `Round[GoldenRatio v]`. This will never lose precision since Mathematica's `GoldenRation` is a symbolic value and therefore `Round` can always compute an accurate result.
In summary:
```
... #0 ... &
```
An unnamed function, where `#0` refers to the function object itself.
```
... /. v:2 :> ...
```
Find a `2` in the expression tree of the function (this `2` of course only matches itself), call it `v` and replace it with...
```
... RuleCondition[Round[GoldenRatio v]]
```
... the next Fibonacci number.
```
ToString[...]
```
And convert the resulting expression tree to its string representation.
[Answer]
## [CJam](https://sourceforge.net/p/cjam), 26 bytes
```
2{0X{_@+_W$>!}go;\;"_~"}_~
```
[Try it online!](https://tio.run/nexus/cjam#@29UbRBRHe@gHR@uYqdYm55vHWOtFF@nVBtf9/8/AA "CJam – TIO Nexus")
Probably not quite optimal. We simply iterate the Fibonacci sequence until the value is greater than the last one and use the result as the new value at the beginning of the program.
[Answer]
# [Python 3](https://docs.python.org/3/), 95 bytes
```
a=b=1
while a<2:a,b=b,a+b
s='a=b=1\nwhile a<%i:a,b=b,a+b\ns=%r;print(s%%(b,s))';print(s%(b,s))
```
[Try it online!](https://tio.run/nexus/python3#@59om2RryFWekZmTqpBoY2SVqJNkm6STqJ3EVWyrDpaMyYPJqmYipGPyim1Vi6wLijLzSjSKVVU1knSKNTXV4QIQPtf//wA "Python 3 – TIO Nexus")
Obviously a fork of [Martin Ender's CJam answer](https://codegolf.stackexchange.com/a/119544/48934).
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 20 bytes
```
2{\5mq)*)Y/io"_~"}_~
```
[Try it online!](https://tio.run/nexus/cjam#@29UHWOaW6ippRmpn5mvFF@nVBtf9/8/AA "CJam – TIO Nexus")
[Answer]
# [Actually](https://github.com/Mego/Seriously), 19 bytes
```
2⌠è@fuF$+";ƒ"@+⌡;ƒ
```
[Try it online!](https://tio.run/nexus/actually#@2/0qGfB4RUOaaVuKtpK1scmKTloP@pZCGRw/f8PAA "Actually – TIO Nexus")
Obviously a fork of [Martin Ender's CJam answer](https://codegolf.stackexchange.com/a/119544/48934).
[Answer]
# [Python 3](https://docs.python.org/3/), ~~81~~ 79 bytes
```
s='s=%r;print(s%%(s,round(%s*(1+5**.5)/2)))';print(s%(s,round(**2***(1+5**.5)/2)))
```
[Try it online!](https://tio.run/nexus/python3#@19sq15sq1pkXVCUmVeiUayqqlGsU5RfmpeioVqspWGobaqlpWeqqW@kqampDlcEV2OEpoTr/38A "Python 3 – TIO Nexus")
Uses the golden ratio to calculate the next number
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
“רp+.ḞṭØv”Ṙv2
```
[Try it online!](https://tio.run/nexus/jelly#AR4A4f//4oCcw5fDmHArLuG4nuG5rcOYduKAneG5mHYy//8 "Jelly – TIO Nexus") or [verify all required iterations](https://tio.run/nexus/bash#@1@SmqqQlpmUX1iamZeql5Wak1PJxZWWX6QQr5CZp1BtoqdnYllrrZCSz8WZmpwBJPXzC0r0weogpEJaKboBCnYKJam5BVycuWVgBoYFnMmJJRiCKfl5qf//P2qYc3j64RkF2noPd8x7uHPt4RlljxrmPtw5o8wIAA "Bash – TIO Nexus").
### How it works
```
“רp+.ḞṭØv”Ṙv2 Main link. No arguments.
“רp+.ḞṭØv” Set the left argument and return value to the string "רp+.ḞṭØv".
Ṙ Print a string representation of the return value and yield the
unaltered return value.
v2 Evaluate the return value as a Jelly program with left argument 2.
רp Multiply the left argument by the golden ratio.
+. Add 0.5 to the resulting product.
Ḟ Floor; round the resulting sum down to the nearest integer.
Øv Yield the string "Øv".
ṭ Tack; append the result to the left to the result to the right.
```
[Answer]
# Swift, 251 bytes
A bit verbose for me, but I can't figure out how to get it shorter:
```
import Foundation;var n="\"";var u="\\";var s="import Foundation;var n=%@%@%@%@;var u=%@%@%@%@;var s=%@%@%@;print(String(format:s,n,u,n,n,n,u,u,n,n,s,n,(round(%f*(1+sqrt(5))/2))))";print(String(format:s,n,u,n,n,n,u,u,n,n,s,n,(round(2*(1+sqrt(5))/2))))
```
Ungolfed:
```
import Foundation
var n="\""
var u="\\"
var s="import Foundation;var n=%@%@%@%@;var u=%@%@%@%@;var s=%@%@%@;print(String(format:s,n,u,n,n,n,u,u,n,n,s,n,(round(%f*(1+sqrt(5))/2))))"
print(String(format:s,n,u,n,n,n,u,u,n,n,s,n,(round(2*(1+sqrt(5))/2))))
```
My trouble is trying to get the quotes around the new version of `s`.
[Answer]
# [Cheddar](http://cheddar.vihan.org/), 136 bytes
```
let b=1;for(let a=1;a<2;a=b-a){b+=a};let s='let b=1;for(let a=1;a<%i;a=b-a){b+=a};let s=%s;print s%b%@"39+s+@"39';print s%b%@"39+s+@"39
```
[Try it online!](https://tio.run/nexus/cheddar#@5@TWqKQZGtonZZfpAFiJwLZiTZG1om2SbqJmtVJ2raJtdYgiWJbdexqVTOxKVYtti4oyswDMlWTVB2UjC21i7VBlDp2Ya7//wE "Cheddar – TIO Nexus")
[Answer]
# Javascript (ES6), 151 60 bytes
New version, credits to @[Leaky Nun](https://codegolf.stackexchange.com/users/48934/leaky-nun)
```
x=i=>console.log('x='+x+';x('+(i*(5**.5+1)/2+.5|0)+')');x(2)
```
Old version :
```
x=i=>{var s=Math.sqrt(5),a=1;f=n=>{return Math.ceil((((1+s)/2)**n-((1-s)/2)**n)/s)};while(f(++a)<=i);console.log('x='+String(x)+';x('+f(a)+')');};x(2)
```
Based on [this](https://stackoverflow.com/a/19892721/6882070).
[Answer]
# [dc](http://enwp.org/dc_(computer_program)), 35 bytes
```
2[r9k5v1+2/*.5+0k1/n91PP93P[dx]P]dx
```
A version with iteration (56 bytes):
```
2[rsP1dsN[lN+lNrsNdlP[s.q]s.=.lFx]dsFxlNn91PP93P[dx]P]dx
```
[Answer]
# Swift, 235 bytes
This is an improved version of [Caleb](https://codegolf.stackexchange.com/users/68374/caleb-kleveter)'s [answer](https://codegolf.stackexchange.com/a/119576/13940).
```
import Foundation;var n="\"",u="\\",s="import Foundation;var n=%@%@%@%@,u=%@%@%@%@,s=%@%@%@;print(String(format:s,n,u,n,n,n,u,u,n,n,s,n,(round(%f*(1+sqrt(5))/2))))";print(String(format:s,n,u,n,n,n,u,u,n,n,s,n,(round(2*(1+sqrt(5))/2))))
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 239 bytes
```
interface a{static void main(String[]p){int a=1,b=1;for(;a<2;a=b-a)b+=a;String s="interface a{static void main(String[]p){int a=1,b=1;for(;a<%d;a=b-a)b+=a;String s=%c%s%c;System.out.printf(s,b,34,s,34);}}";System.out.printf(s,b,34,s,34);}}
```
[Try it online!](https://tio.run/nexus/java-openjdk#pcyxCsMgFIXhV5GAoNQG0nazPkXG0uFqtDhEg/emUEKe3QpdCx26nOV8/DUm8iWA8ww2JKDo2DPHic0QkxipxPS43Re5NcfADMqaQYdchIbrSYOxR5D2YEB/KEPT/VHk09ckdxy50@MLyc99Xqlf2kNBoLLqfFHYRup9736TWt8 "Java (OpenJDK 8) – TIO Nexus")
] |
[Question]
[
*Playing the game of memory against a machine is highly unfair, because they play almost as good as small children. So let's make the machine play alone, but in a fair way:*
* **Input**: 1...26 pairs of lowercase letters in random order like `zz` or `gttg` or `abcdefghiabcdefghi`. You can trust each letter appears exactly twice and no other characters show up.
* Lowercase letters represent unknown cards, uppercase letters are cards we already saw. Being a fair program, your code will not make knowledge of hidden cards.
* With each turn, you are allowed to uncover a pair of cards (making them uppercase). Start to uncover cards at the left side and continue to the right. If the first card was seen before, pick the match. If not, continue with the next unknown card. If you uncover a pair, remove it.
* Play the best you can: If you know an uppercase pair, uncover it. Otherwise never uncover a card you already know!
* **Output**: The number of turns you needed to remove all cards. With the given strategy, this is fixed for a given input. Output as binary, ASCII number or length of output string, whatever you like best.
* **Goal**: The shortest code wins, whatelse!
**Let's illustrate this**:
```
afzaxxzf | This is our input
AFzaxxzf | 1st turn, too bad: no pair
AFZAxxzf | 2nd turn was ZA, again no pair, but ...
FZ xxzf | 3rd turn used to remove the AA pair
FZ zf | 4th turn uncovered XX, which can be immediately removed
F f | 5th turn started with z, so as second card we can pick the Z we already know
| With the 6th turn we solved it, so output will be 6
```
**Some more test data**:
```
aa --> 1
aabb --> 2
abba --> 3
ggijkikj --> 6
qqwweerrtt --> 5
cbxcxvbaav --> 8
zyxzwyvxvw --> 9
tbiaktyvnxcurczlgwmhjluoqpqkgspwsfidfedrzmhyeanxvboj --> 43
```
**Hint**:
You don't have to actually play memory, you don't need to actually turn anything uppercase! All that counts is the correct output with the lowest number of code bytes. Feel free to discover a hidden algorithm (but it's not as simple as it could appear on the first sight).
[Answer]
# [J](https://www.jsoftware.com), 35 bytes
```
[:#(#@]<.[+2-{.+./@e.~2{.}.)~^:a:&2
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Nc9Ba8IwFAfwu58irmyZuGaz28SGCcJgp512FQdJTNqmam1Nk7Qyv8gu3cGvJPhtJiQeHo_34897vN8_2Z1v4z4eLcZ9HEPYu0FQgCkGEDyAJ4AvFSLw_vX5cayVCCfnYI6D-2C2eEPzYRTu0RA9zjg6RHv0gwaHb0zwXeSjp0GPs7QAIzAFAkBCoJuj60ypl2cvlF4zYydJksk8y6XXV6dlaQznVaWU94lzRi2zmhKivcfO28a2ptFWG-8v_qCiGclVozeW1RVrV4lZp3JVF-W2zJPd1uxEthR8WbXrtOFkc9ldSOi-6zrX_wE)
A bit chonky as far as J code goes, but imo a nice simplification of the algorithm:
* We imagine a pointer, starting at index 2, pointing into our string:
```
ggijkikj
^
01234567
```
* On each iteration, we increment the pointer by 2 as a default
+ But: If the character at the pointer, or the character to the right of the pointer, exists within any of the previous characters (left of the pointer), we only increment by 1.
* We keep incrementing until the pointer exceeds the length of the string
* Our answer is the number of iterations that process took
This approach has the advantage of reducing the number of rules/cases down to just a single rule: increment by 2 or 1, depending on whether the next two characters have been seen. This avoids special-casing the `aa` case, or distinguishing between "1st character was already seen" and "2nd character was already seen".
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ṪfṖƊƤŒɠHĊS
```
[Try it online!](https://tio.run/##DcwpEsIwFABQn5PhUcifNEmzdEmaZpMYZioRaASKQWI6SKAzHKNcJCCefZJqnUpZ5ytb59MyLZf38XPevKZtWR/35@G7v@1KAUAAGKM/QJwLqYSSyJgQKLXWOURwJNFjAI9yijkkH31ADgtQLvk2ktGSrHloaqnHzvRG8aEPAxMVo5XNTZ0otP@gkwhYhhgz@wE "Jelly – Try It Online")
This alternate solution kinda grew alongside the one preserved below, for what it's worth. Ultimately derived from [Jonah's description of his J solution](https://codegolf.stackexchange.com/a/265353/85334), but whatever the actual code does I strongly suspect it isn't this.
```
ƊƤ For every prefix:
·π™ Pop the last element
f and filter it by membership in
·πñ all but the last remaining (after the pop!) elements.
Œɠ Take the lengths of all runs of consecutive equal results,
H halve
Ċ and ceiling them,
S and sum.
```
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16~~ ~~13~~ ~~12~~ 11 bytes
```
ṪeṖƊƤœṣØ0KL
```
[Try it online!](https://tio.run/##Dcw7DsIgGADgndN4D72A4w8FyqMPaMtrdDFxNTHuOhlHl8axsffAi6DDt36Sah1LyfOD5vmyntb755zn23LdbHclv1/L8Xt47ksBQAAYoz9AnAuphJLIGO8ptXYcEcGBBIcBHEoxJB9dcB6NWIAao2sDmSxJmvumlnrqTG8UH3o/MFExWtnU1JFC@w86iYAlCCGxHw "Jelly – Try It Online")
*-1 kinda back-porting [Neil's Retina solution](https://codegolf.stackexchange.com/a/265357/85334) since I don't actually have a clue why Jonah's pointer starts at 2 to begin with*
*-1 doing it again*
Vague port of Jonah's J algorithm.
```
ƊƤ For each prefix:
·π™ Is the last element
e also found
·π™ ·πñ two or more indices earlier?
œṣØ0 Split on all non-overlapping occurrences of the substring 0,0,
K join on spaces,
L and take the length of that result.
```
[Answer]
#### *Implementing Jonah's smart trick*
*saved 10 bytes thanks to @DominicVanEssen*
# [R](https://www.r-project.org/) 4.1, 82 bytes
```
a=\(v,x=1,j=duplicated(v))`if`(sum(j|1)>x,1+a(v,x+2-(v[x]!=v[x+1]&j[x]|j[x+1])),1)
```
[Attempt this online!](https://ato.pxeger.com/run?1=TZFNDoIwEIXjlgu4VUxMG8qi6kIT8RBu1cQKotR_hIrGm7jRhYfS0_iA0bj44PUxM6-0t0d8vz_TJHS7r6HyxsyIzJNCe0G6X0e-SuYBM5xPo3DKjumG6avkg0xIR-WVTstlZpRN6h6ejpw0NRZXXWjOheTl5Helavquz-yLLewzyECuT7Q25JnC4xaG81qj1rPKtgT2DERAgRVI_lq31O6DFMSk84g1WFDUBiyBJj-v3YED2NN7RfVH8k6kQ8oPSM9Jx5TznX2mb-pvX4b2vyuyf7_XaVvl-Xxv4AM)
---
#### *Previous solution*
# [R](https://www.r-project.org/) 4.1, 141 bytes
```
b=\(v,x){j=duplicated(v)
ifelse(is.na(v[3]),1,ifelse(j[x],1+b(v[v!=v[x]],x-1),ifelse(j[x+1],2+b(v[v!=v[x+1]],x)-(v[x]==v[x+1]),1+b(v,x+2))))}
```
[Try it online!](https://tio.run/##TVDbboQgFHz3L@oTRGzi9rV@ycYHRW1ZrVdE3abfbg8wbiSZzJnDcAaYjqNI66WTWvUdM2Ljv4@0XIZWyVxXJTM8UHXVzhVT83uXM3P/yLhIBJqP@5aJJCqob95SQyoTW5zwy36UZOJ2cZAmD4@ZdafocD9EbNGN0/o7hs9YsjAPBYEH40WJsHDgwfTqFoD1zq77RcpCER6EBnXjNA@0c42kLFagAiZAO/BgcW6JlI0gweaV7GHIbZz7SWqH64n5O06cJ1dyr86tMUdhToP080R3yV1wO4nJLd5qE34I33hzC2@PVw7gBv4ZvRV1jfwSdYV6Qs45e8defrnX@Q89/rdgg0gsjZ4mT7Mn7WnxZDytRMfxDw "R – Try It Online")
#### Test:
```
w<-c("t","b","i","a","k","t","y","v","n","x","c","u","r","c","z","l","g","w","m","h","j","l","u","o","q","p","q","k","g","s","p","w","s","f","i","d","f","e","d","r","z","m","h","y","e","a","n","x","v","b","o","j")
b(w,1)
```
>
> 43
>
>
>
#### Brief explanation:
b is a recursive function with input:
* v a vector of characters
* x the position of the first unknown element of v
It proceeds :
* If v[x] is duplicated we use one move to remove that pair, and we continue with a shorter vector and one less known element.
* If v[x+1] is duplicated we use a second move to remove its pair (but if its twin is v[x]), and we continue with a shorter vector and as many known elements.
* Otherwise we use one move to see two more elements.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 57 bytes
```
a=>a.map(c=>a[n+=!i|a[c]&i!=c,i=i||a[c]?0:c,c]=1,i=n=0)|n
```
[Try it online!](https://tio.run/##TdDNcsIgEAfwO0@BlwrTyGhtO/0Y7KlPkWZGgiSSD0gIEpLaZ0@j0dY9/fc3u3vYjDnWcCMru1B6J4aEDoxuGClZhfgYQnVPZ/LIQh7dyRnlgaTyeG4/lm884BFdjaToEh/VYCGFW8AY/KvFYgNXo8TxrTyAEditrEGayiyXeXaVZ1DXbSuEMdZO8gR47Ll3MWNukhfQd75vO@ddO8krsLFkue2c8vxgeF@kbbnPioOuqzpPm6ptErlLxM705b4TTI3ndHZefVyDLbFGlgiTpiqkRfMvNcfnT3hIN9BfeZy@uDu5u2xh/A4sSbT5ZHyPUCgDKCJ8mvgGEHKtGl0IUugUCUgpTFBICJERDv4jBj94@AU "JavaScript (Node.js) – Try It Online")
We uncover cards from left to right and, for every next card `c`, with previous uncovered card in this turn `i`:
* Count an extra turn (`++n`) whenever:
+ This is the first card to uncover in this turn (`!i`): as a new turn;
+ This is the second card to uncover in this turn (`i`), AND the card just uncovered in the same turn does not equals to the current one (`i!=c`), AND the card just uncovered had already seen some time before (`a[c]`): as we need an extra turn to match these two cards;
* Leave this card uncovered for this turn (`i=c`) whenever:
+ This is the first card to uncover this turn (`!i`), AND this card is not ever seen before (`!a[c]`);
* Remember the card as a seen card (`a[c]=1`)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~25~~ 20 bytes
```
(.)(?<!\1..+)
1
11|.
```
[Try it online!](https://tio.run/##Dcy7DsIgFADQ/f6FgwmNCQm7iaM/4eCFAgX6glJe8d@xw1lPkNGs2O/k/e2EDuT1vH0YpY8BGDD2o70jAiLncEHQ2lhnnAXvc5YyhBhB8CJK4ogJWi0t11RShsgNuljTWsQZRJt1XiY7n5vfvdPHng9lRiXH0JapSlyvYLOAqmEpTf0B "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Port of @UnrelatedString's Jelly answer, as I don't see how it works, let alone ports @Jonah's J answer.
```
(.)(?<!\1..+)
1
```
Replace the first character of each pair with a `1`, but also the second if it's adjacent.
```
11|.
```
Subtract the number of pairs of `1`s from the length of the string.
Would be `22` bytes as a one-liner: `((.)(?<!\2..+)){1,2}|.`
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~25~~ 15 bytes
```
I⁻Lθ№⭆θ№…θ⊖κι00
```
[Try it online!](https://tio.run/##NYtBDoMgFESv0rjCpE3cd0mXNWnSEyB@AUEQ@Kh4eUqbdBazeG@GSxa4Y6aUV1AWCWURSa9siuQJVqAkvr1eqEvVvbFORM9W4v@IZm6ASvdDD@ABFrAII9FtvalvNV3XtDX3UnBQTGPe7MFT4KcR@yJnk5xfvRZx3eOkxgnGcC4yA7PHNri53DbzAQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @UnrelatedString's Jelly answer, although I'm not entirely sure why it works.
```
θ Input string
L Take the length
⁻ Subtract
θ Input string
⭆ Map over characters and join
θ Input string
… Truncated to length
κ Current index
‚äñ Decremented
‚Ññ Count of
ι Current character
‚Ññ Count of
00 Literal string `00`
I Cast to string
Implicitly print
```
Previous 25-byte solution:
```
FLθM⊕×⊕﹪ⅈ²№…θ⁻ι﹪ⅈ²§θι→I⊘ⅈ
```
[Try it online!](https://tio.run/##VU27DsIwENv5io4XCRZGOqEuIFEJIQbWkFybQJpr86Ll50Ngw4NlWX4IxZ0gbnLuyFVwQtsHBRNjVUsJ4WiFwwFtQAlXPaD/c1qS0RDcgK2rLSvUULQBmkUYbBSNMK2rVtvoQRfxHy68D0crcf6mNPs5u4vuVWD16uz0d4j7AAduUvkqvYI653DX/BmWZGcRnXib/jWoh4k0jdOz9@PLd1p2KN17UAtyO6c7PfImmQ8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FLθ
```
Loop over the indices of the input.
```
M⊕×⊕﹪ⅈ²№…θ⁻ι﹪ⅈ²§θι→
```
Calculate how many cards get turned as a result of this card. This is `1` for the card itself and then a possible further `1` or `2` if this card has been seen before depending on whether an even or odd number of cards have been turned so far, except in the odd case where the previous card is the one seen before.
```
I⊘ⅈ
```
Output the number of turns (which is half of the number of cards turned).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 54 bytes
```
a=>a.map(c=>a[i+=a[c]?i%2?i-a[c]?3:1:2:1,c]=i,i=0)|i/2
^ ^ ^ ^
seen? | | Flip the seen
even-th? |
seen early? (abc[a] | bca[a])
```
[Try it online!](https://tio.run/##TdDLTsMwEAXQvb/CG1RbJIamgKDI7YqvCJFwXCedvJyH6zgBvj2kL9RZjY7uncVkwopOtlAbv9I7NSV8EnwjWClqIuclhHsuQhlt4S7Ygn9aV@vlOlgvPRlx8IA/0h94CCaDOf5CQuD/8f0NXs4Sx7cSoBnEraxQmkKWQ55d5QU1Td8r1bbGnOUZydhJZ2Mh7Fle0Ti4sR@ss/1Z3pCJQeRmsJWTh1aORdqX@6w46KZu8rSr@y6BXaJ27VjuByWq@ZzOTtWnFfpipoWSUNbVBRiy@KwW9PQGh/kGuyvP6Yvbo9tLi9J3ZFii2w8h94SE4GEV0WPiGx8/k5CQMQbRHMNY6qrThWKFTonCnGPjYUPRL53@AA "JavaScript (Node.js) – Try It Online")
[Answer]
# Python3, 126 bytes:
```
def f(a):
s,c=[],0
while a:
if(v:=a.pop(0))in s:s={*s}-{v}
else:s={*s,*[v,(K:=a.pop(0))]*(v!=K)}
c+=1
return c+len(s)
```
[Try it online!](https://tio.run/##ZY7BboQgFEX3fgVNFwPWNtN0MzHxC@YTjAtAUEYHERCQyXy71XQz1eU997y8q2bbDvLnovSy1IwDDjHKE2AyWpRVdk6Ab0XPAF4ZEBy6vMBfalDwjJCQwOSmeKTm@flwz1VgvWF/JEtLl8Hri12l0L0VV7R59KP4ToBmdtJyDT2T0KBFaSEt5LBMTxifKoSSf4SQAyPk4DWNuHWiu@35OHrPmNbW7htKAg2OYOy2Bryv0qBfhTiH6GcXnN@fWiJwZ2cnA500jX3j7@2tn4ZRjV1jlDdc1JzVOt7bmWG5fhkOwzCPOITIN778Ag)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 101 bytes
This is a golfed version of Ajax1234 [answer](https://codegolf.stackexchange.com/a/265333/110585):
```
lambda a,s=set():(A:=iter(a),len([s!=(s:=s-{v})or(K:=next(A))!=v and(s:=s|{v,K})for v in A]+[*s]))[1]
```
[Try it online!](https://tio.run/##ZY7BcoMgFEX3/QoyXQQSu@h003GGhet8gnXxUFCiggIBNM23W9NVq9tzzp33hsk1Wn18DmYR9GvpoGcVIEgstdxhkuIspdJxg4EkHVc4tweKbUrt290/iDb4klLFo8MZIQfqEajqV3/ffXJ5EKEN8kgqlBXn/GQLQvL3YhmMVA4LnJ@OAMcVvvwjjO0YY7uuruW1le11y8cxBM6NcW5rShbL6BmAfxr0ukba/A3mKc5h8tGH7dQxCa2bvIrlzZRzV4e@uXY3PQ5jW9shWCErwSsz983EQa1X9O4xEDPEOIsnX34A "Python 3.8 (pre-release) – Try It Online")
This can be 85 bytes if we can take iterator as input, 95 bytes if you can accept "outputs as length of list containing weird random stuff", and 80 bytes if both are allowed:)
85 bytes iterator solution:
```
lambda A,s=set():len([s!=(s:=s-{v})or(K:=next(A))!=v and(s:=s|{v,K})for v in A]+[*s])
```
[Try it online!](https://tio.run/##bc65csMgGATgPk@BK0PsVGkymqFQ7UdwXPxIIKEDEGAux8@uHGWGdr@d2TXZj1q9fxi7C/q5L7CyHlB7dtRxj0mzcIWv7kCxa6h7e4Qn0RZfGqp48rgl5EADAtX/8dcjnC9PIrRFAUmF2tvp@upuZDdWKo8Flp5bfAQ4EkJe/oeM1WLGau1hkNMs56lC2xYj59Z6X8GOpS4FBhAqWHIqMYcUYgU9kzD7HFTq7rYryxDXcVruejPbPDgTnZC94L0t65g5qJ8RXXsHokBKRfzS/g0 "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ηεRõ1ǝćÃ}Åγ;îO
```
Port of [*@Unrelated String*'s Jelly answer](https://codegolf.stackexchange.com/a/265354/52210), which is based on the explanation of [*@Jonah*'s J answer](https://codegolf.stackexchange.com/a/265353/52210), so make sure to upvote both of those answers as well!
Will see if I can find something shorter using a similar approach, when I have a bit more time later on.
[Try it online](https://tio.run/##ASYA2f9vc2FiaWX//863zrXCplLEh8ODfcOFzrM7w65P//9hZnpheHh6Zg) or [verify all test cases](https://tio.run/##Hcw9DoIwHAXwq5jOLM4OHMHE1Tj8Cy2U8tUC/UqcjLq7ewUXQzxATdw4hBfB4vLe@y2v6QAzMisbo9X3cluh2M7Taxp3flx/7u@rPx39eXpu/GM7R/MeAXVgjKMoQgD/wHgpjBdlGSs440WYQmhNiJR9H5BgkxiFAVSAs8Zpq4zSAT1mwHurapMMMnFlpqu8KIdGtIJnXas7ylJKUumq3BKow0lToMMP).
**Explanation:**
```
η # Get all prefixes of the (implicit) input-string
ε # Map over each prefix:
R # Reverse it
õ1ǝ # Remove the second character by inserting an empty string at index 1
ć # Extract head; push remainder-string and first character separately
à # Keep all occurrences of this extracted head in the remainder-string
}Åγ # After the map: run-length encode the list of strings,
# pushing a list of strings and list of counts of equal adjacent values
; # Halve all counts
î # Ceil each
O # Sum those together
# (which is output implicitly as result)
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), ~~ 108 ~~ 102 bytes
*(97 bytes for buggy old GNU `sed` 4.2.2 by using empty label instead of `1`)*
I insert an underscore `_` as marker up to where cards are known, then do backreference replacements for all possible cases. For each turn, `H` appends the pattern to the hold space, so in the end I output the number of turns as `+`:
```
s/^/_/
t2
:1
H
:2
s/(.)(.*)\1_/\2_/
t1
s/_(.)\1/_/
t1
s/(.)(.*_)\1/\2/
t1
s/_(..)/\1_/
t1
x
s/.\S*/+/g
```
The `t2` at the beginning looks avoidable, but is needed to reset the `t` trigger after the first replacement.
[Try it online!](https://tio.run/##RYuxCoUwEAT7@xKjmCUp7R/Y2x6mUcRGhfg0@vGeCSKWMzvr@64cpr@IRwsHWi1VhmqqLHlkWmU6V2wc2KbRROmiZYMXn8YlxfZLtEK6JQ7RaG5yFBhEziOc@7GFbb/mZR3nyUv5uwE "sed – Try It Online")
[Answer]
## X86\_64/Linux Machine Code, 41 40 39 Bytes
[Try it online!](https://tio.run/##fVRNb9s4ED2Lv2KANKjTxqkbdANsgBzaTbEIUPSSpkEvNfgxkulQpEJSlpQfX3coKZKDLtYHSxTJ9@bNmxkeApbCdMtCyv3@3Ru4s9KVJdoIAo1rQOfw6fYWGh4gYKwr4BHOf56vzgDevGN04Uhhri3CzfXnj1/W6Sx9Z9lZYZzgJluHyH2kdcQ2smF1yTK6eJOYtC3AY6FDRB@Ae4Qn9G4AZ1npdiJ7dbE6hWNl2JHOiWsmYpmIwWTHqFo6gEGzIzQB@2sme/XvusQS3sJq2rRK5z018haurmCV/m5/3K49cjVw9rtKz7vfrm@@jluhC5IbwzKDJGxx7IMmaM/bk8Qg25E4kaUPvGWV4d0g9ovjCiylAOSGey5J7ohqnAqC1ZSMHXpUa25SNN2UI4@9G97VlhDqUqCHhScrvEWV3Ki8KwBbHU9GRG1lnxXNeoxFihA0ZRdEF3FZ8gpcPscRoEHY8B3CSE1Gox2xegcWzyKF6RG/c1MPRoGmnEoecQKxr2N/H@KGKCcS6DCOkHQ4ioywRsCtfcpG@euKaz9Eff//cMFBXSkinjU1Om5Ax8AyAKhc0FE7S/6/P5RCdXQKgx42G8NDoPOEpl7Y848rq1SSufYhQnS0ifIBcudBcPmw7JmiW6bFSCLLikj4QBL0ybO/g5t5ytJkNWlCCLzEA10L0aWVlXiSti1IZ6O2NY74W8wOSkVtuaTimNB7QKQr6pmlb1xuJ2tn8pmzwV6Ip353UxopJz2ctpRHbmCXPH8hUsyZJA9fxDWQDWHdDTa9CE0/1geiXwcwjooo2fVfmv8w7rBaLtmf@Rh652ME6vhU6qLOc/SnQw012hhKR8O71BE0ukhcaqZZ29zCqae3PEttzJSzOAB/pl4bTlPWoJWbwtAzNXy6o9p5UtDYI829sDMRqDLPuNGFzc7/umD9eLqkAxXFDB9Wf1@w/T4KzR9it7OtrL18MkVTbramdo/V40MRqibkWuWo/FO56ZDbdifc9pfMDS/CfmldiMpokd5oUPLaRFqNGzR2c22QVvQetaTnfnlvTpffKLCrVft@Nfz2y@tpwP4G "Assembly (gcc, x64, Linux) – Try It Online")
**Usage:**
```
$> gcc -DIDEAL_BSS -Wl,-Tbss=0x10000000 -s -static -nostartfiles -nodefaultlibs -nostdlib -Wl,--build-id=none memory.S -o memory
$> echo -n "<Input>" | ./memory; echo $?
```
Program reads input from stdin (it is sensitive to the exact byte count of input, i.e stray spaces/new lines will change result).
The return value of the program is the number of rounds.
**Notes:**
* Size is measured in machine code (i.e 39 bytes of PROGBITS; .text, .data, etc...)
* The 39-byte size assumes the above compile command which sets the BSS address at an ideal value. With generic compile commands (no linker inputs), its 41-bytes.
**Program:**
```
/* Uncomment below if BSS was setup at 2^20. */
/* #define IDEAL_BSS */
.global _start
.text
_start:
/* Incoming registers are zero. */
movb $60, %dl
#ifdef IDEAL_BSS
btsl %edx, %esi
#else
movl $G_mem + 0, %esi
#endif
/* eax == 0 == SYS_read. */
/* edi == 0 == STDIN. */
syscall
leal (%rsi, %rax), %ecx
movl %esi, %eax
play:
/* Load next character. */
lodsb
uncovered_already:
/* Increment round number (returned at prog exit). */
incl %edi
/* (rax) is a byte-map of characters we have already seen. */
movb (%rax), %bl
/* Value zero indicates we haven't seen this character yet. */
testb %bl, %bl
jnz uncover_pair
/* We haven't seen this character so update byte-map with its
position + 1. */
movb %dl, (%rax)
/* Load assosiated character. Compare first to check for back-
to-back. */
cmpb %al, (%rsi)
lodsb
/* If we uncovered the same character (by chance) then continue. */
je uncovered_adjacent
/* If the second uncover was an already uncovered character we
reloop with it as the initial value. */
cmpb %bl, (%rax)
jne uncovered_already
/* Update the second unique character's location then continue. */
movb %dl, (%rax)
uncover_pair:
uncovered_adjacent:
/* At end of buffer, this will always a final turn. */
cmpl %esi, %ecx
ja play
done:
/* Exit. */
xchgl %eax, %edx
syscall
.section .bss
.align 256
G_mem: .space 4096
```
**Examples/Tests:**
```
$> for x in aa aabb abba ggijkikj qqwweerrtt cbxcxvbaav zyxzwyvxvw tbiaktyvnxcurczlgwmhjluoqpqkgspwsfidfedrzmhyeanxvboj; do echo -n "${x}" | ./memory; echo "${x} -> $?"; done
aa -> 1
aabb -> 2
abba -> 3
ggijkikj -> 6
qqwweerrtt -> 5
cbxcxvbaav -> 8
zyxzwyvxvw -> 9
tbiaktyvnxcurczlgwmhjluoqpqkgspwsfidfedrzmhyeanxvboj -> 43
```
[Answer]
## C#, 132 bytes
Wanted to keep working on this (ideally finding a smarter algorithm) but never did, so here's where I got up to 3 weeks ago. I just started with a naïve algorithm and golfed it.
```
string d=args[0],s="";int t=0,i=0;for(;i<d.Length;t++)if(!s.Contains(d[i++])){if(s.Contains(d[i]))t++;s+=d[i-1];s+=d[i++];}return t;
```
### Formatted
```
string d = args[0], // deck
s = ""; // seen cards
int t = 0, // turns taken
i = 0; // current index
for (; i < d.Length; t++)
if (!s.Contains(d[i++]))
{
if (s.Contains(d[i]))
t++;
s += d[i - 1];
s += d[i++];
}
return t;
```
] |
[Question]
[
*Disclaimer: This isn't my challenge but [ThisGuy](https://codegolf.meta.stackexchange.com/a/11802/67719) said I was OK to post.*
---
Occasionally I want to make a word into it's opposite, like `happiness` goes to `unhappiness`. Unfortunately when this happens, my brain will sometimes go blank. Then one day, after yet another this happening, I thought to my self "This is what programs are for!"
As the English language has many exceptions, I have created a list which contains the prefix for the starting letter
```
q or h -> dis- (honest -> dishonest)
l -> il- (legal -> illegal)
m or p -> im- (mature -> immature)
r -> ir- (responsible -> irresponsible)
everything else -> un- (worthy -> unworthy)
```
# Task
Given an input as a string, make the string into its negative and output the result. You can assume that all the inputs given will fit the above rules. Submissions may be programs or functions, not snippets.
# Input
A single string, taken either as a parameter or from STDIN
# Output
The negated form of that string, conforming to the above rules
# How to Win
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins
[Answer]
# Python, 55 bytes
```
lambda n:'ddiiiiuiimmlrnss'[5-'rlmphq'.find(n[0])::7]+n
```
[Try it online!](https://tio.run/nexus/python2#JY1BCoMwEEX3nmLoJkpVWkopBOxFrItIkjqQTDSJlCKe3Rr7N/99eMzo5rUZYXspgDiTEvfMiNYaTyGw9l4xb@w4TKzWSDKn9tIVnD@6M21RhRiggZYNjnZmJTCj3sIksCLOXiXyKoyOAvbmmB/n4/BNNM3CoEYl0xhd@Ctdpp2HdBuQjg48g5TRI0U4Lfx6W6F6wrKe6t3dP@VJK0EfXRTbDw "Python 2 – TIO Nexus")
---
We need to handle 7 different starting letters:
`g` -> `dis`, `h` -> `dis`, `p` -> `im`, `m` -> `im`, `l` -> `il`, `r` -> `ir` and *everything else* -> `un`
We can store all these negations in a single string and extract the right one through slicing:
```
d i s
d i s
i m
i m
i l
i r
u n
'ddiiiiuiimmlrnss'[i::7]
```
Now we need to calculate the start index `i`. `'rlmphq'.find` returns 0 for `'r'`, 5 for `q` and -1 for everything not contained in the string.
To get the needed value from 0 to 6 we still need to subtract the return value from 5, resulting in this code:
```
'ddiiiiuiimmlrnss'[5-'rlmphq'.find(n[0])::7]
```
[Answer]
# [GNU sed](https://www.gnu.org/software/sed/), 50 bytes
Includes +1 for `-r`
```
s/^q|^h/dis&/
s/^l|^r|^m/i&&/
s/^p/imp/
t
s/^/un/
```
Nothing fancy. Uses `&` in the replacement to combine a few substitutions, and `t` to skip the last one if one of the first substitutions happens.
[Try it online!](https://tio.run/nexus/sed#JYpBCsMwDMDufkhvw4/pPdAx0xiS2LUdyiBvX9atNwlpOqZjpIwv9gXhsjKSjVSRl9sVuSpC/Bh7wzmzNPKAQvtWoG7RjcDIVZrzsxCcYpHfcPRVKkXmtoOK/9tHNPj65sO@ "sed – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 30 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
1ị“qmlrrhp”iị“3bµWI⁼ṡ÷ʠ$»œs5¤;
```
**[Try it online!](https://tio.run/nexus/jelly#@2/4cHf3o4Y5hbk5RUUZBY8a5mZCBIyTDm0N93zUuOfhzoWHt59aoHJo99HJxaaHllj///8/Iz8vtbgEAA "Jelly – TIO Nexus")**
### How?
```
1ị“qmlrrhp”iị“3bµWI⁼ṡ÷ʠ$»œs5¤; - Main link: string
1ị - 1 index into the string (first character of the string)
i - 1-based index of 1st occurrence of that in (else zero):
“qmlrrhp” - char list "qmlrrhp"
ị - index into (1-based and modulo):
¤ - nilad followed by link(s) as a nilad:
“3bµWI⁼ṡ÷ʠ$» - compressed string "dis"+"imili"+"run"="disimilirun"
œs5 - split "equally" into 5: ["dis","im","il","ir","un"]
; - concatenate with the string
```
Note that the repeated `r` in `“qmlrrhp”` is in the 5th index, which, if referenced, would result in prepending `un`, so it could equally well be anything other than `h` or `p`.
[Answer]
# TI-Basic, 104 bytes
```
Prompt Str0
sub(Str0,1,1→Str2
Str0
If Str2="Q" or Str2="H
"DIS"+Ans
If Str2="L
"IL"+Ans
If Str2="M" or Str2="P
"IM"+Ans
If Str2="R
"IR"+Ans
If Ans=Str0
"UN"+Ans
Ans
```
Requires all capital letters.
Explanation:
```
Prompt Str0 # 4 bytes, input user string to Str0
sub(Str0,1,1→Str2 # 12 bytes, store first character in Str2
Str0 # 3 bytes, store Str0 in Ans
If Str2="Q" or Str2="H # 14 bytes, if the first letter was Q or H
"DIS"+Ans # 8 bytes, store DIS+Ans in Ans
If Str2="L # 7 bytes, If the first letter was L
"IL"+Ans # 7 bytes, store IL+Ans in Ans
If Str2="Q" or Str2="H # 14 bytes, if the first letter was Q or H
"IM"+Ans # 7 bytes, store DIS+Ans in Ans
If Str2="R # 7 bytes, if the first letter was R
"IR"+Ans # 7 bytes, store IR+Ans in Ans
If Ans=Str0 # 6 bytes, if Ans has not been changed (first letter was none of the above)
"UN"+Ans # 7 bytes, store UN+Ans in Ans
Ans # 1 byte, implicitly return Ans
```
[Answer]
# [///](https://esolangs.org/wiki////), ~~59~~ 56 bytes
```
/^/\/\/#//#qu/disqu^h/dish^l/ill^m/imm^p/ipp^r/irr^/un/#
```
[Try it online!](https://tio.run/nexus/slashes#FcVBCoAwDATAx/Qs@yFZkFZIIK1ppE/3HJU5TILYPwUoc6HpPRflX2hQM3Zo73SoOwMaQayBkvmMa6tHlfMF "/// – TIO Nexus")
Input goes after the very last `#`.
**How it works:**
I made an optimization that reduced the size to 56 bytes, but since that complicates things I will explain the original version, then explain the golf.
```
/#qu/disqu//#h/dish//#l/ill//#m/imm//#p/ipp//#r/irr//#/un/# |everything after the ` |` is not code.
/#qu/disqu/ |replace `qu` with `disqu`
/#h/dish/ |replace `h` with `dish`.
/#l/ill/ |replace `l` with `ill`.
/#m/imm/ |replace `m` with `imm`.
/#p/ipp/ |replace `p` with `ipp`.
/#r/irr/ |replace `r` with `irr`.
/#/un/ |replace everything else with `un`.
# |safety control
```
**Intuition:** The challenge is simple enough, just add the negative depending on the beginning of the word. However, in ///, you cannot just `concatenate if [...]`, you can only replace something following a specific pattern. So in this program, the positive word beginnings are replaced with the negative word beginnings. The `#` was added to make sure that once a new beginning was added, no more new beginnings would be added. The `#` also made it possible to do 'everything else: un'.
The golf incorporates a new substitution at he beginning: `/^/\/\/#/`. This replaces all `^` with `//#`, which was a common pattern in the original version.
[Answer]
## Batch, 114 bytes
```
@set/pw=
@set p=un
@for %%p in (dis.q dis.h il.l im.m im.p ir.r)do @if .%w:~,1%==%%~xp set p=%%~np
@echo %p%%w%
```
Checks the first character of the word against the list of custom prefixes and if so changes the prefix from the default of `un`. Special-casing `qu` is possible at a cost of 21 bytes.
[Answer]
# Javascript, ~~72~~ ~~71~~ ~~66~~ ~~61~~ ~~60~~ 59 bytes
~~`w=>('dis....il.im...im.dis.ir'.split('.')[w.charCodeAt(0)-104]||'un')+w`~~
~~`w=>'un.dis.dis.il.im.im.ir'.split('.')['qhlmpr'.indexOf(w[0])+1]+w`~~
~~Yeah, it's *still* longer than an existing solution. :)~~
```
w=>['un','dis','im','il','ir']['qmlrhp'.search(w[0])%4+1]+w
```
In case this needs any explanation, I'm taking advantage of the q/h and m/p pairs by combining their index in the search string with a mod 4, then using that as the lookup into the prefix array.
[Answer]
# JavaScript (~~71~~ ~~64~~ 61 bytes)
`w=>({q:a='dis',h:a,l:'il',m:b='im',p:b,r:'ir'}[w[0]]||'un')+w`
Edits:
* Saved 7 bytes thanks to @ErtySeidohl (`charAt(0)` -> `[0]`)
* Saved 3 bytes thanks to @edc65 (assigning shared prefixes to variables)
```
var f = w=>({q:a='dis',h:a,l:'il',m:b='im',p:b,r:'ir'}[w[0]]||'un')+w;
function onChange() {
var word = event.target.value;
var output = f(word);
document.getElementById('output').innerHTML = output;
}
```
```
Input Word: <input type='text' oninput='onChange()'/><br/>
Output Word: <span id="output">
```
[Answer]
## Haskell, 71 bytes
```
f l=maybe"un"id(lookup(l!!0)$zip"qhlmpr"$words"dis dis il im im ir")++l
```
Usage example: `f "legal"`-> `"illegal"`. [Try it online!](https://tio.run/nexus/haskell#HY07DsIwEESvslmlsBWEuEBuABUlSuHIDl6x/uCPULi8cZBm9OZV0zbg2al9NVg9khYcwqtGwcNwkeOXIr4tu5hw/ISkM2rKcJQYyP2TUE4TN6fIwwxOxRuIWMu9pKuHM2wSHmiDN7ngCdk8FXc6VWoyfSSTY/CZVj6sfxS749J@ "Haskell – TIO Nexus")
Build a lookup table of prefix/replacement pairs for looking up the first char of the input string with a default value of `"un"` if not found.
[Answer]
# [Retina](https://github.com/m-ender/retina), 54 bytes
```
^[^hqlmpr]
un$+
^[hq]
dis$+
^l
il$+
^[mp]
im$+
^r
ir$+
```
Explanation:
```
{implicit replace stage}
^[^hqlmpr] Append un to words starting with none of: hqlmpr
un$+
^[hq] Append dis to words starting with h or q
dis$+
^l Append il to words starting with l
il$+
^[mp] Append il to words starting with m or p
im$+
^r Append ir to words starting with r
ir$+
```
First time I've used Retina. It's a pretty neat language.
[Try it online!](https://tio.run/nexus/retina#@x8XHZdRmJNbUBTLVZqnos0VF51RGMuVklkMYudwZeaAxXILYrkyc0HMIq7MIhXt///L84tKMioB)
[Answer]
# C, ~~109~~ 107 bytes
```
f(char*s){printf("%s%s",*s-109&&*s-112?*s-108?*s-114?*s-104&&*s-113|s[1]-117?"un":"dis":"ir":"il":"im",s);}
```
[Try it online!](https://tio.run/nexus/c-gcc#bY1LCoMwEIb3nkICSiIKTSv04cKDlC5SG5tATCQTKcV67K5tYtuds/gf88HM3OJGMJsBGXsrtWsxSiABlGdQ0M0xTYPTbb3Uw2K0/LbyB3cvONOLD/saDRqd0E2CV2mDqCAdyoFU0@zvxx2TGpNojGI//pswmoNDpOoHBxj58CeK35laAx1zg@VrxHLojQZ5Vav4YawTz7CY5rc2RcMawT8)
[Answer]
## Mathematica, 107 bytes
```
StringReplace[StartOfString~~x:#:>#2<>x&@@@{{"q"|"h","dis"},{"l","il"},{"m"|"p","im"},{"r","ir"},{_,"un"}}]
```
## Explanation:
`StartOfString~~x:#:>#2<>x&` is a pure function where the first argument is a [string pattern](http://reference.wolfram.com/language/guide/StringPatterns.html) to match at the beginning of the string and the second argument is a string to prepend to the match. It returns a delayed rule suitable for use within `StringReplace`. This is then applied to each of the pairs `{{"q"|"h","dis"},{"l","il"},{"m"|"p","im"},{"r","ir"},{_,"un"}}` resulting in the list of rules
```
{
StartOfString~~x:"q"|"h":>"dis"<>x,
StartOfString~~x:"l":>"il"<>x,
StartOfString~~x:"m"|"p":>"im"<>x,
StartOfString~~x:"r":>"ir"<>x,
StartOfString~~x_:>"un"<>x
}
```
Finally this list is passed into `StringReplace` which gives an operator on strings.
[Answer]
# PHP, 101 Bytes
```
echo preg_match("#^(qu|[hlmpr])#",$argn,$t)?[qu=>dis,h=>dis,l=>il,m=>im,p=>im,r=>ir][$t[1]]:un,$argn;
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/4fb8d1549687fcda1a38eac52bc49f4400a987a9)
[Answer]
# Excel 78 bytes
```
=TRIM(MID(" disdisil im im ir un",IFERROR(FIND(LEFT(A1),"qhlmpr"),7)*3,3))&A1
```
I found some close contenders using different methods that scored 81 bytes:
```
=IFERROR(CHOOSE(FIND(LEFT(A1),"qhlmpr"),"dis","dis","il","im","im","ir"),"un")&A1
```
And 84 bytes:
```
=IFERROR(TRIM(MID("im disi"&LEFT(A1),MOD(FIND(LEFT(F1),"qlmhrp"),3)*3+1,3)),"un")&A1
```
[Answer]
## REXX, 78 bytes
```
arg a
s.=un
s.q=dis
s.h=s.q
s.l=il
s.m=im
s.p=im
s.r=ir
p=left(a,1)
say s.p||a
```
Saves a few bytes by replying in UPPERCASE, e.g. potent -> IMPOTENT.
[Answer]
# Perl, 49 + 1 (`-p` flag) = 50 bytes
```
s|^[hq]|dis$&|||s|^[lmr]|i$&$&|||s|p|imp|||s||un|
```
Using:
```
perl -pe 's|^[hq]|dis$&|||s|^[lmr]|i$&$&|||s|p|imp|||s||un|' <<< responsible
```
[Try it online](https://tio.run/nexus/perl5#LYlLCoQwDIb3PUdx54nEAcVgA20Tm4oI/9mnMz5236MZPkPYRixsvgNweUxlBPvuDQpOehP2jNaCZLLqIq1TdGmqeyFXyFSy8RzJqdgDh5Qazq9o5f9rvf4A "Perl 5 – TIO Nexus").
[Answer]
## Clojure, 65 bytes
```
#(str(get{\q"dis"\h"dis"\l"il"\m"im"\p"im"\r"ir"}(first %)"un")%)
```
Well this is boring... but I couldn't make it any shorter. At least there is very little whitespace.
[Answer]
## OCaml, 85
```
(fun s->(match s.[0]with|'q'|'h'->"dis"|'l'->"il"|'m'|'p'->"im"|'r'->"ir"|_->"un")^s)
```
Anonymous function, uses pattern matching on its first char.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 38 bytes
```
«÷c4w«?hḟ:u=[`un`|4%«⟑Ẇf:«2ẇ`Ġ⟨`p$i]?+
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%AB%C3%B7c4w%C2%AB%3Fh%E1%B8%9F%3Au%3D%5B%60un%60%7C4%25%C2%AB%E2%9F%91%E1%BA%86f%3A%C2%AB2%E1%BA%87%60%C4%A0%E2%9F%A8%60p%24i%5D%3F%2B&inputs=honest&header=&footer=)
Messy.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~66~~ 62 bytes
`%4+1` inspired by @[Steve Bennett](https://codegolf.stackexchange.com/a/115467/80745)
```
param($s)(echo un dis im il ir)[('qmlrhp'|% I*f $s[0])%4+1]+$s
```
[Try it online!](https://tio.run/##XZAxT8MwEIV3/4obHBLTIIHEilSJiQWQOjBEEUrTKzGy49Rnq6A2vz3YTlQQN52/9@6d7cEc0VKHSk18Dw9wmobGNrrgJApsOwO@h50kkBqkAmlFVeQHrWw35OcMnq73wKm6rUV2v7qrV5ymkbF1wcoi70yP5PIS8jC/HEQUFH40KnKp5jZR3ThvMWG99IlbpMH0JLdqFu1fkBxHY133HUXfL71gAs6QwYlBKB7orgSOXwO2DnfPYavD8Fj@Push0isXwFX4g@ROvHrdPHpyRr9sP8NgvZ7jYm182yJRzFiGb/Dwf8PF/RYSo/WSHOv3FnNCEkY2Tj8 "PowerShell – Try It Online")
] |
[Question]
[
In some languages, strings are started and ended with a quote mark (`'`). And quote itself is escaped by writing it twice sequentially. For example, empty string is written as `''`, and `I'm` is written as `'I''m'`.
This question is about find out all non-overlapping strings from left to right in such format from the given input, while ignoring anything between or around these string literals.
## Input / Output
You are given a string contains only printable ASCII. Quotes (`'`) in inputs are always paired. And you need to find out all non-overlapping quoted strings in it. Output these strings in the order they appeared.
You are free to choose any acceptable I/O format you want. However, **formats of strings for input and output MUST be the same**. Which means that you cannot take raw string as input, and claim that your output string are formatted in quotes, with quotes escaped by writing twice. As this may trivialize the challenge.
## Test Cases
All testcases here are written in JSON format.
```
Input -> Output # Comment (not a part of I/O)
"abc" -> [] # text out side quotes are ignored
"''" -> [""] # '' is an empty string
"''''" -> ["'"] # two sequential quotes in string converted into a single one
"'abc'" -> ["abc"]
"a'b'" -> ["b"]
"'b'c" -> ["b"]
"a'b'c" -> ["b"]
"abc''def" -> [""]
"'' ''" -> ["", ""] # there are 2 strings in this testcase
"'abc' 'def'" -> ["abc", "def"]
"'abc'def'ghi'" -> ["abc", "ghi"] # separator between strings could be anything
"'abc''def'" -> ["abc'def"]
"a'bc''de'f" -> ["bc'de"]
"''''''" -> ["''"]
"'''a'''" -> ["'a'"]
"''''a''" -> ["'", ""]
"''''''''" -> ["'''"]
"'abc\"\"def'" -> ["abc\"\"def"] # double quotes do not have special meanings
"'\\'\\''" -> ["\\", ""] # backslashes do not have special meanings
"'a'#48'b'" -> ["a", "b"] # hash signs do not have special meanings
"a,'a','a,''a''','a,''a'',''a,''''a'''''''" -> ["a", "a,'a'", "a,'a','a,''a'''"] # Testcase suggested by Command Master
```
[And here are above testcases formatted with line breaks.](https://tio.run/##hVRNj5swEL3nV4zIwbAlpF31UFXdXHraSts9bG@Bg4EJeAs2i02yUdXfno7NR6CttCgfwzzPm3njsZ/5keusFY3ZSJXjJVNSqwqjShW@f@hkZoSS4AfwC7Y3l3vZdAauz2YHj52Z@9bwVdU1SgO@VAY4NLw1oA5wv30MVh5PM28Zv09g/qzB4CsFEKUWOcJLpwxq4C2CKKRqMV95jM05HInnJQsSxkBQlASsG3MGbVohCxu5iHWRbB5K6U8KNL50JEHwaswv5MAB1KAjtgZz8hlFAjV5KwQlkfhJ3yyB47eSE1LO0n9SpxYgf/ZfgC@RGUBJWI4Hb6HfqgP2d3YvhGtvSF2J1EnbzdtBkNNmSuoW6TQZ16MMsCkc3SSDuGzaZFhh8aIUtGa@gjyUcE1NpK3nRrWQojkhyilhproqJy/tz5kyu40ZNfX1j3xsSEetcDA7XGGH9rIX29pvKhsQPoN6hI@QxZZQ36yRcUIHRjYKj73YG0odCx1cTniuurSaJjdXYA9CyY8IusHMDlWNXNpOEF0c288iUxzPNm0NKc9@6orr8m0yztYfP01z1tdmudKJrCQemthCvsXFQ2Kjb9i3cLLsbzg0b@jRNY8LmoxrtGvLj2G8QHdFQTadoPTsbgsuc3jg5GkvN1v4HURGPblR8clsRU1/uqmE8VksGdmVyNC/DWHzIYhq3vivcLeD13GNPf3B/n0yvVN9rF94tAu/PT1@j2g0NfrHIOgBfy9ClQR3u/1qu4UHlYvDGQ6qqtTJnvlKSGo@nfYCDZxKbpCuAMLbmhsNZ9XBidONRw770tKJslfi1t5iZKyYuzY/s3DFqBR4B4Ks/t60ziiKlKvC2PLYF7fEBOEqiZ6VkL3qYLI3w@O8lz8)
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 17 bytes
```
=”'ŻḂ+¥\¬Ä×ḂƲḊƙŻḊ
```
[Try it online!](https://tio.run/##y0rNyan8/9/2UcNc9aO7H@5o0j60NObQmsMth6cDOcc2PdzRdWwmSKLr/8PdWw5tPdz@qHGfklLWo43rsoB6dDQj//9PTErmUlcHIhAB5KhzJaonAZlJ6slgFpAECqqnpKYB1SjAFCmABKBsECs9IxPKg0gAdYKZ6mlgkyEWJEJpEAMqDDVPSQliXAwQgkTUlU0sgHYDAA "Jelly – Try It Online")
Inspired by the prevalence of regex solutions, the core of the logic is a scan by the state transition table
| | \$0\$ | \$1\$ | \$2\$ |
| --- | --- | --- | --- |
| a quote | \$1\$ | \$2\$ | \$1\$ |
| not a quote | \$0\$ | \$1\$ | \$0\$ |
which fortunately simplifies pretty nicely to `Ḃ+`. \$0\$ is anything non-string, \$1\$ is an opening quote or anything inside a string, and \$2\$ is a closing quote or the first quote of an escape pair.
```
=”' For each character, is it a quote?
Ż Prepend a 0, then
Ḃ+¥\ scan by the table.
ƙ Group the input
Ż with a 0 prepended
€ by the cumulative number of zeroes in the scan result
×ḂƲ multiplied by the result mod 2,
Ḋƙ remove the opening quote from each group,
Ḋ and remove the 0 group (everything outside a string).
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 19 bytes
```
TMa@+`'.*?'`R"''"''
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLG51bGwsIlRNYUArYCcuKj8nYFJcIicnXCInJyIsIiIsIiIsIi1wIFwiJycnJ25vJ3llcyAnJ3llcycnJ1wiIl0=)
-11 bytes thanks to DLosc.
```
a@ # Match in input
+`'.*?'` # A regex
TM # Remove the first and last
R"''"'' # Unescape '
```
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes
```
M!`('.*?')+
%`^'|'$
''
'
```
[Try it online!](https://tio.run/##NY09DoMwDIV3n4JS0INWYmLo1hP0BASUhPK3MFSM3D21EyNZ9udn@/k3HdvuQlnZgdCho4J69Aifm63QPN6on1TaAScKIoAQgvNjJEjiBuTgGT3GSJxZxHeaeSe7ljIRlIWWddMuDfgyIubonB44rQIqq5/JTZ4MjZEQFff2xf// "Retina 0.8.2 – Try It Online") Outputs each string on its own line but link wraps each test case in `[` and `]` to make it easier to tell where each output starts and ends. Explanation:
```
M!`('.*?')+
```
List all of the matched strings, still quoted.
```
%`^'|'$
```
Remove the leading and trailing quotes.
```
''
'
```
Deduplicate the interior quotes.
[Answer]
# [R](https://www.r-project.org), 83 bytes
```
\(x)gsub("''","'",substring(a,p<-el(gregexpr("'(''|[^'])*'",a))+1,p+attr(p,"m")-3))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3g2M0KjTTi0uTNJTU1ZV0lIAYyCkuKcrMS9dI1Cmw0U3N0UgvSk1PrSgoAqrRUFeviY5Tj9XUAqpM1NTUNtQp0E4sKSnSKNBRylXS1DXW1IQarZpoq6SemJSsrqCekpoGJNMzMtXVs7JzgEz13Lx8Ja40jUSo4gULIDQA)
Same regex-based approach as [emanresu A's answer](https://codegolf.stackexchange.com/a/249910/95126).
[Answer]
# [J](https://www.jsoftware.com), 31 bytes
```
'''(''''|[^''])*'''".&.>@rxall]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8GCpaUlaboWN5XSbPXU1dU1gFi9JjpOXT1WUwvIVNJT07NzKKpIzMmJhai8xaSSmpyRr6CurqBrpZCmoJ6YlKzOxQUWS7RSsAUKGShYGSjo6ik4B_m4camrc2lCpTVsQKZrYlODqioJm6JEoDBBRUDRZKJMQqjC5miQn9RTUtMQRiVa6SRaaUK8jOZ2BVTHg_Ricxk4nOCWJiUnpGdkYjMPpA5otTpQGi3oEnGGXiI4ABWQ_A12Pw7PQ-SQPKceE6NuDTIbi3OAUkCE5BKgZdbgcMXmdnVlEwtwPEESCyx5AQA)
Mostly a port of [emanresu A's answer](https://codegolf.stackexchange.com/a/249910/15469).
The only difference is that after cutting out the quote pieces, we simply evaluate the resulting quoted string to handle the unescaping. This works because J is one of the languages described by this challenge, which also explains all the escaping in the regex.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~35~~ ~~29~~ ~~28~~ ~~21~~ ~~16~~ 15 bytes
```
''¡¦ι`õÊ0šÅ¡''ý
```
[Try it online](https://tio.run/##yy9OTMpM/f9fXf3QwkPLzu1MOLz1cJfB0YWHWw8tVFc/vPf//0Qd9UR1INZRB9LqCBaIBGKIKAgoAAA "05AB1E – Try It Online"), or [try all testcases](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX/lfXf3QwkPLzu1MOLz1cJfB0YWHWw8tVFc/vPe/zv/EpGQudXUgAhFAjjpXonoSkJmkngxmAUmgoHpKahpQjQJMkQJIAMoGsdIzMqE8iARQJ5ipngY2GWJBIpQGMaDCUPOUlCDGxQAhSERd2cQC5IpEHSAbiHUgmuEsEKkDNQkMAA "05AB1E – Try It Online")
Outputs an empty string if there are no strings. If it has to be an empty array, it's +1 for [placing `ε` before `''ý`](https://tio.run/##AScA2P9vc2FiaWX//ycnwqHCps65YMO1w4owxaHDhcKhzrUnJ8O9//9hYmM)
## Explanation
```
''¡ split on quotes the implicit input
(e.g. ["a,", "a", ",", "a,", "", "a", "", "", ""], for a,'a','a,''a''')
¦ tail, remove the first part
(e.g. ["a", ",", "a,", "", "a", "", "", ""])
ι uninterleave
(e.g. [["a", "a,", "a", ""], [",", "", "", ""]])
` dump to stack
õ push an empty string
Ê for each odd-indexed part, check if it's not equal to it
(e.g. [1, 0, 0, 0])
0š prepend a zero
(e.g. [0, 1, 0, 0, 0])
Å¡ split the even-indexed parts on indices
the odd-indexed parts aren't empty
(e.g. [["a"], ["a,", "a", ""]])
''ý join each on a quote
(e.g. ["a", "a,'a'"])
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 71 bytes
```
t,n;f(char*s){n=*s==39^t;t=n?t&&putchar(n%2?*s:10),n%2:t+t;*s&&f(s+1);}
```
[Try it online!](https://tio.run/##dVDBbsMgDL33KyykBUhSrd1OC4t63mkfsHQSoaHlMDoV97Io354BaUgPG0L4vednLFutj0qNI5ZWaKZO8pI73ts6d3X9/PKJAmu7wyz7vmJIMvvwtMtdtd3w0sMKCxS5yzLNXLHlYhi/pLGMQ78CCH7IsXOopOvcxx5q6IHIVpGSUBqfKXgpREnbSFuqbixGn6SHTkc/LAUQxMQCPp5M4nPS/xIJ1bd@c2OZUIApmf5vSEPmBk0TLiUwCD@XsQgmAH2@ADN@qo0AA6/gzE931ixNzOFx1uJiubcVxbQcAL9Rx8ib9bEiXCzasjGzv9fJ@xXvzfp/5/qPM5UNq2H8BQ "C (gcc) – Try It Online")
| State `t` | Input `*s` | Output | Next | `n` | `n%2` | `t+t` |
| --- | --- | --- | --- | --- | --- | --- |
| 0 | quote | empty | 1 | 1 | 1 | - |
| 0 | others | empty | 0 | 0 | - | 0 |
| 1 | quote | empty | 2 | 0 | - | 2 |
| 1 | others | as-is | 1 | 1 | 1 | - |
| 2 | quote | as-is | 1 | 3 | 1 | - |
| 2 | others | line-break | 0 | 2 | 0 | - |
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~112~~ 95 bytes
* -5 thanks to ceilingcat
* -12 thanks to suggestions from tsh
Implements a simple state machine to determine whether the parser is inside a string.
```
#define P putchar(
t;f(char*s){for(t=0;*s;)t?*s-39?P*s++):*++s-39?t=0:P*s++):*s++-39||P t=10);}
```
[Try it online!](https://tio.run/##RZHLboMwEEX3fMXIqPIDUqVqF21ckh@IKjZdlSzAQLDUQoSdbhK@nY7Nowtm7pmxfe1Bbc5KjWNYVrVuK0jhcrWqyXsWWFkzp4Tht7rrmU22UhjJ7UGYzfPbIRUmivhORJFHbO@WEkYs3e8p2ORpy@UwhrpV39eygndjS909Nvsg0K2Fn1y37LfTJYdbAOD8QJivU@IIgOSFIjGh1IcpYcnlnBYeC6pm8hmbFN/i18P/BnDFlZw@Nxp5cqHLtvlgD7SeTRf3fFVOrs3VJMsy4r7FCXU2hWkFDV9e/aW96cfn8YhiiEEIKwOU05CNBGSwOEiYhnDpcVI1Iw8Gkj2QWFgufaNmq8S/ZhghnoZgGP8A "C (gcc) – Try It Online")
Annotated:
```
t;f(char*s){
for(t=0;*s;) // initialize state to search mode
t? // is inside the string?
*s-'\''? // found quote?
putchar(*s++): // not quote, print it
*++s-'\''? // double quote?
t=0: // reset state to search
putchar(*s++): // print quote
*s++-'\''|| // found initial quote?
putchar(t=10); // print newline, set state
}
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 39 bytes
```
1⊸↓¨(-⟜1·2⊸|⊸×⟜(+`·»⊸<×)·2⊸|⊸+`=⟜''')⊸⊔
```
[Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMeKKuOKGk8KoKC3in5wxwrcy4oq4fOKKuMOX4p+cKCtgwrfCu+KKuDzDlynCtzLiirh84oq4K2A94p+cJycnKeKKuOKKlAoK4oCiT3V04oiY4oCiRm104oiYRsKoICJhYmMi4oC/IicnIuKAvyInJycnIuKAvyInYWJjJyLigL8iYSdiJyLigL8iJ2InYyIKCkYgImFiJ2NkJ2VmJycnZ2hpJ2prJycnJycnbCI=)
### Explanation
The core logic is taken from [Unrelated String's Jelly answer](https://codegolf.stackexchange.com/a/249930/16766):
```
2⊸|⊸+`=⟜'''
=⟜''' Compare each character with ' character (1 if equal, 0 if not equal)
` Scan left-to-right on this function:
⊸+ Add the current value to
2⊸| the accumulated value mod 2
```
This results in a list where:
* 0 represents a character outside any of the strings
* 1 represents an opening quote or a regular character inside a string
* 2 represents a close quote or the first of a pair of quotes
Next,
```
-⟜1·2⊸|⊸×⟜(+`·»⊸<×)
× Get the sign of each number (0 -> 0; 1,2 -> 1)
< Compare each item in that list with
»⊸ the corresponding item in that list shifted to the right
This gives 1 at the beginning of each run of nonzeros, 0 elsewhere
+`· Cumulative sum
We now have a list of nondecreasing nonnegative numbers the same
length as the main list, such that the runs of nonzeros in the
main list are numbered 1, 2, 3, ...
⊸×⟜( ) Multiply that list of numbers by
2⊸| the main list mod 2
This puts zeros at every index where the main list has 0 or 2
(i.e. characters outside of strings, close quotes, and one quote
out of every escaped pair)
-⟜1· Subtract 1 from each (zero becomes -1, and group numbers start at 0)
```
For example (`-` represents `-1`):
```
Input: a'b''c'd''e'''f'
Result: -00-00--1--2-22-
```
Then:
```
1⊸↓¨(...)⊸⊔
⊸⊔ Group the string into buckets
(...) specified by the result of the above function
1⊸↓¨ Drop the first character (opening quote) from each bucket
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~27~~ 22 bytes
```
⪫E✂⪪S'¹±¹¦¹⎇﹪κ²⎇鶦'ιω
```
[Try it online!](https://tio.run/##TYvBCgIxDER/pfTSFOphvfoFCitCPXoJtazB0pbSVfz6mCKigTdJhplwwxYKJuZTo9zhUCjDjBV8ohDB10Qd9rmu3XcJLGCd0kaLTk4d44I9wjQ@4RxbxvaCuVzXVODu1PbPJSlesv7WyYo8rd0xozNoBGdkm981VPi4Y3jzSG8 "Charcoal – Try It Online") Link is to verbose version of code. Outputs a newline-separated list. Explanation: Now based on @CommandMaster's 05AB1E answer.
```
S Input string
⪪ ' Split on literal string `'`
✂ ¹±¹¦¹ Slice off first and last piece
E Map over remaining pieces
κ Current index
﹪ Modulo
² Literal integer `2`
⎇ If current index is odd
⎇ι If current piece is not empty
¶ Replace with newline
' Else replace with literal string `'`
ι Keep even pieces
⪫ ω Join together
Implicitly print
```
[Answer]
# [Python](https://www.python.org), 82 bytes
```
lambda s:[re.sub("''","'",x[1:-1])for x in re.findall("(?:'[^']*')+",s)]
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVPNbptAED705qcYrQ8LMVhx1EPkyuk79ApUWmAwq-Bdwi6J8yy9RKraQ96ofZrO8mdIKgUZbM-3833zzQw_ftfPttTq5WdxiH-1tghv_3yrxCnNBZh91ODWtKnHOGcBo_sc7fbhLvEL3cAZpAI6UEiVi6rymPd1z6PvPLni_oYFxk9W8lTrxtKhgfnV5VUuT9eovGt_vwIZaDjASdSesc2WblkH1bYxdSWtx9Ys2PnRdbId_od3zPdXUDdSWU9Ov3SAKj8wCEOI2BS98jjjm_OGnlPBBWX5gcH6wAJgfVpySfG_DN99xS9_P70ykWYMLld4B1EC82sNFs8WdGvByBzhodUWDYgGQR6VbjBfuQ7CGxLGkgUJ5yApSwGeavsMrhXq6DIXuV0mn6eS_JMGgw8tKitFNeqT254DMq0esbGYU8xqoNFStELQComf_M0EOn5nOVkxwdN30qkDKJ79FxBLZAaQCM-xYAv_zh3wt-puMpNBclciddJ182Yw1HmzJXWLfNpMmNEGOImObrJBXE42GU44_FhKOjM_QRESXFMTa9EIS8uSon1CVJNgptsqpyjNh16YfjCjp77-kY8PctSKDubFBe7Q3vZirP1Q-YCIGdQjYoQctoT6Zo2MEzow8tF4zGI2lDoWOoQ647lu02ra3FyD0hZK8YhgaszcUp1QKNcJootj91koxfFsaGtIRXZvKmHKj8kEX3--nfasr81xpRNZSTy0sUf1nqtYkPXv7D8)
Similar but not exactly the same regex as all the other answers.
### [Python](https://www.python.org), 80 bytes (using @Neil's non-greedy regex)
```
lambda s:[re.sub("''","'",x[1:-1])for x in re.findall("(?:'.*?')+",s)]
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVNLbtswEF1051MM6AWlWDKSoIvAhZMrdG9pQUkji6hMMiKVOGfpJkDRLnKj9jQd6mcpKVDBku15nPfmzYy-_zIvrtLq9Ue5T362rozvfn-txSkrBNjdocGtbbOAcc4iRvf5cLOLb9Kw1A2cQSqgA6VUhajrgAUPO769euDhhkU2TFfyZHTj6MjA--azap-lDargOtytQEYa9nASJrCu2dItTVRvG2tq6QK2ZtFNeLhOt8P_-J6F4QpMI5UL5PRLR6iKPYM4hgObolcBZ3xz3tBzKrekrDCyaPYsAtanpZeU8Mvw3Vf8-ufTGxNZzuByxfdwSGF-rcHh2YFuHVhZIDy22qEF0SDIo9INFivfP3hHwli6IOEcJGUpwJNxL-BboY4-c5HbZfJ5Ksk_a7D42KJyUtSjPrntOSDX6gkbhwXFnAYaLEVrBK2Q-MnfTKDj95bTFRM8-yCdeYDi-T8BsURmAInwAku28O_dAX-v7iczGSR3FVInfTdvB0OdN1dRt8iny4UdbYCX6OgmG8TlZdPhhMePlaQz8xMUIcE1NdGIRjhalgzdM6KaBHPd1gVFaT70uvSDGT319Y98fJCjVnQwLy9wh_a2F2Pth8oHRMygHhEj5LEl1DdrZJzQgZGPxhOWsKHUsdAh1BkvdJvV0-YWGpR2UIknBGsw90t1QqF8J4guSfxnoZQks6GtIRP5N1sLW_2fTPD157tpz_raPFc2kVXEQxt7VB-5ygVZ_87-BQ)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes
```
`(?:'€?')+`ẎƛḢṪ‛''\'V
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJgKD86J+KCrD8nKStg4bqOxpvhuKLhuarigJsnJ1xcJ1YiLCIiLCJcIidhYmMnZGVmJ2doaSdcIiJd)
Regex in golflangs go brr
Uses @Neil's regex, go upvote that.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~28~~ 31 bytes
This non-regex solution ended up considerably longer than [the regex solution](https://codegolf.stackexchange.com/a/249910/16766), but I thought it was still interesting enough to post.
```
YUW:a^''y@1WV(#_\?n''M H S@y)|u
```
Outputs each string on a separate line. [Try It Online!](https://dso.surge.sh/#@WyJwaXAiLG51bGwsIllVVzphXicneUAxV1YoI19cXD9uJydNIEggU0B5KXx1IiwiIiwiIiwiXCJhJ2InJycnYydubyd5ZXMgJyd5ZXMnJydcIiJd)
### Explanation
```
a^'' Split input string on single-quote character
UW: Unweave into two sublists of every other item
Y Yank into y
@y Take the first sublist (substrings "outside" the quotes)
H S Remove the first and last elements
M Map this function to the remaining elements:
#_ Length of substring
\? is nonzero?
n If so, newline
'' If not, single-quote character
y@1WV( ) Weave the other sublist with that result
|u If list is empty, use nil instead to suppress printing
Join together and autoprint (implicit)
```
The idea here is to consider the quotes in pairs. When the end of one matched pair of quotes is immediately followed by the beginning of another pair, that represents an escaped quote (so we reintroduce a quote character); when there are some characters between the end of one pair and the beginning of the next, that represents two separate strings (so we introduce a newline).
] |
[Question]
[
I have a colleague at work that works from home every Tuesday and Thursday. At around 8:00 AM he sends us a message with the following text:
>
> Hello today I'm working from home
>
>
>
In order to relieve him from the burden of doing this every day he stays at home, we would like to automate this task for him.
### The challenge
Write in as few bytes as possible a piece of code that:
* Receives the current time: your code may receive values for the current year, month (1-12), day of month (1-31), hour (0-23) and minute (0-59) and the day of the week (you can choose whether this number starts from 0 or 1, and if 0/1 means Sunday, Monday or any other day); alternatively you may receive a structure such as `Date`, `DateTime`, `Calendar` or any other time-related structure, if your language allows it. You can also receive a string with the date in `yyyyMMddHHmm` if you want, or two separate strings for date and time, and then an integer with the day of week. Feel free.
* Returns two consistent *truthy* and *falsey* values, indicating if the message must be sent to the work chat or not.
### Rules
* This piece of code is assumed to be invoked periodically. The exact periodicity is irrelevant, nonetheless.
* The truthy value must be returned if the day of week is Tuesday or Thursday and the time is 8:00 AM with an error margin of 10 minutes (from 7:50 to 8:10 inclusive).
* The truthy value must be sent only if it is the first time the code is invoked between those hours for the specified day. We don't want the bot to send the same message several times in a row. The way you manage this restriction will be entirely up to you.
* Your code may be an independent program executed repeatedly or it may be part of a bigger code that is always running. Your choice.
* You may assume that there will be no reboots between executions of the code.
* You may assume that the date will always be correct.
* Explanations about your code and specifically about the method used to achieve persistence are encouraged.
### Examples
```
(Week starts on Monday: 1, the following invokations will be made in succession)
2018,08,27,08,00,1 = falsey (not Tuesday or Thursday)
2018,08,28,07,45,2 = falsey (out of hours)
2018,08,28,07,55,2 = truthy (first time invoked this day at the proper hours)
2018,08,28,08,05,2 = falsey (second time invoked this day at the proper hours)
2018,08,28,08,15,2 = falsey (out of hours)
2018,08,29,08,00,3 = falsey (not Tuesday or Thursday)
2018,08,29,18,00,3 = falsey (not Tuesday or Thursday)
2018,08,30,07,49,4 = falsey (out of hours)
2018,08,30,07,50,4 = truthy (first time invoked this day at the proper hours)
2018,08,30,07,50,4 = falsey (second time invoked this day at the proper hours)
2018,08,30,08,10,4 = falsey (third time invoked this day at the proper hours)
2018,08,30,08,11,4 = falsey (out of hours)
2018,09,04,08,10,2 = truthy (first time invoked this day at the proper hours)
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code for each language win!
[Answer]
# JavaScript (ES6), 43 bytes
```
f=(D,t,d)=>5>>d&t>749&t<811&&!f[D]*(f[D]=1)
```
[Try it online!](https://tio.run/##rZPNToQwFEb3PsWVBQGDTosgJRFW8wizMy7ItBUUuaS9TDJPjyVjMGaM0YFN06Q55/586Wt1qOzeND3ddijVOOoi2EYUybAo07KUPpVZkvv0KDj3/Wv9tH2@Caaz4OG4x85iq@5afAl04MWMCybizIs8JhjzoocwhM0GdNVadYSgQ4LdoKysjoAGdvVgpnt49bNHTJ4sSb2IfffgQIAaanT873D6BZMZqHawbowloOZdQdMd8E1JoLqxMDVVuYdaQW@wV@YPfsHOm7PKAXKtAvyy6fM5Ar4ogsnDl3vu2SlKp4v/PcwnnLIZXjfKc//KUZ4KCH5ewMnMen5@wXZzlszNLfwo4wc "JavaScript (Node.js) – Try It Online")
### Input
* the date as a string in `yyyymmdd` format
* the time as a string in `hhmm` format
* the day of week as a 0-indexed integer, with `0` = Tuesday, `1` = Wednesday, ..., `6` = Monday
### Output
Returns `0` or `1`.
### Commented
```
f = ( // named function, as the underlying object will be used as storage
D, // D = date (string)
t, // t = time (string)
d // d = day of week (integer)
) => //
5 // 5 is 0000101 in binary, where 1's are set for Tuesday and Thursday
>> d & // test the relevant bit for the requested day of week
t > 749 & // test whether we are in the correct time slot
t < 811 //
&& !f[D] * // make sure that this date was not already invoked at a correct time
(f[D] = 1) // and store it in the underlying object of f()
```
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
f=lambda w,r,*t,l={0}:r not in l!=w in(2,4)<(7,49)<t<(8,11)!=l.add(r)
```
[Try it online!](https://tio.run/##rZLtTsMgFIb/exVn9Q8YYqAfGTXtXewGUGho7EpDT10a47VXqtlijZpt9hck5Hl4Dy/diNa1yTRVZaP2j1rBgXl2h6wpX/nbg4fWIdQtNJvyEFYSs5QWZMvSnBZYEMmEoJuyuVdaE0@nztctkooIFsVcSC7jbcQk45TCLVSq6c0IZFbuBtNrNYLzsLODn/f05kjHJ1pGLNyVLXA3ILgKrAvYr0z2yaAf0Aamqn2PgPXehCFe3LPRgLbuYY6gwoE10HnXGf@nVrJlkt48uVavoBXnTJicmPyKN13Q4mI8PeIJ/6gkPyPwNybj61Tys/b/nSy8oZOlNzj8KlpxwWfOefolyrUvN70D "Python 3 – Try It Online")
Takes input as `f(day of the week, date, hours, minutes)`, where date can be in any consistent format.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~61~~ ~~53~~ ~~50~~ ~~48~~ ~~37~~ 36 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous infix lambda. Called with `YYYYMMDD f hhmm` and then prompts for weekday number; 2 and 4 are Tuesday and Thursday. Redefines the global `D` to remember dates.
```
D←⍬
{≢D,←⍺/⍨(⎕∊2 4)∧(⍺∊D)<30≥|780-⍵}
```
[Try it online!](https://tio.run/##pZI/S8QwGMb3fop3vIKH6T@agpsdvEnw@gWKTW2xNiVNhaJOwnF30EMHRxdBdBCcXBz9KPkiNb1rB4twnl1C3je/53mTh/hZMg5KP6Fnde2K2Z2o3pQrsXhy99bF576oXkdi9SDmSx1MVcxfRrIrK1c9MJBYPF/bGI1F9XFTh2vFSsKTY7G8/Xo3xOxeVtOTQ7l6R5NprSMNI6zbEALCCCkaiOoRQj/JSQmjlHLwCpIHfgmUgRcVrNmrSivDjcw2LUX/IaMFBxpCRCXeY62O5azgkWTDmOUceHxBIE4v6TkJgEdxDs1IXx5EBDJGM8J@s8OoPzonpzQN/u2n/ekpTpeWsVNajUzbWWagTciOYm69WctaqGUHhty3Gxryxg9rfT@pZQPstO3JOMjsRg/7ft8 "APL (Dyalog Unicode) – Try It Online")
`D←⍬` initialise `D` to be an empty set
`{`…`}` anonymous lambda; `⍺` is `YYYYMMDD`, `⍵` is `hhmm`
`780-⍵` difference between 780 (mean of 0750 and 0810) and the time
`|` absolute value of that
`30≥` is 30 greater or equal to that?
`(`…`)<` and it is not true that:
`⍺∊D` the date is a member of `D`
`(`…`)∧` and it is true that:
`⎕∊2 4` the prompted for weekday is a member of the set {2,4}
`⍺/⍨` use that to compress the date (i.e. gives {} if false, {date} if true)
`D,←` append that to `D`
`≢` and return its tally (i.e. 0 or 1, which are APL's false and true)
[Answer]
## Excel formula, 85 bytes
`=IF(AND(MID(WEEKDAY(A1)/0,684;3;1)="3";A1-INT(A1)>=0,32638;A1-INT(A1)<=0,34028);TRUE)`
Weekday with no parameters are from 1 (Sunday) to 7 (Saturday). The days we want are 3 and 5. Dividing all numbers from 1 to 7 for 0,648, only 3 and 5 gives a result where the first decimal is 3 (Got it by dividing with rand())
Input is inserted on Cell A1
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~343~~ ~~326~~ ~~303~~ ~~279~~ 216 bytes
Clean is so ill-suited to this it's like trying to paint a fence with a chainsaw.
```
import StdEnv,System.Environment,System._Unsafe
?(y,x,z)=y*480+x*40+z
$y h m d=(d-3)^2==1&&((h-8)*60+m)^2<121&&appUnsafe(setEnvironmentVariable"l"(fromInt(?y)))(maybe 0toInt(accUnsafe(getEnvironmentVariable"l")))< ?y
```
[Try it online!](https://tio.run/##rZRLbxMxEIDP7K8Ylap4E6fdzYOkUqxeAKkSB6QULm1B7q43seTHYnvTOIi/TvDuJhVIfUFzm/lkfzPWyJMJRtVG6rwSDCTlasNlqY2DmcvfqyWeeeuYPA4hN1pJptwOffusLC1YdIY8XuF1THxnOEm6q84w6a6jQw8LkJATlPcG8dc@IenREUKL3iTuvE26MqBp2g@MlmUrQpa5P8p8oYbTG8EOxAEqjJbnyqEzH8cxktTfMEicrhHNsu31@UPXw50pnPm7h7XtX3DJopmjgZycgNWSAVs5Q6HgTOQW3II6oIaBYd8rblgOVOU1UG9cYIItqXKAtNkxW5WltuGc0xD6m/MlU0AtcFVWLm5UBRciHOANXzOjo9fgmHUWCFyiH55RQ9J0gqVWZIxlTj3pj/FCV4YEyBVJ8G0NU2xZFhJfJwnmNreOJD8xfKDCshhHrx6QTVrZuJENR62tvxfb6CnbhameIdu@c0@ttbb0pbbTe2YweKEs3YttkPw10dPWNtyLbZQ8YXt8ov8oe2Zr24nu15b@p23S2ob3tfb4P7gOP7@oVOa4VuHzH0akWS@X6A6inDp2XJfD0ISh4C4KyrgN68JbGLZKE9TVgZCwo2wlXHx11arwDsC01y6d682vrBB0bje984@bd15RybM2@SSoK7SRvwE "Clean – Try It Online")
Golfing then explaination.
[Answer]
# [R](https://www.r-project.org/), ~~114~~ 106 bytes
```
function(D,y=D:"%D",u=D$h==7&D$mi>49|D$h==8&D$mi<11&D$w%in%2^4&!y%in%L,`:`=format,`^`=c){L<<-L^y[u];u}
L=F
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0/DRafS1sVKSdVFSafU1kUlw9bWXM1FJTfTzsSyBsy1AHNtDA2BdLlqZp6qUZyJmmIliOWjk2CVYJuWX5SbWKKTEJdgm6xZ7WNjo@sTVxldGmtdWsvlY@v234crTSOxWC/AP9gzIqdEQ93IwNBC18BC19hAwcDCysDIysBAXVOTi4AyU0LKDIkyzcgCVdl/AA "R – Try It Online")
### Persistence:
Date is checked against `L`, the list of dates where the code returned TRUE. When the code returns TRUE, today's date is appended to this list. Otherwise the list is not modified.
Saved 6 bytes thanks to @Giuseppe!
Made the code actually work and saved 2 bytes thanks to @digEmAll!
[Answer]
## Batch, 109 bytes
```
@if %3 neq 2 if %3 neq 4 exit/b1
@if %2 geq 07:50 if %2 leq 08:10 if .%1 neq .%l% set l=%1&exit/b0
@exit/b1
```
Takes input in the form `date` `time` `dow` e.g. `2018-09-04 08:10 2` and outputs via exit code. Explanation: The environment variable `l` (or any other single letter would work) is used to store the last successful date that passes the test. (The date format itself does not matter as long as it is consistent and does not contain spaces.)
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 33 bytes
```
{811>$^t>749>5+>$^w%2>(%){$^d}++}
```
[Try it online!](https://tio.run/##rZLRaoMwFIbv9xSHrB2KXpw4rZFSn6LXBakJkbVGkrghpc/uIl2F4hhd7d2B5Pv4c/40XB9W/bGDNwGb/sQozRc7m6dxlieBG7@WUe4t/dNiV56D4NybogPhkQgpQxalJCTIEEm48tfwCqI4GN6BVysL25ab0t1WGray1cPsv9zibMDTOCEh3uCqtaAESOWw35lkZKxurXSMqLSxYKsjh6r@VB@8BCsrA0OEwh1IDo1WDdd/aBlOohi@V3U510v/9cRs3Cp9ZKsDTh/G3/FSirNE9yb@YRK8Ms8pZaJ9UikXL6MTr3Po@Vp6/@YyjMco875z/w0 "Perl 6 – Try It Online")
Heavily inspired by Arnauld's solution. Uses the same input format.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~78~~ ~~50~~ 49 bytes
```
D;f(d,w,t){w=d-D&&w<4&&w%2&&t>749&&t<811&&(D=d);}
```
[Try it online!](https://tio.run/##rY/BaoNAEIbvPsUgKGpGsmsUtcacpDdPDZTS5iBujB5ii1GkiM9udzUpDdVDoR7Gmf3Yb/9JzVOaDkMUZBrDFmu9a0NmRqrabm1eFEtV651r@/y39ShVVS0KmR70Q5onlQEs@Xw9QAidHL@XfJAR5H1zvFzb5yMrv4d93lS3/rEqrt1TUjfVrW9GRx9IUlHWcNJeMMaIx8rxrEMnAazXHxVHmSYrNjMVYk0FQfEvvFjsQYwQ7kBhb6WMk0CkbA/CgpDdSfWAS/9BaVDCv1Vs8DK6xcFq9PfTMuekKLVpCb6YRaiHHlouEgQPgYxBfgAPKYKLtrMAnHnAVUuA/gI@WvOPC0BnwIbgZkzlLwCH/A3wVIuA3gEfiX3dQ9zohy8 "C (gcc) – Try It Online")
The expected inputs are:
* `d`: the date, as a single number `yyyymmdd`
* `w`: the day of the week, starting with Monday (0)
* `t`: the time, as a single number `hhmm`
# Explanation
```
D; // the date we last said hello.
f(d, // date
w, // day of the week
t) // time
{
w= // replaces return
d-D // if we did not say hello today
&&w<4&&w%2 // and we are Tuesday(1) or Thursday(3)
&&t>749&&t<811 // and time is between 7:50 and 8:10, inclusive
&&(D=d); // then we say hello (evaluated to true) and update D
}
```
# Edits
* Saved 28 bytes thanks to Adám
* Saved 1 more byte, since `abs()` was actually not helping with the new version
[Answer]
## **C#**, 121 Bytes
```
int[] d=new int[]{2,4};
double s=>Now.TimeOfDay.TotalSeconds;
bool h=>d.Contains((int)Now.DayOfWeek)&&s>=470&&s<=490;
```
Moving all three to the same line reduces size to `117` bytes. `h` is used as a property, just read the value prior to sending the message:
```
if (h) SendMessage();
```
[Answer]
## F#, 119 bytes
```
let f w d h m l = if not(l|>Seq.contains d)&&[3;5]|>Seq.contains w&&(h=7&&m>49||h=8&&m<11)then(l@[d],true)else(l,false)
```
`let f w d h m l =`
declare function called `f` with parameters `w` (day of week) `d` (date) `h` (hour) `m` (minute) `l` (list of dates it's run on)
`if not(l|>Seq.contains d)`
if the list of dates doesn't contain the passed date
`&&[3;5]|>Seq.contains w` and the day is Tuesday (3) or Wednesday (5)
`&&(h=7&&m>49||h=8&&m<11)` and the time is between (exclusive) 7:49 and 8:11
`then(l@[d],true)` then return a tuple containing the list of dates with the current date appended, and true
`else(l,false)` else return a tuple containing the list of dates without today and false
] |
[Question]
[
A [Pillai prime](https://en.wikipedia.org/wiki/Pillai_prime) is a prime number \$p\$ for which there exists some positive \$m\$ such that \$(m! + 1) \equiv 0 \:(\text{mod } p)\$ and \$p \not\equiv 1\:(\text{mod }m)\$.
In other words, an integer \$p\$ is a Pillai prime if it is a [prime number](https://en.wikipedia.org/wiki/Prime_number), if there exists another positive integer \$m\$ such that the [factorial](https://en.wikipedia.org/wiki/Factorial) of \$m\$, plus \$1\$ is divisible by \$p\$ and if \$p - 1\$ isn't divisible by \$m\$.
---
Given a positive integer as input, decide whether it is a Pillai prime. The sequence of Pillai primes is [OEIS A063980](https://oeis.org/A063980).
For example, \$23\$ is a Pillai prime because:
* It is a prime number, having only 2 factors.
* \$m = 14\$ and \$m = 18\$ satisfy the above conditions: \$23 \mid (14! + 1)\$ and \$14\$ does not divide \$22\$; \$23 \mid (18! + 1)\$ and \$18\$ does not divide \$22\$ either.
## Test cases
Truthy:
```
23
59
83
109
139
593
```
Falsy:
```
5
7
8
73
89
263
437
```
For the truthy cases, the respective **m**'s are `[(23, [14, 18]), (59, [15, 40, 43]), (83, [13, 36, 69]), (109, [86]), (139, [16]), (593, [274])]`.
---
You can either follow the standard [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") output format (that is, truthy / falsy values) or [have a consistent value for Pillai primes and a non-consistent value otherwise or vice-versa](https://codegolf.meta.stackexchange.com/a/12308/59487).
You can compete in any [programming language](https://codegolf.meta.stackexchange.com/a/2073/59487) and can take input and provide output through any [standard method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), while taking note that [these loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden by default. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest submission (in bytes) for *every language* wins.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ 8 bytes
```
Ṗ!%ẹ’ḍ’E
```
Returns **0** for Pillai prime, **1** otherwise.
[Try it online!](https://tio.run/##y0rNyan8///hzmmKqg937XzUMPPhjl4g6fr/cPujpjVA5P7/f7SRsY6CqaWOggWQNjQAMgyNLUEixrE6CtGmOgrmQCkgCZS1AIobmQEZJsbmsQA "Jelly – Try It Online")
### How it works
```
Ṗ!%ẹ’ḍ’E Main link. Argument: n
Ṗ Pop; yield [1, ..., n-1].
! Take the factorial of each integer.
% Take the factorials modulo p.
ẹ’ Find all indices of n-1.
ḍ’ Test n-1 for divisibility by each of these indices.
E Return 1 if all of the resulting Booleans are equal (all 1 means there is
no suitable m, all 0 means n is not prime), 0 if they are different.
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~115~~ ~~111~~ ~~110~~ 109 bytes
-6 bytes thanks to Mr. Xcoder
```
lambda n:n>2and cmp(*map(all,zip(*[[n%x==1or~f(x)%n,n%x]for x in range(2,n)])))<0
f=lambda x:0**x or x*f(x-1)
```
[Try it online!](https://tio.run/##RcxBCsMgEIXhfU4xm4AjFkyWUnuRJAvb1HZAR5EsbBe9uk2g0OUP73v5tT0Tjy3buQUXr6sDNnwZHa9wi1nI6LJwIag37TFN3Fdrh1Q@XlTsWe29@FSgAjEUx4@7GBXjgohn3Xn7@6xGS1nhGMpdngZsh6K/GrRG0wF5yILQ5EK8AbUv "Python 2 – Try It Online")
The functions consist of two parts `~-n%x<1or~f(x)%n>0` that verifies if `n` **don't** satisfies the "Pillai conditions", and `n%x>0` for the prime validation.
After that `all` is applied to both items, the first item will contain `False`/`0` if there **is** a valid "Pillai number", and the second will contain `True`/`1` if `n` is prime.
These are passed to `cmp` that will return `-1` in this cenario (is a valid Pillai prime). The other combinations `[[0, 0], [1, 0], [1, 1]]` will return `0` or `1`
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 44 bytes
```
p->isprime(p)&&sum(m=2,p,p%m-1&&!((m!+1)%p))
```
[Try it online!](https://tio.run/##FYtBCsIwFAWvkhYa8vEFTL4xzaK9iLjowkrAlE@rC08f425mYGTZs31KXdVUxc75kD2XhxHS@vgUUyYPgQzFOq07Y0p3cjQIUV1EXl8jys6qLdu7Yf@XXq3tJqibZ4SEkeHOCY5Ts1YQERljQorwV8aFI0Jwd6o/ "Pari/GP – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 19 bytes
```
ṗ>.ḟ+₁;?%0&-₁;.%>0∧
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pf/ahtw6OmJrWHO1frKCno2ikEZObkJGYqPdzVWQMX84QJ1T7cOuH/w53T7fQe7piv/aip0dpe1UBNF8TQU7UzeNSx/P//aCNjHQVTSx0FCyBtaABkGBpbgkRAwjoK5kAJIAnkWABFjcyADBNj81gA "Brachylog – Try It Online")
Pretty straightforward translation of the question:
```
ṗ Input is a prime
>. And output is a number less than the input
ḟ+₁;?%0 And output's factorial + 1 mod input is 0
&-₁;.%>0 And input - 1 mod output is greater than 0
∧ No further constraints
```
[Answer]
# [J](http://jsoftware.com/), 30 26 bytes
-4 bytes thanks to FrownyFrog
```
1 e.i.((|1+!)~<1~:|)1&p:*]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DRVS9TL1NDRqDLUVNetsDOusajQN1QqstGL/a3IpcKUmZ@QrKBgBldcpeOoppCkZKGTqGRkYVPwHAA "J – Try It Online")
## Explanation:
```
1&p:*] checks if the number is prime and if not sets it to 0
1~:| checks if p is not 1 mod m
(|1+!)~ m factorial plus 1 modulo n
< are both conditions met?
i. generates successive m's (a list 0..n-1)
1 e. 1's are at the indices of m, so if there's 1 - Pillai
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~65~~ ~~64~~ ~~53~~ 52 bytes
```
f=lambda n,k=3,m=2:~m%n<1<n%k%(n%~-k)or f(n,k+1,m*k)
```
Output is via presence or absence of an error.
[Try it online!](https://tio.run/##RU7LDoIwEDzTr9hLA9WSCFV5BDzyBf4AahsJsJBSErnw67h48TIzO7OZzLi494Dxtpmyq/vHqwaUbalkX8b52nMsogJ5ywPka9iKwYIJ6OEYyf7Qiu2lDVQBipx5zi6EHsWCyGo3W4S7nTXz9OepR5f/7aruJs2YoTqEBiFWEi6ZhJQ4OpGIVLY7uy0hoYCQjpTc@ErirBKqG22DDnyuZghvwCcfONC63yKxfQE "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~109~~ 107 bytes
```
lambda p:any(~-p%m>~l(m)%p<1for m in range(2,p))*all(p%i for i in range(2,p-1))
l=lambda a:0**a or a*l(a-1)
```
[Try it online!](https://tio.run/##XcwxDsIwDIXhvafwEsmOqJR0jCgnYTGCgCUntaIuXXr1UCQWmL//PdvW11KnnudrVy63O4Mlrhvuo7ly2RULOTvHvDQoIBUa1@cDp5MReVZFcwIflB8cI9Gg8/eRU/Ce4ajYK/KB/W8SQ6A0gGTIKJSsSV1B@hs "Python 2 – Try It Online")
---
**Explanation**
The `l` finds the factorial of the number passed in, so `5` as input returns `120`.
The `all(p%i for i in range(2,p-1))` checks to see if a number is prime, we ignore 0 and 1 as our other conditions already rule those out.
Finally, we use `any(~-p%m>-~l(m)%p==0for m in range(2,p))` to iterate through all potential m's looking to see if any satisfies our needs. `~-p` means `p+1`. Then we check to see if it is greater than `-~l(m)%p` (which translates to `(m!-1)%p`, and then we compare it to `0`. Basically `~-p%m` must be greater than 0 and `-~l(m)%p` must be 0.
---
**Sources**
* [Factorial](https://codegolf.stackexchange.com/a/3133/67929) by [0xKirill](https://codegolf.stackexchange.com/users/2214/0xkirill)
---
**Improvements**
* From 109 to 107, [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
[Answer]
### as you probably can see in the tio link not all cases pass, thats because js cant handle big numbers,if such requirement exists ill try to implement it :)
there is a double check `F%n>n-2&(F+1)%n<1` to prevent false positive(but not the other way around with js big number issues,we do really need `(F+1)%n<1` for smaller numbers whice reduces the solution byte count to **60**
# [JavaScript (Node.js)](https://nodejs.org), 90 88 86 72 68 bytes
* thanks to Arnauld for reducing by 1 byte
```
f=(n,F=i=2,g=0)=>n%i?f(n,F*=++i,g|=F%n>n-2&(F+1)%n<1&~-n%i>0):i==n*g
```
[Try it online!](https://tio.run/##dY7LDoIwFET3/gek5WFoK0qNt@74D4K0qSG3BtCV8dcrbkyMuds5czJz7R7d3E/@tpQYLkOMFhgWLXiQhYOKg8HEn@0nyyDPfeGe0CZosJQpa3PBEzyJ9FWuLVPxowfAzMU@4BzGYTsGxyyTigMs033gm19QawI0lCEqShFKkyvk/prbbpz/wIECDWkoUtEUkXtS2inygvyC@AY "JavaScript (Node.js) – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 13 bytes
```
>.ḟ+₁ḋ∋?-₁f≡ⁿ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpmZrpZKi0lQ9BY1cBVuFunJNpYe7Oh81NT7qWKGUlphTnKoHEqitfbh1wn87vYc75msDJR/u6H7U0W2vC2SmPepc@Khx////0aY6RsY65jqmljoWOhZAlrGOoYGljpEZkDa21DExBkkZxwIA "Brachylog – Try It Online")
Succeeds for Pillai primes, providing the smallest *m* through the output variable, and fails for anything else. Since a large part of how this saves bytes over sundar's solution is that it repeatedly computes the prime factorizations of some pretty big numbers, it's quite incredibly slow on larger inputs. (I'll probably run those cases on my local Brachylog installation once my laptop isn't on battery power.)
```
. The output
> is less than the input,
? the input
∋ is an element of
ḋ the prime factorization of
. the output's
ḟ factorial
+₁ plus one,
≡ⁿ and the output is not an element of
f the list of all factors of
? the input
-₁ minus one.
```
[Answer]
# [Perl], 45 bytes
```
use ntheory":all";is_prime($n)&&is_pillai($n)
```
The number theory module has the predicates as built-in functions (is\_pillai actually returns either 0 or the smallest m, so solves A063828 as well). The underlying C and Perl code is not golfed (of course). The C code looks like:
```
UV pillai_v(UV n) {
UV v, fac = 5040 % n;
if (n == 0) return 0;
for (v = 8; v < n-1 && fac != 0; v++) {
fac = (n < HALF_WORD) ? (fac*v) % n : mulmod(fac,v,n);
if (fac == n-1 && (n % v) != 1)
return v;
}
return 0;
}
```
(generically replace UV with uint64\_t or similar, and HALF\_WORD decides whether we can optimize the mulmod into simple native ops).
The pure Perl code is similar to:
```
sub is_pillai {
my $p = shift;
return 0 if $p <= 2;
my($pm1, $nfac) = ($p-1, 5040 % $p);
for (my $n = 8; $n < $p; $n++) {
$nfac = mulmod($nfac, $n, $p);
return $n if $nfac == $pm1 && ($p % $n) != 1;
}
0;
}
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 64 bytes
```
f(n,k,m,r){for(k=m=1,r=0;k<n;m=m*++k%n)r|=m/~-n<<(n%k==1);r/=3;}
```
[Try it online!](https://tio.run/##HY7BisMwDETP8VeIQsBOFJrU7W6Lo/2RtocSSAnGWmOaUzb99VTeizTzRgwamucwbNuoGT0GTGYZf5P2FKjDRK3zPbtAoaprX7JJfxT274b7XnPpiTrj0p6sW7eJXxAeE2ujFlVkN3GcX9c7ECwHi3C6IJxld62Izl4yyRjhWwKZYs5CD18ijlZguzqlivxOrquiNP13OtEOYl0bVRQxSTjqXWlnaH6gnG@8QzlAGHUVjXFq3T4 "C (gcc) – Try It Online")
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), 230 bytes
```
> 1
> Input
>> 1…2
>> L!
>> L+1
>> L∣2
>> L⋅R
>> 2%L
>> Each 4 3
>> Each 5 9
>> Each 6 10
>> Each 7 11 3
> {0}
>> 12∖13
>> Each 8 14
>> L≠1
>> Each 16 15
>> Each 7 17 15
>> 18∖13
>> [19]
>> 2’
>> 21⋅20
>> Output 22
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsGQy07BM6@gtITLDsh51LDMCMTwUQST2oZg6lHHYojoo@7WIBDDSNUHRLkmJmcomCgYw9mmCpZwtpmCoQGcY65gaAhSp1BtUAu2yOhRxzRDhEYLBUMTiA2dCwzhooZAM0yRzTCH8g0t4NqjDS1jwU561DATTBsCHWkEttm/tAToLwUjoD@NjAE "Whispers v2 – Try It Online")
This returns an empty list for non-Pillai primes, and a non-empty list otherwise.
## How it works
Whispers was designed for manipulation on real/complex numbers, with a little bit of array commands added for good measure, hence the repeated use of `Each` to iterate over the generated lists.
**A bit of background on Whispers:**
Whispers is slightly different in it's execution path to most other languages. Rather than work through each line linearly, only branching at conditionals, Whispers begins on the last line in the file beginning with `>` (the rules are slightly more complicated than that, but that's all we need to know for now), and the meanings of numbers differ, depending on whether the line starts with `>` or `>>`.
If the line starts with `>`, such as `> 1` or `> Input`, this is a **constant** line - it returns the same value each time. Here, numbers represent their numerical form, so the first line will always return **1** when called.
If the line starts with `>>` however, numbers are treated as references to other lines, sort of like function calls, if you will. For example, in the line `>> 1…2`, this does not perform the `…` command on the integers **1** and **2**, but rather on the values returned from lines **1** and **2**. In this case, those values are the integer **1** and whatever integer we're passed as input.
For this example, let's consider the input of **23**. Keep in mind that, due to Whispers' preprocessing, the second line (`> Input`) is converted to `> 23`.
Our first command is on line 3: `>> 1…2`. `…` is dyadic range, in this case from **1** to **23**, yielding **{1, 2, ... 22, 23}**. Next, we skip down to lines **9** through **12**:
```
>> Each 4 3
>> Each 5 9
>> Each 6 10
>> Each 7 11 3
```
Here we have 4 consectutive `Each` statements, each of which iterate over the previous result, essentially mapping the 4 commands over the array on line **3**: the range. The first three statements are simple maps, with lines **4**, **5** and **6**:
```
>> L!
>> L+1
>> L∣2
```
These three commands, over an integer **n**, yields **(n!+1)∣x**, where **!** denotes [factorial](https://en.wikipedia.org/wiki/Factorial), **∣** denotes [divisbility](https://en.wikipedia.org/wiki/Divisor) and **x** is the input. Finally, line **12** has a *dyadic map* structure.
A *dyadic map* structure takes three integers: the target, the left and the right, each indexes to other lines. Here, we zip the left and the right to produce a list of pairs, then reduce each pair by the dyadic command (the target). Here, if the input is **23**, the lists are **{1, 2, ... 22, 23}** and **{0, 0, ... 1, 0}** and the command is
```
>> L⋅R
```
which multiplies the left argument by the right. This produces an array of integers, with **0** at the indexes of integers whose factorials incremented aren't divisible by the inputs, and the original index where they are. We'll call this array **A**. Next, we remove the **0**s from **A** by taking the set difference between **{0}** and **A**:
```
> {0}
>> 12∖13
```
With our example input, this produces the set **{14, 18, 22}**. Next we take the remainder of the input being divided by each value in the set, and check if that remainder is not equal to **1**:
```
>> 2%L
>> Each 8 14
>> L≠1
>> Each 16 15
```
Again, we have a list of either **0** or **1**s and need to remove the **0**s and replace the **1**s with the original values. Here we repeat the code we saw above, but with `>> 18∖13` rather than `12`. Finally, we cast this resulting set to a list for a final check. Unfortunately, our code must also reject composite numbers which achieve all these criteria, such as **437**. So we add our final check, multiplying our final list by the primality of the input. Due to how Python multiplication works on lists, **0** replaces it with an empty list, and **1** has no effect. So we calculate the primality of the input, multiply that by the list of **m**s for the input and ouput the final result:
```
>> 2’
>> 21⋅20
>> Output 22
```
[Answer]
# APL(NARS), 65 chars, 130 bytes
```
{∼0π⍵:0⋄m←⎕ct⋄⎕ct←0⋄r←⍬≢a/⍨{0≠⍵∣p}¨a←k/⍨0=⍵∣1+!k←⍳p←¯1+⍵⋄⎕ct←m⋄r}
```
Here 23x it would mean 23r1 and so the fraction 23/1, so all the others; test:
```
f←{∼0π⍵:0⋄m←⎕ct⋄⎕ct←0⋄r←⍬≢a/⍨{0≠⍵∣p}¨a←k/⍨0=⍵∣1+!k←⍳p←¯1+⍵⋄⎕ct←m⋄r}
f¨23x 59x 83x 109x 139x 593x
1 1 1 1 1 1
f¨5x 7x 73x 89x 263x 437x
0 0 0 0 0 0
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 138+22=160 bytes
```
n=>Enumerable.Range(2,n-2).All(x=>n%x>0)&Enumerable.Range(1,n).Any(x=>{BigInteger a,b=1;for(a=1;a<=x;a++)b*=a;return(b+1)%n<1&(n-1)%x>0;})
```
TIO has not implemented the System.Numerics library in it's release of Mono, so you can see the results ~~[Try it online!](https://tio.run/##Zc29asMwFIbhPVfhJUGqf4jsJk2QZWgghULJ0A6dJXNsBM4xSDI4lF67Y4/JmSQ@Ht5T@7T2dhq8xTb6ufkA1@wyXMHZ2svVx4B1aTEkpu@7KmoiNaGqzrgAbTrIvjW2wPIE05xn713HRlXheqy2fEOUSHA2eFvM38m2nxigBRfpxCghm94xPb@6VKPUcczNi9LSQRgcMhMLvsZSbBim82/uy38@ydWvswG@LAJrWF5w/rjsjs/LgRixJUgUR1qi8efhjRwjgkQO5FK@J@i1WNLTHQ "C# (Visual C# Interactive Compiler) – Try It Online")~~ [Here](https://dotnetfiddle.net/yKgxCZ) instead.
Explanation:
```
using System.Numerics; //necessary to handle large numbers created by the factorials
return
Enumerable.Range(2,n-2).All(x=>n%x>0) // is prime
&
Enumerable.Range(1,n).Any(x=>
{
BigInteger a,b=1;for(a=1;a<=x;a++)b*=a; //b = a!
return (b+1)%n<1
& //the condition for PPs
(n-1)%x>0;
});
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 37 bytes
```
ri_mp\[_{_M)m!)@%!\_M)%1=!@&\}fM]);:|
```
Outputs `11` if input is a pillai prime, otherwise `00`, `01` or `10`
**Explanation:**
```
e# Explanation | Stack
ri_mp\[_{_M)m!)@%!\_M)%1=!@&\}fM]);:| e# Whole code | Example input: 593
ri e# Read input as integer | 593
_ e# Duplicate | 593 593
mp e# Is it prime? | 593 1
\ e# Swap top two stack elements | 1 593
[ ] e# Delimits an array. Any operations that
e# push a value are placed into the array
_ e# Duplicate | 1 593 [593]
{ }fM e# A for loop from 0 to (n-1) looped through
e# variable M
_ e# Duplicate top stack value | ...[593 593]
M) e# Get M+1, as if we try M=0 we get an error
e# | ...[593 593 1]
m! e# Factorial | ...[593 593 1]
) e# Add one | ...[593 593 2]
@ e# Rotate stack | ...[593 2 593]
% e# Modulus | ...[593 2]
! e# Equal to 0? | ...[593 0]
\_ e# Swap and duplicate | ...[0 593 593]
M) e# Push M+1 | ...[0 593 593 1]
% e# Modulus | ...[0 593 0]
1=! e# Not equal to 1? | ...[0 593 1]
@ e# Rotate | ...[593 1 0]
& e# AND | ...[593 0]
\ e# Swap | ...[0 593]
}
]
); e# Dump and discard last element
e# | 1 593 [...]
:| e# Flatten array with OR | 1 1
e# Implicit output
```
[Try it online!](https://tio.run/##S85KzP3/vygzPrcgJjq@Ot5XM1dR00FVMQbIUjW0VXRQi6lN843VtLaq@f/f1NIYAA "CJam – Try It Online")
] |
[Question]
[
Your program gets a text as an input, at least 8 characters long, and always consisting of even number of characters. (no need to evaluate correctness of input).
Your goal is to display that text as a rectangle. For example, given `HelloWorld` as an input, display
```
Hell
d o
lroW
```
Rules:
* Text goes around clockwise (starting position as you like)
* It will form a closed rectangle, sides 1 character wide.
* The rectangle will have to encompass the most area inside. (just to rule out the trivial answer of displaying the text in two lines)
* No other characters are printed besides the text itself and the necessary padding spaces and line feeds.
As code-golf, shortest code wins.
Winner is selected not sooner than 10 days after first valid answer.
[Answer]
**PostScript 50 binary, 113 ASCII**
This uses graphical output. Hexdump of the program using binary tokens:
```
$ hexdump -C textRect_binary.ps
00000000 74 5b 30 20 39 5b 74 92 62 34 92 36 92 38 92 10 |t[0 9[t.b4.6.8..|
00000010 32 92 19 5d 7b 92 2c 7b 32 92 19 7d 92 83 92 3e |2..]{.,{2..}...>|
00000020 92 6e 7d 92 49 5d 39 20 39 92 6b 91 c7 39 92 8e |.n}.I]9 9.k..9..|
00000030 92 c3 |..|
00000032
```
[Download to try it](http://www.mediafire.com/?r8sfrl996rlai9t). Using Ghostscript, the to-be-rendered text can be passed to the program as follows:
```
gs -st=helloworld textRect_binary.ps
```
Graphical output looks like this:

The same code using ASCII tokens looks like this:
```
t[0 9[t length
4 div dup
ceiling
2 copy]{cvi{2 copy}repeat
exch neg}forall]9 9 moveto/Courier 9 selectfont
xyshow
```
The strategy is to use `xyshow` for defining where we move after showing each character before showing the next character. We're starting in the lower left corner, moving clockwise, i.e. first up, then right, then down then left. We're always moving 9 units, so first we have a relative movement of `0 9`, then `9 0`, then `0 -9`, then `-9 0`. We can get from one pair of these numbers to the next with the sequence `exch neg`.
We need to build an array for `xyshow` that holds these pairs of numbers, one pair for each character. This means, if we have `helloworld` as example string, which has 10 characters, we want to go up twice, then right thrice, then down twice and left thrice. We get these values (two and three) by dividing the string length by 8, once rounding to the floor, once to the ceiling.
So, we copy `0 9` twice, then switch to the relative x/y coordinates using `exch neg`, copy those thrice and so on.
This commented code shows what happens on the stack:
```
t[0 9 % t [ 0 9
[t length % t [ 0 9 [ length
4 div dup % t [ 0 9 [ length/4 length/4
ceiling % t [ 0 9 [ length/4=height width
2 copy] % t [ 0 9 [height width height width]
{%forall % t [ 0 9 ... x y height_or_width
cvi % t [ 0 9 ... x y height_or_width_integer
{2 copy} % t [ 0 9 ... x y height_or_width_integer {2 copy}
repeat % t [ 0 9 ... x y .. x y
exch neg % t [ 0 9 ... x y .. y -x
}forall] % t [0 9 ... -9 0]
9 9 moveto/Courier 9 selectfont
xyshow
```
[Answer]
## Ruby ~~112~~ 100
I'm new to Ruby and this is my first code golf. I drew upon memowe's perl implementation and tried to make a Ruby version of it. This is ~~112~~ 100 characters and assumes you assign a string to x. Looking forward to seeing others.
```
l=x.size
puts x[0..w=l/2-h=l/4]
1.upto(h-1){|i|puts x[-i]+' '*(w-1)+x[w+i]}
puts x[w+h..l-h].reverse
```
Edited to implement suggestions. I think it's 100 characters now. Thanks guys!
[Answer]
### GolfScript, 56 53 40 38 characters
```
1/..,4/):l<n@l>{)" "l*2>@(n@.,l-}do-1%
```
You may test the script [online](http://golfscript.apphb.com/?c=OydIZWxsb1dvcmxkJwoKMS8uLiw0Lyk6bDxuQGw%2BeykiICJsKjI%2BQChuQC4sbC19ZG8tMSUK&run=true).
[Answer]
## Perl (~~124~~ ~~118~~ 109+3=112)
This formerly was pretty straightforward. Counted all command line options as 1 character each.
```
-nlE
$w=(@s=split//)/2-($h=int@s/4);say@s[0..$w--];say$s[1-$_].$"x$w.$s[$w+$_]for+2..$h;say+reverse@s[@s/2..@s-$h]
```
Example:
```
$ perl -nlE '$w=(@s=split//)/2-($h=int@s/4);say@s[0..$w--];say$s[1-$_].$"x$w.$s[$w+$_]for+2..$h;say+reverse@s[@s/2..@s-$h]'
abcdefghijklmnopqrstuvwxyz
abcdefgh
z i
y j
x k
w l
v m
utsrqpon
```
[Answer]
# Brainfuck - 194 187
```
+>,[>+[>+<-],]
>-->++<[->-[>+>>]>[+[-<+>]>+>>]<<<<<]>[-]>[-]>[<<+<<+>>>>-]<<<<
[[<]>+[>]<-]<[<]>-
[>.[-]<[>+<-]>-]>[>]
++++++++++.<.[-]
>[>+++>>+<<<-]>++>--[<.>-]<<<<[<]>.[-]>[>]>>>>.
<<<<<[.<]
```
[Answer]
# Mathematica 156 199 344
**Edit** : This is a major rewrite of earlier code. It works essentially the same, but now takes as input a string of length < 120 chars and automatically sizes the square.
It could still be golfed a bit but will not get down to the size of the earlier, and buggier, versions.
```
f@s_ := ({a, t, w, q} = {Automatic, Text, Quotient[StringLength@s, 2],
Quotient[StringLength[s], 4] + 1};z = StringSplit[StringInsert[s <> ConstantArray[" ", 0],
"*", {q, 2 q, 3 q}], "*"];
Graphics[{t[z[[1]], {0, q}],t[z[[2]], {q, 0}, a, {0, -1}],t[z[[3]], {0, -q}, a, {-1, 0}],
t[z[[4]], {-q, 0}, a, {0, 1}]},ImageSize -> 500,BaseStyle -> {FontFamily -> "Courier", 21},
PlotRange -> 34,ImagePadding -> 22])
```
**Examples**
```
f["Hello Code Golf World!"]
f["January, February, March,April, May, June, July"]
f["This text is normal, this goes downwards,this is upside-down, and this is upwards"]
```



[Answer]
# Perl + Regexes: 104 (101+3)
(counting code + switches)
Here is a solution using nice Regexes, and a bit of Perl:
```
perl -plE'$w=($l=length)/2-($h=int$l/4);s/..{$w}\K.*/"\n".reverse$&/e;$"x=--$w;s/.\K(.*)(.)$/$"$2\n$1/while--$h'
```
This will only operate correctly on *one* input line.
Inspired by memowe, but essentially without any arrays.
[Answer]
# PostScript (106)
This is inspired by [dude's Mathematica solution](https://codegolf.stackexchange.com/questions/10478/rectangle-of-text/10481#10481).
```
0{= =
4 add dup
t length mod 4
lt{-90 rotate}if}0[0 3 -3 0 9 9]concat
0 moveto/Courier 5 selectfont
t kshow
```
With Ghostscript call this like
```
gs -st=hello! boxtext.ps
```
It produces output like.


It uses `kshow` to show the glyphs one by one. After enough glyphs for one side have been shown, everything is rotated by -90 degrees before continuing with the remaining glyphs.
To know when enough glyphs have been shown on the side, we increment a counter by 4 each time a glyph is shown. If the counter value modulo the string length is less than 4, then we know we have to rotate:
```
char counter mod 6 compared to 4
h 4 4 =
e 8 2 < => rotate
l 12 0 < => rotate
l 16 4 =
o 20 2 < => rotate
! 24 0 < => rotate
```

Commented and un-golfed source code:
```
0 % n
{%kshow % n char1 char2
= = % n
4 add dup % n' n'
t length mod % n' (n' mod t_length)
4 lt % n' bool
{-90 rotate}if % n'
} % n kshowProc
% First 0 for moveto. We add it here to take
% advantage of the surrounding self delimiting tokens.
0 % n kshowProc 0
% We change the graphics state so that the drawn
% text is at a nice size and not off screen.
[0 3 -3 0 9 9]concat % n kshowProc 0
0 % n kshowProc 0 0
moveto % n kshowProc
/Courier 5 selectfont % n kshowProc
t % n kshowProc text
kshow % n
```
[Answer]
# Python 3(120)
```
s=input()
n=len(s)
h=n//4
q=(n+2)//4-1
p=print
p(s[:q+2])
for i in range(1,h):p(s[n-i]+' '*q+s[q+1+i])
p(s[n-h:q+h:-1])
```
## Test
### input:
```
abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz
```
### output:
```
abcdefghijklmn
z o
y p
x q
w r
v s
u t
t u
s v
r w
q x
p y
o z
nmlkjihgfedcba
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~19~~ 17 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
g4/Dîsï‚>4∍IŽ9¦SΛ
```
Port of [my Charcoal answer](https://codegolf.stackexchange.com/a/203221/52210).
[Try it online.](https://tio.run/##AT4Awf9vc2FiaWX//2c0L0TDrnPDr@KAmj404oiNScW9OcKmU86b//9hYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5eg)
**Explanation:**
```
g # Get the length of the (implicit) input-string
4/ # Divide it by 4
D # Duplicate it
î # Ceil the copy
sï # Swap, and floor the other one
‚ # Pair the two together
> # Increase both by 1
4∍ # And extend it to size 4
I # Push the input-string
Ž9¦ # Push compressed integer 2460
S # And convert it to a digit-list: [2,4,6,0]
Λ # Use the Canvas builtin with these three arguments
# (which is implicitly output immediately as result)
```
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Ž9¦` is `2460`.
The Canvas builtin takes three arguments:
1. The length of the lines. For this we use the list of four values we created at the start: \$\left[ \left\lceil\frac{L}{4}\right\rceil+1, \left\lfloor\frac{L}{4}\right\rfloor+1, \left\lceil\frac{L}{4}\right\rceil+1, \left\lfloor\frac{L}{4}\right\rfloor+1 \right]\$.
2. The characters we want to display, which is the input-string.
3. The directions in which to draw, which is `[2,4,6,0]`. These directions map to `[→,↓,←,↑]`.
For a more detailed explanation of the Canvas builtin, see [this 05AB1E tip of mine](https://codegolf.stackexchange.com/a/175520/52210).
[Answer]
## Python 2.x: 137
I'm new to code golfing and quite sure this can be improved…
```
def s(t):c=len(t);w=1+c/4;h=(c-w-w)/2;u=w+h;n='\n';print t[:w]+n+n.join(map(((w-2)*' ').join,zip(t[:w+u-1:-1],t[w:u])))+n+t[w+u-1:u-1:-1]
```
Visual testing code:
```
from itertools import chain
from string import letters
for i in range(8,101,2):
t = ''.join(chain(letters))[:i]
print '%d: %s' % (i, t)
s(t)
print '-----'
```
Something of interest: This solution depends on integer math. If you just do the math symbolically, you'll find that `h=(c-w-w)/2 => h=w-2`, but if you substitute that result every other result will be missing two lower-left characters.
[Answer]
# K, 84
```
{-1'(*r;((|r 3),\:(w-2)#" "),'r 1;|(r:(0,+\(w;h;w;h:_(l-2*w:-_-(1+(l:#x)%4))%2))_x)2);}
```
.
```
k){-1'(*r;((|r 3),\:(w-2)#" "),'r 1;|(r:(0,+\(w;h;w;h:_(l-2*w:-_-(1+(l:#x)%4))%2))_x)2);}"HelloWorld"
Hell
d o
lroW
k){-1'(*r;((|r 3),\:(w-2)#" "),'r 1;|(r:(0,+\(w;h;w;h:_(l-2*w:-_-(1+(l:#x)%4))%2))_x)2);}"Hellooooooooooooooo Worlddddd!"
Hellooooo
! o
d o
d o
d o
d o
d o
lroW oooo
```
[Answer]
# Scala (135)
The following snippet assumes that `x` contains the string to format, and should be pasted in the scala REPL:
```
val (h,w)=((x.size+3)/4,println(_:Any));val s=x.grouped(h)toSeq;w(s(0));for((l,r)<-s(1)zip(s(3)reverse))w(r+" "*(h-2)+l);w(s(2)reverse)
```
If you don't have scala installed, you can quickly check it using this online Scala interpreter: <http://www.simplyscala.com/>.
Just paste the following text end press evaluate:
```
val x="HelloWorld"
val (h,w)=((x.size+3)/4,println(_:Any));val s=x.grouped(h)toSeq;w(s(0));for((l,r)<-s(1)zip(s(3)reverse))w(r+" "*(h-2)+l);w(s(2)reverse)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal/wiki), ~~16~~ 12 [bytes](https://github.com/somebody1234/Charcoal/wiki/Code-page)
```
B⊕L⪪θ⁴⊕⊘⊘Lθθ
```
-4 bytes thanks to *@Neil*.
[Try it online (verbose)](https://tio.run/##S85ILErOT8z5/98pv0LDMy@5KDU3Na8kNUXDJzUvvSRDI7ggJ7NEo1DHRFNTU0cBWYFnXolLZllmSipMaaEmSJWOQqGm9f//iUnJKalp6RmZWdk5uXn5BYVFxSWlZeUVlVX/dctyAA) or [try it online (pure)](https://tio.run/##S85ILErOT8z5///9nkWPuqa@37Pm0apV53Y8atwC5D3qmgFEQLFzO87t@P8/MSk5JTUtPSMzKzsnNy@/oLCouKS0rLyisgoA).
**Explanation:**
Draw a box using the characters in the implicit input-string:
```
Box(..., ..., q);
B...θ
```
With a width \$\left\lceil\frac{L}{4}\right\rceil+1\$ (where \$L\$ is the length of the input), by splitting the input-string into parts of size 4 and getting this list's length incremented by 1:
```
Incremented(Length(Split(q,4)))
⊕L⪪θ⁴
```
And height \$\left\lfloor\frac{L}{4}\right\rfloor+1\$:
```
Incremented(IntDivide(Length(q),4))
⊕⊘⊘Lθ
```
[Answer]
## PHP (149)
The text to print should be in a variable named `$x`.
```
@$s=substr;echo$s($x,-$w=($l=strlen($x)/2)-$h=$i=$l-2>>1).'
';while($i--)echo$x[$l+$i].str_repeat(' ',$w-2).$x[$h-$i-1].'
';echo$s(strrev($x),$l,$w);
```
[Answer]
# **JAVA - 320**
```
public class A{
public static void main(String[] a){
String s=a[0];
int l=s.length(),h=l/2,f=h-1,i=0;
for(i=0;i<f;i++)
System.out.print(s.charAt(i));
System.out.print("\n"+s.charAt(l-1));
for(i=0;i<f-2;i++)
System.out.print(" ");
System.out.println(s.charAt(h-1));
for(i=l-2;i>h-1;i--)
System.out.print(s.charAt(i));}}
```
**Note : -** Input is taken from command line
Input : - HelloWorld
Output : -
```
Hell
d o
lroW
```
Input : - abcdefghijklmnopqrstuvwxyz
Output : -
```
abcdefghijkl
z m
yxwvutsrqpon
```
] |
[Question]
[
[Hamming number](https://en.m.wikipedia.org/wiki/Regular_number) (also known as regular number) is a number that evenly divides powers of 60.
[We already have a task to do something with it.](https://codegolf.stackexchange.com/q/7/100411)
This time we are going to do the opposite.
I define non-Hamming number as in: \$n\$ is non-Hamming number if and only if it satisfies following two conditions:
* \$n\$ is positive integer, and
* \$n\$ does not divide powers of 60 evenly; i.e. \$60^m\mod n\neq0\$ for all positive integer \$m\$.
Make a program, a function, or a subroutine that does one of these:
1. takes no input to print/return/generate a list of non-Hamming numbers infinitely, or
2. takes a positive integer \$n\$ as input to print/return/generate \$n\$th non-Hamming number (can be either 0-indexed or 1-indexed), or
3. takes a positive integer \$n\$ as input to print/return/generate a list of first \$n\$ non-Hamming numbers.
4. ~~takes a positive integer \$n\$ to print/return/generate non-Hamming number until \$n\$ (suggested by @Wasif, can be inclusive or not; i.e. non-Hamming numbers that are either \$<n\$ or \$\leq n\$).~~ abolished by @rak1507.
# Example
This example shows how program/function/subroutine that does 3rd task should work:
* Input: `5`
* Output: `7, 11, 13, 14, 17`
# Rules
* [I/O method is done by your desired format.](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods)
* If you are answering one of 2nd or 3rd task, you can assume that input is a non-negative integer.
* No external resources.
* [Standard loopholes apply.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* If your program/function/subroutine fails to output huge non-Hamming numbers because of overflow (or similar boundary) but is theotically valid, it is acceptable.
* Shortest code in bytes wins. However, if someone have won entire of this post, you can still try to win among languages and tasks.
# P.S.
It's actually [A279622](http://oeis.org/A279622).
[Answer]
# [JavaScript (V8)](https://v8.dev/), 61 bytes
A full program that prints the sequence forever.
```
for(k=6;x=++k;)[2,3,5].some(g=d=>x%d?x<2:g(d,x/=d))||print(k)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/j/Py2/SCPb1sy6wlZbO9taM9pIx1jHNFavOD83VSPdNsXWrkI1xb7CxsgqXSNFp0LfNkVTs6amoCgzr0QjW/P/fwA "JavaScript (V8) – Try It Online")
### Commented
```
for( // infinite loop:
k = 6; // start with k = 6
x = ++k; // increment k and copy it to x
) //
[2, 3, 5] // list of primes less than 7
.some(g = d => // for each of them:
x % d ? // if d is not a divisor of x:
x < 2 // return true if x = 1
: // else:
g(d, x /= d) // divide x by d and do a recursive call
) // end of some()
|| // if true, k is 5-smooth (aka regular, aka Hamming number)
print(k) // otherwise, print it
```
---
# JavaScript (ES6), 65 bytes
Returns the \$n\$th term of the sequence, 1-indexed.
```
f=(n,k=6)=>n?f(n-[2,3,5].every(g=d=>x%d?x>1:g(d,x/=d),x=++k),k):k
```
[Try it online!](https://tio.run/##Dc1BCoMwEEDRvaeYhYUMiba22IV29CCloJgoNjIpWiRFPHvq7i8e/He7tks3j59vwk6bEHoSrCzdkSque8HJ86puKn@lZjXzTwykqfInXfsqKwahlT@TRuVJSovKYmFD72bBQJCVwPAgyC9HSImwRQCd48VNJp3cIJpWxBvveNh4O1a4N1hGe/gD "JavaScript (Node.js) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
30*%µƇ
```
[Try it online!](https://tio.run/##y0rNyan8/9/YQEv10NZj7f///zc0BQA "Jelly – Try It Online")
Takes \$n\$ and outputs all non-Hamming numbers \$\le n\$, as [allowed by the OP](https://codegolf.stackexchange.com/questions/223789/non-hamming-numbers/223790#comment518825_223789).
Thanks to [Delfad0r](https://codegolf.stackexchange.com/users/82619/delfad0r) for [suggesting this](https://chat.stackexchange.com/transcript/message/57693842#57693842) method in chat!
---
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ÆfṀ>5Ʋ#
```
[Try it online!](https://tio.run/##y0rNyan8//9wW9rDnQ12psc2Kf//bwoA "Jelly – Try It Online")
-2 bytes thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor), who noted that \$k\$ is a non-Hamming number if it's ~~smallest~~ largest (thanks [ovs](https://codegolf.stackexchange.com/users/64121/ovs), for catching that) prime factor is greater than \$5\$!
Returns the first \$n\$ non-Hamming numbers
---
## How they work
```
30*%µƇ - Main link. Takes n on the left
µƇ - Filter the range i ∈ [1, 2, ..., n] on the following:
30* - Raise 30 to the power i
% - That is not divisible by i?
ÆfṂ>5Ʋ# - Main link. Takes no arguments
Ʋ - Group the previous 4 links into a monad f(k):
Æf - Prime factors of k
Ṁ - Maximum
>5 - Greater than 5?
# - Read n from STDIN and count up k = 1, 2, 3, ... until n such k return True under f(k)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~7~~ 6 bytes
*-1 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs).*
```
∞ʒÓg3›
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Uce8U5MOT043ftSw6/9/AA)
```
∞ʒÓg3› # full program
ʒ # all elements of...
∞ # [1, 2, 3, ...]...
ʒ # where...
g # the length of...
Ó # the exponents of the prime factorization of...
# (implicit) current element in list...
› # is greater than...
3 # literal
# implicit output
```
[Answer]
# [J](http://jsoftware.com/), 25 bytes
```
(>:[]echo~5<{:@q:)@]^:_&7
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/NeysomNTkzPy60xtqq0cCq00HWLjrOLVzP9rcoGEFdIU1NX/AwA "J – Try It Online")
YAIOXI
>
> Yet Another Implementation Of xnor's Idea.
>
>
>
* `^:_&7` Loop forever, starting with 7:
* `]echo~...` Echo the current count if...
* `5<{:@q:` 5 is less than the last `{:` prime factor `q:` (they're listed in ascending order). This step is merely a side effect.
* `>:[` Return the increment of the counter and keep looping.
[Answer]
# Vyxal, 8 5 bytes
**Huge thanks to @Lyxal for -3 bytes using a filter lambda, so I could beat all!**
```
'ǐG5>
```
Takes an integer input \$n\$, and outputs all non-hamming numbers \$\le{n}\$ (According to new rule)
**Explanation**
```
' # Filter lambda
ǐ # Prime factors of each number
G # Maximum
5> # Greater than 5?
# Implicitly output
```
[Try it!](http://lyxal.pythonanywhere.com/?flags=&code=%27%C7%90G5%3E&inputs=15&header=&footer=)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
Uses xnor's idea.
```
foV>5pN
```
[Try it online!](https://tio.run/##yygtzv7/Py0/zM60wO//fwA "Husk – Try It Online")
Outputs an infinite list.
```
foV>5pN
N From the infinite list of natural numbers,
f keep the ones that satisfy the following predicate
V There exists
p a prime factors
>5 that is greater than 5
```
[Answer]
# [Factor](https://factorcode.org/) + `lists.lazy math.primes.factors math.unicode`, 51 bytes
```
1 lfrom [ factors [ 5 > ] ∃ ] lfilter [ . ] leach
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQk1lcUgwh9XISqyoVchNLMsCEXkFRZm5qsV4aWH0xRKw0LzM5PyVVoaAotaSkEqgir0ShOLWwNDUvObVYwZrrv6FCTlpRfq5CtAJMX7SCqYKdQqzCo45mIJmTlplTkloEFNUD8VITkzP@/wcA "Factor – Try It Online")
## Explanation:
It's a full program that prints non-Hamming numbers forever, using @xnor's tip about prime factors greater than 5.
* `1 lfrom` An infinite lazy list of the natural numbers.
* `[ factors [ 5 > ] ∃ ] lfilter` Select numbers with a prime factor greater than 5. `∃` is shorthand for `any?` and this turns out to be 1 byte shorter than `supremum 5 >`.
* `[ . ] leach` Print every item in the list.
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
```
[n|n<-[1..],mod(30^n)n>0]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfYRvzPzqvJs9GN9pQTy9WJzc/RcPMIC5PM8/OIPZ/bmJmnm1BUWZeiV5JYnaqgpGBSsb/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
The infinite list of non-Hamming numbers.
## How?
A positive integer \$n\$ is Hamming if and only if \$n\$ divides \$30^n\$.
[Answer]
# JavaScript (Browser), 31 bytes
```
for(k=1n;;)30n**++k%k&&alert(k)
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z@Yk1pUYpucn1ecn5Oql5OfrpeUmZeiARXQ/J@WX6SRbWuYZ22taWyQp6WlrZ2tmq2mBtamka35/z8A "JavaScript (Node.js) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 26 bytes
```
1.step{|x|30**x%x>0&&p(x)}
```
[Try it online!](https://tio.run/##KypNqvz/31CvuCS1oLqmosbYQEurQrXCzkBNrUCjQrP2/38A "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~69~~ ~~70~~ ~~69~~ 67 bytes
```
while(T<-T+1)for(i in 1:T+6)if(sum(!i%%2:i)<2&!T%%i){show(T);break}
```
[Try it online!](https://tio.run/##K/r/vzwjMydVI8RGN0TbUDMtv0gjUyEzT8HQKkTbTDMzTaO4NFdDMVNV1cgqU9PGSE0xRFU1U7O6OCO/XCNE0zqpKDUxu/b/fwA "R – Try It Online")
xnor's idea in base R.
*+1 thanks to [@Dominic](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) spotting an error and then -1 golfing `print` to `show`.*
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 44 bytes
```
K`
"$+"{`$
_
)+`^((_+)(?=\2{1,4}$))*_$
$&_
_
```
[Try it online!](https://tio.run/##K0otycxLNPz/3zuBS0lFW6k6QYUrnktTOyFOQyNeW1PD3jbGqNpQx6RWRVNTK16FS0Utniv@/39TAA "Retina – Try It Online") Outputs the `n`th number. No test suite because of the way the program uses history. Explanation:
```
K`
```
Delete the input, replacing it with unary 0.
```
"$+"{`
)`
```
Repeat the input number of times.
```
$
_
```
Increment the current value.
```
+`^((_+)(?=\2{1,4}$))*_$
```
While the current value is a product of powers of 2, 3, 4 or 5...
```
$&_
```
... increment it.
```
_
```
Convert the result to decimal.
To convert the script into one that outputs the first `n` numbers:
* Remove the `)` at the beginning of the 4th line
* Prefix `.*\`` to the last line.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~14~~ 12 bytes
```
7W=hTI<5ePTT
```
[Try it online!](https://tio.run/##K6gsyfj/3zzcNiPE08Y0NSAk5P9/AA "Pyth – Try It Online")
Prints the infinite sequence.
```
7 # First print 7 separately.
W # While
T # Initialized to 10 by default
=hT # Increment T by 1
PT # Lists prime factors of T in increasing order.
>ePT5 # If the highest prime factor is greater than 5, then
T # Print T
```
*-2 bytes thanks to kops*
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
üu§└ÿà♦
```
[Run and debug it](https://staxlang.xyz/#p=817515c0988504&i=15)
~~TIL that `|M` returns infinity for empty lists~~. Found a method without `|M`.
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 56 bytes
inspired by [Julian's answer](https://codegolf.stackexchange.com/a/223827/80745) (loop instead recursion)
```
1.."$args"|?{$a=$_;2,3,5|%{for(;!($a%$_)){$a/=$_}};$a-1}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNydFNzi9K/f/fUE9PSSWxKL1Yqca@WiXRViXe2kjHWMe0RrU6Lb9Iw1pRQyVRVSVeUxMoqQ@Ura21VknUNaz9//@/qYEBAA "PowerShell Core – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Outputs the first `n` terms.
```
Èk d¨7}jU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yGsgZKg3fWpV&input=NQ)
```
Èk d¨7}jU :Implicit input of integer U
È :Function taking an integer as input
k : Prime factors
d : Any?
¨7 : Greater than equal to 7
} :End function
jU :Get the first U integers that return true
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
≔⁰θFN«≦⊕θW¬﹪X³⁰θθ≦⊕θ⟦Iθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DQEehUNOaKy2/SEHDM6@gtMSvNDcptUhDU1OhmovTN7EAqs4zL7koNTc1ryQ1BaKDszwjMydVQcMvv0TDNz@lNCdfIyC/HKjTGGwkCAPNwGdAQFFmXolGtHNicYlGoWYsUKj2/3/T/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Outputs the first `n` numbers. Explanation: Uses @Delfad0r's approach.
```
≔⁰θ
```
Start at zero.
```
FN«
```
Repeat `n` times.
```
≦⊕θ
```
Increment the accumulator.
```
W¬﹪X³⁰θθ
```
While it divides its power of `30`...
```
≦⊕θ
```
... increment it.
```
⟦Iθ
```
Output the found value on its own line.
[Answer]
# [R](https://www.r-project.org/) + gmp, ~~37~~ 51 bytes
*Edit: +14 bytes after the rules were changed to disallow outputting all non-Hamming numbers up to `n`: now outputs the infinite list*
```
n=gmp::as.bigz(1);repeat if(60^(n=n+1)%%n>0)show(n)
```
[Try it online!](https://tio.run/##K/qfk5lUlFhUqZGeW6D5P88WSFlZJRbrJWWmV2kYaloXpRakJpYoZKZpmBnEaeTZ5mkbaqqq5tkZaBZn5Jdr5Gn@/w8A "R – Try It Online")
Outputs infinite list of non-Hamming numbers.
Uses arbitrary-precision calculations to simply check whether `n` divides the `n`th power of 60 (this is sufficient to be certain that it also can't divide any higher power of 60). We could have stopped at the `floor(log2(n))`th power of 60, but it would have made an annoyingly long program.
Of course, the mathematics itself is correct even without the `gmp` library to handle the actual abritrary-precision calculations... so we could have an even shorter version in base-[R](https://www.r-project.org/) if we don't mind going out-of-range for "huge" non-Hamming numbers:
---
# [R](https://www.r-project.org/), ~~35~~ 44 bytes
*Edit: +9 bytes to comply with the changed rules*
```
repeat if(30^(log2(T<-T+1)%/%1)%%T>0)show(T)
```
[Try it online!](https://tio.run/##K/r/vyi1IDWxRCEzTcPYIE4jJz/dSCPERjdE21BTVV8VSKiG2BloFmfkl2uEaP7/DwA "R – Try It Online")
Same approach as above, but goes out-of-range for "huge" non-Hamming numbers, defined as any number greater than 16383.
If we are somewhat more timid and define a "huge" to be any number greater than 12 (and accept that above this the program will output junk or crash), then we can have an even shorter ~~23-byte~~ 34-byte solution of just `repeat if(30^(T<-T+1)%%T>0)show(T)` [Try it!](https://tio.run/##K/r/vyi1IDWxRCEzTcPYIE4jxEY3RNtQU1U1xM5Aszgjv1wjRPP/fwA).
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 66 bytes
It was easier to generate many (seven) times as many numbers as needed, then trim the excess:
```
h(n)=select(x->factor(x)[,1][-1..-1][1]>5,vector(7*n,i,i+1))[1..n]
```
[Try it online!](https://tio.run/##HclBCoAgEADA7@yWK3mQTvkR8SBhuRAmJuHvTTrNYbIvTGfuPULC7QlX2Cs0Moff612goRXKWVJS0lA5o8Ub/lqnJFjwrBDt6OR6LpwqRNALYv8A "Pari/GP – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 56 bytes
Generates an infinite sequence of non-Hamming numbers
```
i=7;while(1,if(factor(i)[,1][-1..-1][1]>5,print(i));i++)
```
[Try it online!](https://tio.run/##K0gsytRNL/j/P9PW3Lo8IzMnVcNQJzNNIy0xuSS/SCNTM1rHMDZa11BPTxdIG8bameoUFGXmlQBlNK0ztbU1//8HAA "Pari/GP – Try It Online")
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), ~~137~~ 89 bytes
```
filter d{param($b)if($_%$b){$_}else{$_/$b|d $b}}1.."$args"|d 3|d 5|d 2|?{++$t;$_-1}|%{$t}
```
[Try it online!](https://tio.run/##DYjLCoMwEAB/RWQFRXzjqYd@Skh0bYWIsgn0kOy3b/cwzDDP/UMKX/S@225CkeP0EanY02PJXjW45jxqMJVGAsPoA6oHcHkvwDFPfV@CpU8odSzKqsz5ndoW4gtMN3GuEkQWkXUc/w "PowerShell Core – Try It Online")
Thanks [mazzy](https://codegolf.stackexchange.com/users/80745/mazzy)!
[Answer]
# [Zsh](https://www.zsh.org/), ~~[44](https://codegolf.stackexchange.com/a/213718)~~ 43 bytes
```
seq inf|factor|grep ' 7
.[^ ]'|cut -d: -f1
```
[Try it online!](https://tio.run/##qyrO@K/xvzi1UCEzL60mLTG5JL@oJr0otUBBXcGcS0EvOk4hVr0mubREQTfFSkE3zfC/Zk1GamKKgq6hgcF/AA "Zsh – Try It Online")
-1 thanks to @tail spark rabbit ear
* `seq inf`: count up infinitely
* `factor`ise each number in the form `52: 2 2 13`
* `grep`: keep only lines matching the `r`egular `e`xpression `7\n .[^ ]`
+ The newline acts like "or"
+ Essentially matches either a factor that starts with 7, or a factor with more than one digit. This will match any prime > 5, so as long as there's at least one matching factor, the whole line will be printed
* `cut -d: -f1`: take the first field (where fields are separated by colons) of each line. This gets only the number itself
# [Zsh](https://www.zsh.org/), 45 bytes
```
for ((;++a;)){>`factor $a`;><7->&&<<<$a;rm *}
```
[Try it online!](https://tio.run/##DcpBCsIwEAXQq3ywhMTiwpWLhJylg0zpQNOEzhRR8eyx28f76NJ9n@sO7@M4Ugzhm6eZnnbSQFPM6XHLzqWUBop7wfXXg9OVueGOCwgqpa0Mk8L1MIjCFgaTCqvhRW9YhVptkG2WTYxxvnZY/wM "Zsh – Try It Online")
* `for ((;++a;)){}`: for each integer up to infinity:
+ `factor $a`: factorise the number in the form `52: 2 2 13`
+ `>```: create the files according to the words in the factorisation (e.g. `52:`, `2` (duplicates are just ignored), and `13`)
+ `<7->`: look for a file which is a number greater than or equal to 7
- If the number has a prime factor greater than 5, it is not a Hamming number and will be matched
- The number itself always has a trailing colon, so it can never be matched by this
+ `>`: and try to output to it
+ `&&`: if that works, then:
- `<<<$a`: print the number
+ `rm *`: remove all the files (so we're fresh for the next iteration)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 235 bytes
```
param($k)$s='$f;$n/=$f';function F($n){$m=[math]::sqrt($n);$f=2;while(!($n%$f)){iex $s};$f=3;while($f-le$m-and$n-ge$m){while(!($n%$f)){iex $s};$f+=2};$n};$a=@();$a=@();$g=1;while($a.length-lt$k){$j=(F($g)[-1])-gt5;if($j){$a+=$g}$g++}$a
```
[Try it online!](https://tio.run/##dY5BCsIwFESvojDShBKliiCGD668hHQRNEmradQ2olB69piCunMxzDCP/5nb9anbrtLOxXhTrWoYLhwdZTASfkEwmTQPfwz11U/2DJ73aOjQqFCV2213b8PYSRhaymdVO82mqZjBcN7X@jVBN4xw9YEwwmk0QvkTvLAp8v7/WU7LZD5J0Y7xn1kqvv/U3GlvQyVcSMN7nImllZYfRFFyYcNa1obhnIjKCXaAzfMBKsa4eQM "PowerShell – Try It Online")
[Answer]
# [Julia 0.4](http://julialang.org/), 52 bytes
```
x=1;while x>0 keys(factor(x+=1))⊆1:5||print(-x)end
```
[Try it online!](https://tio.run/##yyrNyUz8/7/C1tC6PCMzJ1Whws5AITu1slgjLTG5JL9Io0Lb1lBT81FXm6GVaU1NQVFmXomGboVmal7K//8A "Julia 0.4 – Try It Online")
I'm using Julia 0.4 for `factor`, which was then moved in the package `Primes.jl`
also works with recent versions of Julia + Primes.jl
`factor(x)` returns a `Dict` with the keys been the prime factors and the values the exponent of each factor
in more recent version with `Primes.jl`, `factor(Set,x)` can be called instead for the same result
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 92 bytes
Previously 93 bytes that outputs intfinite list.
Given a line of an integer \$n\$, outputs first \$n\$ nunbers.
Pretty naïve.
```
{for(k=j=7;$0--;k=++j){for(;k%2-1;k/=2);for(;!(k%3);k/=3);for(;!(k%5);k/=5);if(k>1)print j}}
```
[Try it online!](https://tio.run/##SyzP/v@/Oi2/SCPbNsvW3FrFQFfXOttWWztLEyxqna1qpGtona1va6RpDRZQ1MhWNdYEiRgjiZiCRYBkZppGtp2hZkFRZl6JQlZt7f//hgYGAA "AWK – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~38~~ ~~37~~ 35 bytes
```
x=1
while[30**x%x>0==print(x)]:x+=1
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v8LWkKs8IzMnNdrYQEurQrXCzsDWtqAoM69Eo0Iz1qpC29bw/38A "Python 3 – Try It Online")
Where'd the python answers go???
Port of [G.B.](https://codegolf.stackexchange.com/a/223845/109916)'s answer.
-2 thx to @Steffan
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 16 bytes
```
7`Đϼ6<Π?ŕ:ŕĐƥ;⁺ł
```
[Try it online!](https://tio.run/##ASEA3v9weXT//zdgxJDPvDY8zqA/xZU6xZXEkMalO@KBusWC//8 "Pyt – Try It Online")
Prints the list of Hamming numbers without end.
```
7 push 7 (the first Hamming number)
` ł do... while the top of stack is truthy
Đ Đuplicate
ϼ get unique ϼrime factors
6<Π? are they all less than 6?
ŕ if so, ŕemove top of stack
:ŕĐƥ otherwise; ŕemove top of stack, Đuplicate top of stack,
and ƥrint top of stack
;⁺ either way, increment top of stack
```
] |
[Question]
[
The dihedral group \$D\_4\$ is the [symmetry group](https://en.wikipedia.org/wiki/Symmetry_group) of the square, that is the moves that transform a square to itself via rotations and reflections. It consists of 8 elements: rotations by 0, 90, 180, and 270 degrees, and reflections across the horizontal, vertical, and two diagonal axes.
[](https://i.stack.imgur.com/0Y558.gif)
*The images are all from [this lovely page](http://ecademy.agnesscott.edu/~lriddle/ifs/symmetric/D4example.htm) by Larry Riddle.*
This challenge is about composing these moves: given two moves, output the move that's equivalent to doing them one after another. For instance, doing move 7 followed by move 4 is the same as doing move 5.
[](https://i.stack.imgur.com/JTollm.gif)
Note that switching the order to move 4 then move 7 produces move 6 instead.
The results are tabulated below; this is the [Cayley table](https://en.wikipedia.org/wiki/Cayley_table) of the group \$D\_4\$. So for example, inputs \$7, 4\$ should produce output \$5\$.
\begin{array}{\*{20}{c}}
{} & {\begin{array}{\*{20}{c}}
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\
\end{array} } \\
{\begin{array}{\*{20}{c}}
1 \\
2 \\
3 \\
4 \\
5 \\
6 \\
7 \\
8 \\
\end{array} } & {\boxed{\begin{array}{\*{20}{c}}
1 & 2 & 3 & 4 & 5 & 6 & 7 & 8 \\
2 & 3 & 4 & 1 & 8 & 7 & 5 & 6\\
3 & 4 & 1 & 2 & 6 & 5 & 8 & 7\\
4 & 1 & 2 & 3 & 7 & 8 & 6 & 5\\
5 & 7 & 6 & 8 & 1 & 3 & 2 & 4\\
6 & 8 & 5 & 7 & 3 & 1 & 4 & 2\\
7 & 6 & 8 & 5 & 4 & 2 & 1 & 3\\
8 & 5 & 7 & 6 & 2 & 4 & 3 & 1\\
\end{array} }} \\
\end{array}
**Challenge**
Your goal is to implement this operation in as few bytes as possible, but in addition to the code, **you also choose the labels** that represent the moves 1 through 8. The labels must be *8 distinct numbers from 0 to 255*, or the 8 one-byte characters their code points represent.
Your code will be given two of the labels from the 8 you've chosen, and must output the label that corresponds to their composition in the dihedral group \$D\_4\$.
**Example**
Say you've chosen the characters C, O, M, P, U, T, E, R for moves 1 through 8 respectively. Then, your code should implement this table.
\begin{array}{\*{20}{c}}
{} & {\begin{array}{\*{20}{c}}
\, C \, & \, O \, & M \, & P \, & U \, & \, T \, & \, E \, & R \, \\
\end{array} } \\
{\begin{array}{\*{20}{c}}
C \\
O \\
M \\
P \\
U \\
T \\
E \\
R \\
\end{array} } & {\boxed{\begin{array}{\*{20}{c}}
C & O & M & P & U & T & E & R \\
O & M & P & C & R & E & U & T\\
M & P & C & O & T & U & R & E\\
P & C & O & M & E & R & T & U\\
U & E & T & R & C & M & O & P\\
T & R & U & E & M & C & P & O\\
E & T & R & U & P & O & C & M\\
R & U & E & T & O & P & M & C\\
\end{array} }} \\
\end{array}
Given inputs E and P, you should output U. Your inputs will always be two of the letters C, O, M, P, U, T, E, R, and your output should always be one of these letters.
**Text table for copying**
```
1 2 3 4 5 6 7 8
2 3 4 1 8 7 5 6
3 4 1 2 6 5 8 7
4 1 2 3 7 8 6 5
5 7 6 8 1 3 2 4
6 8 5 7 3 1 4 2
7 6 8 5 4 2 1 3
8 5 7 6 2 4 3 1
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 18 bytes
```
->a,b{a+b*~0**a&7}
```
Ungolfed
```
->a,b{ (a+b*(-1)**a) % 8}
# for operator precedence reasons,
#-1 is represented as ~0 in the golfed version
```
[Try it online!](https://tio.run/##VYzNCoJAFEb39ynEgSi7if26ss0wy2GGYWYlLrQUFCINhULt1W1Agtodzsd3Hl32mopo2pxTzPp0nXnvwPPSRThOy8D3w5V/S@t@KAdwnNr5VdVQxBWWyQgjQBPFAe7wgCfcY4hbPCZW/n2b782lTBiupHbjuTAnCHvW@aXNr869a@uuBUIFl0YzBcQCZUobIBaENooBscAVMxqIUZpRLgUQzYziVEgbs1JIyoHY0UjBKUwf "Ruby – Try It Online")
Uses the following coding numbers 0 to 7
In order native to the code:
```
Native Effect Codes per
Code Question
0 rotate 0 anticlockwise 1C
1 / flip in y=x 7E
2 /| rotate 90 anticlockwise 2O
3 /|/ flip in x axis 5U
4 /|/| rotate 180 anticlockwise 3M
5 /|/|/ flip in y=-x 8R
6 /|/|/| rotate 270 anticlockwise 4P
7 /|/|/|/ flip in y axis 6T
```
In order per the question
```
Native Effect Codes per
Code Question
0 rotate 0 anticlockwise 1C
2 /| rotate 90 anticlockwise 2O
4 /|/| rotate 180 anticlockwise 3M
6 /|/|/| rotate 270 anticlockwise 4P
3 /|/ flip in x axis 5U
7 /|/|/|/ flip in y axis 6T
1 / flip in y=x 7E
5 /|/|/ flip in y=-x 8R
```
**Explanation**
`/` represents a flip in the line `y=x` and `|` represents a flip in the y axis.
It is possible to generate any of the symmetries of the group D4 by alternately flipping in these two lines For example `/` followed by `|` gives `/|` which is a rotation of 90 degrees anticlockwise.
The total number of consecutive flips gives a very convenient representation for arithmetic manipulation.
If the first move is a rotation, we can simply add the number of flips:
```
Rotate 90 degrees + Rotate 180 degrees = Rotate 270 degrees
/| /|/| /|/|/|
Rotate 90 degress + Flip in y=x = Flip in x axis
/| / /|/
```
If the first move is a reflection, we find we have some identical reflections `/` and `|` symbols next to each other. As reflection is self inverse we can cancel out these flips one by one. So we need to subtract one move from the other
```
Flip in x axis + Flip in y=x = Rotate 90 degrees
/|/ / /|/ / (cancels to) /|
Flip in x axis + Rotate 90 degrees = Flip in y=x
/|/ /| /|/ /| (cancels to ) /
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 31 bytes
Using integers \$0, 5, 2, 7, 1, 3, 6, 4\$ as labels.
```
BitXor[##,2Mod[#,2]⌊#2/4⌋]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfKbMkIr8oWllZx8g3PyUaSMU@6ulSNtI3edTTHav2PycxKTWnGKiy2kBHwVRHwUhHwVxHwVBHwVhHwUxHwaTWmiugKDOvxMHBQcO/tCS1KDpNRwGiCUbHKujrKYRkFKUmpkRDjdO1UwhKzEtPjbaIjdW0/g8A "Wolfram Language (Mathematica) – Try It Online")
## Explanation:
The Dihedral group \$D\_4\$ is isomorphic to the unitriangular matrix group of degree three over the field \$\mathbb{F}\_2\$:
$$D\_4 \cong U(3,2) := \left\{\begin{pmatrix} 1 & a & b \\ 0 & 1 & c \\ 0 & 0 & 1 \end{pmatrix} \mid a,b,c \in \mathbb{F}\_2\right\}.$$
And we have
$$\begin{pmatrix} 1 & a\_1 & b\_1 \\ 0 & 1 & c\_1 \\ 0 & 0 & 1 \end{pmatrix} \cdot \begin{pmatrix} 1 & a\_2 & b\_2 \\ 0 & 1 & c\_2 \\ 0 & 0 & 1 \end{pmatrix} = \begin{pmatrix} 1 & a\_1+a\_2 & b\_1+b\_2+a\_1c\_2 \\ 0 & 1 & c\_1+c\_2 \\ 0 & 0 & 1 \end{pmatrix},$$
which can easily be written in bitwise operations.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 51 bytes
```
⌊#/4^IntegerDigits[#2,4,4]⌋~Mod~4~FromDigits~4&
```
[Try it online!](https://tio.run/##ZVBdS8MwFH3Pr7i0MObI0GbpVh8KfRBBUBT1rVTItts2kLWSxi@G/QG6X@kfmYlZ9@JDknPOPTf3JBthatwII1diX6b7n91XeMqfrhqDFeoLWUnT5SGjnPLiZ/fd37TrnveXut34Ws9H@/FEiSWqbnJCVLplLKEQLygs7BlxC5hd0cJt5046Sz4JGU@etWwMCDBiqRDepKktqVGsUduLhrps1nKFHbQl@CEUtEuswdSisRvCcfid68gyuBdNhdk1NpWpM9Xfy7JU2AcQHB3BNOgf3dz@n2saEJ8ohdsXgzq/aztpZNvkipZ5SENWFHke0agoRlRRVXh7Z7TteDB2QOWvyh9bT0@zbRh@jrIs@3MWhxRDG3Gf8Ypalh/2Dfj@jCuD65QEETCYAYcY5rCAhHgWQWKZ1YhnzFZjpxHPZs7rNBJbNLc4shoDThx22swqHBjx1dhh5yG@Onde5zn8Vj7kTNMhW0H2vw "Wolfram Language (Mathematica) – Try It Online")
Using labels `{228, 57, 78, 147, 27, 177, 198, 108}`.
These are `{3210, 0321, 1032, 2103, 0123, 2301, 3012, 1230}` in base 4. Fortunately, 256=4^4.
---
Lower-level implementation, also 51 bytes
```
Sum[4^i⌊#/4^⌊#2/4^i⌋~Mod~4⌋~Mod~4,{i,0,3}]&
```
[Try it online!](https://tio.run/##ZVDdboIwGL3vU3yBxDhToxQQdkHSB9gyo7sjmFQp0qSCgbqfGHmAbU@5F2GtFW920fac852v32kPTJX8wJTYsb5I@vXpkAYb8fvz5c6CjTnI7Mq/u@c674I7wGeB59i/ZKN@PJFsy2U7eUAyORMSYwgjDJE@vUADopcXme3RSPP4gtB4cmxEpYCBYlvJ4V2oUpOSs5w3@qKhLqpc7HgLdQF2CIbGJG5AlazSG4f78KXpoBRWrNpz@sSrvSqp7FaiKCTvHHDuDmfqdK9mbvfPNXWQTZTAy0nxJl3WrVCirlKJi9TFLsmyNPWwl2UjLLHMrL1Vje5YKz1gb69KX2tLZ/TsupcRpfTqzG4phjZkPuONN6L41G/gH0e@UzxPkOMBAR8CCGEBEcTIMg9izbSGLCO6GhoNWeYbr9FQqNFCY09rBAJksNF8rQRAkK2GBhsPstWF8RrP7bfSIWeSDNmy/g8 "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 22 bytes
A port of [my Mathematica answer](https://codegolf.stackexchange.com/a/185151/9288). Using integers \$0, 6, 1, 7, 2, 3, 5, 4\$ as labels.
```
lambda a,b:a^b^a/2&b/4
```
[Try it online!](https://tio.run/##RYvBCoJAFEX3fsVdhdIjdbICoS8xhffQoSc2irmor59GFDrLwznTd3mOzniLOx5@4Je0DCYpuZGGU3OQtAhauuEdiiojXAk54UYwhDPhQijqyI4zFOqwpWWEwDSrW1DlOO76pK7tPrGNldAnCdar/1@1/wE "Python 2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~26~~ ~~23~~ 21 bytes
```
lambda x,y:y+x*7**y&7
```
[Try it online!](https://tio.run/##TY2xDoIwFEVn@xU3HYziG6CIJCR8Se1Qg40kUEhB0359DWXQ5eQM5@bOYX1NVkTT3uOgx0en4Sk04eKzOsvCsY5Wj88FLSTvO07gS77RFckTnUgu/rzkin308N6XOUEQroQboSCUhIpQK8bM5BDQW@xtww6z6@0KmU6lOXlCOCtsnf91Kn4B "Python 2 – Try It Online") Port of my answer to [Cayley Table of the Dihedral Group \$D\_3\$](https://codegolf.stackexchange.com/questions/171962/cayley-table-of-the-dihedral-group-d-3). Edit: Saved 3 bytes thanks to @NieDzejkob. Saved 2 bytes thanks to @xnor for suggesting the `and` (rather than `xnor`) operator. Uses the following mapping:
```
id | r1 | r2 | r3 | s0 | s1 | s2 | s3
----+----+----+----+----+----+----+----
0 | 2 | 4 | 6 | 1 | 3 | 5 | 7
```
[Answer]
# TI-BASIC, 165 bytes
```
Ans→L₁:{.12345678,.23417865,.34126587,.41238756,.58671342,.67583124,.75862413,.86754231→L₂:For(I,1,8:10fPart(.1int(L₂(I)₁₀^(seq(X,X,1,8:List▶matr(Ans,[B]:If I=1:[B]→[A]:If I-1:augment([A],[B]→[A]:End:[A](L₁(1),L₁(2
```
Input is a list of length two in `Ans`.
Output is the number at the `(row, column)` index in the table.
There could be a better compression method which would save bytes, but I'll have to look into that.
**Examples:**
```
{1,2
{1 2}
prgmCDGF1B
2
{7,4
{7 4}
prgmCDGF1B
5
```
**Explanation:**
(Newlines have been added for readability.)
```
Ans→L₁ ;store the input list into L₁
{.123456 ... →L₂ ;store the compressed matrix into L₂
; (line shortened for brevity)
For(I,1,8 ;loop 8 times
10fPart(.1int(L₂(I)₁₀^(seq(X,X,1,8 ;decompress the "I"-th column of the matrix
List▶matr(Ans,[B] ;convert the resulting list into a matrix column and
; then store it into the "[B]" matrix variable
If I=1 ;if the loop has just started...
[B]→[A] ;then store this column into "[A]", another matrix
; variable
If I-1 ;otherwise...
augment([A],[B]→[A] ;append this column onto "[A]"
End
[A](L₁(1),L₁(2 ;get the index and keep it in "Ans"
;implicit print of "Ans"
```
Here's a **155 byte** solution, but it just hardcodes the matrix and gets the index.
I found it to be more boring, so I didn't make it my official submission:
```
Ans→L₁:[[1,2,3,4,5,6,7,8][2,3,4,1,8,7,5,6][3,4,1,2,6,5,8,7][4,1,2,3,7,8,6,5][5,7,6,8,1,3,2,4][6,8,5,7,3,1,4,2][7,6,8,5,4,2,1,3][8,5,7,6,2,4,3,1:Ans(L₁(1),L₁(2
```
---
**Note:** TI-BASIC is a tokenized language. Character count does ***not*** equal byte count.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
N⁹¡+%8
```
A dyadic Link accepting the first transform on the right and the second transform on the left which yields the composite transform.
Where the transforms are:
```
as in question: 1 2 3 4 5 6 7 8
transformation: id 90a 180 90c hor ver +ve -ve
code's label: 0 2 4 6 1 5 7 3
```
**[Try it online!](https://tio.run/##y0rNyan8/9/vUePOQwu1VS3@//9v9t8cAA "Jelly – Try It Online")** ...Or see [the table mapped back onto the labels in the question](https://tio.run/##y0rNyan8/9/vUePOQwu1VS3@RxvoGOmY6JjpGOqY6pjrGMceXn54X6bDo6Y1QKTi/h8A "Jelly – Try It Online").
(The arguments could be taken in the other order using the 6 byter, `_+Ḃ?%8`)
### How?
Each label is the length of a sequence of alternating `hor` and `+ve` transforms which is equivalent to the transform (e.g. `180` is equivalent to `hor, +ve, hor, +ve`).
The composition `A,B` is equivalent to the concatenation of the two equivalent sequences, and allows simplification to subtraction or addition modulo eight...
Using the question's `7, 4` example we have `+ve, 90c` which is:
`hor, +ve, hor, +ve, hor, +ve, hor , hor, +ve, hor, +ve, hor, +ve`
...but since `hor, hor` is `id` we have:
`hor, +ve, hor, +ve, hor, +ve , +ve, hor, +ve, hor, +ve`
...and since `+ve, +ve` is `id` we have:
`hor, +ve, hor, +ve, hor , hor, +ve, hor, +ve`
...and we can repeat these cancellations to:
`hor`
..equivalent to subtraction of the lengths (`7-6=1`).
When no cancellations are possible we are just adding the lengths (like `90a, 180` \$\rightarrow\$ `2+4=6` \$\rightarrow\$ `90c`).
Lastly, note that a sequence of length eight is `id` so we can take the resulting sequence length modulo eight.
```
N⁹¡+%8 - Link: B, A
¡ - repeat (applied to chain's left argument, B)...
⁹ - ...times: chain's right argument, A
N - ...action: negate ...i.e. B if A is even, otherwise -B
+ - add (A)
%8 - modulo eight
```
---
It's also 1 byte shorter than [this implementation](https://tio.run/##y0rNyan8///oZHuHY5NMjk46tP9/tKGOoYGOobmOoaWOkYmOhY6hqY5Z7MOdaw@3H1p6eF9CpsOjpjVApOL@HwA "Jelly – Try It Online") using lexicographical permutation indexes:
```
œ?@ƒ4Œ¿
```
...a monadic Link accepting `[first, second]`, with labels:
```
as in question: 1 2 3 4 5 6 7 8
transformation: id 90a 180 90c hor ver +ve -ve
code's label: 1 10 17 19 24 8 15 6
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~22~~ 17 bytes
```
(x,y)=>y+x*7**y&7
```
[Try it online!](https://tio.run/##Jc7LCoMwEIXhfZ/irBpjp@KlrYsSQV9DXIg3LNZILCV5@hSnm58PhgPzar/t3pl5@1xX3Q9@VD6w5KQq3MWGeRi6c@5LKNSICSnhRngQEkJGuBNyNM9TxXcx94Ig9vioSdhck7K5JmNn4th1et31MkSLnoIyerdb4KAK/GkPVvXI7zRSSv8D "JavaScript (Node.js) – Try It Online") Port of my answer to [Cayley Table of the Dihedral Group \$D\_3\$](https://codegolf.stackexchange.com/questions/171962/cayley-table-of-the-dihedral-group-d-3) but golfed down using the suggestions on my Python answer. Uses the following mapping:
```
id | r1 | r2 | r3 | s0 | s1 | s2 | s3
----+----+----+----+----+----+----+----
0 | 2 | 4 | 6 | 1 | 3 | 5 | 7
```
Older versions of JavaScript can be supported in a number of ways for 22 bytes:
```
(x,y)=>(y&1?y-x:y+x)&7
(x,y)=>y-x*(y&1||-1)&7
(x,y)=>y+x*(y<<31|1)&7
```
[Answer]
# [Rust](https://www.rust-lang.org/), 16 bytes
```
|a,b|a^b^a/2&b/4
```
[Try it online!](https://tio.run/##dZDLboMwFET3fMV0g0C6TcqzkaJ8CUoq0xrJESUpOGqVJt9O7XuJd12wmTNnsD1eJjt3Az6VGZIUvxHQa4tuN98UtTd1aA9qncftupy3C9M/Z/1u9Qd2iJuoyQg5oSCUhIpQE14Jmz1FTYhdZcOx556EOGehEu5JiAvZEe5JxUHNWcbctUpPJBNeMHQruSdBqCQT05Mg1LIjpiP7xzV71ep@4ku@cC3jvhzN73GzO41IDGE8facww2KtjNVjkq6u5pw8nksedzGOhNiBfxQekzagpkmP9k1/PSWd/9MxpUVp3ILDuEzmqvHsjp9uWbpH/rvPfw "Rust – Try It Online")
Port of alephalpha's Python answer. But shorter.
[Answer]
# [Elm](https://elm-lang.org), ~~42 bytes~~ 19 bytes
```
\a b->and 7<|b+a*7^b
```
Port of the Neil's [Node.js version](https://codegolf.stackexchange.com/a/185156/86885)
[Try it online](https://ellie-app.com/5vpH624w8rPa1)
**Previous version:**
```
\a b->and 7<|if and 1 a>0 then a-b else a+b
```
[Answer]
# Python, ~~82~~ 71 bytes
0-7
-11 bytes thanks to ASCII-only
```
lambda a,b:int("27pwpxvfcobhkyqu1wrun3nu1fih0x8svriq0",36)>>3*(a*8+b)&7
```
[TIO](https://tio.run/##XcvdCoIwAEDha32K4UVutsC5UBHyRSpwK5ezmnP5@/QroyC6PB8cPXdVoyIrdgd7Y3d@ZoBhnknVQS9K9KinQZwaXl3ntiej6RVVPRGyCqf0MRjZhh6mMcpzGkAWpGuOVonVZtkFJHiLkPutGNOfojh@lWgMkEAqYJi6lDBFmessVv@Z895AIaDEoEbFPtuQI3Y/7Pv2CQ)
[Answer]
# [Scala](http://www.scala-lang.org/), 161 bytes
Choosing **COMPUTER** as labels.
```
val m="0123456712307645230154763012675446570213574620316574310274651320"
val s="COMPUTER"
val l=s.zipWithIndex.toMap
def f(a: Char, b: Char)=s(m(l(a)*8+l(b))-48)
```
[Try it online!](https://tio.run/##JY5NS8NAFEXX5lcMWc3TWuZ7SiELKV24CBatuBAXL21qI5M0JIOopb99fKHw4Jx7F4877jBgOlVf9S6yEpsuO2c3@/rAWnKOy4dhwN/3lzg03ecHnHtiDB0/cOQC6GYMuZwE4JK@MbC2yIVU2ljnCcI7YwnSGu8IynlrjLNeKKmtN04JLSkaLYWiaKVWIs@mR2ORr57Kzet2/XwtQjHO/5r@rYnHx25f/8zjqcQ@m8bSnCVbHXGYseoqUIy85YEj3C7uAq8A7s0C0iWlddr8Aw "Scala – Try It Online")
[Answer]
# [Scala](http://www.scala-lang.org/), 70 bytes
Choosing 0-7 native integers as labels.
Compressed the matrix into 32 byte ASCII string, each pair of numbers n0, n1 into 1 character c = n0 + 8\*n1 + 49. Starting from 49 to that we don't have \ in the encoded string.
```
(a:Int,b:Int)=>"9K]oB4h]K9Vh4BoVenAJne3<_X<AX_J3"(a*4+b/2)-49>>b%2*3&7
```
[Try it online!](https://tio.run/##K05OzEn8n5@UlZpcouCbmJnHVc3FmZKappALZGskWjkWFSVWRgeXFGXmpcdqVhcA6ZKcPI00jUQNA00g0jWx0FFI1DCEsjU1a7nKEnMU0mz/AzV75pXoJIFITVs7JUvv2Hwnk4xYb8uwDBOn/LDUPEevvFRjm/gIG8eIeC9jJY1ELRPtJH0joDmWdnZJqkZaxmrm/2v//zf7bwwA "Scala – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 17 bytes
```
a=>b=>a^b^a/2&b/4
```
Port of alpehalpha's Python answer.
[Try it online!](https://tio.run/##PY2xCsIwFEVn@xXBQRJ8tlqrDpqMgiI4KDiIQhoTfVBSaKIWit8eK4rDhcvlHK5yA@UwLO9WLdB6@Jc2QhgeJBc5F/Kcn2WS9vIkC/PoIStSyFwXjnBi9fN4aoYwhRHMIIUxTCB7xftyg85TNo9MWWmpbvRjIUH7Uxlpos6hQq83aDV1vkJ7jdclWtolXfhC8U4XWnlac/EbVvai662hhiKjNWP9EWPtySu8AQ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 19 bytes
```
{($^x*7**$^y+$y)%8}
```
Port of [Neil's Python solution](https://codegolf.stackexchange.com/a/185157/14109).
[Try it online!](https://tio.run/##FczdCoMgAIbh43kVH2FD2yb7rUErupKGBwmOfsR2MBGv3eXxy/OawY5lnBz2qome0f5XVEVBe3egjufPkFI3osHrjCvuKHHBDQ9UbU22lNvUctaNQs5fbaS2K6@JWmxSpxZUw5PdKtNFTNIwvxGvGNVH0DcPgYvPomeWIdtciH8 "Perl 6 – Try It Online")
] |
[Question]
[
# Challenge:
Your job is to create a simple interpreter for a simple golfing language.
---
# Input:
Input will be in the form of string separated by spaces.
**You can replace space separation with what you want**
---
# Output:
Output the result (a number or a string) obtained after performing all operations. If there are more than one output join the together to give a single result (no separators). The variable's initial value is always zero. i.e: It start at `0`
---
# Language Syntax :
The language has following operators :
```
inc ---> add one to variable
dec ---> remove one from variable
mult ---> multiply variable by 2
half ---> divide the variable by 2
Pri ---> print the variable to console (or whatever your language has)
exit ---> end the program (anything after this is ignored)
```
---
# Examples:
```
inc inc inc dec Pri exit ---> 2
dec inc mult inc inc Pri ---> 2
inc inc inc mult half Pri exit inc ---> 3
inc Pri inc Pri inc Pri exit half mult ---> 123
Pri exit ---> 0
inc half Pri exit ---> 0.5
```
---
# Restriction:
This is code-golf so shortest code in bytes for each language will win.
---
# Note:
* Input will always be valid . (string of operators separated with space)
* You can round down to nearest integer if you don't want decimal places.
[Answer]
# shell + sed + dc, 56 ~~61~~ bytes
```
sed '1i0
s/.//2g;y"idmhe"+-*/q";i1
/[*/]/i1+
/P/crdn'|dc
```
[Try it online!](https://tio.run/##Tce9DkAwFAbQ/T6FdGlC@NTqJexioC29iZ9QEhLvXgmL6eR0rXfBardEkmdN1cb017Vj/8aevH@bjnGXd/DWRFJxTh4ZUAzlJdhMzookjbGKkhWhjtGAVUKooDczy9voEB4 "Bash – Try It Online")
Converts the program into a dc program, then evaluates it as dc code. This takes the input separated by newlines. Note that dc is stack-based and uses reverse polish notation, so `5 2-` gives `3`, and numbers are always rounded down.
The input is first piped to sed
`1i0` on the first line of input, insert (prepend) a 0, this will be the accumulator
`s/.//2g` remove everything but the first character on each line
`y"idmhe"+-*/q"` transliterate `idmhe` into `+-*/q` respectively, + - \* / are the arithmetic commands and q quits the program
`i1` on every line insert a `1` - this satisfies addition and subtraction
`/[*/]/` on every line containing \* or /, `i1+` additionally insert `1+` because of the preceding `1`, which dc will eventually evaluate into `2`
`/P/` on every line containing P, `crdn` change it into `rdn`, equivalent to reverse the top two elements, to rid the inserted `1`, and duplicate and output as a number without newline (whilst popping it, hence the earlier duplicate) in dc
Now this is evaluated as a dc expression.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
ḲḢ€O%11ị⁾’‘j“IȮḤH”¤VI
```
[Try it online!](https://tio.run/##y0rNyan8///hjk0Pdyx61LTGX9XQ8OHu7keN@x41zHzUMCPrUcMczxPrHu5Y4vGoYe6hJWGe////z8xLVgDhgKJMhZTUZDAGsWFiIDq3NKcEQgBFAA "Jelly – Try It Online")
---
Note that the ASCII values of the first characters (`idmhPe`) modulo 11 are unique modulo 6.
---
Using modulo 16:
# [Jelly](https://github.com/DennisMitchell/jelly), 21 bytes
```
ḲḢ€O%⁴ị“ḢwġḞkz’ṃØJ¤VI
```
[Try it online!](https://tio.run/##y0rNyan8///hjk0Pdyx61LTGX/VR45aHu7sfNcwBCpQfWfhwx7zsqkcNMx/ubD48w@vQkjDP////Z@YlK4BwQFGmQkpqMhiD2DAxEJ1bmlMCIYAiAA "Jelly – Try It Online")
The string that is used to index into is `ḤH‘’IȮ` in this case. The `‘’` are no longer on the boundaries.
[Answer]
# [R](https://www.r-project.org/), ~~128~~ 125 bytes
```
Reduce(function(x,y)switch(y,i=x+1,d=x-1,m=x*2,h=x/2,P={cat(x);x}),substr(el(strsplit(gsub("e.*$","",scan(,""))," ")),1,1),0)
```
[Try it online!](https://tio.run/##XYhLDsIgFACvQoiLR31@6NZwh8YbUErlJZQaPpHGeHasWzczk4nN0xh13GCx2a1TEu1up2IszCWYTGuAiptIL8rGwYak6lHipOpJ4qJq16NT9dLjoN5GZ6jiVj8CUxlTjmA97EpPTxke@wNuz92BI@eYjA6whxDI2Y8SpcCraJyCYUMk9m9bKTOn/cyW4jNvXw "R – Try It Online")
Must be called with `source(echo=FALSE)` to prevent the return value from being printed automatically. The alternative would be to [wrap everything in `invisible`](https://tio.run/##XYhLDsIgFACvQoiL9@rz024Nd2i8AaVUXkLRAFUa49mxbt3MTCZWz0PUcYXZZncfE1YOT048eAtXOy7GwrQEk/keoNCK6cXZOFiJVdm3NKpyaGlWpenIqXLqqFdvozMUvJQPUlqGlCNYD5vSw3OG2/ZA2mOzkyQlJaMDbIFIUvzYUot0RqySgxF9ZPFvWzgLp/0k5sVnWb8) but that's much less golfy (and ruins my [still] nice byte count).
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 25 bytes
```
΀¬"idmhPe"S"><·;=q"S‡J.V
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cN@jpjWH1ihlpuRmBKQqBSvZ2Rzabm1bqBT8qGGhl17Y///R6pl5yeo6CuoBRZkgCh8vtSKzBERnJOakgejc0pwS9VgA "05AB1E – Try It Online")
Maps each of the language function with the corresponding 05AB1E function (using the first char of each function), and then executes the resulting string as 05AB1E code.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~110~~ ~~91~~ 82 bytes
`exit` will cause the program to exit with an error.
```
x=0
for c in input():c=='P'==print(x,end='');x+=(1,-1,x,-x/2,c,0)['ndmhx'.find(c)]
```
[**Try it online!**](https://tio.run/##XcXBCsIwDADQu1@RW1rMdNObI/@wu3iQdmWBLSulg/j11bPw4OVPXXa9t2bcn9JeIIDoTz6q84/AjBMy5yJandGskRH9aGd2A3UDGXV2vVGg3j9R47YYXpJodMG/WhMNMBWB/2eTCst7TbAda/0C "Python 3 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 121 bytes
```
func[s][v: 0 parse s[any[["i"(v: v + 1)|"d"(v: v - 1)|"m"(v: v * 2)|"h"(v: v / 2.0)|"P"(prin v)|"e"(exit)]thru" "| end]]]
```
[Try it online!](https://tio.run/##ZYxBCoMwEEX3nuIzK21pa116itJtyEJMggENEqO04N3TRFTaugiTN/P@t1L4pxSMJ6r0ajQ1GzibSuToKztIDKwyb8ZIUxq2E864ZzOJlS4LdSudUARqVrqhuOaBH5T2VhtM4S8plS/tMu4aOxJohjSCc@4VSJsa2xOyxsNqRJmSGHcgSoIVL9HoxtbtelB/re@uxWyqVu2NcX304/V/LvaSjS3HzFZL/gM "Red – Try It Online")
## Readable:
```
f: func [s] [
v: 0
parse s [
any [
[ "i" (v: v + 1)
| "d" (v: v - 1)
| "m" (v: v * 2)
| "h" (v: v / 2.0)
| "P" (prin v)
| "e" (exit)]
thru [" " | end]
]
]
]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~131~~ ~~125~~ ~~122~~ ~~121~~ ~~118~~ ~~117~~ 115 bytes
```
v=0;o=""
for x in input().split("x")[0].split():
if"Q">x:o+=`v`
else:v+=(1,-1,v,-v/2.)['idmh'.find(x[0])]
print o
```
[Try it online!](https://tio.run/##LcyxDoMgFEDRna94eYsQ0aqjDf2GdjYmNlXCSygQpYR@PXVocpez3PCNxruhlKS6q1eITPsdMpA7C5/IRXsES5FjRjF1819iZEAaH3jLo6/VkhYGmz22MdWK97LpZZJNugytmCpa36ZqNbmV5/MgZhZ2chF8KUjuBeZpNdx3wh8 "Python 2 – Try It Online")
-6 and -3 with thanks to @Rod
-3 and -2 with thanks to @etene
-1 by replacing `"Pri"==x` with `"P"in x`
[Answer]
# JavaScript (ES6), ~~83~~ 79 bytes
*Saved 4 bytes thanks to @l4m2*
Iteratively replaces the instructions with either the output or empty strings.
```
s=>s.replace(/\S+./g,w=>m<s?'':w<{}?m:(m+={d:-1,e:w,i:1,m}[w[0]]||-m/2,''),m=0)
```
[Try it online!](https://tio.run/##jc/dCoIwFAfw@55i7Eal6dToZrh6haDL6kLmrMWm4SyD8tmtGX2ZRQfG4LDf/5xt40OsWSF2pZvlCW9S2mg60V7BdzJm3MbL@dDDa1TRiYr01LJIFZ3qqSK2GtJTQtwAcVIhQQKk6kW18Fer89lVOESW5SBFfadheaZzyT2Zr@3UhiJj4H4SzsCsEIAfRQnBWzkOwBiEg442wki1l@Uj5hrxn36d3SZsYpk@NjBt@NSjPm3edu/WtkkmE950EH74Lz/t1s37fdPf1oW/tDduLg "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // given the input string s
s.replace(/\S+./g, w => // for each word w in s:
m < s ? // if m is a string:
'' // ignore this instruction
: // else:
w < {} ? // if w is 'Pri' ({} is coerced to '[object Object]'):
m // output the current value of m
: ( // else:
m += // add to m:
{ d: -1, // -1 if w is 'dec'
e: w, // w if w is 'exit' (which turns m into a string)
i: 1, // 1 if w is 'inc'
m // m if w is 'mult'
}[w[0]] // using the first character of w to decide
|| -m / 2, // or add -m/2 (for 'half') if the above result was falsy
''), // do not output anything
m = 0 // m = unique register of our mighty CPU, initialized to 0
) // end of replace()
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~37~~ 35 bytes
```
≔⁰ηF⎇№θx…θ⌕θxθ≡ιn≦⊕ηd≦⊖ηm≦⊗ηh≦⊘ηrIη
```
[Try it online!](https://tio.run/##bY@xCsIwEIb3PsXRKYEKzjpJRXQoOPgCZxJNIE1sktaK@OwxpTpEnI77/o87fibRMYs6xo336mrIsgJJ18XFOiAn4Qy6B6ltbwLpKijHklbQWM2nbacM/9KEO0rB31VgEoii8CwYegGlKVfQ4O1z/mCYE60wQfD50SzxTNqKv1KbS7Y/61yQmbBHPeS5S/nRqdSlRh@IpCl5xagMmzD8TjGqABL1BdpehyIuBv0G "Charcoal – Try It Online") Link is to verbose version of code. Inspired by @RickHitchcock's answer. Explanation:
```
≔⁰η
```
Clear the variable.
```
F⎇№θx…θ⌕θxθ≡ι
```
Truncate the input at the `x` if there is one, then loop over and switch on each character of (the remainder of) the input.
```
n≦⊕η
```
`n` i**n**crements the variable.
```
d≦⊖η
```
`d` **d**ecrements the variable.
```
m≦⊗η
```
`m` **m**ultiplies the variable by two (i.e. doubles).
```
h≦⊘η
```
`h` **h**alves the variable.
```
rIη
```
`r` p**r**ints the variable cast to string.
[Answer]
# JavaScript (ES6), ~~77~~ 75 bytes
(Borrowed (*stole*) @Arnauld's trick of using `m` as the variable name, saving 2 bytes.)
```
f=([c,...s],m=0)=>c<'x'?(c=='P'?m:'')+f(s,m+({h:-m/2,d:-1,n:1,m}[c]||0)):''
```
Recursively walks the string, looking for distinct letters per instruction and ignoring the rest:
* n: inc
* d: dec
* m: mult
* h: half
* P: Pri
* x: exit
Takes advantage of the fact that `undefined` is neither greater than nor less than `'x'`, causing the recursion to stop at the end of the string *or* when it encounters the `'x'` in **exit**.
```
f=([c,...s],n=0)=>c<'x'?(c=='P'?n:'')+f(s,n+({h:-n/2,d:-1,n:1,m}[c]||0)):''
console.log(f('inc inc inc dec Pri exit')); //--> 2
console.log(f('dec inc mult inc inc Pri')); //--> 2
console.log(f('inc inc inc mult half Pri exit inc')); //--> 3
console.log(f('inc Pri inc Pri inc Pri exit half mult')); //--> 123
console.log(f('Pri exit')); //--> 0
console.log(f('inc half Pri exit')); //--> 0.5
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 107 bytes
```
f=s=>s.split` `.map(([o])=>F?0:o=="i"?i++:o=="d"?i--:o=="m"?i*=2:o=="h"?i/=2:o=="P"?S+=i:F=1,F=i=0,S="")&&S
```
[Try it online!](https://tio.run/##bY/BioMwFADv@xUhBzFrtK32UFxevXkueBShQWP7lmiksWX/3k1CtyzSQ8gQZl6Sb/EQpr3hNMej7uSy9GDgaBIzKZzP5JwMYgrDWjcMjmWxzTUARVpgFHnsLMaxx8HiJ6Ser5Y3Tz7RoooA8xJ2vASELa@AUhYE1dLq0WglE6UvYR9SHFvytzrZktMNifzBmTKAlH2sbGc4c7ir@ZXZhDLyTv8/3CdXofrXFe7Yhxn7elc6b737zk9x89wjd2nGVp@q9w2vDw0/cJJZoxfKSPYL "JavaScript (Node.js) – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 91 bytes
```
_=>_.split` `.map(o=>o<{}>!_?S+=+i:o<"e"?i--:o<"f"?++_:o<"i"?i/=2:o<"j"?i++:i*=2,i=S="")&&S
```
[Try it online!](https://tio.run/##bYxBCoMwEEX3PUWahWhTLbi0jl6h4AE0xNiORCNqS6H07DYRKiIuhvnMvPdr/uKD6LEb/VaXcqpgyiHJg6FTOBakCBreuRoSHX@@yTFPMwYMIx1TSVP0fZsqmjKW24TmdoHQxtpExiI8QXhGyIBSz3GySeh20EoGSt/dyqXYCvKfUgpy65HIN47U8w4b1L4t1jzVuDiG30HXrTP@4Kpaulfidc@03HbP3txi@4w5/QA "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 96 bytes
```
_=>_.split` `.map(o=>F?0:o<"Q"?S+=i:o<"e"?i--:o<"f"?F=1:o<"i"?i/=2:o<"j"?i++:i*=2,F=i=0,S="")&&S
```
[Try it online!](https://tio.run/##bYzLDoJADEX3fgWZBQF5iCzRwo61hg8AAjNaMjAE0Pj3OCWRGMKi6U17zm3KdzlWA/aT16mazwLmHOLcH3uJU2EUflv2loI4TYJIXdmdJZkDSJGzBD2PkmBJCmdKqG8nCCk2OjpOhEcI3RQQAjcDxmzTzOZKdaOS3JfqYQmLYVcZv6l5ZdwGNPgHJ2bbhw1Kb8Lal5xWR/M76H/rgj9LKdZuOmvpsmcRs92LszRQlzbnLw "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 99 bytes
```
s=>s.split` `.map(_=>eval('++i7--i7++e7u+=+i7i*=27i/=2'.split(7)[Buffer(e+_)[0]%11%6]),e=i=u='')&&u
```
[Try it online!](https://tio.run/##XY09D4IwFAB3f0UXbWv5EAc7PQYHZndDsMJDn6lAaGv679HExThdbrjcw7yMa2eafDqMHS553uE13CBCKdpxcKPFzI43EWUS5aqCxUHpMjdZ8hd2yZ5mEg2U@DJWcKVIpylppVAHBR@jLew15bDn30RoeT6GvsdZoGrkeVevi2J9qGWCQBCAc7nZhOV3XAlOQ8tOM7F/YiTP7sb27Bms51Kuljc "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript, 107 bytes
```
s=>eval('x=0;x'+(s.split` `.map(v=>({i:"++",d:"--",m:"*=2",h:"/=2",P:";alert(x)",e:"//"})[v[0]]).join`;x`))
```
[Answer]
# [Haskell](https://www.haskell.org/), 93 bytes
```
(0!)
a!(c:t)|c=='P'=show a++a!t|c>'w'=""|1<2=(a+sum(lookup c$zip"ndmh"[1,-1,a,-a/2]))!t;a!e=e
```
[Try it online!](https://tio.run/##Xc0xDoIwFADQ3VP8NiZtA0RhVL9nYFeHnwrS0JaGlpAYzm51dnrjGyiOnbW5x3uWR6Z2xKQ@JbVpRNEKjMO0AhUFsbTpq1gFcr7VlwYlFXFx0k7TuATQ@7cJ3D/dwG91WdUllRUdmodSLJ2JddhlR8YDQpiNT/CruPEa2tnAn1zlj@4tvWKudAhf "Haskell – Try It Online")
Essentially a translation of [mbomb007's Python answer](https://codegolf.stackexchange.com/a/163596/3852).
[Answer]
# Lua, 207 bytes
```
s=0;n=0;for a in io.read():gmatch'.'do if s==0 then s=1;n=a=='i'and n+1 or a=='d'and n-1 or a=='m'and n*2 or a=='h'and n/2 or n;if a=='P'then print(n)elseif a=="e"then break end elseif a==' 'then s=0 end end
```
[Answer]
# [Python 3](https://docs.python.org/3/), 114 110 109 116 bytes
Actually would have taken two bytes less in Python 2 because `exec` is a statement and doesn't need parentheses...
* *Saved 4 extra bytes thanks to @ElPedro*
* *Saved an extra byte by taking advantage of the fact that `find` returns -1 on error, which can then be used as an index*
* *+7 bytes because I hadn't noticed the no-newlines rule :(*
```
i=0;exec(";".join("i+=1 i-=1 i*=2 i/=2 print(i,end='') exit()".split()["idmhP".find(h[0])]for h in input().split()))
```
[Try it online!](https://tio.run/##XY29DsMgEINf5XRLoD80bceId8geZagCiKvIBREipU@fwtClkvXZg2XHT/YLP4@DdNvZ3U4CO1TvhVggnfUd6Fpx0g@gW0FMxFnQxbLRTSPB7pSFRLXGUMOAZGbfo3LERvihHeXolgQeiIviVjq/rpTllSfoE8G/11nwr@Bg3kL@Ag "Python 3 – Try It Online")
Maps the first character of every input word to a piece of Python code. These are then concatenated and `exec`ed.
Pretty straightforward approach, that could probably be golfed a bit more. The difficulty mostly resides in finding the shortest form out of many possible ones...
[Answer]
# [Ruby](https://www.ruby-lang.org/) + `-na`, ~~81~~ ~~73~~ 65 bytes
```
x=0;$F.map{|w|eval %w{x+=1 x-=1 1/0 $><<x x*=2 x/=2}[w.ord%11%6]}
```
[Try it online!](https://tio.run/##KypNqvz/v8LWwFrFTS83saC6prwmtSwxR0G1vLpC29ZQoUIXSBjqGyio2NnYVChUaNkaKVTo2xrVRpfr5RelqBoaqprF1v7/n5mXrJBbmlOClcAliSoO51HIICQcUJT5L7@gJDM/r/i/bl4iAA "Ruby – Try It Online")
Pretty straightforward. For the first letter of each word, find the corresponding command string and `eval` it. Uses integer division, and `exits` by throwing a `ZeroDivisionError`.
-5 bytes: Use `.ord%11%6` instead of a string lookup. Credit goes to [user202729](https://codegolf.stackexchange.com/a/163573/77973)
-3 bytes: `.ord` only considers the first character of the string, so I can skip a `[0]`.
-8 bytes: Use `-a` flag to automatically split input, thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l)
[Answer]
# [Emojicode](http://www.emojicode.org/), 270 bytes
```
üêñüî•üçáüçÆc 0üîÇjüç°üí£üêïüîü üçáüçäüòõjüî§incüî§üçáüçÆc‚ûïc 1üçâüçãüòõjüî§decüî§üçáüçÆc‚ûñc 1üçâüçãüòõjüî§multüî§üçáüçÆc‚úñÔ∏èc 2üçâüçãüòõjüî§halfüî§üçáüçÆc‚ûóc 2üçâüçãüòõjüî§Priüî§üçáüëÑüî°c 10üçâüçìüçáüçéüçâüçâüçâ
```
[Try it online!](https://tio.run/##jZBfDsFAEMbfnWKOgJO4gmwrVtBESDwiEkGoP201ITaCV8/O4wL2Bsxs19JqxcN0d7q/b2a@sRtOjTPHsh9SLKZSeAcpZiNKAkzOlGBcGOQxHdTwjsDqiO8@/hCggYkU4RZfvRNvMjqM8Lb3GRTwOsaYGsyyk1iQhjU69Xac2wX3q8ug@IVWy/VKouQmjSu1@BtbDskyds5rbq3lc52reNAnJ4Xbp9ccRJtRXuEVaAiwNNhdriZGPOxFjTAxEsIIJ2NGq0fKkHx2UTJyanqBXvgPMaHJU0lVodeKMwr84YlqxmbSLC7uCQ "Emojicode – Try It Online")
```
üêãüî°üçá
üêñüî•üçá
üçÆc 0
üîÇjüç°üí£üêïüîü üçá
üçäüòõjüî§incüî§üçáüçÆc‚ûïc 1üçâ
üçãüòõjüî§decüî§üçáüçÆc‚ûñc 1üçâ
üçãüòõjüî§multüî§üçáüçÆc‚úñÔ∏èc 2üçâ
üçãüòõjüî§halfüî§üçáüçÆc‚ûóc 2üçâ
üçãüòõjüî§Priüî§üçáüëÑüî°c 10üçâ
üçìüçáüçéüçâüçâüçâüçâ
üèÅüçá
üî•üî§inc inc inc dec Pri exitüî§
üòÄüî§üî§
üî•üî§dec inc mult inc inc Priüî§
üòÄüî§üî§
üî•üî§inc inc inc mult half Pri exit incüî§
üòÄüî§üî§
üî•üî§inc Pri inc Pri inc Pri exit half multüî§
üòÄüî§üî§
üî•üî§Pri exitüî§
üòÄüî§üî§
üî•üî§inc half Pri exitüî§
üçâ
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 165 bytes
```
P =INPUT ' exit '
x =0
S P LEN(1) $ L ARB ' ' REM . P :S($L)F(end)
i X =X + 1 :(S)
d X =X - 1 :(S)
P O =O X :(S)
m X =X * 2 :(S)
h X =X / 2. :(S)
e OUTPUT =O
END
```
[Try it online!](https://tio.run/##Nc5NC4JAFIXh9Z1fcRaCM0WW4kqYRZFBYM7gB7itNBwwhWrhv5@ModXlue/mvMfpNg2xtaQhz7muK/joZvNZDqMZcsfKJWVpzkMBDxn2xWFpPor0ggCakpJ7mTjxbmwFM9RANlgjpISXgrXOm781KUiFhhyfLq8QOffOW0SBe3Sk6uo3SiqW5kdrzXhHfx0e0C/zBQ "SNOBOL4 (CSNOBOL4) – Try It Online")
Gross.
```
P =INPUT ' exit ' ;* append ' exit ' to the input to guarantee that the program will stop
x =0 ;* initialize x to 0 else it won't print properly if the program is 'Pri'
S P LEN(1) $ L ARB ' ' REM . P :S($L)F(end) ;* set L to the first letter of the word and goto the appropriate label
i X =X + 1 :(S)
d X =X - 1 :(S)
P O =O X :(S) ;* append X to the output string
m X =X * 2 :(S)
h X =X / 2. :(S) ;* divide by 2. to ensure floating point
e OUTPUT =O ;* print whatever's in O, which starts off as ''
END
```
[Answer]
# C# (.NET Core), 186 Bytes
```
class P{static void Main(string[]a){int v=0;foreach(var s in a){var i=s[0];if(i=='i')v++;if(i=='d')v--;if(i=='m')v*=2;if(i=='h')v/=2;if(i=='P')System.Console.Write(v);if(i=='e')break;}}}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, 61 bytes
```
eval'$,'.qw(++ -- ;exit ;print$,||0 *=2 /=2)[(ord)%11%6]for@F
```
[Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHXUVHXa@wXENbW0FXV8E6tSKzRMG6oCgzr0RFp6bGQEHL1khB39ZIM1ojvyhFU9XQUNUsNi2/yMHt///MvGSFjMScNIWAokwFkMZ/@QUlmfl5xf91fU31DAwN/usmAgA "Perl 5 – Try It Online")
Stole @user202729's `ord%11%6` trick
## How?
```
-a # split the input by whitespace, store in @F
eval # Execute the string that results from:
'$,' # $, (the accumulator)
. # appending:
qw( # create an array for the following whitespace separated values:
++ -- # operators for inc & dec
;exit # exit
;print$,||0 # Pri (||0 ensures that 0 is output if accumulator is null
*=2 /=2) # mult div
[(ord)%11%6] # @user202729's trick selects one of the preceding operations
for@F # for every term input
```
[Answer]
# Pyth, 44 Bytes
```
Vmx"idmhPe"hdcwd=Z@[hZtZyZcZ2ZZ)NIqN4pZIqN6B
```
[Test Suite](https://pyth.herokuapp.com/?code=Vmx%22idmhPe%22hdcwd%3DZ%40%5BhZtZyZcZ2ZZ%29NIqN4pZIqN6B&input=inc+inc+inc+mult+half+Pri+exit+inc&test_suite=1&test_suite_input=inc+inc+inc+dec+Pri+exit%0Adec+inc+mult+inc+inc+Pri%0Ainc+inc+inc+mult+half+Pri+exit+inc%0Ainc+Pri+inc+Pri+inc+Pri+exit+half+mult%0APri+exit%0Ainc+half+Pri+exit&debug=0)
## explanation
```
Vmx"idmhPe"hdcwd=Z@[hZtZyZcZ2ZZ)NIqN4pZIqN6B ## full program
cwd ## split input on space
Vmx"idmhPe"hd ## iterate through list of numbers corresponding to operators
=Z@[hZtZyZcZ2ZZ)N ## assign the variable Z (initialliy Zero) it's new value
IqN4pZ ## print Z if the current operator is "Pri" (4)
IqN6B ## break if the current operator is "exit" (5)
```
[Answer]
# TI-BASIC, 112 bytes
This takes advantage of some assumptions that are AFAIK perfectly acceptable. Number one being that all variables are initialized to zero prior to execution; number two being that input is taken via `Ans`.
```
Ans+" E‚ÜíStr1
While 1
I+4‚ÜíI
sub(Str1,I-3,1‚ÜíStr2
A+(Ans="I")-(Ans="D
If inString("MH",Str2
Then
I+1‚ÜíI
2AAns+A/2(1-Ans
End
If Str2="P
Disp A
If Str2="E
Stop
Ans‚ÜíA
End
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 164 bytes
```
a->{int c=0;for(String g:a.split(" ")){char b=g.charAt(0);if(b==105)c++;if(b==100)c--;if(b==109)c*=2;if(b==104)c/=2;if(b==80)System.out.print(c);if(b==101)return;}}
```
[Try it online!](https://tio.run/##lVHdSsMwFL7vUxx6lThaO1FQSwUfQCrsUrxI07TLbNOSngyl7NlrUmemA6FehOQ7nO@P7NieRV0v1K58m3jDhgGemFRjACAVCl0xLiAf950sQZMNaqlqYDQ92IUBGUoOOeQGe4OQwcSih9HygGdJWnWeUN@zeOgbiSSEkNKRb5mGIqtj93hEktBUVqTIsnVyQ/lq5VFCeRR5dEf5RXbl4TXllx7eJnTzMaBo485g3FtbJPwku6ZaoNEqPRym1GbvTdHY7McKc73W9j4GfnlldAy@asWahFJx@D6l4PCsJYh3iSFNg3PXRhE7PXHdvuO1pkEvYgWWcH/6zvwtayrv7sZLVRzn/J41ZkWnvUTpP72dy6@4f5MC@ymf "Java (OpenJDK 8) – Try It Online")
Above is my solution that rounds off to integers, but below is my solution that handles decimals. The obnoxious way that java prints doubles adds another 55 byes to the score. I left the new lines to make the code more readable in the second submission only because it’s essentially the same solution with one extra command and an import statement.
# [Java (OpenJDK 8)](http://openjdk.java.net/), 219 bytes
```
a->{
double c=0;
for(String g:a.split(" ")){
char b=g.charAt(0);
if(b==105)c++;
if(b==100)c--;
if(b==109)c*=2;
if(b==104)c/=2;
if(b==80)System.out.print(new DecimalFormat("0.#").format(c));
if(b==101)return;}}
```
[Try it online!](https://tio.run/##lVHRSsMwFH3PV1zqS7LR2ImCWioI4ptM2KP4kKXplpmmJb2dk7Jvr2k31zkQ5kNIzuWec@65WYm1CItS2VX60eq8LBzCytc4qg3yUUykEVUFL0LbhgBoi8plQiqYNutCp@DoDJ22CxAs3vqGCgVqCVOY1ljWCAm0InxoSFrUc6NAJlFMsuLAWtwLXpVGIw0gYKwhcikczJMF7x6PSCMWE53ReZJMohsmx@MBRkyG4QDvmBwlVwO@ZvJywLcRm31VqHJe1MhLb47Uqk94UlLnwjwXLhd@iIhfBIxnOyTZkfmEOYW1s/F228Y@aOnz@KD7vP0ucr@kfbC3d@HD7HbAHQ20lfBzUiXh1WlQG42Bdzidy1jqqwO36@94eW3wIOIFzuEe@/b8pTDZwb0rn6vScU7vXqNX7LTPUfpP7s7l17h/k4j/lG8 "Java (OpenJDK 8) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~120~~ ~~114~~ 111 bytes
-6 bytes thanks to ceilingcat.
```
x,d;f(char*s){for(x=0;s>1;s=index(d^1?s:"",32)+1)d=*s-100,x+=d?d==5:-1,x*=d^9?d^4?1:.5:2,d+20||printf("%d",x);}
```
[Try it online!](https://tio.run/##XY9disMgFIWf6ypEKGiiQ8y0DxOx2cKsIBC8SSq0aYlpEdquPROFhE4f5Mo537k/RnTGTJPnoFpqjvWQOPZoLwP1OlPuIJXTtofGU6hk6QpC@HfOUslAJ07ILOM@1VCC1vtCSO4TDdVPCdWulMXXvsg5pHn2fF4H248tJVsg3DP1mu4XC7iLA/E8ET3QZmXETjoshDhgwrFjCm1aGsv1NjpKyPx9ITTD@FzbnsZwR4ntDV4eNAb/DhY33o6BD37Qgne@ncYVnKHFf89H5lif2rVLkN/JoH/WyMVUyC/05x6B/tc6HjT9AQ "C (gcc) – Try It Online")
# 124 bytes
Floating-point version:
```
d;f(char*s){for(float f=0;s>1;s=strchr(s,32)+1)d=*s-80,f+=d==25,f-=d==20,f*=d^29?d^24?1:.5:2,s=d^21?s:"",d?:printf("%f",f);}
```
[Try it online!](https://tio.run/##XY9hisMgEIV/11OIsGBSXZq0hd0EmyvsCRaCdhIhTYpjl4XSs2dVSOj2h87w3vfGUctO63k2NXDdty7H7A6T4zBMraegdjWeihoVeqd7x1Hsy2xbZEblKD92ArbKKFUeBcjUBCVX5rv8bMJ1aIrq/ViVAqNUNFgxJkxTXZ0dPXD2BkxAVj/mn8ka2qX3aViA3MlmZeShQCqlPFEmKGY12QBP5XrzyBkL7YOQANNLa0eewh1ndtR0Oeas6Zez9PxrfeSjH7XoXW6DX8EALf5zPjF9O8A6JcrPZNRfa@JSKuYX@nWPSP8bnT40/wE "C (gcc) – Try It Online")
I did not bother with a version that rounds down, but makes an exception for 0, which would be allowed, if I understand the comment-chain correctly.
[Answer]
# [33](https://github.com/TheOnlyMrCat/33), 62 bytes
```
s'i'{1a}'d'{1m}'m'{2x}'h'{2d}'P'{o}'e'{@}It[mzsjk""ltqztItn1a]
```
[Try it online!](https://tio.run/##Mzb@/79YPVO92jCxVj0FSOXWqueqVxtV1KpnAKmUWvUA9er8WvVU9WqHWs@S6Nyq4qxsJaWcksKqEs@SPMPE2P//AQ "33 – Try It Online")
This program takes the instructions delimited by newlines
## Explanation:
```
It[mzsjk""ltqztItn1a]
[mz n1a] | Forever
It jk It | - Get the first character of the next instruction
qz | - Call the function declared previously
s ""lt t | - Make sure we don't lose track of the variable
```
The code before that segment defines all the functions.
[Answer]
# [JavaScript (V8)](https://v8.dev/), 152 bytes
```
i=>{return n="",p=0,e=1,i.split(" ").map(i=>{e&&("inc"==i&&p++,"dec"==i&&p--,"mult"==i&&(p*=2),"half"==i&&(p/=2),"Pri"==i&&(n+=p),"exit"==i&&(e=0))}),n}
```
[Try it online!](https://tio.run/##XY1BDoIwEEWv0syi6UhBdOVmPINXaLDomFqaUoiJ4ewVUDauJv9lXt7DjKZvIodUjqfcUmY6v6NNQ/TCE4AOVGtLB81VHxwnBQKwepqglkcrpQL2DRCxlKEoNFzttspSw3Nw6TtV2NERNdyNazeyX8kl8g/4gsIM7Is3yVKNOKH2U24633fOVq67qXatitkU/3eRxRIRaxsxfwA "JavaScript (V8) – Try It Online")
] |
[Question]
[
This is the inverse of "[Encode the date in Christmas Eve format](https://codegolf.stackexchange.com/questions/178003/encode-the-date-in-christmas-eve-format)."
Write a program that takes as input the string `Christmas`, possibly followed by `Eve` between 1 and 365 times, and outputs the date encoded in YYYY-MM-DD format, or any format from which the year, month, and date can be easily obtained. Assume that the "Christmas" being referred to is the next Christmas, or today, if today is Christmas. Christmas is December 25.
Your program may also take the current date as input in the same format used for output, if there is no way to get it in the language you use.
Remember to take leap years into account.
Examples if run on or before Christmas 2023:
| Input | Output |
| --- | --- |
| Christmas | 2023-12-25 |
| Christmas Eve | 2023-12-24 |
| Christmas Eve Eve | 2023-12-23 |
| Christmas Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve | 2023-11-15 |
| Christmas Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve Eve | 2022-12-26 |
[Answer]
# Excel, ~~35~~ 33 bytes
```
"26/12"-ROWS(TEXTSPLIT(A1,," "))
```
Input in cell `A1`.
[Answer]
# shell + coreutils, ~~78~~ 76 bytes
```
d=date\
$d-d$(((`$d+%s`>=`$d+%s -d12/26`)+`$d+%Y`))-12-25-$((${#1}/4-2))day
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70kKbE4Y8GCpaUlaboWN31SbFMSS1JjFLhUUnRTVDQ0NBJUUrRVixPsbCEMBd0UQyN9I7METW2wQGSCpqauoZGukakuULVKtbJhrb6JrpGmZkpiJcRMmNFro5WcM4oyi0tyE4sVXMtSBzNWioW6GgA)
Edit: the previous version outputs (incorrectly) the *previous* Christmas \$n\$-th Eve when the current date is between December 26th and 31st.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~35~~ ~~56~~ 55 bytes
```
($c=date 12/26)|% *ars((date)-ge$c)|% *ys(-$args.Count)
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9X0Ml2TYlsSRVwdBI38hMs0ZVQSuxqFhDAySmqZueqpIMFqss1tBVSSxKL9Zzzi/NK9H8X8ulpgA0wjmjKLO4JDexGI2r4FqWikUIj/BgxVz/AQ "PowerShell – Try It Online")
+21: Fixed to get the *next* Christmas eve, including when called between 12/26 and 12/31, thanks to @i-t-delinquent.
-1: Setting/outputting $c, thanks to @julian
Returns DateTime objects.
Nothing remarkable; gets a date object for the 26th of December, adds a year if past the 25th, and subtracts the argument count as days.
`(date) -ge $c` will return a boolean, which will be evaluated as 0/1 when passed to AddYears, which expects an integer.
*Disclaimer:* Don't use 'date' in your day-to-day scripts; this is fit for golfing only. PowerShell will first search through all available commands, and if it doesn't find one named "date", it will prepend "Get-" and try again. Very slow, and will fail if a command line program date.exe exists somewhere in the path.
**Ungolfed** (method call using ForEach-Object; golfs better):
```
$c = Get-Date 12/26
$c | ForEach-Object -MemberName AddYears ((Get-Date) -ge $c) | ForEach-Object -MemberName AddDays (-$args.Count)
```
**Ungolfed alternative** (usual method call):
```
$c = Get-Date 12/26
$c.AddYears((Get-Date) -ge $c).AddDays(-$args.Count)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 79 bytes
```
s=>new Date(/c 2[6-9]|c 3/.test(t=new Date)+t.getFullYear(),11,109-s.length>>2)
```
[Try it online!](https://tio.run/##zYlLCsIwFEXnXUVmTbBNbQWhg3SidQ@iQkN8/UialLxnnbj3OhIRXICDC@ece9OzRhOGiVLnr7C0akFVOXiwvSbgmWHFaZuWl6dhm0wSIHFS71usSHZAh7u1R9CBiyTPk3xdpigtuI76qirEopliTbTrw4A0avwQq2f4tt/lXxc1ksIwciFxsgPx@OxiEWnZ@lBr03NkqmLGO/QWpPUdbzkKIZYX "JavaScript (Node.js) – Try It Online")
73 bytes if take today as input.
[Answer]
# Google Sheets / Microsoft Excel, ~~30~~ ~~67~~ ~~58~~ ~~50~~ 39 bytes
`=(year(now()+6)&"-12-26")-(len(A1)-5)/4`
Put the input in cell `A1` and the formula in `C1`.
The formula outputs a numeric dateserial value. The question specifies *"any format from which the year, month, and date can be easily obtained"*. To obtain those date fields, format the formula cell as **Format > Number > Date** or similar.
The question also specifies "next Christmas". When the current moment is within 26 to 31 December, the formula looks at Christmas *next year*, and outputs a date counting down from that Christmas date. Otherwise, it looks at Christmas in the current year.
The first part of the formula obtains a string in the [ISO8601](https://en.wikipedia.org/wiki/ISO_8601) format `yyyy-MM-dd` which is a valid date format in any locale. The string gets coerced to a dateserial while subtracting the second part (the number of `Eve`s plus one.)
You can include formatting in the formula at a cost of 9 bytes (Google Sheets):
`=to_date((year(now()+6)&"-12-26")-(len(A1)-5)/4)`
...or at a cost of 17 bytes (Microsoft Excel):
`=text((year(now()+6)&"-12-26")-(len(A1)-5)/4,"M/d/yyyy")`
| input | expected | output (as Date) |
| --- | --- | --- |
| Christmas | 2023-12-25 | 12/25/2023 |
| Christmas Eve | 2023-12-24 | 12/24/2023 |
| Christmas Eve Eve | 2023-12-23 | 12/23/2023 |
| Christmas Eve Eve Eve... (40 times in total) | 2023-11-15 | 11/15/2023 |
| Christmas Eve Eve Eve... (364 times in total) | 2022-12-26 | 12/26/2022 |
[Answer]
# G[AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 74 65 64 bytes
```
$0=mktime(strftime("%Y",systime()+720^2)" 12 26 0 0 0")-86400*NF
```
[Try it online!](https://tio.run/##SyzP/v9fxcA2N7skMzdVo7ikKA3MUFKNVNIpriwGczS1zY0M4ow0lRQMjRSMzBQMQFBJU9fCzMTAQMvP7f9/54yizOKS3MRiLjhLwbUsFZWHXWSwYgA "AWK – Try It Online")
* -9 bytes, reassign `$0`, as epoch time will be `>1` will print the line. And replaced the make time to one day later to account for the first field.
* -1 byte, replaced `518400` with its root squared `720^2`
This will print the epoch time of the date you asked for. From which you can easily obtain any date format.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 68 bytes
```
s=>new(D=Date)(new D(+new D+5184e5).getFullYear(),9,353-s.length>>2)
```
[Try it online!](https://tio.run/##zYhNDoIwEEb3nKI7ZgI0USTRRdkI3sHEBQ0OP6a0pFPx@GjcGBMP4OLle9@76UVz68c5ZNZdae3Uyqq09IBKVToQwstFBcl7kmKz31GBsqdwuhtzJu0B00OaF3nG0pDtw1CWW1y1UKKJjoMfOUyaPybqhb7f7/KvRI0MfpwAJc9mDBBfbIyRlp3ztW4HYKFK0TrLzpA0rocOGBHXJw "JavaScript (Node.js) – Try It Online")
From tsh's
-3B from Arnauld
[Answer]
# Python, ~~136 125 121~~ 94 bytes
Returns a `datetime` object.
```
lambda x:d((d.today()+t(6)).year,12,25)-t(len(x)/4-2)
from datetime import*
d=date
t=timedelta
```
[Answer]
# Bash + GNU date, ~~48~~ ~~43~~ 38 bytes
```
date -d`date -d6day +%Y`1226-$#day +%F
```
We count the number of arguments and subtract that from Boxing Day (26 December).
If today is after Christmas, we need to start from *next* Boxing Day, so we look ahead six days from today to find the appropriate year to use.
Thanks to Nahuel Fouilleul for suggesting we read standard input rather than command arguments, saving 5 bytes.
Thanks to Neil for suggesting we let the shell do the splitting and counting.
[Online version](https://tio.run/##S0oszvifnJ9XllpUoqGpUP0/JbEkVUE3JQFKm6UkVipoq0YmGBoZmemqKEO4bv9rubjS8osUMrlS8hWg2hVUQLy81P//nTOKMotLchOLESwF17JUVB52kcGKh45LR/EoHsWjeBRDMAA)
[Answer]
# [Julia](https://julialang.org), 72 bytes
```
using Dates
~s=tonext(==((12,26))∘monthday,today())-Day(sum(<('D'),s))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fjc9Sosz89IVXBJLUou56optS_LzUitKNGxtNTQMjXSMzDQ1H3XMyM3PK8lISazUKckHkhqamrouQKq4NFfDRkPdRV1Tp1hTE2LeLUbBzLyC0pJiBVuFaC5OJeeMosziktzEYiUdZJ6Ca1kqpghu0cGKga6N5eKKVigoyswrycnTqKvQVEjLL1KoUMjMU4AGRCwkZGAhDgA)
Based on [the Julia solution](https://codegolf.stackexchange.com/a/254623/114865) to the inverse problem
* -2 bytes thanks to MarcMush: replace `sum(==(' '),s)` with `count(' ',s)`
* -1 byte thanks to MarcMush: replace `count(' ',s)+1` with `sum(<('D'),s)`
[Answer]
# [R](https://www.r-project.org), ~~67~~ 65 bytes
```
\(x)as.Date(ISOdate(substr(Sys.Date()+6,1,4),12,25))-nchar(x)/4+3
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGiNNulpSVpuhY3HWM0KjQTi_VcEktSNTyD_VNAdHFpUnFJkUZwJVRcU9tMx1DHRFPH0EjHyFRTUzcvOSOxCKhR30TbGGqQbZpGQWIxULGSc0ZRZnFJbmKxko4CRKgotUBDybUsFShgbAY0RiE5PycnsaA4VcFWQUlBSVNTE2LIggUQGgA)
A function taking a string and returning a date.
* Thanks to @pajonk for saving two bytes
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 61 bytes
```
(Get-Date '25/12').AddDays(-($c-split"( )"-match"^\s").count)
```
[Try it online!](https://tio.run/##BcFLCoAgEADQq8gQpAuNhJYtgqBLRCDTgIJ9aKai09t75/HSxZFyLkVPJHYMQqr2XdP62rhhXcfwsba6QstnTgJaGbBbEIywzAzG4XHvYkqpsAeMV2LZAit6CH4 "PowerShell – Try It Online")
`$c` would need to be declared with the "Christmas eve" string in the same environment. Would output in the format of:
>
> 23 December 2023 00:00:00
>
>
>
*FYI doesn't seem to run in the browser but runs fine in ISE and PowerShell console.*
[Answer]
# [Go](https://go.dev), 108 bytes
```
import(."time";."strings")
func f(s string)Time{return Date(Now().Year(),12,25-Count(s," Eve"),0,0,0,0,UTC)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=zVLdSsMwGAXv1qf4DAwSSEvbOZGNCrLNyyFaL8SJhJHOsjUtyVd_KHsSb4bgQ_go-jSm7cCJei8hJHw53zmH8-X5ZZFv3goxX4qFhEykykmzItfokSRD8lpi4h69r9oa9QimmSRDjxjUqVoYwpykVHNIqIG2xGKLqLTEUisYC5R0mj9Q5l1JoSnjQcjDvjvKS4XUcAKTe0kY97frMh6xdav5sdfHp0JCXPOWc6xSVXD5WGxl1q1ubZgyqByUBg0MIri-iSunIqM7nRrMhCEcSOiHPTcI3bBP1nz3sZHfBRz8AvgB6v0B-q_7y3zgBk0ENr1cZwLrwOyTf-j6geuHxDmz2eJKURJFEVzEJ-cx2Fs95VzDLW8atFD2q7SBV05HzJtqQtGzI2LeacNMWwHmdNIE8uUgQq8enmW1-CHs50uooFFLKOmamYLoGLoGaNcw6OJMWdMNIa8b6rtt55aJwdra_-YTJtMxbH1uf89m056f)
Returns a `Time`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 84 bytes
```
ċ⁶“£ṠạƙƓḢỤṢ]Ẉ¬z=æ¦ŀḥØo?3€ñḥqṅẹḂḟ⁽ḟ“œ4»j “ÇyṪ⁸ȷ6Ė|6¤ƤY¢ḷ/q³ȦþỵMñ§.ṣs)~ṛßẠ»Ḳ¤ṣḢ}¹jʋƒŒV
```
[Try it online!](https://tio.run/##TY6xasJQGEZfxbVLHSpu4iAdXQWHDg6CBqVoRLBUSQRRcFMQRUFNYgrFRaX13gQd/muC@BbffZFr3BzOx/m2oxUrlZZSl6E0/6WxIBt8BW8dzsIxmAXfAbc@4A1o@5USLrmBAbYR08/0m@xuxS46NfAePA7WBVtK8/RYYxGME@RrschEvwX@K012PSYvk@8kOaGTJwvsGK/R4eqKM/y/rNjRzyu4rb90wOdiCW9FPtieogA7KmkT127DcBSMckqpTKle1hvVgh57bxafuQM "Jelly – Try It Online")
A monadic link taking a Jelly string and printing a date to STDOUT. Jelly lacks date handling, so this builds and executes a Python expression that looks like this:
```
print(__import__("datetime").date((__import__("datetime").date.today()+__import__("datetime").timedelta(7)).year,12,25)-__import__("datetime").timedelta(x))
```
where `x` is the count of spaces in the input. Most of the Jelly code is compressed strings. These are used to shorten the code along with some simple substitutions of repetitive code (`__import__("datetime").`, `date` and `timedelta(`). `__import__()` is used because Jelly doesn’t import the datetime
module itself.
[Answer]
# [Scala](http://www.scala-lang.org/), 98 bytes
Golfed version. [Try it online!](https://tio.run/##bY4xC8IwEIX3/oqjUwI1YlGHQgVRN53EQcTh1LRG2qQkZ62Kv70Gq5vDO3jfuwfPHbHA1hwu8kiwQqXhGQCcZAalNwxt7hKYWov33Zqs0vmeJ7DRiiD9fAJUnlKhWcbC2dkqRyU6WNTyp5ALMl2X@8IrAH9rLCBLWIfTyQVrFKRKKZbGD5ojSZ4CtM3fSJiM/cPa3ERVXN0c746NucglbSXaaBBH8YiLUulv1ginHrI/7MW8fbVv)
```
x=>java.time.LocalDate.of(java.time.LocalDate.now.plusDays(6).getYear,12,25).minusDays(x.size/4-2)
```
Ungolfed version. [Try it online!](https://tio.run/##TY9BS8QwEIXv/RWPPaVQIxb1UPAg1puCIB5EPIxt0s3SJiUZ6y7L/vYatrvRwxxm5n3vzYSGeppnM4zOMzY0kWQzKLl/cnFTE6sCL8ob1x6yzH1tVMN4JmOxz4BWaQyxEeS7UOHee9p9vLI3tvvMK7xZw7g7KoExTrm3QovVw9qbwAMFPE7qXKtcslvYPAIxbfHXYlvhNK@Qrkq@E/VoY5c20rofkcux/w417YK4zZOuScH/9U6LVnaK3xX5AldlgfLmj2mjR220jshW9sp2vMYlrnGB8qhJnnIw9hR5ZpZHDvP8Cw)
```
import java.time.{LocalDate, Period}
object Main {
def main(args: Array[String]): Unit = {
println(f("Christmas Eve Eve Eve").toString)
}
def f(x: String): LocalDate = {
val d = LocalDate.now().plusDays(6)
val christmas = LocalDate.of(d.getYear, 12, 25)
val daysDiff = x.length / 4 - 2
christmas.minusDays(daysDiff)
}
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 65 bytes
```
≔”8±AHF@ε✂hλ”θ≔≕⁺θ.resolutionη⁻▷θ⟦I…⭆¹⁺▷⁺θ.today⟦⟧×⁷η⁴⁺²χ²⁵⟧×№S η
```
[Try it online!](https://tio.run/##ZY6xCsIwEIZ3nyJkSiGKFcXBSYKIgyAoLuJw1mADMWmTS8Gnj1cVHVyOhPu//7uqhlB5sDkvYzQ3J/gVUKO561H/4JK1xWLw2a01HiEYuFgtdjZF0UrGR0FHbxMa73hRSFZTfheMQ7E1jjKrDmyiqi9J0ElBRKEeldWq9o3YIwG3LTSilOzV/Ef9fOiv8OBkOp1pHOjUKOa9t7dP@/HKTiQrx/SZzH4x5RPdtXFNwreS@hgv3vAiZ1UHE/EOka06PcjDzj4B "Charcoal – Try It Online") Link is to verbose version of code. Based on @NickKennedy's Jelly answer. Explanation:
```
≔”8±AHF@ε✂hλ”θ
```
Get the compressed string `datetime.date`, which prefixes all of the necessary functions.
```
≔≕⁺θ.resolutionη
```
Get the result of `datetime.date.resolution`, which is another way of saying `datetime.timedelta(1)`, but golfier because it reuses the string `datetime.date`.
```
⁻▷θ⟦I…⭆¹⁺▷⁺θ.today⟦⟧×⁷η⁴⁺²χ²⁵⟧×№S η
```
Take today's date, add on 7 days, cast to string so that the year can be extracted (Charcoal can't call instance methods), create Christmas Day in that year, then subtract a day for each space in the input string.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~103~~ 36 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ð¢žg’IO.ÃÍ Dâì.‚±(~D[ÿ-12-25],-ÿ)’.E
```
Outputs the date in `yyyy-mm-dd` format with automatically trailing `"\nok"`.
[Try it online](https://tio.run/##yy9OTMpM/f//8IZDi47uS3/UMNPTX@9w8@FeBZfDiw6v0XvUMOvQRo06l@jD@3UNjXSNTGN1dA/v1wSq03P9/985oyizuCQ3sVjBtSx1MGMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/8MbDi06ui/9UcNMT3@9w82HexVcDi86vEbvUcOsQxs16lyiD@/XNTTSNTKN1dE9vF8TqE7P9b/Of@eMosziktzEYi44S8G1LBWVh11ksOKh49JRPIpH8SgexRAMAA).
**Explanation:**
```
ð¢ # Count the amount of spaces in the (implicit) input-string
žg # Push the current year
’IO.ÃÍ Dâì.‚±(~D[ÿ-12-25],-ÿ)’
# Push dictionary string "IO.puts Date.add(~D[ÿ-12-25],-ÿ)",
# where the first `ÿ` is filled with the pushed year
# and the second `ÿ` is filled with the amount of spaces of the input
.E # Evaluate it as Elixir:
```
```
IO.puts % Print
~D[y-12-25] % Christmas Day of the given year `y` as Date-object
Date.add(...,-n) % After we went back in time the given `n` amount of days
```
[See this 05AB1E tip of mine (section *How to use the dictionary?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `’IO.ÃÍ Dâì.‚±(~D[ÿ-12-25],-ÿ)’` is `"IO.puts Date.add(~D[ÿ-12-25],-ÿ)"`.
[Answer]
# [Elixir](https://elixir-lang.org/), 110 bytes
```
fn(s)->Date.add(Date.new(Date.utc_today.year,12,25)|>elem(1),-(s|>String.graphemes|>Enum.count(& &1==" ")))end
```
Only my second or third Elixir answer, so can definitely be golfed.
[Try it online.](https://tio.run/##7ZW7CgIxEEV7v2JIIQnsBlaw3G3UwkrBD5BgJruBTSJ5@AD/fX2BnWKpkOLAZe5wmeoO9vqk/SBRGSdTj7D2rvXCgHQjAFUPytLAymYuInIhJX0Ii8enSHG3jU6KMz@j8EU1KSZTdmmwR0MrVpQ0XJpN9Nq2/Ja679DgbbKwyfCdSzbSMYyruiZAGGNo5QCwXPF9igEUp2TWeR2iEYGw0RsHFgf87H638av87@WZTCaTeTX5/cNdAQ)
**Explanation:**
```
fn(s)-> % Function with string argument and Date return-type
Date.add( % Go back in time by adding a negative amount of days:
Date.new( % Create a new {:ok,Date}-tuple:
Date.utc_today.year, % Using the current year
12,25) % And Christmas Day
|>elem(1), % Extract the Date from the ok-tuple
-( % And go back the following amount of days:
s|>String.graphemes % Convert the input-string to a list of unicode characters
|>Enum.count(& &1==" ")))end
% And then count the amount of space characters among them
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~80~~ 73 bytes
```
f=->s,a=Date.today{a.to_s=~/12-25/?a-(s.count'v'):f[s,a+1]}
require"date"
```
[Try it online!](https://tio.run/##KypNqvz/P81W165YJ9HWJbEkVa8kPyWxsjoRSMcX29bpGxrpGpnq2yfqahTrJeeX5pWol6lrWqVFA9VrG8bWchWlFpZmFqUqpQD1Kv0vKMrMK1FI00tOzMnRUHLOKMosLslNLFbS1FHiUtLBEFdILUvFJ4dX3hUoP4ixkoLCEHX5KB7Fo3gUj2JoSa75HwA "Ruby – Try It Online")
Instead of using date range I've switched to recursion.
`a.to_s=~/12-25/?` If current date matches /25-12/ then
`a-(s.count'v')` return that day minus how many 'v' in input
`:f[s,a+1]` else try next day
[Answer]
# [Lua](https://www.lua.org/), 108 bytes
```
d=os.date a=86400_,n=(...):gsub(' ',0)t=os.time()while d('%d%m',t)~='2512'do t=t+a end print(d('%x',-n*a+t))
```
[Try it online!](https://tio.run/##7cpBCsIwEADAr@ylbGJjiEVFhJzEd8jKBhtoU2m26smvR/oLDznMbYaFSmE/ZcskAcifjnvnbiZ5Za3V50de7goBjdOyLoljUPrdxyEAK2y4GdGI/nrsDrsOeQLx0hKExPCcYxK1rg@abdpQK1qXUi79HLOMlOH6ClVVVdX/@wE "Lua – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) -MPOSIX, 71 bytes
```
sub f{strftime"%Y%m%d",1..3,25-$_[0]=~s/E//g,11,(gmtime 518400+pop)[5]}
```
[Try it online!](https://tio.run/##tZRdT8IwFIbv@RUny0i3UFhbNgIzyIXxwmjERC40fgVdN4mMza0aCRl/HdsNdIjESPQsS5eec57zkbyLeTJ2Fi8ph7P@@dEFoFQkvhiFHO1V/CiBcAq64KkAowLSZiLyhtPuPmLEJpSxFsIgM0aTQN4dPCajVITDFA5fefmVQfwt5g@Ce0UqlakUZXidSTudjnR0fmTKAGVrTKLaYRtMRnZn0q1MNTuhu81Ovp2dEdaUDmcnZp76S@Zy3rJtMp1tTPsfmK3dmPZ2JqWtP9/nNiZqGChnvVHWtE280SchbdJWTHOWY5XmBlJornsSPQzHgJTqglDqTnlz3cmLO1W68BgEq0fP9Vg0lXXn1q1x7c3szFQH@zh0q2foTUxqOqtTrFPT9Ubc/GQHkYAu@AYsccVAGf6sCsvoWDpEkcCfV@Gr0TLoAYqeELiATvsD6B@jUpavya@8URfW2i4tx91EAshiblESlqt2vzR6PdFwJVukL/fgz1b/LK16WQ2rnoZpo9HEzKnrd1fkpjtPrUPLCjCl2AhCFQgObduE1OIoNq@cm2yxeAc "Perl 5 – Try It Online")
```
sub f{
strftime "%Y%m%d", #return date as eight digits YYYYMMDD
1..3, #three args for sec, min, hour, values dont matter
25-$_[0]=~s/E//g, #day of month, 25th minus the number of E's ("Eve"s)
#strftime deals with overflow into negative numbers
#in previous months and years potentially
11, #11 = December with 0=the first month January
(gmtime 518400+pop)[5] #output year found from given date pop'ed from @_ the
#input args plus 6 days (518400 sec) to account for
#the last days of the year after 25th Dec that should
#focus on Christmas the next year
}
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), with [`date`](https://dfns.dyalog.com/n_date.htm) and [`days`](https://dfns.dyalog.com/n_days.htm) dfns, 43 bytes
```
{n(⊃(n←date days)0 0 6+3↑⎕TS),12,27-⌊4÷⍨≢⍵}
```
[Try it online!](https://tio.run/##7ZC/TsMwEMZ3nsJbbdkJjh27zcKCeALYoEOklD9SUxCpkKKSCamiUYNgQNlRkdhYQN3Jm9yLhEsilj4BQ4af5Pu@83dnhzdTJ0rD6fVFHYXzCYHlM1mkIhYejxwaYxlzF1abiEH@0JT8TBLtCaoCpyr9ew/llERowDpHxxpXGcg3NvClNhxFipoyVQnFt2OlazhSlV2N1shn1bZp8ZkIoPgyiPaIltleFKZJt9Di59MGehRYTvHawVBLIyVr0tubbViXYjJslZzvo3KqxrB8obB@/FvrvVExfMzEzhvQ2J1fn3fDZxR9OsNz@0PNVkwSSSzXGA9PryfHTHhKqKGDC/nVFooPWL1hYlZjxuDw8vYqmcdhQo7uJj09PT09/5/BLw "APL (Dyalog Unicode) – Try It Online")
] |
[Question]
[
(or: Output the plural demonym.)
When in Rome, do as the Romans do. This is a well-known English phrase meaning that it’s best to follow what others are doing around you — to go with the flow. Today, you're going to rewrite the phrase to fit most (Western) place names.
To get the name of a group that lives within a region, there are a couple of cases:
* If the name ends with an ‘i’, ‘o’, or ‘u’, append ‘ans’. If the name ends with an ‘e’ or ’a’, drop it and append ’ans’.
* If the name ends with a ‘y’, replace it with an ’i’ if the preceding character is a consonant, and finally append ‘ans‘.
* If the name ends in a consonant (excluding ‘y’), append ‘ians’.
Some examples:
* “Italy” ends with a consonant followed by a ‘y’, so we replace the ‘y’ with an ‘i’ and append ‘ans’ to get “Italians”.
* “Rome” ends with an ‘e’, so we drop it and append ‘ans’ to get “Romans”.
* “Hungary” → “Hungarians”
* ”Paraguay” → “Paraguayans”.
So, your task is: Given a name starting with an uppercase letter and ending with a lowercase letter, output the name of that group of people.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code per language wins! Defaults for code-golf apply.
## Test cases:
When in Rome, do as the Romans do.
When in Transylvania, do as the Transylvanians do.
When in Code Golf, do as the Code Golfians do.
When in Hawaii, do as the Hawaiians do.
When in Sparta, do as the Spartans do.
When in America, do as the Americans do.
When in South Dakota, do as the South Dakotans do.
When in Korea, do as the Koreans do.
When in India, do as the Indians do.
(And yes, I know there are plenty of outliers, e.g. group names ending in ‘stani’, ‘ese’, ‘er’, etc. However, this formula seems to work for many English place names.)
[Answer]
# [Lexurgy](https://www.lexurgy.com/sc), ~~72~~ 65 bytes
```
y:
{y,*}=>i/!{a,e,i,o,u,y} _ $
a:
{e,a}=>ans/_ $
Else: *=>ans/_ $
```
Expects input as just the country name, and outputs the plural demonym.
Requires that spaces in the input be replaced with some non-space character due to how Lexurgy processes spaces.
* -7 bytes by @SuperStomer by using `else`
Used test cases:
```
Italy
Rome
Hungary
Paraguay
Transylvania
Code_Golf
Hawaii
Sparta
America
South_Dakota
Korea
India
Noodle
Noodly
Noodley
Ay
By
Aby
Bay
Ohio
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 40 bytes
```
{_[-~0 3'a;x],(0<a:"yeaiou"?*|x)_"ians"}
```
[Try it online!](https://ngn.codeberg.page/k#eJwljMsKwjAURPf5inA3bX1AwV0riCioiCDWnYhc2lSDba7ERFt8fLsm3Z0zM0yZvE6H4TfmowDT5jgI4zEm0AqUZGHSezfRCSSqO3wYM0kIO6oFpBz2+h+21QOVROczKgRfUFU6WeITpXSU3VAbP5jWQsvcY0bWXPgcr9RVa9LCw0oV3dtGNDInf2XVGXXrcCu0hYixfmjSMjDRD9rRN+M=)
[Answer]
# sed, 35 bytes
Using sed with extended regexes:
`s/([^aeiouy])y?$/\1i/;s/[ea]?$/ans/`
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 31 bytes
```
([^aeiouy])y?$
$1i
r`[ea]?$
ans
```
[Try it online!](https://tio.run/##DcrBCoJAEIfx@zyFBwM79gQRBSpdIruJ4Z@cbFB3Ytot9uk3j9@Pz9iLQ9oUZZ@K9g4WDbHbxn1O@U7I@pbRrQH3San2mCNddWGqghthkS4wjAGRbrYucf7CCeioA2elzk@q8IMINW@YBx0WNnmAGg3@lZ0w6YpnNQbVbhD8AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
([^aeiouy])y?$
$1i
```
Add `i`s after trailing consonants and replace consonant + `y` with consonant + `i`.
```
r`[ea]?$
ans
```
Remove any trailing `e` or `a` and append `ans`. The `r`` is needed to prevent a second empty match after removing the trailing `e` or `a`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
P←⮌SM⁼KKy←¿№aeiouKKMⅈ←«→Pi»M¬№aeKK→ans
```
[Try it online!](https://tio.run/##TY5NC4JAEIbP@SuWPc2C/QE7RocgQ@zSdZBRlxbX9kOQ6LdvkxJ5mcM77/PMND26xqJJqYwm6NHpIUBxoTbkoqaJnCc4D2MMt8CrDpRSh6y0E8HpGdF4qIgeoHIhZ8lzIbmhWwFHG9klkbSNMhdrUSmx0HfYtMl4Eq9st2yKWnf9N91tPpJacvJeL19t@Ms3Zhb@2GqlcPDMpVShwy7inPaT@QA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
P←⮌S
```
Write the input to the canvas, but with the last letter under the cursor and the first letter to the left.
```
M⁼KKy←
```
Move left if the last letter is a `y`.
```
¿№aeiouKK
```
If the (previous) letter is a vowel, then...
```
Mⅈ←
```
... move back to the last letter, otherwise...
```
«→Pi»
```
... move right and place an `i`, which either overwrites a trailing `y` or appends if there was no trailing `y`.
```
M¬№aeKK→
```
Move right unless the last letter is an `a` or an `e`.
```
ans
```
Overwrite the `a` or `e` with `ans` or append `ans` otherwise.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 33 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
žPSD'y«s„aeS)vDyÅ¿àiNi'i«ë¨]…ans«
```
[Try it online](https://tio.run/##AUEAvv9vc2FiaWX//8W@UFNEJ3nCq3PigJ5hZVMpdkR5w4XCv8OgaU5pJ2nCq8Orwqhd4oCmYW5zwqv//0NvZGUgR29sZg) or [verify all test cases](https://tio.run/##JYzBasJAEIZfZZmLCOIrBDHQSkHFiD0UD1OzmsG4I7tJZG9eim8hPZVC3qHCpr6ILxKTzWm@@Wf@jw1@kqwLeE@kEqQEBDaAgYhZoBFZItsA6vvfPAp71pXmcb6ijPr/F1OEtvpyt@qbptQjV1al@10/zj@ojCtrGK4CaDRDGNQfMMkwtY0WFnyQ7XzN1Q61j@aocZej56Vu2jYtUBG2@5hjKV443foOnpCopeiIOvMPo4PUtPEYcZ4lIsQ9d6c31tLDRMWdbZYQw/oJ).
**Explanation:**
```
žP # Push all consonants (minus "y")
S # as a list of characters
D'y« '# Duplicate it, and append an "y" to each consonant
s # Then swap so the consonant-list is at the top again
„aeS # Push pair ["a","e"]
) # Wrap all three items on the stack into a list
v # Pop and loop over this triplet of lists:
D # Duplicate the current string
# (which will be the implicit input in the first iteration)
i # If
Å¿ # the current string ends with
à # any of the items of
y # the current list of the loop:
Ni # If this is the second iteration (the 0-based index is 1):
'i« '# Append an "i" to the string
ë # Else (index is 0 or 2):
¨ # Remove the last character instead
] # Close both the if-else statement and loop
…ans« # Append string "ans"
# (after which the result is output implicitly)
```
[Answer]
# [Python](https://www.python.org), 119 bytes
-5 bytes thanks to `noodle man`.
```
lambda c,v='iouea',s='ans':(((c+'i'+s,(k:=c[:-1])+'iy'[c[-2]in v]+s)['y'==(l:=c[-1])],k+s)[l in v[3:]],c+s)[l in v[:3]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TY8xTsQwEEV7TuFuHMUpYBsUKQVaClY0iEWiCC4GJ9lYcezIcbKyVpyEJhKC03ABbsM6SbHTzJ83X-Pvz5_Ou9ro6avK3r4HVyW3f0eF7XuBRLAxA2mGEoH1GaDuIaWUihgkxD2jTZqJPE2ueXQmHnKRJzdcajLyuI9y8JBlVAVPsHDWBKpIMOSblHMmLkC64Xx9_rcylggzaGd9WObwbNoSGIEXe87g1YhaYpi3pijJ1qgqDA94RCmD2ndo3Wy4a0srxSz3ZnA1ucfGLKtHY8tZ7HSxXNs5VH6-NOgD2lk-ocXDgB54ekXO1VmpHa3gtS51yHZac36QwhDsyamiK4kCgmj50zQt_R8)
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), 96 bytes
```
x=>((p=[...x])[l=x.length-1]=`${"iou"[c="contains"](r=p[l])?r:!"ae"[c](r)?"i":""}ans`)&&p.join``
```
[Try it online!](https://tio.run/##bY89a8MwFEX3/gr1UYI0RKFrQPXSod1CpoAx@FlRZKWyJPSROpT@dlddOhSv59wL917xhklGE/I2BXNWcfLuQ92Xi1hm8UJpEC3nfO5Ya8XMrXI6j9vnTvRPX2B8gVYKkN5lNC5BR6MIre1YE/ePgKrailgDBvYA3@hSzzabwK/euL5fai95q7j1ml4oHP2kgLGHf/g9o72v8LfiNMY1c8CIuuCaevWTcUaiI0cVymCNrCGy25ETP5E0@mLPZFB/si4mQ8lEjmh/vytiEvmM3ulm@QE "JavaScript (SpiderMonkey) – Try It Online")
[Answer]
# [Python](https://python.org) >= 3.8, 173 bytes
```
import re
lambda k:any((l:=re.subn(a,b,k))[1]for a,b in map(lambda m:f'({m}ans'.split('|'),(r'\w[iou])$|\1',r'\w)[ea]$|\1',r'[aeiou]y)$|\1',r'[^aeiou])y$|\1i','$)|i')))*l[0]
```
`any` stops iterating after the first truthy result (in this case, when `subn` replaces at least 1 time)
[ATO!](https://ato.pxeger.com/run?1=PZHPTgIxEMbvPEUPJtOahcjNbIKJwYPEixFvZU0GaKGhfzallTTAk3jhondfwPfwbaS7iz19v_mmk28yH191CmtnT6fPGGT_9vdbmdr5QLzoSTIiGs18iWRTok2U6nLkxWAb55ZiMS82jPFhJZ0nZyLKEoM17X6YUgLdmyPaLQy2tVaBwgFYQT3Mdly5WLGrw2wIRWbGBVYX5Ciynf59_tZWWMoVBQVcsYMCxti15jdVF_wn51i4aINPOQuHF2cEFARe_TlE0u9oFWYeu6UgY6dlhkfcoVJZTWv0oWm4N8KrRSOnLoY1ecCNa60n50UjJnbZTpsE1KmZFO0KfSOf0eMqYoKq7JHzq72ygUrYd_mOpH9H9pJ2yI7A2i0uZ_gD) (`f =` added to run test cases)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Ṫ`, 186 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 23.25 bytes
```
÷‛aeF:\y=¨iȮ:\o+Ah¬\i*`□⟑
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyLhuapBPSIsIiIsIsO34oCbYWVGOlxceT3CqGnIrjpcXG8rQWjCrFxcaSpg4pah4p+RIiwiIiwiUm9tZVxuVHJhbnN5bHZhbmlhXG5Db2RlIEdvbGZcbkhhd2FpaVxuU3BhcnRhXG5BbWVyaWNhXG5Tb3V0aCBEYWtvdGFcbktvcmVhXG5JbmRpYVxuRWdnIl0=)
] |
[Question]
[
*Inspired by [this SO post](https://stackoverflow.com/questions/71017483/closest-subsequent-index-for-a-specified-value).*
Given a vector (first parameter), e.g.:
```
char = ["A", "B", "C", "A", "A"]
```
For each element of the vector, find the distance to the closest **subsequent** specified value (second parameter). When the element is identical to the specified value, return 0.
```
f(char, "A") -> [0 2 1 0 0]
```
**Explanation**
`f(char, "A")` returns `[0 2 1 0 0]` because `f` returns the distance to the closest following value that equals "A". The first value of `char` is "A", so as the element is equal to the desired value, return 0. For the second element, "B", the closest "A" is two positions away from it (position 4 - position 2 = 2). For the third element "C", the closest subsequent "A" is 1 position away from it.
When there are no subsequent values that match the specified value, return nothing. When the specified value is not part of the vector, the function can either return an empty vector or throw an error.
The function should work for string vectors or integer vectors.
**Tests**
```
char = ["A", "B", "C", "A", "A"]
f(char, "B") -> [1 0]
f(char, "C") -> [2 1 0]
f(char, "D") -> []
int = [1, 1, 0, 5, 2, 0, 0, 2]
f(int, 0) -> [2 1 0 2 1 0 0]
f(int, 1) -> [0 0]
f(int, 2) -> [4 3 2 1 0 2 1 0]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest code in each language wins.
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
x#(a:b)|x==a=0:x#b|y:q<-x#b=y+1:y:q
_#_=[]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/v0JZI9EqSbOmwtY20dbAqkI5qabSqtBGF8iwrdQ2tAJyuOKV422jY//nJmbm2RYUZeaVqCglKilHAwkdpSQgTgbiRChOUYr9DwA "Haskell – Try It Online")
For every element, if it equals the search value then it's `0`, if it doesn't then it is 1 greater than the next value.
[Answer]
# [R](https://www.r-project.org/), 48 bytes
*-2 bytes thanks to Giuseppe. -1 byte thanks to Dominic van Essen.*
```
\(v,x)sequence(d<-diff(c(0,which(v==x))),d-1,-1)
```
**output**
```
f(int, 0)
# [1] 2 1 0 2 1 0 0
f(int, 1)
# [1] 0 0
f(int, 2)
# [1] 4 3 2 1 0 2 1 0
f(int, 3)
# integer(0)
f(char, "A")
# [1] 0 2 1 0 0
f(char, "B")
# [1] 1 0
f(char, "C")
# [1] 2 1 0
f(char, "D")
# integer(0)
```
Works for R >= 4.1.0.
[Answer]
# [R](https://www.r-project.org/), ~~56~~ 51 bytes
*Edit: -5 bytes thanks to Giuseppe*
```
f=function(l,x)if(y<-match(x,l,0))c(y-1,f(l[-1],x))
```
[Try it online!](https://tio.run/##VVDLCoMwELz7FVt7SWCFJG1vtaD2L8SDBIKCjUUi6NfbPNQqLJNkZrOTybAsKlWjlqbtNelwoq0i8zP51EY2ZMIOGaWSzAlHRboy4ZVtoYts6gFSkCTOYoQ4d1A4yALQSBHX4zUKV0heUHJg1Z8vdl7AWXnvSmU9dA/9aL6juURRq4135Qi2GMIDQfiNLeFMbYc9nCZDQO/gZb7JR1Js5B1ucLhXedc9L18zsnUN7uED8nh9wZojOyb3s5Yf "R – Try It Online")
Works for any version of [R](https://www.r-project.org/).
For [R](https://www.r-project.org/) version ≥4.1.0, change "`function`" to "`\`" for 44 bytes.
[Answer]
# [Python](https://www.python.org), 38 bytes
```
def f(a,x):f(a[1:print(a.index(x))],x)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY31VJS0xTSNBJ1KjStgFS0oVVBUWZeiUaiXmZeSmqFRoWmZixQDqraKi2_SCFHITNPIb8gNU_DQNOKS6GkqNIqWitNQyu1LDFHIweonkshtSI5taAEapS6rq6uOtSEBTfTo9Ud1XXUnYDYGYgdwTgWRHDhkHHCKeOMU8ZFHWIfAA)
Finishes with an exception
-5 bytes thanks to AnttiP
-1 thanks to dingledooper
## [Whython](https://github.com/pxeger/whython), 40 bytes
```
def f(a,x):f(a[1:print(a.index(x))],x)?0
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728PKOyJCM_b8GCpaUlaboWNzVSUtMU0jQSdSo0rYBUtKFVQVFmXolGol5mXkpqhUaFpmYsUM7eAKpeMy2_SCFHITNPIb8gNU_DAKRLK7UsMUcjR1PTGqJXXVdXV10TomHBzfRodUd1HXUnIHYGYkcwjgURXDhknHDKOOOUcVGH2AcA)
No error
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 11 bytes
```
ṘKRṘ=vTvßhf
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZhLUuG5mD12VHbDn2hmIiwiIiwiW1wiQVwiLFwiQlwiLFwiQ1wiLFwiQVwiLFwiQVwiLFwiRFwiXVxuXCJBXCIiXQ==)
```
·πòKR·πò # Get suffixes
= # Find those that are equal
vT # Get truthy indices of each
vßh # For each, if it is truthy, get the first
f # Flatten (remove empty values)
```
Or if we can return zeroes if the required value is not at the end:
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
·πòKR·πò=∆õTh
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZhLUuG5mD3Gm1RoIiwiIiwiW1wiQVwiLFwiQlwiLFwiQ1wiLFwiQVwiLFwiQVwiXVxuXCJBXCIiXQ==)
```
·πòKR·πò # Over suffixes...
= # Check if each value is equal to the second input
∆õ # Map...
Th # Find the first index where it is equal
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~73~~ 71 bytes
```
(load library
(d F(q((L V)(filter inc(i L(c(first-index L V)(F(t L)V))(
```
[Try it online!](https://tio.run/##NYsxCoQwFER7TzHlpBCSwF4hIAQrsXeNCx9Cdo0p9PTZINgMj5l5RdIV5fjVyvhdAqK885KvjgGOO@kxK34kli1D0kqB59qKfJReUthO3A/HAq9mpVibOYwTmmxgoPGCbalhO7p70Q@YB2z9Aw "tinylisp – Try It Online")
Ports, e.g., [Dominic van Essen's answer](https://codegolf.stackexchange.com/a/242555/67312).
Uses [this tip](https://codegolf.stackexchange.com/a/242255/67312) to filter out `nil` results from `first-index`.
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), 79 bytes
```
(d I(q((L V)(i L(c(i(e(h L)V)0(a(h(I(t L)V))1))(i(a(h(I(t L)V))1)(I(t L)V)()))(
```
[Try it online!](https://tio.run/##XYw9CoAwFIN3T5Exb@sreIhCcZLuokILIopdPH0tBR1cwpcfktN@b@k6SuECx5P0CMIEz5mJKyO8BDGcGOmYmxOVOvlHH1Nq3f6GEfVSoTDoYasa2I6uNeYFfcGWBw "tinylisp – Try It Online")
Without `library` it's a little longer, but the recursion was fun to figure out (and likely still golfable somehow).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 49 bytes
```
c=>g=z=>~(r=z.indexOf(c))?[r,...g(z.slice(1))]:[]
```
[Try it online!](https://tio.run/##dVDLCoMwELz7FSGnLKTBCL20xKL23g8QDxKjTZFYVErx0F@3xlgo1cIyCTv7mJ1b/sg72ep7vzNNocZSjFKElRhE@CKtGJg2hXpeSiIBTmlLGWMVGVhXa6kIB8gOaTbKxnQ9kte8RQKlOMIU4dhCYiFykB09W9fUitVNRUoylQCxTQC/TPKXOW8z4HlOhDa91cApmsKnaE9RMH@mCFYSfCBTw2oL304HW@nvzR8H@HK1v7xOgbMk3jAiwvNkd9f4Bg "JavaScript (Node.js) – Try It Online")
Byte shorter than Arnauld and tsh
# [Python 3](https://docs.python.org/3/), ~~51~~ 49 bytes
1 byte from AnttiP
```
f=lambda a,k:a*(k in a)and[a.index(k)]+f(a[1:],k)
```
[Try it online!](https://tio.run/##bY/RCoMgFIbvfYqDN2mTkcZugi6qvYV4cUaLhZuL0cX29M7cxoqC83vkA/8Ph9d4ubvc@6684u3UIqCwBabMQu8AObpW47537fnJLDe7jqGWhRGWe5RQgk6qRCR1SBNSxRhChkfvRtYxnaI0AgLkfAXrLdhsweMfckJQTWIpIEwm4CBAxUsYtXSr8Dhb9k1IrpEKaGbIvwZa0dgb98dCaxoPM6/If5/0bw "Python 3 – Try It Online")
[Answer]
# Ruby 2.7.4, ~~56~~ 54 bytes
```
->(a,l){a.filter_map.with_index{|_,i|a[i..].index(l)}}
```
Filter maps over the array and finds the index of the target offset from the current index.
[Try it on Replit!](https://replit.com/@jackHedaya/Code-Golf-1#main.rb)
Excited to have gotten my first Golf!
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 62 bytes
```
lambda n,k:[n[i:].index(k)for i in range(len(n))if k in n[i:]]
```
[Try it online!](https://tio.run/##bY/BCoJAEIbvPcWwF3dhiTSCEDyoXXoG87Cl5qKNsniop7fZzcJEmH9n@Jj9f6Z/DXWH@2Nvxiq6jK16XAsFKJsww0yH@VZjUT55I6rOgAaNYBTeS96WyFEIXUFjodvNx1utDESQebEnvYSUkmKnfLPpjcaBV9xuSSAmxJIlKyxdYSfLJkjDGQcb60ug2kk4SAjcQBXMkmmP2MzOAX8Jgj9zat@7yJ3FzNm6/glhCXNP/nOZvkxHjm8 "Python 3.8 (pre-release) – Try It Online")
Pretty straightforward: for each index `i`, find the index of the list starting at index `i` of `k` (second argument) and add it to the output if `k` is in fact in the list starting at index `i`.
[Answer]
# [Factor](https://factorcode.org/), 56 bytes
```
[ indices -1 prefix differences [ 0 (a,b] ] map concat ]
```
[Try it online!](https://tio.run/##jVGxCsIwFNz7FY9MDlpawUVBsAri4iJOpUNMEw1qWpMnKNJvry@t0q2a8C6X3IU8LooLLGy932226ylw5wrh4CytkRdw8naXRkjXsVA@0HIHV46n0CFH7VCLz95ycyRzaSXis7TaIMyC4BUAjRewhHlcsIaxJWs5VQXV17P8w7P67YmoYpoRTGBMGBF2atyrjntV/47X/Ro16D1NJ0nbQVWnoE2ufW6j2Keh9ANyrZS0bZop3Rjw4SGDjIIrQRRGcISsVu0HzP1hWL8B "Factor – Try It Online")
## Explanation
Takes input as `element sequence`.
```
! 0 { 1 1 0 5 2 0 0 2 }
indices ! V{ 2 5 6 }
-1 prefix ! V{ -1 2 5 6 }
differences ! { 3 3 1 }
[ 0 (a,b] ] map ! { { 2 1 0 } { 2 1 0 } { 0 } }
concat ! { 2 1 0 2 1 0 0 }
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
iÐƤ¹Ƈ
```
[Try it online!](https://tio.run/##y0rNyan8/z/z8IRjSw7tPNb@P9pQx0jHWMcQCE1iDy83/A8A "Jelly – Try It Online")
Returns values 1-indexed. Tack on a `’` for 0-indexed values. Port of my Vyxal answer.
```
ÐƤ Map over the suffixes...
i Find the first index of the other value in each
¹Ƈ Filter out zeroes
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 18 bytes[SBCS](https://github.com/mlochbaum/BQN/blob/master/commentary/sbcs.bqn)
```
{‚àæ‚åΩ‚àò‚Üאַ+`‚ź1+/ùﮂä∏‚â°¬®ùï©}
```
[Run online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAge+KIvuKMveKImOKGlcKoK2DigbwxKy/wnZWo4oq44omhwqjwnZWpfQoKYyDihpAg4p+oIkEiLCAiQiIsICJDIiwgIkEiLCAiQSLin6kKaSDihpAg4p+oMSwgMSwgMCwgNSwgMiwgMCwgMCwgMuKfqQppYyDihpAg4p+oMSwgIkEiLCAwLCAiQSIsIDIsIDAsICJCIiwgIkIi4p+pCgriiJjigL8x4qWK4p+oCiJCIiBGIGMsICJDIiBGIGMsICJEIiBGIGMKMCBGIGksIDEgRiBpLCAyIEYgaQoiQSIgRiBpYwrin6k=)
`ùﮂä∏‚â°¬®ùï©` binary mask with 1's where the left argument appears in the right.
`1+/` 1-based indices.
`+`⁼` differences between adjacent indices with the first value staying.
`⌽∘↕¨` reversed range for each difference.
`‚àæ` join into a single list.
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 32 bytes [SBCS](https://github.com/abrudz/SBCS)
```
{∊(⍳≢⍵)(×∘≢⍴|)⍤(-⊢⍤⌿⍨0≥-)¨⊂⍸⍺=⍵}
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=q37U0aXxqHfzo85Fj3q3amocnv6oYwaYs6VG81HvEg3dR11AzpJHPfsf9a4weNS5VFfz0IpHXU2Penc86t1lC9RUCwA&f=S85ILFJ41DZBQd3RydnRUZ1Lw1DBQFPDSAFEPepdo/Coc6GCupOzi7pC2qEVCo@6mpKBOri4MvNKwNoMQQoVTBWMgKSBghEXRKcChAQaBCZMFIwVkMQ1wYYaAJlGMEOBxoHNTIY5xxDoIHWgGhAJMlvdSR2EuQzB@gwgzgLKpSlAdQEA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
or
# [APL(Dyalog Unicode)](https://dyalog.com), 32 bytes [SBCS](https://github.com/abrudz/SBCS)
```
(∊⍳∘≢⍤⊢(×∘≢⍴|)⍤(-⊢⍤⌿⍨0≥-)¨⊂∘⍸⍤=)
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=03jU0fWod/OjjhmPOhc96l3yqGuRxuHpMO6WGk2gmIYuUBQk17P/Ue8Kg0edS3U1D6141NUEUta7AyhjqwkA&f=S85ILFJ41DZBQd3RydnRUZ1Lw1DBQFPDSAFEPepdo/Coc6GCupOzi7pC2qEVCo@6mpKBOri4MvNKwNoMQQoVTBWMgKSBghEXRKcChAQaBCZMFIwVkMQ1wYYaAJlGMEOBxoHNTIY5xxDoIHWgGhAJMlvdSR2EuQzB@gwgzgLKpSlAdQEA&i=AwA&r=tryapl&l=apl-dyalog&m=dfn&n=f)
Equivalent submissions, first one is a dfn and second one is tacit.
[Answer]
# JavaScript (ES10), 50 bytes
Expects `(list)(value)`.
```
a=>v=>a.flatMap((_,i)=>~(j=a.indexOf(v,i))?j-i:[])
```
[Try it online!](https://tio.run/##fVBLCoMwFNx7ipBVAqmo0E1LLGq3pQcQKcFPG5FENEhXvXqaGLuptvCYhJmBN/NaNrGxHHivdkJWtW6oZjSeaMz8pmPqwnqEboRjGr9QS5nPRVU/rw2aDIdP7Y4f8gLrUopRgfLBBkBBDhNIAEwtZBYSB8XRsz7Z1X4n76hB1o@RMWK8rWQ/lfO3gj3PheBC2QwhAWYCAvYERPPHTLSKYNwYBastMx1u09GfzZ8LhEvrYHldAneSFG6lWHolppd@Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 8 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.sRIδk®K
```
[Try it online](https://tio.run/##yy9OTMpM/f9frzjI89yW7EPrvP//j1ZyVNJRUHICEc4gwhFCxHI5AgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V@m5JNZXGKloGRf6RKqU3l4lbrLoVVl6gr2lfZKCo/aJoEkIv7rFQcVn9uSfWid93@d2kPb7P9HRys5KukoOQGxMxA7gnGsTrShjqGOgY6pjhGQNNAxAouAZA3AJEgUrMdJKTYWAA).
**Explanation:**
```
.s # Get the suffixes of the first (implicit) input-list
R # Reverse it
δ # Map over each inner suffix:
I k # Get the (first) 0-based index of the second input
# (or -1 if it isn't present)
®K # Remove all -1s
# (after which the result is output implicitly)
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
Min[p=p-1/.-1->{}]&~Array~Max[0,p=Position@##]&
```
[Try it online!](https://tio.run/##fYuxDoMgFEV3v6KRhOlhgaSjBrWriTthIE1NGURjGdoQ/HVKmKvDOcM9ubN2r@esnXnoONVxMFau9UrYtSKMND4ovLfbpr/7oD@SwlqPy9s4s1iBkMJx3Ix10iMUSDNJxAEphYUQvvBlW0JW2SX6RJsJAVLszmJ/Fu/HsfAULp4BAwo34MkUeH6xg53/24sQfw "Wolfram Language (Mathematica) – Try It Online")
Input `[vector, value]`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 52 bytes
```
a=>v=>a.map((u,i)=>a.indexOf(v,i)-i).filter(x=>x>=0)
```
[Try it online!](https://tio.run/##dZDRCoMgFIbvewrxJgWLNHapUO1@DzC6kMrhaBnVord35rrZKji/@n8Hzn/wKWc5VoPup6gzdWMVt5KLmQsZv2SP0JtovBrd1c1yU2h2PtI4VrqdmgEtXCyCJ9hKCji4h1lIwtypcMq8yiCoTDeatolb80AKSYqR4xgf8fyEFyf8uvKfhrOSrbtQAlwlBFwIYP7hiu3XYRgl@@GO0kPKjgLTLRBm0Mf4@xsKc@iP8n9Wun2D/QA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
IΦEθ⌕✂θκLθ¹η⊕ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zpyS1SMM3sUCjUEfBLTMvRSM4JzM5FcTL1lHwSc1LL8nQKNTUUTAE4gxNIOGZl1yUmpuaV5KaopGpCQTW//9HRxvqKCg5KukoGEBpIwjTSQlMxIJFY//rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input array
E Map over elements
‚åï Find index of
η Value to match in
θ Input array
‚úÇ Sliced from
κ Current index to
θ Input array
L Length
¬π Step literal integer `1`
Φ Filtered where
ι Current value
‚äï Is not -1
I Cast to string
Implicitly print
```
Slicing arrays is very awkward in Charcoal but it's the same length as filtering (`IΦEθ⌕Φ謋μκη⊕ι`).
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 13 bytes
```
iSjqFi_+m[:+.
```
[Try it online!](https://tio.run/##SyotykktLixN/Z@TV62ka6dkba0bW5D6PzM4q9AtM147N9pKW@9/bW50Qdz/anWnWoVqdUcFdScFdWcFEMOxVkHXTqHaUMGglqta3RmHtJECVIELDgVAOYNakDFAdQqmCkZA0kDBCEmzAoQEGWKISyFE2giXtImCsQKSWSDnOILVAt1hACJAqkEuc4L7CawOAA "Burlesque – Try It Online")
Takes input as value as a list and the list of search, i.e. `{1} {1 2 3}`. The filter works because the `+.` increment operation works as: `-1+. -> 0`, `0+. -> 1`, `1+. -> 2...` and `0` is falsy.
```
iS # Generate all tails
j # Swap stack
qFi # Quoted Find index (returns -1 on fail)
_+ # Append to value (making {value Fi})
m[ # Map block as function
:+. # Filter for not -1
```
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
```
lambda a,k:[[a.index(k),a.pop(0)][0]for i in[*a]if k in a]
```
[Try it online!](https://tio.run/##bY/BCoMwEETvfsWSi6YEMZFeCh7U/kWawxYbGmw1iIf26@2aWqgo7GSHBztD/Hu8910@2eIyPfB5bRBQtCetMXVdc3slLReY@t4nGTc6M7YfwIHr9AGNs9CSBTQTSihAx2Us4opUk8ogE0V@cN2Y2IROpBFAkPMNrPZgvQfPM1woGVRzsxRAkwk4ClDB0Kh1uaLrbB04I7lFat2QLw2sZCE37G8Lq1h4zH9E/vvl9AE "Python 3 – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 48 bytes
```
x\y=[(:).(diff([0;findall(x.==y)]).-1,-1,0)...;]
```
[Try it online!](https://tio.run/##XY/BasMwDIbveQrhkw2asdPtsuJBur6Fm0NoY@bhhZJmI336VIpdug2E4nz69Uv6/E6xs/OyzIer8/JVaXmKIUhvtiEOpy4lOWvnrqpV@skihVFa6227BJniZcI49V/Yz2cc@4tjcmCi3HmMw5QG@VAp90YaBAEgEH76o6Q2Bc4BYVVVx49uBAdeNFQWO07vnJqc2ipIlpSat2Ba9WAs9TX8o3umBCpahr0tAoVBeEGo1wdFzdYkWH@yB@ScvdYStfk/gNr9M2zgl74Muh9iy/KmfPPAfNlOlKFl0aaclG2WGw "Julia 1.0 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 81 bytes
```
j;i;f(a,n,h)int*a;{for(j=i=0;i<n&j<n;a[i++]=j-i)for(j=i;j<n&&a[j]-h;++j);i-=j/n;}
```
[Try it online!](https://tio.run/##nVTbjpswEH3frxghBWEwWha6D1uH9qHqVxC0QgQWs40TBaRGjfj10sE2BkJWWhUBvpzjmXOGEbn/lud9XzPOSiejglaEi9bN2LU8np065nHA@FbY9VawLOGel8a1z4kGGW7bdpbUqV8xz6sJ435cPwrW9RgFDhkXDoHrA@A1bLRF0z4lKcRwfaKAd0DhmUIoJ3iHHTO88JO86JO810oRA0lEZKHqVSi04X@KY@lIoeRRr1y1pDBDwyUaLtFoiUZkSufKfI1KJwNT5VcN0UxYcTkVeVvsdcnC0aKZBNrfSAyNxVtEV@kLhWh2Xk8U1zVkxTXZ6RR/mt7TeVNEE2AqxrRlymVir1nhmhWtWaa4@VE0LeRVdnbxXeTvxVnpsXaXn@Hu8vIDn2eLwnwdWfo0tjQ4gxsu9sUFjwVMT7e3ItYaCAPPk2wig6mWn744hlNfXXJSNodBaBTLdw@uRrhawZNmrRe1CimFGM5wnc5IKh1r02z26J9/H4rw1UpwaBOekmXCBoNhG8ufAVsaKRAyXXJP7GFG@MDPKWuGDPjEcJigUWNKYbMH/xuguHn@e14b5XVWbhlJJZCDbUOBDodcg1P2n2Xp1jJh0@wEMsdOG9KNR7qHrv@bl7@yt6b3f/8D "C (gcc) – Try It Online")
Inputs a pointer to an array of integers, its length (because pointers in C carry no length info), and a target value.
Returns the length of the the array of distances to the closest subsequent target and that array is returned in the input array.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 51 bytes
```
f(a,b)=[l[1]-i|i<-[1..#a],l=[j|j<-[i..#a],a[j]==b]]
```
[Try it online!](https://tio.run/##bU1BCsIwELz3Fct6SWBT2oI3I1T9RdjDVqimFAnFi9C/x6TBiwrLsDPDzARZvLmFGEclNGjrZtey8as/GNfW9U6YZuumdUrcFy5uYmsH5ni9ywIWHPZIgKcM5wx9Aa4khPmlBMwRwuIfT4WjyqFkgwDqbCB8NNGafssuyLqqUjgvtQTpGoI9Qbc96br/QznyPVS0MtRsXR3r@AY "Pari/GP – Try It Online")
---
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 53 bytes
```
f(a,b)=s=t=0;r=Vecrev;r([s=!d*s++|c<-r(a),t+=d=c==b])
```
[Try it online!](https://tio.run/##bU/RCoJAEHz3K7Z7us0VTOjJNrD6hl7Eh/XUEiKOU4Kgf7c7pZcKhmGZYWZYK65PLnaaOi1UIw88cpo7PrfGtY/c6XLgVbMe4vhldonTgjTG3LBhriuczFUcMJSqUATqEOgYqFioisTa21MLJHuwrr@PWnU6hLwNAgqDoeCjCSL9lp1UhVHkw2FpQ@CREmwJsvnwyP4Phcj30KItQ@nclfk/3g "Pari/GP – Try It Online")
] |
[Question]
[
This is similar in concept to [this challenge,](https://codegolf.stackexchange.com/questions/12851/game-of-set-puzzle) but that is pretty restrictive on input and output and I think opening up these restrictions would lead to a completely different set of solutions that would be interesting in their own right.
---
## Background
*[Set](https://en.wikipedia.org/wiki/Set_(card_game))* is a card game in which players compete to construct sets of three cards from a collection based on certain rules. Each card has four attributes: number, shape, color, and pattern. For a set to be valid, the cards must all either match or differ in each of the attributes.
For example, three cards being 1 empty green diamond, 1 shaded red diamond, and 1 filled purple diamond would constitute a Set. An example of a non-set is 1 empty green diamond, 2 shaded red diamonds, and 3 filled green diamonds. This is not a valid Set because while the numbers are different, patterns different, and shape the same, two of them share a color that the third does not.
## The Challenge
Your job is to write a function that takes a list of twelve cards as a parameter and outputs the number of valid Sets. The cards must consist of a collection of four values, each representing an attribute on the card. Each attribute may have its own set of values to represent the different states, but there are only three states, and your choice of representation must be consistent across cards and inputs. This is Code Golf, so the shortest solution wins.
## Test Cases
In my test cases, cards are represented by a 4-tuple with each attribute being encoded by a number 0-2. The first column is the expected output, and the second column is the input.
```
0 | (0, 2, 1, 1), (0, 0, 0, 2), (0, 1, 0, 0), (1, 2, 1, 0), (1, 1, 2, 2), (0, 1, 2, 1), (0, 1, 1, 0), (1, 0, 2, 0), (1, 1, 0, 1), (2, 2, 0, 1), (1, 0, 2, 1), (2, 1, 1, 2)
1 | (0, 2, 0, 2), (0, 2, 0, 0), (2, 2, 2, 1), (2, 0, 0, 0), (1, 0, 2, 2), (2, 1, 2, 2), (0, 1, 2, 1), (2, 0, 1, 1), (1, 0, 1, 1), (1, 2, 2, 1), (0, 1, 2, 2), (2, 1, 0, 2)
2 | (2, 0, 1, 0), (1, 0, 1, 1), (0, 1, 0, 0), (2, 0, 1, 2), (2, 0, 0, 1), (2, 2, 2, 0), (0, 1, 2, 2), (1, 1, 0, 0), (0, 2, 2, 2), (1, 1, 1, 1), (0, 1, 0, 2), (0, 1, 0, 1)
3 | (2, 1, 0, 2), (1, 0, 2, 1), (2, 2, 1, 1), (2, 0, 1, 2), (1, 2, 1, 1), (1, 2, 2, 2), (0, 0, 1, 2), (0, 0, 2, 1), (2, 0, 0, 0), (2, 1, 2, 0), (0, 2, 2, 0), (0, 0, 1, 0)
4 | (1, 0, 1, 0), (2, 2, 0, 1), (2, 0, 1, 2), (0, 0, 2, 1), (1, 2, 0, 1), (2, 2, 1, 0), (2, 0, 2, 1), (1, 1, 0, 2), (2, 1, 0, 2), (0, 1, 2, 2), (1, 2, 2, 0), (1, 0, 1, 2)
5 | (2, 2, 1, 0), (1, 2, 1, 0), (2, 0, 0, 0), (0, 0, 1, 2), (0, 0, 0, 2), (0, 1, 2, 0), (0, 2, 0, 1), (2, 2, 2, 0), (1, 2, 1, 2), (0, 1, 1, 0), (2, 0, 1, 0), (2, 1, 2, 1)
6 | (2, 1, 1, 0), (0, 1, 0, 1), (1, 1, 0, 2), (0, 0, 2, 2), (1, 0, 2, 0), (2, 1, 0, 0), (2, 2, 2, 2), (2, 0, 1, 1), (1, 0, 2, 1), (2, 2, 0, 1), (2, 2, 1, 2), (0, 1, 0, 0)
7 | (1, 0, 1, 0), (1, 1, 0, 0), (2, 1, 2, 0), (2, 0, 1, 1), (0, 0, 2, 0), (0, 2, 1, 1), (0, 1, 1, 0), (0, 0, 1, 2), (1, 0, 0, 2), (0, 2, 2, 1), (1, 0, 2, 2), (0, 0, 0, 1)
8 | (1, 2, 0, 1), (2, 2, 2, 1), (1, 2, 2, 0), (0, 1, 2, 2), (1, 1, 0, 1), (0, 0, 1, 1), (0, 2, 2, 0), (2, 0, 2, 1), (2, 1, 0, 2), (0, 1, 0, 0), (1, 2, 1, 2), (2, 0, 0, 2)
9 | (0, 2, 2, 1), (0, 1, 0, 0), (2, 1, 1, 0), (2, 0, 1, 0), (2, 0, 0, 2), (2, 1, 2, 1), (2, 2, 1, 0), (0, 2, 1, 1), (1, 2, 0, 2), (0, 0, 1, 0), (0, 1, 0, 2), (1, 1, 1, 0)
10 | (0, 1, 2, 0), (1, 1, 2, 0), (1, 0, 1, 2), (2, 0, 2, 0), (1, 1, 1, 2), (1, 2, 1, 2), (0, 2, 2, 0), (1, 1, 0, 1), (2, 0, 0, 1), (2, 1, 0, 1), (0, 0, 0, 1), (2, 2, 1, 2)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
œc3S€3ḍẠ€S
```
[Try it online!](https://tio.run/##hVU7TsNAEO1zCpdEcvHm5SgpI1eIBuUCtDRUVFyAA3AARIs4SLiIcbLe9b7ZsZEs2eMdz7z5vOfHh/P5aRx/3u4Px9/nj8Pl8/Xy9T49Hcfvl@k2jqfd6Q59x76z6dr33dVKF2fL0ourZdkzW@lF5ckliolnSlJ9h9mT6WC2imc@m5Psh74grbBxwZbiVF9CcGNByg3cMxRBU1n0FWpMFKQlDto42tPiScFtUhPajCZRkD2rsyafTtQK0uq06X@1GYrU5MwkP8QTPiakepMKtd7cwxtSk57q3nAjo3lPShT1rHrBoG@U6unnu0xfedJkhK@Ra9zT3sSbUTKw5R591/K2V9M32TCE3YBwSBlNv9EUZjSMYsh9BlVgZfrmM5qggdcz7aKFKgW/3/BaQ1@FTs0K0mhS1u7NCqNN0FjLDAYq@Y9iq7qInnJNl7a2CJ4nDPmFQCXgVQKtStmSPSM1/wcJ2Ff3BhKHIU@48VdSHW4mE2ztsBv@AA "Jelly – Try It Online")
### How it works
```
œc3S€3ḍẠ€S Main link. Input: a list of 4-tuples of 0,1,2
œc3 3-card combinations
S€3ḍẠ€ For each combination,
S€ Sum all the cards' values for each attribute
3ḍ Test if each sum is divisible by 3
Ạ€ Test if all of them are true
S Sum the boolean array (count the valid Sets)
```
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
Zœc€3§3ḍPS
```
[Try it online!](https://tio.run/##hVU7TsNQEOxzCpdEcjE7uQgSHZErRINyAdo0qag4BA0HoAZxELiIk/D8nt/sWxvJzXrXu7OfGT89Hg7P43j//frwe3zffb7tfj5ebu/Gr9PFHMf9Zn@DvmPf2eXZ9t3VSg8ny9KLq2U5MlvpRRXJOYtJZCpSfYcpkskxWSUy@6Yi26EvSCtsnLGlPNWXENyYkXIF9wRF0FQWfYeaEwVpyYM2j860RFJwm/SEtqJJFuTIytfU041aQVp5m/lXl6FITXwm9SGR8Dkh3Zt0qP3mGf4hNZmp3g1XKpqPpGTRyGoWDOZG6Z5@v/P2lSdNRfgeucQ9nU18GaUCW@7RTy1fe7V9kwtDOA0Ih5TR9BdNYUbDKIbcZ9AFFrZvvqIJGng90ylaqFLw9w2vNfRd6NasII02Ze3dLDDaBI21zGCgkv8otqqL6CmXdGntiuB5wpBfCFQCXiXQqpTN1TNS83@QgH31bCB5GPKEK38l1eFmM8HVDpvhDA "Jelly – Try It Online")
Alternative solution, which can make a 9 by omitting the leading `Z` if taking the input transposed is allowed.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~27~~ 25 bytes
```
{-2+-6!+/*/~+3!+/x@!3#12}
```
[Try it online!](https://ngn.bitbucket.io/k#eJzVVctOw0AMvO9XpOoBSraq7SIOPfEF/ESkfEEOSAi+nZR9xGObcEaKVDnr2uPx7GS+fZxlPL8cxsvT5Wu8rr/vr4frkeUzpWW60dvwfHykPEgeeH1OebhH5ZEacXlxj7hltqi8UJmyVWHILE3U/6hmSjmoUc9sZ7XJKc3DMv2Azv8J9Yp3mTJAViBlA1kKqhIEA9AGWXYGqJgAlorEjoo1yUPuBckXRJZ7psAADMORb81QhVqmOnP9cMfsIas0txolGoTMcMYAhCCTbE0CGhhGxcEbmQiZgWXUluy0ZpspUAUzFSkSMClAg1J96+5YxkvlWpOdWg3gWiu2YtH0Dup/2I/tBmJhcNYqpJCfzjJKiIA7vLYCQGJXiHZl/WpPGGxbM8DCq0mWV7xGHG6H7XaUY6AL9T1aliNNol7/8AEGWAxAAmVHWnbOj54U+zI6I7L8q9IUW0p37jLiBjpF6C0oSzRAKwy8OGwj58SY6SxPPMvue4d+7nYVKDul+WH9an8D+nhxWQ==)
*-2 bytes thanks to @ngn*
K doesn't have a built-in for combinations. This code uses simple Cartesian 3rd power instead. If you count the number of sets the same way, you get 12 plus 6 times the desired answer (for 12 self-triples and 6 different permutations for each valid Set). Then just divide by 6 and subtract 2.
[Answer]
# ARM T32 machine code, 48 bytes
```
b570 0084 2000 e00f 590a 594b 18d2 598b
18d2 230b 435a f012 3f0c bf08 3001 3e04
d5f2 3d04 1f2e d5ef 3c04 1f25 d8fa bd70
```
Following the [AAPCS](https://github.com/ARM-software/abi-aa/blob/2bcab1e3b22d55170c563c3c7940134089176746/aapcs32/aapcs32.rst), this takes the number of cards in r0 ([permitted here](https://codegolf.meta.stackexchange.com/a/13262/104752); this can handle an arbitrary number of cards), and in r1 the address of the cards as an *array* of size-4 *array*s of 8-bit integers, and returns the result in r0.
Assembly:
```
.section .text
.syntax unified
.global countsets
.thumb_func
countsets:
push {r4,r5,r6,lr} @ Save some registers and LR to the stack
lsls r4,r0,#2 @ First card selector is 4 times number of cards: this is done because narrow LDR can only use for the address the sum of two registers, while only the wide version can have one of the registers shifted
movs r0,#0 @ Initialise count to 0
b start
loop:
ldr r2,[r1,r4]
ldr r3,[r1,r5]
adds r2,r3
ldr r3,[r1,r6]
adds r2,r3 @ Add up the cards
movs r3,#11
muls r2,r3,r2 @ Multiply by 11
tst.w r2,#0x0C0C0C0C @ AND with this constant...
it eq
addeq r0,#1 @ and increment count if the result is 0
subs r6,#4 @ Decrease third card selector
bpl loop @ Repeat if still nonnegative
subs r5,#4 @ Decrease second card selector
middle:
subs r6,r5,#4 @ Third card selector goes to below second card selector
bpl loop @ Repeat if that's nonnegative
start:
subs r4,#4 @ Decrease first card selector
subs r5,r4,#4 @ Second card selector goes to below first card selector
bhi middle @ Jump if that's positive
pop {r4,r5,r6,pc} @ Restore saved registers and return
```
This uses three nested loops to iterate over all combinations of three cards. For each combination, it adds the cards up (as 32-bit integers, but the four parts don't interact) and multiplies by 11. The possible results of that are as follows, in binary:
```
0 -> 00000000
1 -> 00001011
2 -> 00010110
3 -> 00100001
4 -> 00101100
5 -> 00110111
6 -> 01000010
-------------
AND: 00001100
```
As 11 is a bit more than 32/3, the result's bottom bits form a low number when the sum is a multiple of 3, and a higher number otherwise. Taking the bitwise AND (`tst`) with an immediate value with each byte being `0C` then yields zero if and only if all four sums are multiples of 3, which means that it is a set.
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 91 bytes
Outputs `False` for `0`.
Python has a builtin called `itertools.combinations` to get all of the triplets, but it's shorter just to implement it from scratch.
```
f=lambda a,*v:a and f(t:=a[1:],*v,a[0])+f(t,*v)or len(v)==3*all(sum(y)%3<1for y in zip(*v))
```
[Try it online!](https://tio.run/##hVXRTuswDH3PV@QFkXArZHvAhen2SxAPRWyiUtdVoxsa4t93Q9tsOUk2pEqVY9c@do5Pu33/vm5nj93mcFiWTbV6fat0Vdzs5u7Vvuml6edl9czzF3dWVM/0Yv@4M2fY9UY3i9bsbFnObqqmMR/bldnbq9k/XjrfXtet/qo740Lt4fO9bhaa50qvt31XOF@nS72qOrPYVc1gb3tjbz@6pu7N9fe1tUp3m7rtzdI4p0tBWn9rQ4WWQrN7bDFY4yOTxePBj8U@0lvjQRAppywMkWOR4DuaImV0TNYx0vumIlZxgDVAJyd0Y6bgWwLkdMIqF5BPYABPYEncI@YckCkZsB4zUZoJ53qMFEDO0BWlNRmykI8MfEk9vFW2auaxBv7kFgJ@IFYGHwMCgkiKcxL0z9AjduynqO4GrAxzRf7IhZocRwpkwchgGpKZnUD/Et@x48C9nytuTFKT4j7l3BbifPL8OFaQdAslnptnvXoIOMDANMpOhGCbcLslZrbAjiS7JVkdkEwfQ071N8MBjmsy4KFY3XCSnNUsinlOse5I3AfenJvro8eauy9O@XNmuxnwcLojklHNXxQclcbx9SnQVzmnUpfYRPHGSHbTKKMYFCsGpZrFp@qKacLK8V8ls4nhfAgySXZj5MKfCnU5uZ0Me/8D "Python 3.8 (pre-release) – Try It Online")
### [Python 3](https://docs.python.org/3/), 94 bytes
```
lambda a:sum(all(sum(y)%3<1for y in zip(*x))for x in combinations(a,3))
from itertools import*
```
[Try it online!](https://tio.run/##hVXbTsMwDH3PV@QFLUEVsj3ugj/hpYNNi9Q2VZcBQ/z76Npmi5NsSJUqx6597Byftju3ts18v3p921dlvfgoZfm82daqrCp1eO/01fwFV7aTO2ka@WNadf2t9eHg@3DwbuuFaUpnbLNRZTHXWqw6W0vjlp2zttpIU7e2c9f7r7WplhKfhbRb1xb9x618lXXZquVnWQ321il9s2kr49Tsd9ankm1nGqdWqndqvQcpf6WCQlIhsX90MVjjQ5OF48HBQh/prfEgiKRTFmSRY5HgO5giaXRM1jHS@6YiWmCANUBHJ3RjpuBbYMjhhJUuIJ/AMDyBRXGPPOeATNCA9ZgJ0kx8rsdIYsiRdQVpTWRZwEcGvqQev1XUYu6xBv7kFgJ@cKzIfMgQAIuEOCew/pH1yDv2UxS3A1Zkc@X8oQs1MY4kloVHBtOgzOyI9U/xHfccuPNz5RuT1IS4Tzq3hXw@eX4cK1C6hRTPzbNe3AccQMY0yE4E2Dbx7aaY2cR2JNktyuoAZfoYcoqHDAcwrokMD8TqxieJWc2CmOcQ6w7FffCb6@f66LHm7gtT/pzZbmR4MN0RyqjmPwrOlabn61Ogr3ROpS6xCeKNoeymQUYxIFYMSDULT9UFwoQV479KZhPD@QDLRNmNoQt/Kq7Lye1k2PsH "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~84~~ 81 bytes
```
lambda a:sum({*map(sum,zip(x,y,z))}<={0,3,6}for x in a for y in a for z in a)/6-2
```
Incorporating ideas from the answers of @dingledooper and @Bubbler
[Try it online!](https://tio.run/##hVXbTsMwDH3PV@SNBgWwPRgXsT/hpYhNq7RLNTpgY/v20bXNmpNkQ@pDXLv2sXN8Wm6q6XIxOExGb4dZPn//yHX@8rmeZ7/X87zM6pPdFmX2Yzd2a8z@dfRLdmCH@8lypX90sdC5Ph43/XHbHM3d8EYO39NiNtb8ovRyXZW29pR6pI@Jx1/5rLHXVWZuP8tZUWVXuytjlC5XxaLKJlntNOZAWu90RlaL1Vw/xjZW@0hncfviaLGLdFb7wouUPgtDZFvE@466SGkdnXWKdL6uiFHsYfXQSY@uzeR9S4CceqxyAXkHBvB4loQ9Ys4GmZIG6ykTxZlwrqdIAeQMXVFckyELuUjPF9XDW2WjBg6r549uweMHYmXwMSAgiKQwJ0H/DD1ix26K6r7ByjBX5I9cqMlhpEAWjPSmIYnZCfQv4R3XHHhwc8WNiWpS2Kec20KcT5ofpwoSb6GEc3OsV0OPAwxMo@RECLYJt1tCZgvsSLRbktQBSfTR5FSPCQ5wWJMBD4XqhpPkpGZRyHMKdUfCPvDm6rk@Oayp@@KYP2e2mwEPxzsiCdX8R8FRaWq@Pnv6KudU6hKbKNwYSW4aJRSDQsWgWLO4r66YOqwc/lUSm@jPhyCTJDdGLvypUJej20mw9w8 "Python 3 – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 48 41 bytes
```
1#.](0=1#.3|1#.|:)@#~2(#~3=1#.])@#:@i.@^#
```
[Try it online!](https://tio.run/##ZVE9C4MwEN39FUctaMDK3bVTQBAKnTp1t0up1C5dOnQQ/7qNJtFcJCS5dx/vXi7vcVdmLVQaMigAQZt9KOF8u15GSssmx8pcx94cvVZ1OnCeDsfJ1xik666s7@mokufj9YEWiOEEe2DDQsv2Fjo/z7e3QptcHroIuWXrF9aoW84FkBFfAKsCcmca34TYmivCGfnMIGYRuxiKTIw5rQMdsqXoMlkgy4IqiVWjqKMYBd3Zdw8yN2/gbXfyc5GqaVXtEcYxz2lU/7pvliXr6KRAX05iIBvxkjoYD60jJ8GC4juWR8t@LBCp8Q8 "J – Try It Online")
*-7 after reading Bubbler's divide by 3 trick*
[Answer]
# [J](http://jsoftware.com/), 27 bytes
```
_2+6%~1#.[:,0=1#.3|+"1/^:2~
```
[Try it online!](https://tio.run/##bVFNC8IwDL3vV4SpbGN1JlE8FHYSPHnyKuhBHOLFPyD767Vqa5t20K/He0le0ocpu2qAXkMFChC03csOdsfD3ly43S5GmnUnrbC39/rVlrQ6ax5NU9yu9ycMQAwbmEPNNloB2bNRUJNH9EGOcNxfyQGhU1r0Wxji2ClJZEGvjLisHgtEU6YjoXsKKxRQZJoER8IKCiWmOVEMgkSzsnU/ziJ1jSKOUpQNVyqzHjivTmFkU18UcTjxfd@c5g0 "J – Try It Online")
J makes it hard to construct the Cartesian 3rd power directly, but easy to compute the attribute-wise sum of the cards in it. The result of "Table" `x f/ y` is dependent on the function rank of `f`. `+"1` has rank 1 on both sides, so it computes the table of "rows of x added to rows of y".
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 12 bytes
```
{⊇Ṫ\{=|≠}ᵐ}ᶜ
```
[Try it online!](https://tio.run/##bVQ7TsRQDLzKaguqINnTw0VCCqCAAgmJZoXCNluAlooDUFBT0YAEt0kuEvJ@/rxEaSw79ozt8bt6uLy@fby7v8HU77ab0/PNdncyPn@Nh8Pwd9wP329TP76@DL@fF/3Z03j8CK798PM@TW3bUoOGG@6a2QofosXBni2O0WQFu0SRM1iioU75j2IUwROtFE2@WKebzYhc8JDxQk75k4QDZWSscIgYglIsGIaaSxk55ZDL0Z5TFMKBhRe5iiwZkZ/4bD2dJmfk4rUzKRtQZBYfS22SKJlcEtYsDJVr6jMgs/Sse8FKRTZRSIZGC3@4/iCsYeZapq0ashXJcMRCf9pLvYFUBU5/MN0lZZRps2yNqg5IdKXqhVEBRDlWYai0DceGFtNmU5EFhczNaadcXRUZPZC5FRg2OjnOyH5i7PZSq5cFhZ1y4C52/VXQC9F7xuKW1jZERkOotEZO@WSUT@6qOFdOyGxeH6/A0gtJDioNYeXl0ru3U/Ib77p/ "Brachylog – Try It Online")
```
{⊇Ṫ\{=|≠}ᵐ}ᶜ
{ }ᶜ Count all …
⊇ subsets of the input …
Ṫ that are length 3 (Ṫriplets) …
\ which transposed …
{ }ᵐ only have rows that …
=|≠ are all equal or all different.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 8 bytes
```
3ḋƛ÷Ṡ3ḊA
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=s&code=3%E1%B8%8B%C6%9B%C3%B7%E1%B9%A03%E1%B8%8AA&inputs=%5B%5B0%2C%201%2C%202%2C%200%5D%2C%20%5B1%2C%201%2C%202%2C%200%5D%2C%20%5B1%2C%200%2C%201%2C%202%5D%2C%20%5B2%2C%200%2C%202%2C%200%5D%2C%20%5B1%2C%201%2C%201%2C%202%5D%2C%20%5B1%2C%202%2C%201%2C%202%5D%2C%20%5B0%2C%202%2C%202%2C%200%5D%2C%20%5B1%2C%201%2C%200%2C%201%5D%2C%20%5B2%2C%200%2C%200%2C%201%5D%2C%20%5B2%2C%201%2C%200%2C%201%5D%2C%20%5B0%2C%200%2C%200%2C%201%5D%2C%20%5B2%2C%202%2C%201%2C%202%5D%5D&header=&footer=)
Jelly port be like
[Answer]
# [Perl 5](https://www.perl.org/), 126 bytes
```
sub{1/6*grep{@s=map@$_,@_[map-65+ord,/./g];!/(.).*\1|[M-Z]/&&!grep{$m=$_;eval(join'+',@s[grep$_%4==$m,0..11])%3}0..3}AAA..LLL}
```
[Try it online!](https://tio.run/##bVXfb9pADH7nr7iilAaaBtsU9gNFC89j68ueRiPUrQGxNRABm4oYfzu7u1zufClCSNb57O@z/flS5tuX4bk4BIvkvPvz44j9UW@5zctjukuKpzIN5lE6n0nrbjS83Wyfo37cX2bjq34Yd@PeI/6bfbn7nvU7nSsdFRRJMB/nf59ewl@b1frm9iZKdzPlCubX90kSFBHEMWLWvR6cpDU4TSaTOJ5Op6fzuFUcRLrPd/skbAkxg0j9KcIIs0ha6kfaQmVLC7W3spRde8lEoPWqPPU90F5SJ9qqvNWZzpNlkcJHg1@jkkFVkfV9sEzA4NMFJhrJYtUWMZ4uFiw@RcJEghfp6q@8ZJmgZQdeXrQRmqU94/lcZ9HgDzR@7eNdqmfi8NGeoUUA6wUWC5Y7Wp6OcVVthX8fCVM1ePOiC3mReclGOG9dBXm1kuVOrMd1/4e6fqcwnhcYX3qjTldXcyZVFvLUSazGSjEV/sj0H@00oVENWNU5hRNTB1ldcf1RQ//kcQLb/3de/5HlRYsFbDtd1djYP2A6AbZPxDi5Ltb1v9f4fg/Rm1dT4Wix0NMVeRt@@RVxW1TP/4PZf3qzdZcmB0xh1FAieNsBbDvA2z80mc37A1xNyCy@9c7LN5G8@vmr594J3jFfCRK/O24tNttQP8fdo6QjRHEIg/y1jNLVuuwm8sswNsciWG72SSdYhNpVHZfb1XovVIB89aVffBLtze@2@CjavV7v68M38fC5za@2pSVv5z/3@XOi4oRQaVXs41rePJ3/Aw "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
IΣ⭆θ⭆…θκ⭆…θμ⬤E⁴E⟦ιλν⟧§ςπ⬤π⁻²№πς
```
[Try it online!](https://tio.run/##dY7LCoMwEEV/ZZYJTEGlu65KVl0UCi6Di2ClSmO0GqX9@nTioz6gswlnzp1L0lw1aaW0c7emMJYJ1VoWdyWLLfHjqmr2QlhAfFKdibwa1k/@V5WkzlozL44I/pEFgkYwCRl7MffszXqEmvMpWlOsMF3LIgRRdfQZ2vT8NyfnpJQBQohAkYB6ZLinSXuKBtomZzcezTTGtklftLSsaOWCvZs7k8Qdev0F "Charcoal – Try It Online") Link is to verbose version of code. Explanation: A group of cards forms a Set if no single attribute appears exactly twice in any aspect.
```
θ Input
⭆ Map over cards and join
θ Input
… Truncated to length
κ Outer index
⭆ Map over cards and join
θ Input
… Truncated to length
μ Current index
⭆ Map over cards and join
E⁴ Map over aspects
E⟦ιλν⟧ Map over cards
§ςπ Aspect of current card
⬤ All aspects satisfy
π Current aspect
⬤ All attributes satisfy
№ Count of
ς Current attribute
π In current aspect
⁻ Subtract i.e. does not equal
² Literal `2`
Σ Take the sum (i.e. count)
I Cast to string
Implicitly print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
3.Æ€øO3ÖPO
```
Port of [*@Bubbler*'s Jelly answer](https://codegolf.stackexchange.com/a/231877/52210), so make sure to upvote him!
[Try it online](https://tio.run/##yy9OTMpM/f/fWO9w26OmNYd3@Bsfnhbg//9/dLSRjqGOgY5RrE40mNYxBLKMQDSUZQBkQWRhYiCWEVjMAC5rgKQXxDYAs0AqDcCyRnAWSIdBbCwA) or [verify all test cases](https://tio.run/##bVQxTsRADPzK6eqA7Lmee8LRRylAoqCiQEK6loIn8AoeQJ@f8JFwuxuP7U2UxrJjz9ge79v70/Pry/JxPR8Pdw@H4/m6nO7nr7/Pn/n3cpq/Hy/LsIzjKAMGHXQablb5UC0t9s3SGm1WsS2KNUMZLXXsP6lRFE@1WrT5ap1pGg4N2gCxApYk@1VIQlZo7JCoIIQxC4Gi54pBtyRJSd51i4IklMQklVRmVIL0xXo@TzVoc8ex2BIcWulTFhdGJeQKaSspOtnWaIVWdu27wU5JDVEww6PWAFKHIG2EyXLgLqRYUgJLbETo3fRLaFWQRIjQXlMHB67cnHQ9CMXlGkZQAiifKDN0CkeiI9uBayiphJFwet6rdsclQRMSLgaBjs9ODToPTdNueg0rYTTJB@ly918Hv5Nw19ic1N6WJAgJneAk6V@C/iUdl66VV2gN71DWoXUjTEInJOy8YX7/cU5569P0Dw).
**Explanation:**
```
3.Æ # Get 3-element combinations of the (implicit) input list of lists
€ø # Zip/transpose each inner list of lists; swapping rows/columns
O # Sum the inner lists of columns together for each inner-most list
3Ö # Check for each sum whether it's divisible by 3
P # Check if all inner-most were divisible by 3 by taking the product
O # And check of many are truthy by taking the sum
# (after which the result is output implicitly)
```
] |
[Question]
[
Inspired by [I reverse the source code, ...](https://codegolf.stackexchange.com/search?q=I+reverse+the+source+code)
Your task, if you wish to accept it, is to reverse text and mirror select characters. Yes, yes, I know. Very surprising.
## Input
A string, `stdin`, an array of characters, or any other source of text. All characters of the input are guaranteed to be in the printable ASCII range (32-126).
## Output
The reversed text with some characters mirrored. To do this:
* You replace any occurrences of the characters `(`, `)`, `/`, `\`, `<`, `>`, `[`, `]`, `{`, or `}` in the text with the corresponding "mirrored" character: `)`, `(`, `\`, `/`, `>`, `<`, `]`, `[`, `}`, or `{`.
* and then reverse the text.
You may assume a maximum line length of 255.
## Rules
* Standard loopholes apply.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), which means that the shortest answer in each programming languages wins. Consequently, I will not be accepting an answer.
## Testcases
```
(s)t/r\i<n>g[i]e{s} -> {s}e[i]g<n>i/r\t(s)
stringies -> seignirts
()/\<>[]{} -> {}[]<>/\()
{s}e[i]g<n>i/r\t(s) -> (s)t/r\i<n>g[i]e{s}
seignirts -> stringies
{}[]<>/\() -> ()/\<>[]{}
qwertyuiop database -> esabatad poiuytrewq
```
As seen above, the output should go back to the input if run through the program again.
[Sandbox link](https://codegolf.meta.stackexchange.com/a/18732/89298)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~61~~ ~~60~~ 59 bytes
```
lambda s,t="(/<[{}]>\)":[(c+t)[~t.find(c)]for c in s][::-1]
```
[Try it online!](https://tio.run/##bZBBboMwEEX3nGLkDbbqBKWpVAkBy56gO@OFA4a6Sg2xByURolenJonSVsrK9vzx@zO/P@NHZ7dzk5fzXn3tagWeY05okolxkkXJSCpo9YRMfOO6MbamFZNN56ACY8FLkaarjZxRe/SQA42oI9QzTFxpMlu0wkg9@olwR8Khw7MNZRNkDG2E8YgSj87Y1mhPOPHatNY49BcpsFhSZoWQ4xUxCZkVSUnZTX7E5I8nuFrd8fyP7Y31C@f/jC8/D0ft8DyYrodaodoprwND@3BDVUPfmeGMTh8PSzuLXD6@u0GnMMTl8Py62cYc3tTe3ysvVTxFS5DIT0uUlwTTCJYU43j92RlLG4qMRdCHOZE2ZMQJVgWEZWB0wuf5SYbh5h8 "Python 3 – Try It Online")
-1 byte thanks to @xnor.
Changed the lookup string, so that the `c in t` test is eliminated.
---
# [Python 2](https://docs.python.org/2/), 63 bytes
```
lambda s,b='(/<[{}]>\)':map(dict(zip(b,b[::-1])).get,s,s)[::-1]
```
[Try it online!](https://tio.run/##bZHLboMwEEX3fMXIErItOUFJK1VCwLJf0B2wMMGhrhIgnkFJivh26jyUtlI2ftw7Pnc07s/02bXreZsW807vq1oDqirlIkrycSqzQvJ4r3tR2w2Jb9uLSlV5HC9WpZTLxpBChfImzGSQEFIQgXBMoKTIFTZpsya3pRlxYsoxvxl/bbxsvU2@jEkVCIbkbNtYg0wxNLZprSO8Wp4loyLJ8nK8Iaa8TLKoEPJuP2Oq5x3coh549Sf2zvqFq3/B15eHo3F0HmzXQ61JVxqNZxj0J9I19J0dzuTM8XApl4FLxw83mBgGXgzrt9ULV/Cud/hQXjd8CradA1InsC1cJxgHcJki58uvzrZiK0jKAHrfJwkWIiwy8GseYskgBEHK/xhgmp6knH8A "Python 2 – Try It Online")
-1 byte thanks to @xnor.
# [Python 3](https://docs.python.org/3/), ~~65~~ 64 bytes
```
lambda s,b=b'(/<[{}]>\)':s.translate(dict(zip(b,b[::-1])))[::-1]
```
[Try it online!](https://tio.run/##bZBNboMwEIX3nGLkjW3JCUpTqRIClj1Bd8DCBENdpYZ4BiUp4uzU@VHaSl15PG/8vecZzvTeu@3SZuWy1591owFVndVcxGkxzVVeSp7gmrx2uNdkRGN3JL7sIGpVF0my2lRSyluxkEFCyEBEwjOBkmJf2tTlXWErM@HMlGfhMOHahbYNMoUxJlUkGJK3rrMGmWJobOesJ7xKgSXjMs2Laroh5qJK87gU8i7/x1T/J7hZPfDql@2d9QNXf4yvLw9H4@k82n6ARpOuNZrAMBgq0g0MvR3P5M3xcBmXkc@mNz@aBEZejk8vmy1X8Kr3@Og87/gctb0HUiewDq4bTCK4bJHz9UdvnWgFSRnBEHKSaNlEM6xyCJ@ByReYZacqhFu@AQ "Python 3 – Try It Online")
Just for fun using idiomatic Python. (More idiomatic would be using `str.maketrans`, but it's *way* too long.)
-1 byte for both because the `\` in `'\)'` doesn't need to be escaped.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 2 bytes
```
:R
```
[Try it online!](https://tio.run/##Ky5JrPj/3yro/3@NYs0S/aKYTJs8u/TozNjU6uKQIE8/d0/X4FoA "Stax – Try It Online")
Well, um, yeah, Stax has a two-byte built-in that exactly does the job.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + GNU utilities, 33 bytes
```
tr '(<[{/)>]}\' ')>]}\\(<[{/'|rev
```
[Try it online!](https://tio.run/##HYsxDgMhDAR7XkEHVHwA8RGg4BSLuCGJ7SSKCG/n0FUrzc4cle9rCWljQxrexTKz0ebafCHzJ/isZdmJp4yhx5awwOCpWAh7Q2Blnc8hpjKm2gdsoW0RdyA7VAzYOpKwGjOVEH22Tr2@QPJ74@Opb1XqURlO "Bash – Try It Online")
A straightforward solution seems best here. Really the only golfing is making sure that the backslash appears last in one of the arguments to tr, because then that backslash doesn't have to be escaped, saving 1 byte.
[Answer]
# JavaScript (ES6), ~~65~~ 59 bytes
*Saved 6 bytes thanks to @Bubbler*
I/O format: array of characters
```
a=>a.map(c=>(S='()/\\<>[]{}')[S.indexOf(c)^1]||c).reverse()
```
[Try it online!](https://tio.run/##fY@xbsMgEED3fgXyYhgK6m77FzpkxK5E7bN1UQoOR5JGjr/dpW2iRgkpI3f39N7a7A21HsfwbF0HS18upqyM/DAjb8uKr8qcC1XXRaWbac6FXkm0HXy@9rwVby/N6dQK6WEPnoCLpXWW3Abkxg2851pKmXESQfm6xsJWg8YGJpqzRsi1Q8vzXAimFIt/EGdD3MG4HOLRU4JFwaMdEChjf@@WRYCDRR8oRbiKyR4Splk3RaVqnpS4cf2RvQs6V19HJ4Murv8GXaqTNmfXKPs46Lv6NzqF2B7Ah@MO3cg6E8y7IcjuEEBxEEzHRoe7Y/Bw2C5f "JavaScript (Node.js) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 (or 3?) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ºsK
```
Doesn't work for single-character inputs that are not in the mirror character-set (i.e. `"a"`).
Thanks to *@Grimmy* for this version.
[Try it online](https://tio.run/##yy9OTMpM/f//0K5i7///NYo1S/SLYjJt8uzSozNjU6uLawE) or [verify all test cases](https://tio.run/##DcsxDgIhEEDRfk5BtoLEhAsQtrHzCEDBxgmZhlUGNRvc1gN4HEuP4kWQ@r@/clwI@/O@zZP4vd5imrdj/3741A9dsqq6eDLZJkcBG@/AtVBOhAxSaW@sC22HEXCANCCNoY4RGCllKpWh7S4Yq71UcH1gqduN1os4xxqXyAgN4h8).
```
º2äθ
```
Also works for single-character inputs that aren't in the mirror character-set.
[Try it online](https://tio.run/##yy9OTMpM/f//0C6jw0vO7fj/X6NYs0S/KCbTJs8uPTozNrW6uBYA) or [verify all test cases](https://tio.run/##DcsxDsIgFIDh/Z2CdCqJCYlzQw8CDDS@kLe0ykMNoV09gGfwEMZRdw/hRZD5//6F/URY10seO/G73UU35vp@7T@P77Puas8yqWhpmHUw5LDwBpwizYGQoZfKDtq4skEL2EBokNqQ2giMFGaKiaFsxg1a2V7C6Yox5TMtR3HwyU@eEQr4Pw).
**Explanation:**
```
º # Mirror the (implicit) input-string
# i.e. "(s)t/r\i<n>g[i]e{s}" → "(s)t/r\i<n>g[i]e{s}{s}e[i]g<n>i/r\t(s)"
sK # And remove the input-string from it
# → "{s}e[i]g<n>i/r\t(s)"
# (after which it is output implicitly)
º # Mirror the (implicit) input-string
# i.e. "(s)t/r\i<n>g[i]e{s}" → "(s)t/r\i<n>g[i]e{s}{s}e[i]g<n>i/r\t(s)"
2ä # Split it into two equal-sized parts
# → ["(s)t/r\i<n>g[i]e{s}","{s}e[i]g<n>i/r\t(s)"]
θ # Pop and only leave the mirrored second part
# → "{s}e[i]g<n>i/r\t(s)"
# (after which it is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
lambda s,t=r"()/\[]{}<>":[[c,t[t.find(c)^1]][c in t]for c in s][::-1]
```
[Try it online!](https://tio.run/##bY9Bi4MwEIXv@RUhpwhqKXsT9Y/EFFKN7iw2ppkpRYq/3U2E7V56yuS9b95j/Erfi/vax6bbZ3O7DoZjTk0QMjt1Sr@2uhWVUn1OisoR3CD77HLWWvUcHCc9LoEfI2pVVcVZ73DzSyCOK7JkzuDs4a9YIg3gKhYb4k7Db8ZLpBDlAD4/yBL9DCRF0YosYzxESojyZwEnR4lJ8gEcyZDzUahX9Bveb1pke3TpFDqoXTsp0PaFGy9aHh8bv1OUIdoUMZb63AQWE4AWJgeBkKWL6zbdfCxuStftqZMZ@5CRiA@N7J12RP/1sP@wY/FdxO5PG2h9wOL5YMhcDdpEWIwjmYH7BR4rBfu8/wI "Python 3 – Try It Online")
**Input**: A sequence of character.
**Output**: The reversed string, as list of characters.
**How**:
For each character `c`:
* `c in t` checks if `c` is a bracket.
* `t.find(c)` finds the index of `c` in the bracket string. `t.find(c)^1` finds the index of the mirrored bracket, which is 1 more or 1 less than the index of `c`.
* `[c,t[t.find(c)^1]][c in t]` evaluates to the same character if `c` is not a bracket, otherwise evaluates to the mirrored bracket.
* `[::-1]` reverses the result.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 22 bytes
```
T`(/<[{}]>\\)`Ro
O^$`.
```
[Try it online!](https://tio.run/##DcvBCkIhEEDR/XxFiwJdlD8gblsG0U4NXzTIQPjKmYoQv91c33MrCpVl7NQxjUtSxvrWowtBp/MKp@s2HcZQrMXUQLa47Cli4w4slUomZFDaBOt8bB1mwAnyhDQHmSMwUi5UhaF1H60zQWl4fbHK703rc3NfZLktjGP/efwB "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`(/<[{}]>\\)`Ro
```
Transliterate the string `(/<[{}]>\)` to its reverse.
```
O^$`.
```
Reverse the whole string.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
Pθ‖TFθ¿№βι←ι←
```
[Try it online!](https://tio.run/##JcuxCgIxEATQ/r5iywQUeyM2th6I2KlFLm50IV7uNpsTEb89Rq0G3sy4m2UXbSilzUFoYOpFjdo0e/QBnRzY9slHvqtqNaGWQB7UJua67GZAWsPud1tu0csXDGBICG2c8I/alPJKbzzS@brq17Tgk6ikAZPtrNgLDJHyUxgfY1PmU/gA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Pθ
```
Print the input string without moving the cursor.
```
‖T
```
Reflect the canvas. This mirrors the characters `()/\<>[]{}bdpq`.
```
Fθ
```
Loop over the original string.
```
¿№βι
```
Is the current character a `b`, `d`, `p`, `q` (or any other lowercase letter that wouldn't have been transformed)?
```
←ι
```
If so then replace it with the original lowercase letter and move left.
```
←
```
Otherwise leave the current character, which might be a transformed `()/\<>[]{}`.
[Answer]
# batch, ~~442~~ 408 bytes
```
@Echo off&Setlocal EnableDelayedExpansion
for %%A in (a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z)do Set %%A=%%A
for %%B in ("(=)",")=(","<=>",">=<","[=]","]=[","{=}","}={","/=\","\=/")do Set "%%~B"
Set "_=%~1"
Call :M
Echo(!$!
Endlocal
Exit /B
:M
For /L %%C in (0,1,256)do (
If "!_:~%%C,1!"=="" Exit /B
Set ".=!_:~%%C,1!"
For %%D in ("!.!")do IF "!%%~D!"=="" (Set "$= !$!")Else (Set "$=!%%~D!!$!")
)
```
Output:
[](https://i.stack.imgur.com/6M0Tt.png)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~112~~ \$\cdots\$ ~~84~~ 83 bytes
Saved a whopping 27 bytes thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler)!!!
Saved a byte thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
char*t,*b="()/\\<>[]{}";f(char*s){*s&&putchar((t=index(b,*s))?b[t-b^1]:*s,f(s+1));}
```
[Try it online!](https://tio.run/##fZDfboMgFIfv@xSEZA04G9PbtXUPIi5Bi46LWeTQ1D/x2R0ek65ZSm8IhwPfd/iVu7os57n8ljZycVScKOOJEMc0y8eJHiqGHeBjBNutubqlZMyddHNWHSti3@KfReZ2xdc@/4ggrhi87zk/TPOP1A3j42Z5Qros92jgLrFC6GOT1pnO1QjekUSE@o3yB7VvaH/D@ZuURMnGWN24ilFB30BQskuJoDTu@GFTsWX964uG@hpd/eIC51u1VrAKQOm60dbBC2yP2D6EHfALj@ng5FOWH1N/yF5NPCB6CKHlgv6XwRoCOp7mFpZJlMmQzGA89zzWeO5phbEGsSaEbfEPD2msoz/kFUa3iG5DaLug25uyrr/qiyFn6WQhQa0KBb5w8kzMRV97Z9WtfaGyqLJPVNP8Cw "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~111~~ \$\cdots\$ ~~75~~ 69 bytes
```
lambda s,b=r'()/\<>[]{}':[[c,b[b.find(c)^1]][c in b]for c in s][::-1]
```
[Try it online!](https://tio.run/##bZBNasMwEIX3PsWgjSRQEtIUCsb2sifoTlbBP7KrksqONCYJxmd3ZTekLWSl0czoe0@vv@JHZw9zk@bzsfgq6wK8KFNHGd/lSSbVONFYykqUstw2xtas4u97pWQFxkKpms7BWnol43izVzNqjx5SYBFzhHmOO5ebxGatNEqPfiLCkXDocG1D24QxhjXCRcSIR2dsa7QngnhtWmsc@nUUWHdHK2KSKsl2OeO38SOmeOzgR@qOF39kb6xfuPgnvL48nbXD62C6HuoCi7LwOjC0DxUWNfSdGa7o9Pm0rPPIpeObG3QMA82Hp5f9gQp4LY7@3nmu6BQtQaK4LFGuCcYRLClSuv3sjGUNQ84j6INPZA0ZcYJNBuEzMDrp0/Sigrn5Gw "Python 3 – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 111 bytes
```
s->{var a="(\\<[{}]>/)";for(int i=s.length,j;i-->0;System.out.print(j<0?s[i]:a.charAt(9-j)))j=a.indexOf(s[i]);}
```
[Try it online!](https://tio.run/##XZAxT8MwEIX3/opTJSQbEbcDCyQNQp0RQ8ckg0mdcCF1gu9SqEJ@u3GqCokOluV737335EYfddTsPzwe@s4xNOGtBsZWVYMtGTurbuNFP7y1WELZaiJ40WhhXABcpsSaw3XscA@HoIkdO7R1VoB2NckzCrDtLA0H45LyXbusSKGCjacoHY/agd4sRZ4n2TgV6Uou46pzAi0Dbki1xtb8ftfEGEXpOt6diM1BdQOrPsSwaJL1E2VYPGo1Wz@zeIgaKWWz0Qrt3ny/VmLWZTz5@Fxldj@nuvrxX0eAa/dKLG/u1wQ/sLybURlfwErpsjQ9izBU3G3nZOf0Scg/5NqrteKiTYv5TN4LkrxyOSY2rUNFM9Lk6fx7aMgLucqTNCvGyQfBBKAOIIYFDoueDNYWHZMfp6xI0lUupP/8Mo5PA3Y97DXrN03mFw "Java (JDK) – Try It Online")
## Credits
* -1 byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 1 [byte](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
Exactly. A 1 byte built-in.
```
↔
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXUyMTk0,i=JTI4cyUyOXQvciU1Q2klM0NuJTNFZyU1QmklNURlJTdCc1RSSU5HSUVTJTdE,v=8)
[Answer]
# [J](http://jsoftware.com/), ~~32~~ ~~28~~ 26 bytes
-4 bytes thanks to Bubbler!
-2 bytes thanks to FrownyFrog
```
|.rplc(;"0|.)@'([{/<>\}])'
```
[Try it online!](https://tio.run/##HYyxDsIgGIT3PsWfDgKJ0s5tJSYmTk6uwFArRYxpK2CMoX32igw3XO777rHmFPWwrwDBFkqoYnYUjpfzaZ2pnZ4drvNypuSAMA9Fw8QiCVpJBpnq7iPguicbBgg74gsrTDMwzY1UwS2oBuS8NYM2yv0LJoVoGJchTZFQkdTRMNH08SEZyujBWJ@MsHDZsELgNL0@yvrv24wT3FrfXlun0PoD "J – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~69~~ 58 bytes
`+` to [@Bubbler](https://codegolf.stackexchange.com/a/202927/68224)
-11 bytes thanks to @mazzy
```
$t='(/<[{}]>\)'
$args|%{$a="$_$t"[-1-($t|% i*f $_)]+$a}
$a
```
Expects input via [splatting](https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_splatting).
[Try it online!](https://tio.run/##bVDLboMwELzzFSu01NCAaNpKvQDqfxgrchNDXEU8bEdJRPh2upQ2ueTinfGMZ6zt2pMydq8OhwmrfJjQ5SxMMz6Moigj5qE0tb0GA8rcxw06nyfrJER3DUA/V4CbSKxQjuSb6LA53@6lES/n14/3bQx3tn7zQhbayKWm1FlT1FwLNdiRxcBoKKI1XWuSHdlYFJPfOqObWis7u6zSdaONs4sWRmmZFVwMS8TIRVakZfj38lEk2R59YGm6hc9Nt9ol6549R9x7f9We9ucuR912sJNOfkmrZpuyBJ3cQdfq48UZdepZBFcIBg8AuxjwDDmtb2aG0BNgBZ/dP02@W90QJO5jB0kx@/0VWk4zUT1JwhunHw)
[Answer]
# [Red](http://www.red-lang.org), 69 bytes
```
func[s][reverse s forall s[s/1: any[select"()([][{}{<></\/"s/1 s/1]]]
```
[Try it online!](https://tio.run/##NY7BasQwDETPzVcIn5xDMb0uwR/Rq6KDmyipIXW2lrdlMfn2VJBaoIOYeaPJPJ/vPCN1yw3O5ZEmFMLMP5yFQWDZc9g2EBT3doOQnii88VSM7S0S1qMOfnCjM6qDLhGdynCYPkFKjmkF7EDHWOmLy2Mckl8xElc5zKVcvsjyf9vejYNHqs2gVlZkVTRqRNGohnJcU8ylofVAGrwbbTN8/3Iuz0fc7zCHEj6CsOnoqnTXtwUQvvZtbmXNqzewtIs6ejn/AA "Red – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) -pl, 37 bytes
```
$_=reverse;y|(){}[]<>/\\|)(}{][><\\/|
```
[Try it online!](https://tio.run/##NYw7DgIhEEB7TmFhAYWhshK5CBCDcUIm2bDIjJoNy9VFGuv3KVCX8xjH27XCGyrBZdulat0FY7X3u5K9BWeN93ofQ5JiXT2abJPDAI26IK6YEwIJqbQ31oXWxQQwhTRFnAHPUBBgyliZxH8vlXh@oPL2wrUcHpHjPRJ818K4ZhqnsvwA "Perl 5 – Try It Online")
[Answer]
# [PHP](https://php.net/), 52 bytes
```
<?=strrev(strtr($argn,$a='(/<[{}]>\\)',strrev($a)));
```
[Try it online!](https://tio.run/##bYxBCoMwEEX3OUfAjFhygMZk10sYkUBFA20cJqkb8epNI7hp6erD472PM@asTBsT0biKMokEdzSFhru2ElJ1295ra6FqToc7ALhmo5kyOCOT9epouL@eeORDxIdP4jcuBfujfV3WkhmdRYQkyXoV9NT5ftziXtB7weSXEPPl9gE "PHP – Try It Online")
Glad that this time PHP has an elegant way of doing it ^^
[Answer]
# [Icon](https://github.com/gtownsend/icon), ~~76~~ 68 bytes
```
procedure f(s)
r:=reverse
return map(r(s),t:="([{/<>\\}])",r(t))
end
```
[Try it online!](https://tio.run/##TY9BDoIwEEX3nKJ2NU1I2BPgIm0XVUYyCwpOB40hnF2LUeIs///vJUOXKb5eM08X7BdGdYVkCq5bxjtywoJRFo5qDDNwrkqpWw12rZrOuc0bXTKIMQXG/k8yBopgCpVv1zzVg0kQrvCJTlZnk1TsHDWxGyx5XNOmy0@rkzDFgTD9AjCVc01n/Xps8hwzNmScdo9k4cEjDZFYDn7drG@67IBjc3sgy3OhaVZ9kHAOCbX/vvEG "Icon – Try It Online")
] |
[Question]
[
## Time sheets
In a work place you often have to complete time sheets. This task is write code to help this.
# Input
Two times in a slightly non- standard 12 hour clock signifying the start and end of the day separated by a space. A third number represents the number of minutes taken for lunch. For example
```
9:14 5:12 30
```
This means you started work at 9:14am, finished work at 5:12pm and took 30 minutes for lunch.
You can assume that
* Any time in the first column is from 00:00 (midnight) up to but not including 1pm and any time in the second column is 1pm at the earliest up until 11:59pm.
* The lunch break is no longer than the working day!
The input format must be as in the examples given.
# Task
Your code should read in a file (or standard input) of these triples, and for each one output how long you worked. This output should indicate the number of hours. For the example above this is:
7hr and 58min minus 30 minutes which is 7hr 28min.
## Output
Your output must specify the (whole) number of hours and minutes and must not list more than 59 minutes. That is you can't output 2hr 123min. Apart from that, your code can output in any easily human read format that is convenient for you.
# Examples
```
10:00 1:00 30 --> 2hr 30min
12:59 1:00 0 --> 0hr 1min
00:00 11:59 0 --> 23hr 59min
10:00 2:03 123 --> 2hr 0min
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 28 bytes
```
`jYb0&)YOd.5+wgU13L/- 15XODT
```
[Try it online!](https://tio.run/##y00syfn/PyErMslATTPSP0XPVLs8PdTQ2EdfV8HQNMLfJeT/f0MDKwMDBUMQYWzAZWhkZWoJ4RlwGUCkDEFCQCkwz8jKwFjB0MgYAA "MATL – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 83 bytes
```
\d+
$*
(1+:)
12$*1$1
+`1:
:60$*
(1*) :\1(1*)(1*) \2
$3
:(1{60})*(1*)
$#1hr $.2min
```
[Try it online!](https://tio.run/##JYq9CgIxEIT7fYoFt8gPyM4GD9xnSaGg4BVecdiJzx6TXDM/38z@/KzbvbX6yCSJOCB7JIZJgoDyDU6@aJ8CUmSvGD5zNZJCHvBd9BfTYCQnvHaWs73XrTWoqzKGFCWYX65HU9LpB@rTPJpr6aj8AQ "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\d+
$*
```
Convert the input to unary.
```
(1+:)
12$*1$1
```
Add 12 hours to the stop time.
```
+`1:
:60$*
```
Multiply the hours by 60 and add to the minutes.
```
(1*) :\1(1*)(1*) \2
$3
```
Subtract the start time and break time from the stop time.
```
:(1{60})*(1*)
$#1hr $.2min
```
Divmod by 60. (Save 5 bytes for a more boring output format.)
[Answer]
# [Perl 5](https://www.perl.org/) -pl, ~~80~~ ~~74~~ 71 bytes
```
/:(\d+) (\d+):(\d+) /;$m=720+($2-$`)*60+$3-$1-$';$_=($m/60|0).":".$m%60
```
[Try it online!](https://tio.run/##NYrBDsIgEETv/QrSrBEklF0QTLfpn5joQQ8mpSXq0W8Xg9XLy7yZydf7FEqxLI8XrcSXv2wHSOPBoZbgDJzVLqIGb4AMbAc4jRKSjfhC1bXcdpA2EUvpmfYiMDnhsSFkREEV1RyHfjVscJ2oVv@jY/SCnH8v@Xlb5kcxefoA "Perl 5 – Try It Online")
[Answer]
# Python 3, 161 bytes
I know this won't even be close to smallest, but it does read in a file:
```
for l in open('t'):
l=l[:-1].split(':')
m=-int(l[0])*60+int(l[1][:2])+(int(l[1][3:])*60+720+int(l[2][:2])-int(l[2][2:]))
print(f'{m//60}hr {m-(m//60*60)}min')
```
I'm feeling the irony of pausing my timesheet to do this...
# Python 2.7, 133 bytes
Thanks for the suggestions in the comments! Switching to python 2.7 saves a few more bytes because it defaults to integer division:
```
for l in open('t'):i,h,l=int,60,l[:-1].split(':');m=-i(l[0])*h+i(l[1][:2])+(i(l[1][3:])*h+720+i(l[2][:2])-i(l[2][2:]));print m/h,m%60
```
The same approach with python3 is 135 bytes because of the print statement and defaulting to float division:
```
for l in open('t'):i,h,l=int,60,l[:-1].split(':');m=-i(l[0])*h+i(l[1][:2])+(i(l[1][3:])*h+720+i(l[2][:2])-i(l[2][2:]));print(m//h,m%60)
```
[Answer]
# C, 105 bytes
```
a,b,c,d,e;f(){for(;scanf("%d:%d%d:%d%d",&a,&b,&c,&d,&e);)a=(12+c-a)*60+d-b-e,printf("%d:%d ",a/60,a%60);}
```
Completely straightforward. Try it online [here](https://tio.run/##NY3BCsIwEEQvnvoVpdCQ2A1uEgyY4MdsN6300CjVm/jt1Vi9DLx5DMP6wryuBD0wJBjiKNVzvC4y3pnyKJs2hTb9ogFBIHoQDCKBGFRUdJbGdqxJ7T12Sfd6gNsy5cd/WjdAB49ArUcVX@tMUy4XsoDBgFibEg4rY8PxtBFWuClTqo/6kg3oamNdtXsD).
Ungolfed:
```
a, b, c, d, e; // start hours, minutes; end hours, minutes; break - all implicitly int
f() { // function - return type is implicitly int (unused)
for(; scanf("%d:%d%d:%d%d", &a, &b, &c, &d, &e) ;) // until EOF is hit, read line by line
a = (12 + c - a) * 60 + d - b - e, printf("%d:%d,", a / 60, a % 60); // calculate the minutes and store, then output separated: "h m"
}
```
[Answer]
# Wolfram Language ~~125 119~~ 111 bytes
```
i=Interpreter;j=IntegerPart;Row@{j[t=(i["Time"][#2<>"pm"]-i["Time"][#])[[1]]-#3/60],"hr ",j[60Mod[t,1]],"min"}&
```
---
8 bytes saved thanks to user 202729
**Example**
Abbreviations are not used here, to make it easier to follow the logic.
```
Row[{IntegerPart[
t = (Interpreter["Time"][#2 <> "pm"] -
Interpreter["Time"][#])[[1]] - #3/60], "hr ",
IntegerPart[60 Mod[t,1]], "min"}] &["9:00", "4:12", 20]
```
>
> 6hr 51min
>
>
>
`Interpreter["Time"][#2 <> "pm"]` interprets as a time the second parameter followed by "pm", namely, in this case, "4:12pm", returning a `TimeObject` corresponding to 4:12 pm.
`-Interpreter["Time"][# <> "am"])[[1]] - #3/60]`. `#3` is the third parameter, namely 20min. The minus sign subtracts the lunch hour interval from the end of shift time. It returns the adjusted end of shift time, that is, the end of shift that would apply had the person not taken a lunch break.
`Interpreter["Time"][#]` interprets as a time the first parameter, in this case, "9:00", returning a `TimeObject` corresponding to 9:00 am.
Subtracting the shift start from the adjusted end of shift time yields `t`, the time interval expressed in hours. `IntegerPart[t]` returns the number of complete hours worked. `IntegerPart[60 Mod[t,1]], "min"}]` returns the additional minutes worked.
[Answer]
# JavaScript, ~~83 bytes~~ 76 bytes
```
s=>(r=s.match(/\d+/g),r=(r[2]-r[0]+12)*60-r[4]-r[1]+ +r[3],(r/60|0)+':'+r%60)
```
Just got rid of the inner funtion from below solution (What was I thinking?). Changed the output format as well.
[Try it online!](https://tio.run/##PZDNboMwEIRfZWWpil07sDYNUlyRWw695kp8QEB@KmKQMVUPfXdqQ9rLajXfzEqzn9VXNdbuPvit7Zt2vky2LuaxOFBXjMmj8vWNpueGp1cmXEFdqczWlWi4VOw1x7C/RUEaDtyVmRHUpTn@IOMbveHuJUc2v0NZEokaEWQcGRJB1M2F5XG3xIhAld7tVxohBij/GK5JGR1LMgt0t/@PLlhpzECq7Hl5PWySS@@OVajgoThA3dux79qk66@UfNhh8hoAiAAfCgkgZ3v8Htrat41eRLmKp3acumgNYnwPjXa2IMLY/As)
---
# OLD: JavaScript, ~~112 bytes~~ ~~111 bytes~~ 110 bytes
```
s=>(t=(h,m,a)=>(a?12+h:h)*60+m,r=s.match(/\d+/g),r=t(+r[2],r[3]-r[4],1)-t(r[0],+r[1]),`${r/60|0}hr ${r%60}min`)
```
**Explanation:**
Inside the main function, we start by defining another that will help us calculate the minutes of a giving time, adding 12 hours to the hours parameter if the third parameter is truthy:
```
(hours, minutes, addTwelve) =>
(addTwelve? hours + 12: hours) * 60 + minutes
```
Next, we ~~split the string by either `' '` or `':'`~~ match the numbers inside the string resulting in an array of all the numbers in the string.
Then we calculate the difference of end time and start time and substracting lunch time using the function defined previously (converting the strings to numbers when needed).
Finally we produce the result string: hours are the integer part of `r/60` and minutes are `r%60`.
[Try it online!](https://tio.run/##PZDNboMwEIRfZWWpil07sDYNUlyRWw695kp8QEB@KmKQMVUPfXdqQ9rLajXfzEqzn9VXNdbuPvit7Zt2vky2LuaxOFBXjMmj8vWNpueGp1cmXEFdqczWlWi4VOw1x7C/RUEaDtyVmRHUpTn@IOMbveHuJUc2v0NZEokaEWQcGRJB1M2F5XG3xIhAld7tVxohBij/GK5JGR1LMgt0t/@PLlhpzECq7Hl5PWySS@@OVajgoThA3dux79qk66@UfNhh8hoAiAAfCgkgZ3v8Htrat41eRLmKp3acumgNYnwPjXa2IMLY/As)
[Answer]
# [Python 2](https://docs.python.org/2/), 100 bytes
```
for I in open('x'):x,y,z,w,l=map(int,I.replace(':',' ').split());d=60*(12+z-x)+w-y-l;print d/60,d%60
```
[Try it online!](https://tio.run/##Nc3BTgMhFAXQvV/xEmMeWAYfTJxEmn5Av0FdoEAlIkNwTGf689h2dHMXJ/fmlmX6GLNutxDspwcL5QoQYvLw5mM@QPXWSSlvnA8wFp9ZyNycdfqpGZ5RkSECdYmeXjIKQKXN49NKf0JrSV38v3QlbagHpXt8bWGssIeY1xOckZtZLOIkjiLtvmxhMU9iL6svyb57hgYFAnL5XVKcGOdbtxvonim9OXUz3xy7pUvbUs8rcA8DCXc3UGvtFw "Python 2 – Try It Online")
Full program that reads multiple lines from a text file, as directed by OP. A function that just parses a single line would save an addition al 10 bytes.
[Answer]
# Java 10, ~~194~~ 191 bytes
```
u->{var s=new java.util.Scanner(System.in).useDelimiter("\\D");for(int i,a[]=new int[5];;i=(12+a[2]-a[0])*60+a[3]-a[1]-a[4],System.out.println(i/60+":"+i%60))for(i=0;i<5;)a[i++]=s.nextInt();}
```
I/O is painful in Java. Terminates abnormally when there is no next line of input to read. Try it online [here](https://tio.run/##TVCxTsMwEF2Y8hVWJCSbtMZJaCViwtSFgalsqQeTuuVK4laxU0BVvz3Ybqi44Z3e3endu9vJo5zu1p/DoX9voEZ1I41BrxI0OkXIBWiruo2sFXqDVo1FH8c9rJH5UMpiN4N63Ru1Jjz0zwFHSWOldSnMt04YL20HelsJJLutIf8kwwbroURDP30@HWWHTKnVF9o5n7S30NBlLbVWHV7@GKtaCppQt3mhGmjBWcXxarWICd/su@ALJrISQcKxaiY4hxKnWSKrTExlxQS5mzPHcs9SDw9iMmrve0sPzqttNIZ7NxYXcQK3c0ZIkC8Zh6cZJ7KCJBGloVp92xdtMeHn4e8ofj3PX0YvH2PXR52HlBWModRDzqI0K2aPF8YidmmlvuRagWUFy1Ga5dHNLw).
Ungolfed:
```
u -> { // lambda taking a dummy input – we're not using it, but it saves a byte
var s = new java.util.Scanner(System.in).useDelimiter("\\D"); // we use this to read integers from standard input; the delimiter is any character that is not part of an integer
for(int i, a[] = new int[5]; ; // infinite loop; i will be used to loop through each line and to store the result in minutes between lines; a will hold the inputs
i = (12 + a[2] - a[0]) * 60 + a[3] - a[1] - a[4], // after each line, calculate the result in minutes ...
System.out.println(i / 60 + ":" + i % 60)) // ... and output the result in hours:minutes, followed by a newline
for(i = 0; i < 5; ) // read the five integers on the current line ...
a[i++] = s.nextInt(); // ... into the array
}
```
[Answer]
# [Red](http://www.red-lang.org), 35 bytes
```
func[s e l][e + 12:0 - s -(l * 60)]
```
[Try it online!](https://tio.run/##XY07CoAwEER7TzGlH4TdRAX3GLYhlSYgiIif88eIiGIzxZt5zOqG0LnB2MRL8Mfcmw0OkzUOBVgJocSGMp2Qo6HMhmUd5x0erXCFWlhBU/JAJiECX/GlSur2pi@MSzBfxV@Ppzo6Opw "Red – Try It Online")
Note: The output is in the format `hh:mm:ss`
[Answer]
# [R](https://www.r-project.org/), 97 bytes
```
s=matrix(strtoi(unlist(strsplit(scan(,""),':'))),5,,T)%*%c(-60,-1,60,1,-1);paste(12+s%/%60,s%%60)
```
[Try it online!](https://tio.run/##NYpBCsIwEEX3PUUohGZ0ijOJFRrxFl4gFBeB2pZOBG8fE4qb9@f9P3vO8niHtMevkbSnNZrPMkdJ1WSbYzmmsBhsW8DOdwCAA@IT9ElPpr8R9oyFXBLuW5D0MmzPoi@6tKILIY@er2rwbJWjhskTKa6oZv0wHkYNHRPX6v9oPTnF1uUf "R – Try It Online")
For each line returns `"hours minutes"`
* -16 bytes thanks to JayCe !
] |
[Question]
[
**This question already has answers here**:
[Is it a weak prime?](/questions/131503/is-it-a-weak-prime)
(23 answers)
Closed 6 years ago.
>
> [In number theory, a strong prime is a prime number that is greater than the arithmetic mean of the nearest prime above and below (in other words, it's closer to the following than to the preceding prime).](https://en.wikipedia.org/wiki/Strong_prime)
>
>
>
Given an input integer, `n`, where `n >= 0`, your task is to generate the first `n` strong primes. For example, the sixth, seventh, and eighth primes are 13, 17, and 19, respectively:
```
(13 + 19) / 2 < 17
```
Therefore, 17 is a strong prime.
### Input
* an integer
### Output
* if `n` is 0
+ program: output nothing
+ function: return an empty array
* if `n` is greater than `0`
+ program: output the first `n` strong primes, each on its own line
+ function: return an array containing the first `n` strong primes
### Test cases
```
0
[]
4
[11, 17, 29, 37]
7
[11, 17, 29, 37, 41, 59, 67]
47
[11, 17, 29, 37, 41, 59, 67, 71, 79, 97, 101, 107, 127, 137, 149, 163, 179, 191, 197, 223, 227, 239, 251, 269, 277, 281, 307, 311, 331, 347, 367, 379, 397, 419, 431, 439, 457, 461, 479, 487, 499, 521, 541, 557, 569, 587, 599]
```
See also: [Strong primes on OEIS](https://oeis.org/A051634)
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~12~~ 11 bytes
```
↑§foẊ<Ẋ-tİp
```
[Try it online!](https://tio.run/##yygtzv7//1HbxEPL0/If7uqyAWLdkiMbCv7//29iDgA "Husk – Try It Online")
-1 byte thanks to H.PWiz.
## Explanation
```
↑§foẊ<Ẋ-tİp Input is n.
İp The infinite list of primes.
Ẋ- Take pairwise differences,
oẊ< then pairwise comparisons.
t Frop the first element from İp
§f and filter the rest using the result of oẊ<Ẋ-.
↑ Take first n elements of this list.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 14 bytes
```
Æp+ÆnH<ȧÆP
3Ç#
```
[Try it online!](https://tio.run/##y0rNyan8//9wW4H24bY8D5sTyw@3BXAZH25X/v//v4k5AA "Jelly – Try It Online")
## Explanation
```
Æp+ÆnH<ȧÆP Helper link. Input: k
Æp Prime less than k
+ Plus
Æn Prime greater than k
H Halve
< Less than k?
ȧ Logical AND
ÆP Is k prime?
3Ç# Main link. Input: n
# Find n matches
3Ç Call the helper link on 3, 4, 5, ...
```
[Answer]
# Java ~~182~~ ~~167~~ 153 bytes
## Second version
Thank's to Roman Gräf for saving 29 bytes!
```
n->{int s[]=new int[n],i=1,p=i,q=i;while(n>0)if(java.math.BigInteger.valueOf(++i).isProbablePrime(n.MAX_VALUE)){if(p>(i+q)/2)s[--n]=p;q=p;p=i;}return s;}
```
### ungolfed
```
int[] strongPrimes(Integer n) {
int[] strongPrimes = new int[n];
int i=1;
int p1=i; //last prime
int p2=i; //2 primes ago
while(n>0) if(java.math.BigInteger.valueOf(++i).isProbablePrime(n.MAX_VALUE)) { //increment i and if prime
//System.out.println("p1:"+p1+" i:"+i+" p2:"+p2);
if(p1>(i+p2)/2) strongPrimes[--n]=p1; //if the previous one was strong
p2=p1;
p1=i;
}
return strongPrimes;
}
```
### General
I don't think I can get it any smaller without help. Doesn't anyone now of an other build in function to check for primes?
### concerns
technically there is 2^(-2^31) chance that `isProbablePrime(Integer.MAX_VALUE)` returns true on a non prime but this doesn't happen for an integer.
It also outputs the numbers in reverse order but I didn't see anything about the order in which the primes should be outputted but that's an easy fix (although it could cost some bytes)
[Answer]
# [Python 2](https://docs.python.org/2/), 106 103 bytes
**Edit:** -3 bytes thanks to [@Mr.Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder)
```
n=input()
a=2;b=i=3
while n:
i+=2
if all(i%k for k in range(3,i)):
if i+a<b*2:print b;n-=1
a,b=b,i
```
[Try it online!](https://tio.run/##DcrBCoMwDADQs/2KXIR2VtB60@VjEtAZLLGUytjXd72800u/ct4aalUUTU@xzhCGjVFwMd9T4g66GpABQ/MAitFKf8FxZ7hAFDLpZ7eLF@fa61qRgd78CmvKogV40xFn05FnZC@1ztP0Bw)
Quite straight forward. Loop through all prime numbers keeping track of the two last primes. When a new prime is found, we check if the previous prime is a strong prime, and then update the two primes kept track of. This is done until n strong primes have been found.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 25 bytes
```
.f&P_Z>yZ+fP_ThZefP_TUZQ3
```
**[Try it here!](https://pyth.herokuapp.com/?code=.f%26P_Z%3EyZ%2BfP_ThZefP_TUZQ3&input=4&debug=0)** or **[Check out the test Suite!](https://pyth.herokuapp.com/?code=.f%26P_Z%3EyZ%2BfP_ThZefP_TUZQ3&input=4&test_suite=1&test_suite_input=0%0A4%0A7%0A47&debug=0)**
---
# Explanation
Quite happy with this golf given that Pyth kind of lacks prime built-ins.
```
.f&P_Z>yZ+fP_ThZefP_TUZQ3 Full program. Note that Q means input.
.f Q3 First Q inputs with truthy results, starting at 3 and counting up by 1.
fPThZ First prime after the current number.
efP_TUZ The last prime before the current number.
+ Sum.
>yZ Is the current number doubled higher than the sum?
&P_Z And is the current number prime?
Output implicitly.
```
[Answer]
# Mathematica, ~~81~~ 66 bytes
```
Select[Partition[Prime@Range[#^2],3,1],Apply[#+#3<2#2&]][[;;#,2]]&
```
*thanx to @Marthe172 for -15 bytes*
[Answer]
# [Actually](https://github.com/Mego/Seriously), 17 bytes
```
⌠;D;⌐P@P+½@P>⌡╓♂P
```
[Try it online!](https://tio.run/##ASkA1v9hY3R1YWxsef//4oygO0Q74oyQUEBQK8K9QFA@4oyh4pWT4pmCUP//NA "Actually – Try It Online")
Explanation:
```
⌠;D;⌐P@P+½@P>⌡╓♂P
⌠;D;⌐P@P+½@P>⌡╓ first n values (starting with k=0) where:
D P (k-1)th prime
;⌐P@ + plus (k+1)th prime
½ divided by 2
; @P> is less than kth prime
♂P primes at those indices
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 19 bytes
```
µNØN<ØN>Ø+;›i¼NØ}})
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0Fa/wzP8bIDY7vAMbetHDbsyD@0BCtXWav7/b2IOAA "05AB1E – Try It Online")
[Answer]
## C++, 334 bytes, 318 with MSVC
-1 byte thanks to Mr.Xcoder
-1 byte thanks to Zacharý
With the MSVC compilation, you don't need to include the `cmath` header yourself, it compiles without
```
#include<vector>
#include<cmath>
typedef std::vector<int>v;v p{2};int i(int t){int m=sqrt(t)+2,i=2;for(;i<m;++i)if(t%i<1)return 0;return 1;}void n(){int l=p.back()+1;while(!i(l))++l;p.push_back(l);}auto s(int m){if(!m)return v();n();n();v r;while(r.size()!=m){if((p[0]+p[2])/2<p[1])r.push_back(p[1]);p.erase(p.begin());n();}return r;}
```
## tsh and Mr.Xcoder answer : 131 bytes
tsh rewrote the answer in 139 bytes ( -195 ), and Mr.Xcoder golfed it more with 131 bytes
```
int N,t,o,a,b,i;void n(){t=++N;for(o=2;++o<t;)if(t%o<1)n();}void s(int m,int*r){b=N=t=5;for(;i<m;)if(a=b,b=t,n(),b+b>a+t)r[i++]=b;}
```
[Mr.Xcoder TIO Link](https://tio.run/##JY5BbsMgEEX3PsVIVSS7UKmN2hXgI/gCkReASYQUDxaM24Xls7uDs4D5g/77fL8sHw/vjyMiwSBJJmmlk1H9pjgBtt1GRohB3VNuk7kqIZIm1cV7S5ekvzp2qP30lrZGzJLv99xtzgyGzM8Jqqjnk7HGSWdIMiWdcL0V1OVbFGI0Tu3HW0T/XKegYyqUg537Zi0RH4B2DmWxPkChSTXnRzZyCmwNQF1RsfARoe9futaADAYw/NXlhmN9Li1KyF2V3AzOzpFdn4qHZhS4zSuW89JKoDVwxbHOgNOzkjufHGjNyFyzN8f39R8)
First version ungolfed :
```
#include<vector>
#include<cmath>
typedef std::vector<int> v;
v p{2};
//Tells if a number is prime or not
int i(int t) {
int m = sqrt(t) + 2, i = 2;
for (;i < m;++i)
if (t%i < 1)
return 0;
return 1;
}
//Push back the next prime number
void n() {
int l = p.back() + 1;
while (!i(l))
++l;
p.push_back(l);
}
//Generate a list of m strong primes
auto s(int m) {
if (!m)
return v();
n();
n();
v r;
while (r.size() != m) {
if ((p[0] + p[2]) / 2 < p[1])
r.push_back(p[1]);
p.erase(p.begin());
n();
}
return r;
}
```
[Answer]
# Haskell, ~~123~~ ~~121~~ ~~114~~ 85 bytes
```
import Data.List
g=(`take`(tails(nubBy(((>1).).gcd)[2..])>>=(\(a:b:c:_)->[b|b-a>c-b])))
```
(anonymous function [courtesy](https://codegolf.stackexchange.com/questions/141444/generate-strong-primes/141501#comment346810_141501) of [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz); I initially thought I must both print and then return, so had a longer code)
(not counting the `g=` bit)
Running it:
```
~> g 7
[11,17,29,37,41,59,67]
```
[Answer]
# [Python 2](https://docs.python.org/2/) + [SymPy](https://pypi.python.org/pypi/sympy/1.1.1), 118 bytes
Not as short as the classic approach, but I think it's worth posting.
```
from sympy.ntheory import*
def f(i):
k=3
while i:
if prevprime(k)+nextprime(k)<k*2and isprime(k):i-=1;yield k
k+=2
```
[Try it online!](https://tio.run/##NclNDsIgEEDhdTnFLKGNJqIrlMOYMIQJv6GTKqdHN12@77XBoRY9p@81wz5yG9fCAWsfQLnVzqtw6MFLUkZAtHcBn0AJgYxYyEPreLROGWVUW8Evn/GKq34XB7SfYuhib89BmBxEscTN6vl/hWWinaWXD6XU/AE "Python 2 – Try It Online")
[Answer]
# Axiom, 109 bytes
```
h(n)==(c:=s:=3;r:=[];for i in 5..by 2|prime?(i)repeat(#r>=n=>break;p:=c;c:=s;s:=i;p+s<2*c=>(r:=cons(c,r)));r)
```
ungolf and results
```
f(n)==
p:=c:=s:=3;r:List INT:=[]
for i in 5.. by 2|prime?(i) repeat
#r>=n=>break
p:=c;c:=s;s:=i;(p+s)/2<c=>(r:=cons(c,r))
r
(4) -> f 47
(4)
[599, 587, 569, 557, 541, 521, 499, 487, 479, 461, 457, 439, 431, 419, 397,
379, 367, 347, 331, 311, 307, 281, 277, 269, 251, 239, 227, 223, 197, 191,
179, 163, 149, 137, 127, 107, 101, 97, 79, 71, 67, 59, 41, 37, 29, 17, 11]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 86 bytes
```
n=input()
u=p=2;v=i=3
while n:
p*=i;i+=1
if p*p%i:
if u+i<2*v:print v;n-=1
u,v=v,i
```
[Try it online!](https://tio.run/##DcpBCoQwDEbhtTlFN4KjdWFnMdCa4yj@IDFIm8HT1@7eB0@ffFwSahWGaMnDhworh2QM/tL/wLk5ieR0ZCRMvJDD3qQ9InUty4Q1jBb1hmRnSeb2dMUbm0etvxc "Python 2 – Try It Online")
Uses Wilson's theorem for the primality test.
[Answer]
# [Kotlin](https://kotlinlang.org), ~~181~~ 180 bytes
```
fun f(l:Int):Array<Int>{var a=1
var b=1
var i=0
var c=0
val o=Array(l,{0})
while(l>0){c++
if((1..c).filter{c%it==0}.size==2){if(c-b<b-a){o[i]=b
if(++i>=l)break}
a=b
b=c}}
return o}
```
[Try it online!](https://tio.run/##jVNLb5wwEL7zK6ZRK9ldQnguYRVWitQeKlXqoe2p6sGwkLhxYGubRA3it29nTDbk0JXKwfPNzDcPM@O73irZHeT9vtcWfokHEQxWquA9XFzAd9PsoO016KHrGn1ohw5apjafOss311qLP1cIt@OD0CDKyCNZPUtZhk7WTiroSxfAlD@GE/ceb6VqmNqGfKxXK0@2jEVBUPOglco2eqzfSVuW4RQY@dSUZcxHpNTn1VV1LvjY/5A/y4qiViu5LRWvdCPuJk@gsSrrafJ0YwfdQT8ddsIKqJUwBr41xn5AlVFDstsPdgN4AR9cg4N1huVe3PPoxvdCdkzoG3P0fbVadjdbDqMH@FGwxcwGSlDS2C8tc/bj91I19EFQAiRw7v@bky6cKPIhyn2ICx@S/GREfirChxT1DPH6dHT6X@E@5IhzxAXiKCRiSCimg7hRis5onVAGQgVRiBzHCR2EEnTEGTriNaGcbJeoJpQqoepJQgf1lFDRhFIlhWsFUUrelLKkGdnWpBIlvSS1QJTF1LNrnCgZFcrImxUF5@4X4FRJ0FozGhsuwjy@4zyPM50XAofaOl7gFoa/UGQL7I1bCBM0vwehDJsjfJcumBX@Oit99lb3j3BtTKOt7LuPWveandE8oBX4JuYH93ZcSk4@qnO2wPafccMYd7ZXZRbH2dLh5C3nHlfWqu650h5fQ7ND6nT4Cw "Kotlin – Try It Online")
## Explained
```
fun f(l: Int): Array<Int> {
var a = 1 // Lowest prime
var b = 1 // Middle prime
var i = 0 // Current prime index
var c = 0 // Highest prime
val o = Array(l, { 0 }) // Output array
while (l > 0) { // Functions as while true, while skipping for the 0 case
c++ // Increment the highest prime
if ((1..c).filter { c % it == 0 }.size == 2) { // Only if it is prime
if (c - b < b - a) { // If it is strongly prime
o[i] = b // Then record it
if (++i >= l) break // If we have all the answers then stop
}
a = b // Rotate the primes
b = c // As above
}
}
return o // Return the answer
}
```
] |
[Question]
[
Create a program that determines, given an input of the path, whether Mario can reach the end, denoted by `E`, from the start, denoted by `S`.
A path will look something like this:
```
S = E
=====
```
In a path, the various symbols and what they represent are:
* `=`: wall/floor/ceiling. Mario cannot walk through wall , and cannot fall past a floor, or jump past a ceiling (he would hit his head)
* (space): air. Mario can walk through this, and jump through it, and fall through it
* `S`: air, except showing where Mario starts. This will always appear in the left-most column of the input, at ground level.
* `E`: air, except showing where Mario wants to get. This will always appear in the right-most column of the input, at ground level.
The input will have spaces at every place where Mario could walk.
Mario can only move forward; in this example Mario cannot get to the goal
```
S
===
===
E
====
```
nor can he in this one
```
E
==
==
#==
==
==
==
S ==
======
```
However, he can reach the space denoted by `#` (which will not appear in input), because he can jump up to four cells high; Mario is superhuman. As another example of his superhumanity:
```
S
=
=
=
=
=
= #
= =
=
=
=
= E
=======
```
Mario can get to the `E` by falling the great distance, surviving, and walking calmly to `E`. Note that he cannot reach the `#`, because Mario falls straight down.
Mario can jump *really* high, but not very far forward by comparison.
```
S E
== ==
= =
```
Mario may attempt to jump the gap, but he will fail, and fall straight in. he cannot reach the end.
Mario can reach the goal in all of these examples:
```
E
=
=
=
S=
==
```
```
=
= E
S= =
== =
= =
=====
```
```
S
=
= E
====
```
This is code golf, so fewest bytes wins!
[Answer]
## [Slip](https://github.com/Sp3000/Slip), ~~38~~ ~~27~~ 25 bytes
```
S>(`=<<`P{1,5}>`P>`P*)+#E
```
Requires input to be padded to a rectangle such that there are spaces in every cell Mario needs to traverse (potentially with a leading line full of spaces). Prints either a string representing the valid path (which includes `S`, `E` and all the `=` walked on except the last) or nothing if no path exists.
[Test it here.](https://slip-online.herokuapp.com/?code=S%3E%28%60%3D%3C%3C%60P%7B1%2C5%7D%3E%60P%3E%60P%2a%29%2B%23E&input=%20%20%20%20%20%20%0A%20%3D%20%20%20%20%0A%20%3D%20%20%20%20%0A%20%3D%20%20%20E%0AS%3D%20%20%20%3D%0A%3D%3D%20%20%20%3D%0A%20%3D%20%20%20%3D%0A%20%3D%3D%3D%3D%3D&config=)
### Explanation
Slip was [Sp3000's entry](https://codegolf.stackexchange.com/a/47532/8478) to our 2D pattern matching language design challenge. It's a bit like a 2D-extension of regex where you can give instructions to the engine's cursor when it's allowed or required to make left or right turns. It also has a convenient feature where you can prevent the cursor from advancing, allowing you to match a single position twice in a row (with different patterns).
Slip doesn't have something comparable to lookarounds in regex, but since you can move over any position multiple times, one can just test the condition and then return. We use this to ensure that we only jump when on the ground by moving into the ground tile after each step.
```
S Match the starting position S.
> Turn right, so that the cursor points south.
( One or more times... each repetition of this group represents
one step to the right.
`= Match a = to ensure we've ended up on ground level before.
<< Turn left twice, so that the cursor points north.
`P{1,5} Match 1 to 5 non-punctuation characters (in our case, either space,
S or E, i.e. a non-ground character). This is the jump.
> Turn right, so that the cursor points east.
`P Match another non-ground character. This is the step to the right.
> Turn right, so that the cursor points south.
`P* Match zero or more non-ground characters. This is the fall.
)+
# Do not advance the cursor before the next match.
E Match E, ensuring that the previous path ended on the exit.
```
[Answer]
# Java ~~234 230 221 216 208 207 205~~ 179 Bytes
Look, I beat C and python? I have acheived true transcendence among mortals! All jokes aside, this was a fun challenge. The following function takes input as an array of column strings each with the same length. If this is against the rules please do let me know. It outputs 1 meaning a successful mario run, and any other value implying a failed mario run.
```
int m(String[]a){int l=a.length-1,z=a[l].indexOf(69),m=a[0].indexOf(83),i=1,x;a[l]=a[l].replace("E"," ");for(;i<=l;m=x,i++){if(m-(x=a[i].indexOf('='))>3|x<1)return-1;}return m-z;}
```
Here is the older logic (which is similar to the current version) with example use and output. Plus some comments explaining the logic
```
/**
*
* @author Rohans
*/
public class Mario {
int m(String[] a) {
//declare variables for the finish the location of mario and the length
int z, l = a.length - 1, m = a[0].indexOf("S");
//treat the exit as a space
z = a[l].indexOf("E");
a[l] = a[l].replaceAll("E", " ");
//go through the map
for (int i = 1, x, r = 1; i <= l; i++) {
//if mario can safely jump to the next platform (it picks the highest one)
if (((x = a[i].indexOf("=")) != 0 && (x = a[i].indexOf(" =")) == -1) || m - x > 4) {
return 0;
}
//adjust marios y location
m = x;
}
//make sure mario made it to the end of the level
return m == z ? 1 : 0;
}
public static void MarioTest(String... testCase) {
System.out.println(new Mario().m(testCase) == 1 ? "Mario made it" : "Mario did not make it");
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
MarioTest(" S=", "=====", " =", " =", "= =", " E=");
}
}
```
[Answer]
# Python, ~~260~~ ~~239~~ ~~222~~ ~~215~~ ~~209~~ 206 Bytes,
### [try it on ideone (with test cases)](https://ideone.com/EGKuPW)
```
f=lambda m,y=-1,x=0:f(m,m[0].find("S"))if y<0else y<len(m[0])-1and x<len(m)and m[x][y]!="="and(m[x][y]=="E"or m[x][y+1]=="="and any(f(m,y-i,x+1)for i in range(5)[:(m[x][y::-1]+"=").find("=")])or f(m,y+1,x))
```
call like: `f([' S=', ' E='])`
### patch notes:
*Now, like some of the other solutions, assumes input is an array of coloumn strings, each starting with a " "*
*Wrapper for old input form:* `g=lambda x:f(map("".join,zip(*([" "*x.index("\n")]+x.split("\n")))))`
*Also, I fixed a bug where Mario could jump through blocks above him.*
### ungolfed version with explanations:
`f` recursivly calls itself in all directions Mario can move to from `y,x`. It returns `True` when it reaches the `"E"nd`, which then goes back through all the function calls until `g` finally returns `True`.
```
def g(x):
#create a array of strings which are the rows of the input
global m
m=x.split("\n")
m=[" "*len(m[0])]+m # because Mario can jump over sometimes
#Mario starts at the S
return f([i for i,a in enumerate(m) if a[0]=="S"][0],0)
def f(y,x):
#print y,x
if y>len(m)-2 or x>=len(m[0]) or y<0: return False #out of bounds
if m[y][x]=="E":return True #Reached the goal
if m[y][x]=="=":return False #We got stuck inside a wall
if m[y+1][x]=="=": #if you have ground under your feet
for i in range(5): #jump max 4
if f(y-i,x+1): #go one forward and try to go further from there
return True
return f(y+1,x) ##fall down
```
[Answer]
## [Snails](https://github.com/feresum/PMA/blob/master/doc.md), ~~41~~ ~~37~~ 29 bytes
*Thanks to feersum for some help with avoiding overlapping paths and for saving 4 bytes.*
```
=\S(^=d=\=u\ ,4(r!\=d.),r),\E
```
Requires input to be padded to a rectangle such that there are spaces in every cell Mario needs to traverse (potentially with a leading line full of spaces).
[Try it online!](http://snails.tryitonline.net/#code=PVxTKF49ZD1cPXVcICw0KHIhXD1kLiksciksXEU&input=ICAgICAgCiA9ICAgIAogPSAgIEUKUz0gICA9Cj09ICAgPQogPSAgID0KID09PT09)
### Explanation
Snails was [feersum's entry](https://codegolf.stackexchange.com/a/47495/8478) to our 2D pattern matching language design challenge. Like Slip it's also similar to regex, but the major difference is that a) this one supports assertions (lookarounds) and b) aside from these assertions, it's not possible to traverse any cell in the grid twice. That makes this problem a bit tricky, since there are cases where Mario needs to fall into a hole and jump back out, e.g.:
```
S E
= =
===
```
Apart from these differences, the syntax of the two languages also differs quite a lot.
To circumvent the issue that we can't traverse a cell twice, we always alternate a horizontal step with a vertical step. However, this means that we have need to handle a fall before we step over the ledge. So falls will technically actually go through ground tiles but we'll ensure that they only happen next to open space.
```
=\S Ensure that the match starts on an S, without actually matching it.
( This group matches zero or more steps to the right (with a potential
vertical step after each one).
^= Match a non-ground cell, stepping right (on the first iteration,
there is no step yet, so this matches the S).
d=\= Ensure that there's a ground tile below, so that the step ends on
a valid position.
u\ ,4 Match 0 to 4 spaces going up. This the optional jump.
( This group matches zero or more steps down, if a fall is valid here.
r!\= Ensure that there is no ground-tile right of the current cell.
d. Take one step down onto any character.
),
r Reset the direction to right for the next iteration.
),
\E Match the exit.
```
[Answer]
# C, ~~256~~ ~~236~~ ~~213~~ 197 bytes
*20 bytes saved by "This will always appear in the left-most column of the input"*
*23 bytes saved thanks to @RohanJhunjhunwala's column-based system*
[Try it on ideone, with test cases...](https://ideone.com/8FQC16)
```
k,y,x,h;f(v,l)char**v;{h=strlen(*v);x=strcspn(*v,"S");while(y<l&x<h)if(v[y][x]==69)return 0;else if(v[y][x+1]^61)x++;else{if(v[y+1][x]==61)while(k<4)if(v[y+1][x-++k]^61){x-=k;break;}y++;}return 1;}
```
# Usage:
```
$ ./mario "S=" " =" " =" " =" "E="
main(c,v)char**v;{printf("%s",f(v+1,c-1)==0?"true":"false");}
```
---
Ungolfed with explanation:
```
k,y,x,h; //omitting int for saving 4 bytes, global variables initialize as 0 by default
f(v,l)char**v;{ //saving 2 bytes
h=strlen(v[0]); //get height of map
x=strcspn(v[0],"S"); //where is start point?
while(y<l&&x<h) //while not out of bounds
if(v[y][x]==69)return 0; //if we hit end return 0 (69 is ASCII E)
else if(v[y][x+1]!=61)x++; //we fall one block if there isn't floor underneath us (61 is ASCII =)
else{
if(v[y+1][x]==61) //if there is a wall in front of us
while(k<4) //start counting
if(v[y+1][x-++k]!=61){ //if found a way
x-=k; //go to there
break; //we don't want to jump multiple times
}
y++; //finally, walk one block forwards
}
return 1; //if out of bounds
}
```
[Answer]
# PHP, ~~399~~ ~~338~~ ~~284~~ ~~265~~ 251 bytes
```
<?function w($m,$p){$w=strpos($m,"
")+1;if($p>strlen($m)|($p%$w)>$w-2|$p<0|'='==$m[$p])return 0;if('E'==$m[$p])die(1);if('='!=$m[$p+$w])return w($m,$p+$w);else for(;$z<5&'='!=$m[$q=$p-$w*$z];$z++)if(w($m,$q+1))die(1);}die(w($m=$argv[1],strpos($m,S)));
```
expects input as command line argument with unix style line breaks and trailing spaces in every line, returns exit code `1` for success, `0` for failure
**breakdown** to function
```
function w($m,$p) // function walk
{
$w=strpos($m,"\n")+1;
if($p<0|$p>strlen($m)|($p%$w)>$w-2 // too high / too low / too far right
| '='==$m[$p] // or inside a wall
)return 0;
if('E'==$m[$p])return 1; // Exit found
if('='!=$m[$p+$w])return w($m,$p+$w); // no wall below: fall down
else for($z=0;$z<5 // else: jump
& '='!=$m[$q=$p-$w*$z] // do not jump through walls
;$z++)
if(w($m,$q+1)) // try to walk on from there
return 1;
// no success, return failure (NULL)
}
function m($i){$argv=[__FILE__,$i];
return w($m=$argv[1],strpos($m,S)); // walk through map starting at position of S
}
```
**tests** (on function m)
```
$cases=[
// examples
"S = E\n=====",0,
"S \n=== \n \n ===\n E\n====",0,
" E \n == \n== \n == \n== \n == \n== \nS == \n======",0,
"S \n= \n= \n= \n= \n= \n= \n= = \n= \n= \n= \n= E\n=======",1,
"S E\n== ==\n = = ",0,
" E\n =\n =\n =\nS=\n==",1,
" \n = \n = E\nS= =\n== =\n = =\n =====",1,
"S \n= \n \n \n \n \n \n \n= E\n====",1,
// additional cases
"S \n= \n=E",1,
" == \n == \n \nS==E\n== ",1
];
echo'<table border=1><tr><th>input</th><th>output</th><th>expected</th><th>ok?</th></tr>';
while($cases)
{
$m=array_shift($cases);
$e=array_shift($cases);
$y=m($m);
$w=strpos($m,"\n");
echo"<tr><td><div style=background-color:yellow;width:",$w*8,"px><pre>$m</pre></div>width=$w</td>
<td>$y</td><td>$e</td><td>",$e-$y?'N':'Y',"</td></tr>";
}
echo'</table>';
```
[Answer]
# Ruby, ~~153~~ 147 bytes
Sorry, Java... your spot as best non-golf lang for the job is being taken over!
Input is a list of column strings, prepended with a single space in the style of how the Slip and Snails solutions require their inputs to be padded with a rectangle of empty space.
[Try it online!](https://repl.it/Cfqj/2)
```
f=->m,j=0,s=p{c,n=m[j,2]
s||=c=~/S/
e=c=~/E/
s+=1 while(k=c[s+1])&&k!=?=
s==e||(0..4).any?{|i|k&&s>=i&&c[s-i,i]!~/=/&&n&&n[s-i]!=?=&&f[m,j+1,s-i]}}
```
[Answer]
## Grime, 46 bytes (non-competing)
```
A=\E|[S ]&<\ {,-4}/0/./* \ /*/A/\=/./*>
n`\S&A
```
I have updated Grime several times after this challenge was posted, so this answer is not eligible for winning.
Some of the changes are so new that I haven't been able to get them into TIO, but once I do, you can [try out the program](http://grime.tryitonline.net/#code=QT0uJjxcRXxbIFxiXXsxLC00fS8wL1tdLyogWyBcYl0vKi9BL1w9L1tdLyo-Cm5iYFxTJkE&input=ID0KUz0KPT0KICAgRQo9PT09CiA).
In any case, my [repository](https://github.com/iatorm/grime) contains a version that handles this code correctly.
The program prints `1` if Mario can reach the goal, and `0` if not.
The input has to contain spaces in all places Mario needs to visit.
For general inputs, I have the following **57-byte** solution:
```
A=\E|[ \bS]&<[ \b]{,-4}/0/[]/* [ \b]/*/A/\=/[]/*>
nb`\S&A
```
## Explanation
The high-level explanation is that the nonterminal `A`, defined on the first line, matches a **1×1** sub-rectangle of the input where Mario can reach the goal.
`A` is defined as either the literal `E` (Mario is already at the goal), or as a **1×1** pattern that's on the left column of some **2×n** rectangle containing a valid Mario jump to another match of `A` on the right column.
The second line counts the number of matches of `A` that also contain the start character `S`, and prints that.
Here's a break-down of the code:
```
A=\E|[ S]&<\ {,-4}/0/./* \ /*/A/\=/./*>
A= Define A as
\E| a literal E, or
[ S]& a literal space or S
< > contained in a larger rectangle
that this bracketed expression matches.
\ {,-4}/0/./* Left half of the bracketed expression:
\ {,-4} Rectangle of spaces with height 0-4,
/ below that
0 the 1x1 rectangle we're currently matching,
/. below that any 1x1 rectangles
/* stacked any number of times vertically.
\ /*/A/\=/./* Right half of the bracketed expression:
\ /* Spaces stacked vertically,
/A below that another match of A,
/\= below that a literal =,
/./* below that 1x1 rectangles stacked vertically.
```
The idea is that the `\ {,-4}` part on the left matches the space through which Mario jumps upward, and the `\ /*` part on the right matches the space trough which he then falls down.
We require that he lands on a match of `A` (since we want to reach the goal) that's on top of a `=`.
The vertical stacks below both columns will simply guarantee that the columns have the same height, so we can concatenate them (which is what the single space in the middle does).
Here's an ASCII art diagram of an example jump, broken into the aforementioned rectangles, and with spaces replaced by `*`s:
```
Left column: Right column: +---+---+
a = \ {,-4} d = \ /* | * | * |
b = 0 e = A + + + d
c = ./* f = \= | * | * |
g = ./* a + +---+
| * | * | e
+ +---+
| * | = | f
+---+---+
b | S | = |
+---+ | g
c | = | * |
+---+---+
```
On the second line, the option `n` triggers counting of all matches, instead of finding the first match.
In the general solution, the spaces can also be special out-of-input characters, and option `b` causes the input to be padded with out-of-input characters.
I hope all of this makes sense!
] |
[Question]
[
**Cue Storyline:** It is the early 21st century, and most things have become a thing of the past. You and your fellow code-golf-eteers, however, are on a quest to reenact the 1990s. As a part of this challenge, you must recreate a minimalistic chatroom.
**The Goal:** To create a chatroom with as few bytes as possible. The program(s) that you write shall function as a simple server, which serves a webpage, which allows users to post text onto the screen.
**The Actual Goal:** To actually host a working chatroom from your own computer. You don't have to do this, but it is a lot more fun this way.
**Requirements:**
* Users should be able to give themselves a username that lasts for the session
* Users should be able to repeatedly type and submit text, which will be displayed to other users
* Each user should be able to see the text that is submitted by all users, along with the usernames of the submitters, and the information should be displayed in chronological order
* The page should also display the number of people online and a list of their usernames
* Your chatroom should be accessible to anyone on the internet who knows where to find it (such as knowing the IP address).
* It should function in modern web browsers.
All else is up to you!
**Submissions:**
* Should include the source code, or a link to the source code
* Should include screenshots of the functional chatroom
* Should include the total size, in bytes, of all of the programs/files that you have written that are required to make it work.
This challenge has been in the sandbox for a while now, so hopefully all of the kinks have been worked out.
[Answer]
## PHP + JQuery + HTML + CSS, 1535 bytes
This is a submission leaning more towards what the OP deemed as 'the actual goal'. That is, a fully functional chat server, which may be hosted on just about any web server anywhere.
Functionality includes:
* Notifications when users enter or leave the chat room.
* Notifications when users change their alias.
* Real time polling for new messages, without generating excess server traffic, or server load.
* Layout and usability strongly resembling existing chat clients, such as X-Chat.
To being a session, enter an alias in the appropriate box, and press `Tab` or `Enter` to submit. If the alias is already in use, you will be notified. Sending messages is also done via `Enter`.

For your convenience, an archive of all files may be found here: [chat.zip](https://docs.google.com/file/d/0Bz5cOzIgiwAgVkpfbktvcndQTFk/edit) (choose Download from the File menu). To install, unpack to a web directory on any server running PHP 5.4 or higher.
Caveats:
* IE 8 or lower will spin into an infinite loop while polling, because for some reason unknown to humanity, all Ajax requests are cached by default. It also prevents you from sending the same message twice, and updating the user list properly. This could be fixed by adding `cache:false` to every Ajax request.
* In all version of IE, messages will not be sent by pressing Enter, because the `change` event is not triggered (pressing Tab, however, does work). This could be fixed by adding an `onkeypress` handler, checking if the key was Enter, and then calling `$(v).blur().focus()`.
In short, IE is not supported.
---
### Client
Positioning of elements could be a bit more robust, but it should look alright with a minimum window size of about ~800x600.
chat.htm (190 bytes)
```
<script src=jquery.min.js></script>
<script src=c.js></script>
<link rel=stylesheet href=c.css>
<select id=u multiple></select><pre id=o></pre>
<input id=n onchange=u()><input id=v onchange=s()>
```
c.css (136 bytes)
```
i{color:#999}
#u{float:right;height:100%;width:200px;margin-left:10px}
#o{border:1px solid #999;height:93%;overflow-y:scroll}
#v{width:54%}
```
c.js (435 bytes)
```
var l
(function p(){
$.ajax({url:'p.php',data:{n:$('#n').val()},success:function(d){
$('#o').html(d).scrollTop(1e4);$('#u').load('n.php');
},complete:p,timeout:2e4})
})()
function s(){
$.get('s.php',{n:$(n).val(),v:$(v).val()})
$(v).val('')
}
function u(){
$.get('u.php',{l:i=l,n:l=$(n).val()}).fail(function(){
alert("This name is already in use!")
$(n).val(l=i)
})
}
$(window).on('unload',function(){$.ajax({url:'l.php',data:{l:l},async:false})})
```
---
### Server
I apologize for the server being broken up into so many tiny chunks. The alternative would be to use an adequate message protocol (via JSON encode/decode), or having a large `if ... elseif ...` according to which post variables are present. Making separate scripts, an just requesting from the one you need is a lot shorter, and perhaps simpler than both.
o.php (119 bytes) **O**pens as connection to the 'database'
```
<?$m=array_slice(unserialize(file_get_contents(m)),-300);
$u=unserialize(file_get_contents(u));$t=time();extract($_GET);
```
c.php (57 bytes) **C**ommits changes to the 'database'
```
<?foreach([u,m]as$c)file_put_contents($c,serialize($$c));
```
p.php (151 bytes) **P**olls for new messages
```
<?for($t=time();@filemtime(m)<$t;usleep(1e3))clearstatcache();include('o.php');
foreach($m as$v)if($n&&$v[0]>=$u[$n])echo@date("[H:i]",$v[0])."$v[1]\n";
```
s.php (62 bytes) **S**end a message to the server
```
<?include('o.php');$m[]=[$t,"<b>$n</b>: $v"];include('c.php');
```
u.php (222 bytes) **U**ser registration or alias change
```
<?include('o.php');if(!trim($n)||$u[$n])exit(header('HTTP/1.1 418'));
$m[]=[$t,$u[$l]?
"<i><b>$l</b> is now known as <b>$n</b>.</i>":
"<i><b>$n</b> has entered the chat.</i>"];
$u[$n]=$u[$l]?:$t;unset($u[$l]);include('c.php');
```
n.php (65 bytes) Retrieves the list of user **n**ames
```
<?include('o.php');foreach($u as$k=>$v)echo"<option>$k</option>";
```
l.php (98 bytes) User has **l**eft (closed their browser)
```
<?include('o.php');$m[]=[$t,"<i><b>$l</b> has left the chat.</i>"];
unset($u[$l]);include('c.php');
```
[Answer]
## Python, 230
This is fairly minimal, but it seems to be up to spec. Users are counted as "viewing the page" if they've chatted in the last 99 seconds.
```
import cherrypy as S,time
@S.quickstart
@S.expose
def _(n='',p='',l=["<form%sn value='%s'%sp%s'' type=submit>"],u={},t="><input name="):u[n]=time.time();l+=p and[n+':'+p];return'<br>'.join([k*(u[n]-99<u[k])for k in u]+l)%(t,n,t,t)
```
This uses one of my very favorite tricks in python: default values are just references to whatever you passed in. If it's a mutable object, it just comes along for the ride.
Another I don't get to use often -- currying!
**Running the Server:**
*Run the chat script from python (for example, `python chat.py`) and then* point your browser at `http://localhost:8080` to see something like

## Python, 442
This one is actually nice to use. This is golf, so I consider this a less-satisfactory solution. Now, I abuse an iframe and a form with keyhandling... and a meta refresh to poll for new content.
```
import time,cherrypy as S
class C:
c=S.expose(lambda s:"<form action=w target=t method=post><input name=n><input name=p onkeyup='if(event.keyCode==13){this.form.submit();this.value=\"\"}'><br><iframe name=t width=640>")
@S.expose
def w(s,n='',p='',l=[],u={}):u[n]=time.time();l+=p and[n+':'+p];return'<meta http-equiv=refresh content="1;url=w?n=%s">'%n+','.join(k for k in u if(u[n]-9<u[k])*k)+'<hr>'+'<br>'.join(l[::-1])
S.quickstart(C())
```

[Answer]
## Meteor: 575 characters
I had a lot of fun with this one! The application is live at <http://cgchat.meteor.com/>.
### chat.html: 171 characters
```
<body>{{>b}}</body><template name="b">{{#if l}}Online: {{#each u}}{{n}}, {{/each}}<hr>{{#each m}}{{n}}: {{t}}<p>{{/each}}<hr><input>{{else}}Name: <input>{{/if}}</template>
```
### lib/chat.js: 45 characters
```
c=Meteor.Collection;u=new c('u');m=new c('m')
```
### client/client.js: 359 characters
```
j=$.now;s=Session;t=Template.b;t.events({'change input':function(){v=$('input').val();s.get('u')?(m.insert({n:s.get('u'),t:v}),u.update(u.findOne({n:s.get('u')})._id,{$set:{l:j()}})):(s.set('u',v),u.insert({n:v,l:j()}))}});t.l=function(){return !!s.get('u')};t.u=function(){return u.find({l:{$gt:(j()-20000)}}).fetch()};t.m=function(){return m.find().fetch()}
```
[Answer]
# Node/Meteor javascript + html + css + websocket: 1,105 bytes
Here's one using node.js/[meteor](http://meteor.com). Obviously written in js, realtime, and using websockets. Uses meteor's default built-in packages.
It could be a lot smaller. Also it's persistent by way of the included mongo (not that that is a good thing).
A working screenshot:

To execute, install meteor.
Linux:
```
curl https://install.meteor.com | /bin/sh`
```
Windows: win.meteor.com
Clone my repo and execute meteor:
```
git clone http://github.com/bradgearon/meteor-chat
cd meteor-chat
meteor
```
point your browser to localhost:3000
# chat.js: 703 bytes (client/server):
```
l='subscribe',d=[],n='n',i='i',b='b',c='click #',r='return ',u='u',y=0
f=Function,m=Meteor,o=m.Collection,p=new o(b),t=new o(u)
w=f('t.remove({i:d.pop()})'),g=f('_(d.length).times(w)')
m.isClient&&(h=Template.h,e=h.events={},m[l](b),m[l](u),s=Session,
w=f(r+'s.get(i)'),h.p=f(r+'p.find()'),h.t=f(r+'t.find()'),a=f('a','a','y=$("#3").val(),s.set(i,1)'),
e[c+'2']=f('p.insert({c:(y||"?")+": "+$("#l").val()})'),
e[c + '4'] = f('w()||m.call("x",$("#3").val(),t._connection._lastSessionId,a)')
)||(
m.startup(f('t.remove({}),p.remove({}),m.setInterval(g,100)')),j=f('h=this.id;h&&d.push(h)'),
m.methods({x:f('k','d','s=m.default_server.sessions[d].socket,s.on("close",j),t.insert({n:k,i:s.id})')}))
```
# chat.css: 132 bytes
```
g{display:block;overflow-y:scroll;margin:10px;}
n{float:right;width:40%;min-height:100%;}
d{float:left;width:60%;min-height:100%;}
```
# chat.html: 270 bytes
```
<body>
{{> h}}
</body>
<template name="h">
<d>
<g>{{#each p}}{{c}}<br />{{/each}}</g>
<input id=l>{{this.k}}</input>
<input type=submit id=2 />
</d>
<n>
<g>{{#each t}}{{n}}<br />{{/each}}</g>
<input id=3 />
<input type=submit id=4 />
</n>
</template>
```
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 6 years ago.
[Improve this question](/posts/1663/edit)
The object of this puzzle is to take a deck of 52 cards and shuffle it so that each card is in a random position.
## Given:
* An array, `deck`, of 52 distinct integers representing the cards. When you start, `deck` contains exactly one of each card in some unknown order.
* A function, `int rand(min, max)`, that returns a random integer between ints `min` and `max`, inclusive. You can assume that this function is truly random.
* A function, `void swap(x, y)` that swaps two cards in the deck. If you call `swap(x, y)`, the cards at positions `x` and `y` will switch places.
## When:
* The program calls `shuffle()` (or `shuffle(deck)` or `deck.shuffle()` or however your implementation likes to run),
## Then:
* `deck` should contain exactly one of each card in perfectly random order.
## The Catch:
**You can't declare any variables.** Call `swap` and `rand` as much as you like, but you can't declare any variables of your own. This includes `for` loop counters--even implicit ones like in a `foreach`.
## Clarifications:
* You can change minor details to suit your chosen language. For example, you can write `swap` to switch two integers by reference. Changes should be to make this work with your language, not to make the puzzle easier.
* `deck` can be a global variable, or you can take it in as a parameter.
* You can do anything you want to the contents of `deck`, but you can't change its length.
* Your cards can be numbered 0-51, 1-52, or anything you like.
* You can write this in any language, but no cheating with your language's built-in `shuffle` function.
* Yes, you could write the same line 52 times. No one will be impressed.
* Execution time doesn't matter, but true randomness does.
* This isn't really code golf, but feel free to minimize/obfuscate your code.
---
## Edit: Boilerplate code and visualizer
If you used .NET or JavaScript, here's some test code you may find useful:
### JavaScript:
* Quick-and-dirty JavaScript visualizer, with CoffeeScript source: <https://gist.github.com/JustinMorgan/3989752bdfd579291cca>
* Runnable version (just paste in your `shuffle()` function): <http://jsfiddle.net/4zxjmy42/>
### C#:
* ASP.NET visualizer with C# codebehind: <https://gist.github.com/JustinMorgan/4b630446a43f28eb5559>
* Stub with just the `swap` and `rand` utility methods: <https://gist.github.com/JustinMorgan/3bb4e6b058d70cc07d41>
This code sorts and shuffles the deck several thousand times and performs some basic sanity testing: For each shuffle, it verifies that there are exactly 52 cards in the deck with no repeats. Then the visualizer plots the frequency of each card ending up at each place in the deck, displaying a grayscale heat map.
The visualizer's output should look like snow with no apparent pattern. Obviously it can't prove true randomness, but it's a quick and easy way to spot-check. I recommend using it or something like it, because certain mistakes in the shuffling algorithm lead to very recognizable patterns in the output. Here's an example of the output from two implementations, one with a common flaw:

The flawed version does partially shuffle the deck, so might look fine if you examined the array by hand. The visualizer makes it easier to notice a pattern.
[Answer]
## Haskell
Here is a point-free implementation. No variables, formal parameters, or explicit recursion. I used [lambdabot](http://www.haskell.org/haskellwiki/Lambdabot)'s `@pl` ("pointless") refactoring feature quite a bit.
```
import Data.List
import Control.Applicative
import Control.Monad
import System.Random
shuffle :: [a] -> IO [a]
shuffle = liftM2 (<$>) ((fst .) . foldl' (uncurry ((. flip splitAt) . (.) .
(`ap` snd) . (. fst) . flip flip tail . (ap .) . flip flip head .
((.) .) . (. (++)) . flip . (((.) . (,)) .) . flip (:))) . (,) [])
(sequence . map (randomRIO . (,) 0 . subtract 1) . reverse .
enumFromTo 1 . length)
main = print =<< shuffle [1..52]
```
Here's my test procedure to make sure the numbers were uniformly distributed:
```
main = print . foldl' (zipWith (+)) (replicate 52 0)
=<< replicateM 1000 (shuffle [1..52])
```
Here is the original algorithm:
```
shuffle :: [a] -> IO [a]
shuffle xs = shuffleWith xs <$>
sequence [randomRIO (0, i - 1) | i <- reverse [1..length xs]]
shuffleWith :: [a] -> [Int] -> [a]
shuffleWith xs ns = fst $ foldl' f ([], xs) ns where
f (a,b) n = (x:a, xs++ys) where
(xs, x:ys) = splitAt n b
```
[Answer]
# JavaScript
I believe this is the intended form of solution, I use the card in position 0 to keep track of progress, only shuffling the cards that have already been used as counter, this achieves the standard 52! permutations with a perfect equal distribution. The procedure is complicated by XOR swap not allowing that an element is swapped by itself.
Edit: I built in a sorting that sorts each element into place just before it is used, thus allowing this to work with an unsorted array. I also dropped recursive calling in favour of a while loop.
```
deck=[]
for(a=0;a<52;a++){
deck[a]=a
}
function swap(a,b){
deck[a]=deck[b]^deck[a]
deck[b]=deck[b]^deck[a]
deck[a]=deck[b]^deck[a]
}
function rand(a,b){
return Math.floor(Math.random()*(1+b-a))+a
}
function shuffle(){
while(deck[0]!=0){ //Sort 0 into element 0
swap(0,deck[0])
}
while(deck[0]<51){ //Run 51 times
while(deck[deck[0]+1]!=deck[0]+1){ //Sort element deck[0]+1 into position deck[0]+1
swap(deck[deck[0]+1],deck[0]+1)
}
swap(0,deck[0]+1) //Swap element deck[0]+1 into position 0, thus increasing the value of deck[0] by 1
if(rand(0,deck[0]-1)){ //Swap the element at position deck[0] to a random position in the range 1 to deck[0]
swap(deck[0],rand(1,deck[0]-1))
}
}
if(rand(0,51)){ //Swap the element at position 0 to a random position
swap(0,rand(1,51))
}
}
for(c=0;c<100;c++){
shuffle()
document.write(deck+"<br>")
}
```
[Answer]
# J
Ignoring that deck is a variable, there's the obvious...
```
52 ? 52
```
Of course, if you really want a function, there's this, which will work even if you forget to remove the jokers (or try to shuffle something other than cards).
```
{~ (# ? #)
```
So that...
```
shuffle =: {~ (# ? #)
deck =: i. 52
shuffle deck
```
This is probably outside the intent of the question, which would be to implement the shuffle yourself from rand (`?`). I might do that later when I'm not supposed to be working.
# Explanation
Explanation of `52 ? 52`:
* `x ? y` is x random unique items from y.
Explanation of `{~ (# ? #)` is harder because of [forks and hooks](http://www.jsoftware.com/help/jforc/forks_hooks_and_compound_adv.htm). Basically, it is the same as `shuffle =: 3 : '((# y) ? (# y)) { y'`, which has one implicit argument (`y`).
* `# y` gives the length of y
* This gives 52 ? 52 like before, which is a random permutation of 0..51
* `x { y` is the item of y in index x, or (in this case) items in the indexes in x.
* This lets you shuffle whatever is passed in, not just integers.
See [J Vocabulary](http://www.jsoftware.com/help/dictionary/vocabul.htm) for details of operators, though the syntax and semantics are quite a bit tricky because of rank and tacit programming.
[Answer]
### Using factoradic representation
In the [factoradic representation](http://en.wikipedia.org/wiki/Factorial_number_system) of a permutation an element i takes values from 0 to N-i. So a random permutation is just `rand(0,i)` for every N-i.
In J:
```
? |.>:i.52
2 39 20 26 ... 2 0 1 0 0 0
```
where `? x` is `rand(0,x-1)` and `|.>:i.52` is `52 51 ... 1`
Then, if `a` is the value of ith factoradic, we do the swap: `swap(deck[i], deck[i+a])`.
The list of pairs to swap are:
```
(,. i.52) ,. (,. ((?|.>:i.52)+i.52))
0 33
1 20
2 3
...
49 50
50 50
51 51
```
The swap we'll be using works like this:
```
deck
24 51 14 18 ...
deck =: 0 1 swap deck
51 24 14 18 ...
```
It's not really "by reference" but there are no real functions in J.
We'll use deck's length (`#deck`) to avoid using a constant.
### Complete program in J:
```
deck =: 52 ? 52 NB. Initial random deck
swap =: 4 : 'deck =: (x { y) (|.x) } y' NB. Given swap "function"
f =: 3 : 0 NB. function that calls the swap for a pair
({.y) swap deck
}.y
)
f^:(#deck) (,.,.[:,.]+[:?[:|.>:) i.#deck
```
[Answer]
## Python
```
import random
def rand(x, y):
return random.randrange(x, y+1)
def swap(deck, x, y):
deck[x] ^= deck[y]
deck[y] ^= deck[x]
deck[x] ^= deck[y]
def shuffle(deck):
if len(deck)>1:
deck[1:]=shuffle(deck[1:])
if rand(0,len(deck)-1)>0:swap(deck, 0, rand(1, len(deck)-1))
return deck
print shuffle(range(52))
```
[Answer]
# C#
Here's my own answer based on [the Fisher-Yates algorithm](http://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle). Should give you a perfect shuffle if your random number generator is good enough.
English version:
1. Repeatedly swap the card at `deck[0]` with the one at `deck[v]`, where `v` is the face value of the card at `deck[0]`. Repeat until `v == 0`. This will partially sort the deck, but that doesn't matter. You now know Card 0 is at the front of the deck, which means you can steal that space in the array and use it as a loop counter. This is the key "cheat" for the problem of local variables.
2. Starting at position 1 (the second card in the deck), swap the card at `i` with the one at `rand(i, 51)`. Note that you need `rand(i, 51)`, **NOT** `rand(1, 51)`. That won't ensure that each card is randomized.
3. Set `deck[0]` back to 0. Now the whole deck is shuffled except for the first card, so swap `deck[0]` with `deck[rand(0, 51)]` and you're done.
C# version:
```
public static void shuffle(int[] deck)
{
while (deck[0] > 0)
swap(ref deck[0], ref deck[deck[0]]);
for (deck[0] = 1; deck[0] < 52; deck[0]++)
swap(ref deck[deck[0]], ref deck[rand(deck[0], 51)]);
deck[0] = 0;
swap(ref deck[0], ref deck[rand(0, 51)]);
}
```
Javascript version:
```
while (deck[0] > 0)
swap(0, deck[0]);
for (deck[0] = 1; deck[0] < 52; deck[0]++)
swap(deck[0], rand(deck[0], 52));
deck[0] = 0;
swap(0, rand(0, 52));
```
...where `swap(a, b)` swaps `deck[a]` with `deck[b]`.
[Answer]
# Ruby, one line
Is this considered cheating? It should be as random as it gets.
```
deck=(0..51).to_a # fill the deck
deck[0..51] = (0..51).map{deck.delete_at(rand deck.length)}
```
(Ruby's `rand` method only takes one argument and then generates a number n such that 0 <= number < argument.)
Additionally - similar to sogart's Perl solution, but as far as I know it doesn't suffer from the problem:
```
deck = deck.sort_by{rand}
```
Ruby's sort\_by is different than sort - it first generates the list of values to sort the array by, and only then sorts it by them. It's faster when it's expensive to find out the property we're sorting by, somewhat slower in all other cases. It's also useful in code golf :P
[Answer]
## JavaScript
**NOTE: This solution is technically not correct because it uses a second parameter, `i`, in the call to `shuffle`, which counts as an external variable.**
```
function shuffle(deck, i) {
if (i <= 0)
return;
else {
swap(deck[rand(0,i-1)], deck[i-1]);
shuffle(deck, i - 1);
}
}
```
Call with `shuffle(deck,52)`
A complete working example (had to modify `swap` slightly because there is no pass-by-reference of ints in JavaScript):
```
function rand(min, max) { return Math.floor(Math.random()*(max-min+1)+min); }
function swap(deck, i, j) {
var t=deck[i];
deck[i] = deck[j];
deck[j] = t;
}
function shuffle(deck, i) {
if (i <= 0)
return;
else {
swap(deck, rand(0,i-1), i-1);
shuffle(deck, i - 1);
}
}
// create deck
var deck=[];
for(i=0;i<52;i++)deck[i]=i;
document.writeln(deck);
shuffle(deck,52);
document.writeln(deck);
```
[Answer]
## C++
```
#include <cstdlib>
#include <ctime>
#include <iostream>
int deck[52];
void swap(int a, int b) {
deck[a] ^= deck[b];
deck[b] ^= deck[a];
deck[a] ^= deck[b];
}
int r(int a, int b) {
return a + (rand() % (b - a + 1));
}
void s(int *deck) {
swap(1, r(2, 51));
deck[0] *= 100;
for(deck[0] += 2; (deck[0] % 100) < 51; deck[0]++) {
swap(deck[0] % 100,
r(0, 1) ? r(1, (deck[0] % 100) - 1) : r((deck[0] % 100) + 1, 51));
}
swap(51, r(1, 50));
deck[0] = (deck[0] - 51) / 100;
swap(r(1, 51), 0);
}
int main(int a, char** c)
{
srand(time(0));
for (int i = 0; i < 52; i++)
deck[i] = i;
s(deck);
s(deck);
for (int i = 0; i < 52; i++)
std::cout << deck[i] << " ";
}
```
Avoids swapping elements with themselves, so has to call twice to be random.
[Answer]
## D
```
shuffle(int[] d){
while(d.length){
if([rand(0,d.length-1)!=0)swap(d[0],d[rand(1,d.length-1)]);
d=d[1..$];
}
}
```
[Answer]
Another Perl solution, which actually produces uniformly distributed output:
```
sub shuffle_integers {
map int, sort {$a-int $a <=> $b-int $b} map $_+rand, @_;
}
say join " ", shuffle_integers 1 .. 52;
```
This solution uses Perl's `rand`, which returns a random number *x* in the range 0 ≤ *x* < 1. It adds such a random number to each integer in the input, sorts the numbers according to their fractional parts, and finally strips those fractional parts away again.
(I believe the use of the special variables `$_`, `$a` and `$b` falls within the spirit of the challenge, since those are how perl passes the input to `map` and `sort`, and they're not used for any other purpose in the code. In any case, I believe they're actually aliases to the input values, not independent copies. This is not actually an in-place shuffle, though; both `map` and `sort` create copies of the input on the stack.)
[Answer]
## Java
I am surprised nobody stated the obvious:
(I'll assume swap(x,x) does nothing.
```
static void shuffle(){
swap(1,rand(0,1));
swap(2,rand(0,2));
swap(3,rand(0,3));
swap(4,rand(0,4));
swap(5,rand(0,5));
swap(6,rand(0,6));
swap(7,rand(0,7));
swap(8,rand(0,8));
swap(9,rand(0,9));
swap(10,rand(0,10));
swap(11,rand(0,11));
swap(12,rand(0,12));
swap(13,rand(0,13));
swap(14,rand(0,14));
swap(15,rand(0,15));
swap(16,rand(0,16));
swap(17,rand(0,17));
swap(18,rand(0,18));
swap(19,rand(0,19));
swap(20,rand(0,20));
swap(21,rand(0,21));
swap(22,rand(0,22));
swap(23,rand(0,23));
swap(24,rand(0,24));
swap(25,rand(0,25));
swap(26,rand(0,26));
swap(27,rand(0,27));
swap(28,rand(0,28));
swap(29,rand(0,29));
swap(30,rand(0,30));
swap(31,rand(0,31));
swap(32,rand(0,32));
swap(33,rand(0,33));
swap(34,rand(0,34));
swap(35,rand(0,35));
swap(36,rand(0,36));
swap(37,rand(0,37));
swap(38,rand(0,38));
swap(39,rand(0,39));
swap(40,rand(0,40));
swap(41,rand(0,41));
swap(42,rand(0,42));
swap(43,rand(0,43));
swap(44,rand(0,44));
swap(45,rand(0,45));
swap(46,rand(0,46));
swap(47,rand(0,47));
swap(48,rand(0,48));
swap(49,rand(0,49));
swap(50,rand(0,50));
swap(51,rand(0,51));
}
```
OK, ok, it can be shorter:
```
package stackexchange;
import java.util.Arrays;
public class ShuffleDry1
{
static int[] deck = new int[52];
static void swap(int i, int j){
if( deck[i]!=deck[j] ){
deck[i] ^= deck[j];
deck[j] ^= deck[i];
deck[i] ^= deck[j];
}
}
static int rand(int min, int max){
return (int)Math.floor(Math.random()*(max-min+1))+min;
}
static void initialize(){
for( int i=0 ; i<deck.length ; i++ ){
deck[i] = i;
swap(i,rand(0,i));
}
}
static void shuffle(){
while( deck[0]!=0 ) swap(0,deck[0]);
for( deck[0]=52; deck[0]-->1 ; ) swap(deck[0],rand(deck[0],51));
swap(0,rand(0,51));
}
public static void main(String[] args) {
initialize();
System.out.println("init: " + Arrays.toString(deck));
shuffle();
System.out.println("rand: " + Arrays.toString(deck));
}
}
```
[Answer]
## Burlesque
What you are actually asking for is a random permutation of a list of integers? `r@` will give us all permutations, and we just select a random one.
```
blsq ) {1 2 3}r@sp
1 2 3
2 1 3
3 2 1
2 3 1
3 1 2
1 3 2
blsq ) {1 2 3}r@3!!BS
2 3 1
```
Since we need true randomness, something Burlesque isn't capable of doing because Burlesque has no I/O functionality you'd need to provide some source of randomness through STDIN.
That's probably something I'll fix in later version (i.e. generate a random seed at startup and push it to the secondary stack or something like that, but the Burlesque Interpreter itself has no I/O).
[Answer]
## Javascript
I'm not sure if it's "cheating" but my solution uses the native local array of a function's arguments. I included my self-made functions of `rand()` `swap()` and `filldeck()`. Of interesting note, this should work with a deck of any size.
```
var deck = [];
function shuffle(){
main(deck.length);
}
function main(){
arguments[0] && swap( arguments[0]-=1, rand(0, deck.length-1) ), main(arguments[0]);
}
function rand(min, max){
return Math.floor( Math.random()*(max-min+1) )+min;
}
function swap(x, y){
var _x = deck[x], _y = deck[y];
deck[x] = _y, deck[y] = _x;
}
function filldeck(dL){
for(var i=0; i<dL; i++){
var ran = rand(1,dL);
while( deck.indexOf(ran) >= 0 ){
ran = rand(1,dL);
}
deck[i] = ran;
}
}
filldeck(52);
shuffle();
```
[Answer]
# [Tcl](http://tcl.tk/), 32 bytes
Abusing `time` function which serves to measure how much time is spent a script is running, but also can serve as a looping mechanism without declaring any variables.
```
time {lswap $D [rand] [rand]} 52
```
[Try it online!](https://tio.run/##dY/BCoMwEETPzVcM1IP2ZsA/8C/EQ5qsEJrGEGMbEL/dRg2FHnpYdnnMLDNBmu2qSD6gaNBWBz1aFvSTsBjhHFmFFp220kP2KxrOmPOjhJnewmFpQTWIr1jYZXYv4ZNasctEAbFGZ7RVFFEoFFT3mfNfzjNXCXtyRkjKhnPiXwE/J6bPa47lRQq8pDgUnUepbSh3VFa3hlfVrprDhDsNo6fzLtot1z0aFant7ujz2itvh1AMgfzX8wE "Tcl – Try It Online")
[Answer]
**perl - this is not a proper shuffle as explained in comments!**
```
my @deck = (0..51);
@deck = sort {rand() <=> rand()} @deck;
print join("\n",@deck);
```
I think I didn't use anything as a swap etc. was that needed as part of the problem?
[Answer]
# JavaScript 4 lines
```
function shuffle() {
while(deck[0]!=0)swap(deck[0],rand(1,51))
while(deck[0]++!=104)swap(deck[0]%51+1,rand(1,51))
deck[0]=0
swap(0,rand(0,51))
}
```
Original answer that wasn't random enough. The swap wasn't guaranteed to touch each item in the deck.
```
// shuffle without locals
function shuffle() {
deck.map(function(){swap(deck[rand(0,51)],deck[rand(0,51)])});
}
```
] |
[Question]
[
## Introduction *(may be ignored)*
Putting all positive integers in its regular order (1, 2, 3, ...) is a bit boring, isn't it? So here is a series of challenges around permutations (reshuffelings) of all positive integers. This is the sixth challenge in this series (links to the [first](https://codegolf.stackexchange.com/questions/181268), [second](https://codegolf.stackexchange.com/questions/181825), [third](https://codegolf.stackexchange.com/questions/182348), [fourth](https://codegolf.stackexchange.com/questions/182810) and [fifth](https://codegolf.stackexchange.com/questions/183186) challenge).
This challenge has a mild Easter theme (because it's Easter). I took my inspiration from this highly decorated (and in my personal opinion rather ugly) goose egg.

It reminded me of the [Ulam spiral](https://en.wikipedia.org/wiki/Ulam_spiral), where all positive integers are placed in a counter-clockwise spiral. This spiral has some interesting features related to prime numbers, but that's not relevant for this challenge.
[](https://i.stack.imgur.com/ITBfV.png)
We get to this challenge's permutation of positive integers if we take the numbers in the Ulam spiral and trace all integers in a *clockwise* turning spiral, starting at 1. This way, we get:
```
1, 6, 5, 4, 3, 2, 9, 8, 7, 20, 19, 18, 17, 16, 15, 14, 13, 12, 11, 10, 25, 24, 23, etc.
```
If you would draw both of the spirals, you'd get some sort of an infinite [mesh](https://www.youtube.com/watch?v=hpghMn2Vg1c) of (egg shell) spirals (*note the [New Order](https://en.wikipedia.org/wiki/New_Order_(band)) reference there*).
This sequence is present in the OEIS under number [A090861](https://oeis.org/A090861). Since this is a "pure sequence" challenge, the task is to output \$a(n)\$ for a given \$n\$ as input, where \$a(n)\$ is [A090861](https://oeis.org/A090861).
## Task
Given an integer input \$n\$, output \$a(n)\$ in integer format, where \$a(n)\$ is [A090861](https://oeis.org/A090861).
*Note: 1-based indexing is assumed here; you may use 0-based indexing, so \$a(0) = 1; a(1) = 6\$, etc. Please mention this in your answer if you choose to use this.*
## Test cases
```
Input | Output
---------------
1 | 1
5 | 3
20 | 10
50 | 72
78 | 76
123 | 155
1234 | 1324
3000 | 2996
9999 | 9903
29890 | 29796
```
## Rules
* Input and output are integers.
* Your program should at least support input in the range of 1 up to 32767).
* Invalid input (0, floats, strings, negative values, etc.) may lead to unpredicted output, errors or (un)defined behaviour.
* Default [I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods) apply.
* [Default loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answers in bytes wins
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~16 14 11 10 9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-1 thanks to Lynn (mod-2; logical NOT; add to self: `Ḃ¬+` -> bitwise OR with 1:`|1`)
```
|1×r)ẎQi
```
A monadic Link accepting an integer, `n`, which yields an integer, `a(n)`.
**[Try it online!](https://tio.run/##y0rNyan8/7/G8PD0Is2Hu/oCM////29oAAA "Jelly – Try It Online")** (very inefficient since it goes out to layer \$\lceil\frac n2\rceil\$)
An 11-byte version, `½‘|1×rƲ€ẎQi`, completes all but the largest test case in under 30s - [Try it at TIO](https://tio.run/##y0rNyan8///Q3kcNM2oMD08vOrbpUdOah7v6AjP/H91zuB3Icf//31DHVMfIQMfUQMfcQsfQyBiETXSMDQwMdCyBAAA) - this limits the layers used to \$\lceil\frac{\lfloor\sqrt n\rfloor+1}2\rceil\$.
### How?
The permutation is to take the natural numbers in reversed slices of lengths `[1,5,3,11,5,17,7,23,9,29,11,35,13,...]` - the odd positive integers interspersed with the positive integers congruent to five modulo six, i.e `[1, 2*3-1, 3, 4*3-1, 5, 6*3-1, 7, 8*3-1, 9, ...]`.
This is the same as concatenating and then deduplicating reversed ranges `[1..x]` of where `x` is the cumulative sums of these slice lengths (i.e. the maximum of each slice) - `[1,6,9,20,25,42,49,72,81,110,121,156,169,...]`, which is the odd integers squared interspersed with even numbers multiplied by themselves incremented, i.e. `[1*1, 2*3, 3*3, 4*5, 5*5, 6*7, 7*7,...]`.
Since the differences are all greater than 1 we can save a byte (the reversal) by building ranges `[x..k]` directly, where `k` is the 1-indexed index of the slice.
Due to this structure the permutation is a self-conjugate permutation, i.e. we know that \$P(n) = v \iff P(v) = n\$, so rather than finding the value at (1-indexed) index `n` (`|1×r)ẎQị@`) we can actually get the (1-indexed) index of the first occurrence of `n` (`|1×r)ẎQi`).
```
|1×r)ẎQi - Link: integer, n e.g. 10
) - for each k in [1..n]: vs = [ 1, 2, 3, 4, 5, 6, 7, 8, 9,10]
|1 - bitwise-OR (k) with 1 [ 1, 3, 3, 5, 5, 7, 7, 9, 9,11]
× - multiply (by k) [ 1, 6, 9,20,25,42,49,72,81,110]
r - inclusive range (to k) [[1],[6..2],[9..3],[20..4],...,[110..10]]
Ẏ - tighten [1,6,5,4,3,2,9,8,7,6,5,4,3,20,...,4,......,110,...,10]
Q - de-duplicate [1,6,5,4,3,2,9,8,7,20,...,10,......,110,...82]
i - first index with value (n) 20
```
[Answer]
# JavaScript (ES7), ~~46 45~~ 41 bytes
0-indexed.
```
n=>((x=n**.5+1&~1)*2-(n<x*x+x)*4+3)*x+1-n
```
[Try it online!](https://tio.run/##Zc/BDoIwDAbgu0@xk9lGBt3GgCbiuxAEoyGbEWN28tUn3ljtqcn/tU3vw3tYx@ft8VI@XKY098n3Z85j76UsXaGPHy2kUdyfooxFFLIurNg6rXwag1/DMpVLuPKZa/YrxbQQrKoY04c8dyS3JDdA5oEuIKA1BLQdAQ0B2tj8hHP/os6ENTUhFgD2xCDSO7jVniDC37fYIWRbWmzSFw "JavaScript (Node.js) – Try It Online")
### How?
This is based on the 1-indexed formula used in the example programs of [A090861](https://oeis.org/A090861).
\$x\_n\$ is the layer index of the spiral, starting with \$0\$ for the center square:
$$x\_n=\left\lfloor\frac{\sqrt{n-1}+1}{2}\right\rfloor$$
[Try it online!](https://tio.run/##PY9NbsIwFIT3OcXssGlwY8cUUEVvkBVLmoUFBIJSOzJWr5@Oqchi5PfzzTz57n7d4xT7Ma18OF@mqcEexwI4otYlakPVlKXW1Ae1QVv@E1UJza3mVnOrudUbEtsXYXacMAOkQAqZ2pLYzQQ7zUvIVH5zBl22mgkmal4CpyAN9oa91TNBj2Gy4QXDS4ZZhlnWvAibE@m19FrSlrQlbWu0RftZFB2/7bH/QuPSTXVDCFEI4bGCllguUak13nL9DiOL4hT8IwwXNYSraNSPG0XM5vgsnzmd8FKlcEix91ch1ejOh@RiErWU6h56LxaLufr2rKfpDw "JavaScript (Node.js) – Try It Online")
\$k\_n\$ is set to \$6\$ for the bottom part of each layer (including the center square), and to \$-2\$ everywhere else:
$$k\_n=\begin{cases}
-2&\text{if }n\le 4{x\_n}^2+2x\_n\\
6&\text{otherwise}
\end{cases}$$
[Try it online!](https://tio.run/##PY/NboMwEITvPMXcYlPi4sX5a5v2CTjlmHJASciPUhsRVOXt6ThVOIzY9Xw7Iy71b33bdee2n/qwPwxDiTW2CbBFYTMUQhWUo2bUnFqgyv6JPIOla@laupauXZBYPglZ8YUZIAVSiNSSxGokuFk2IVLxGzN45fKRYKJlE/gK0uAu3J0dCd4Ik4UNwiZhljDLyZNwMZG3jreOtCPtSLsCVVK9J0nD3/ZYf0LdOZV1fzLNNYROKeUxhdVIU@Rmhpc4v0J0Rv5jDYcU92gKLXksX5gK3jDXSbIL/hauB3MNR1Wan7pVXSzpHuOjr1Femz5s@u7sj0qbtt5v@rrrVaG1uYSzV5PJOH17zsPwBw "JavaScript (Node.js) – Try It Online")
Then \$a\_n\$ is given by:
$$a\_n=8{x\_n}^2+k\_nx\_n+2-n$$
[Try it online!](https://tio.run/##PY/NboMwEITvPMXcYqfg4sX5a0v7BDnlmHJA@Y9SGxFU5e3pmCocVuzsfjNrrvVvfd@1l6bLfNgf@n6NEtsE2KKwKQphFSzHmrHmrAWq9J/IU1huLbeWW8utXZBYPglZccIMkAIpRGpJYjUSVJaXEKn4jRl0uXwkmGh5CZyCNKiF2tmRoEeYLLwgvCTMEmY5eRIuJtLr6HWkHWlH2hWokuo9SY78bY/yE0tMoR5U67o7m@MthFYp5ZHBakynyM0ML7F/hehhItQEPko4eh/PkQziC5ngDXM9qDjN4JNkF/w93A7mFk5qbX7qRrXxeDu0wzuOymvThU3XXvxJadPU@01Xt50qtDbXcPFqMhm7b8@@7/8A "JavaScript (Node.js) – Try It Online")
Which can be translated into:
```
n=>8*(x=(n-1)**.5+1>>1)*x+(n<=4*x*x+2*x?-2:6)*x+2-n
```
Making it 0-indexed saves 5 bytes right away:
```
n=>8*(x=n**.5+1>>1)*x+(n<4*x*x+2*x?-2:6)*x+1-n
```
The formula can be further simplified by using:
$${x'}\_n=2\times\left\lfloor\frac{\sqrt{n}+1}{2}\right\rfloor$$
which can be expressed as:
```
x=n**.5+1&~1
```
leading to:
```
n=>2*(x=n**.5+1&~1)*x+(n<x*x+x?-1:3)*x+1-n
```
and finally:
```
n=>((x=n**.5+1&~1)*2-(n<x*x+x)*4+3)*x+1-n
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 60 bytes
```
8(s=⌊(⌊Sqrt[#-1]⌋+1)/2⌋)^2-#+2+If[#<=4s^2+2s,-2,6]s&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n27730Kj2PZRT5cGEAcXFpVEK@saxj7q6dY21NQ3AtKacUa6ytpG2p5p0co2tibFcUbaRsU6ukY6ZrHFav8DijLzShy00hX0HRSqDXVMdYwMdEwNdMwtdAyNjEHYRMfYwMBAxxIIdIwsLSwNav//BwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~12~~ 11 bytes
```
Eq1YL!tPG=)
```
[Try it online!](https://tio.run/##y00syfn/37XQMNJHsSTA3Vbz/39DI2MA)
Very memory-inefficient. Prepending `X^k` makes it [more efficient](https://tio.run/##y00syfn/PyIu27XQMNJHsSTA3Vbz/38jSwtLAwA).
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 67 bytes
```
n=>8*(x=(int)Math.Sqrt(--n)+1>>1)*x+(n<4*x*x+2*x?-2:6)*x+1-n;int x;
```
[Try it online!](https://tio.run/##FYu7CgIxEEV/ZcuZxEiyiIh52FlpZWEtYYPTjJiNMH8fs8WBey6cvJq8Ur/@OAfithukEjvHdFIgEYbj/dXe@8e3NjCGUbuUHCrRwOGgZIxZycXM5@N2OsN@NJP4Xj51yyeK1pPWwVnr8VmpLTfiBQoQou9/ "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# Python 3.8, ~~104~~ ~~74~~ ~~65~~ ~~60~~ 57 bytes
```
lambda n:(-2,6)[n>4*(x:=(n**.5+1)//2)*x+2*x]*x+2+~n+8*x*x
```
Edit: Thanks to Johnathan Allan for getting it from 74 to 57 bytes!
This solution uses 0-based indexing.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 53 bytes
A direct port of [Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/183531/53748), go upvote that, and/or [J42161217's Mathematica answer](https://codegolf.stackexchange.com/a/183529/53748), and/or [Kapocsi's Python answer](https://codegolf.stackexchange.com/a/183536/53748) :)
```
lambda n:((x:=int(n**.5+1)&-2)*2-(n<x*x+x)*4+3)*x+1-n
```
0-indexed.
**[Try it online!](https://tio.run/##JY3LCsIwFET3fkVW5nVTTNLSJNh@iZuKFgv2ttQsIuK3xxQHDsxszqzv@FjQunXLY3fJz2G@3gaCgbEUugkjQyGqRmp@VIYLoxiek0gycVFLy0vTCvO4bCTeX5FMSNgJatAeag9tC9qYgrVgvPdQcKU553k4kJJ12y/oJ/TNl1ZFMw@R7SYOhKqeAhn/k@cf "Python 3.8 (pre-release) – Try It Online")**
[Answer]
# Befunge, ~~67~~ 57 bytes
This solution assumes 0-based indexing for the input values.
```
p&v-*8p00:+1g00:<
0:<@.-\+1*g00+*<|`
0g6*\`!8*2+00g4^>$:0
```
[Try it online!](http://befunge.tryitonline.net/#code=cCZ2LSo4cDAwOisxZzAwOjwKMDo8QC4tXCsxKmcwMCsqPHxgCjBnNipcYCE4KjIrMDBnNF4+JDow&input=Mjk4ODk)
**Explanation**
We start by calculating the "radius" at which the input *n* is found with a loop:
```
radius = 0
while n > 0
radius += 1
n -= radius*8
```
At the end of the loop, the previous value of *n* is the offset into the spiral at that radius:
```
offset = n + radius*8
```
We can then determine if we're on the top or bottom section of the spiral as follows:
```
bottom = offset >= radius*6
```
And once we have all these details, the spiral value is calculated with:
```
value = ((bottom?10:2) + 4*radius)*radius + 1 - offset
```
The radius is the only value that we need to store as a "variable", limiting it to a maximum value of 127 in Befunge-93, so this algorithm can handle inputs up to 65024.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 15 bytes
Port of Jonathan's Jelly solution. 1-indexed.
```
gUòȲ+X*v)õÃcÔâ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Z1XyyLIrWCp2KfXDY9Ti&input=OA)
```
gUòȲ+X*v)õÃcÔâ :Implicit input of integer U
g :Index into
Uò : Range [0,U]
È : Map each X
² : Square X
+X* : Add X multiplied by
v : 1 if X is divisible by 2, 0 otherwise
) : Group result
õ : Range [1,result]
à : End map
c : Flatten
Ô : After reversing each
â : Deduplicate
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
!uṁS`…S*v1N
```
[Try it online!](https://tio.run/##yygtzv7/X7H04c7G4IRHDcuCtcoM/f7//29oAAA "Husk – Try It Online")
Instead of creating a range, an infinite list is created and nubbed. Hence, will be be very very slow for larger \$n\$
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 88 bytes
```
#import<cmath>
int a(int n){int x=(sqrt(n-1)+1)/2;return x*(8*(x+(n>4*x*x+2*x))-2)+2-n;}
```
1-indexed; uses the formula on the OEIS page, but manipulated to save a few bytes.
[Try it online!](https://tio.run/##VVHLboMwEDyHr1ilF5uHakxeBJJL1UO/ocrBMm5rCQwFIyGlfHu6BvqIpfWuxjvj9Vg2TfQu5e1BG1n2hYJc151tlajOiFVN3dpcVsJ@nD1tLAjidkOvLg0n0n22lpgopkFMH3nWKtu3BgafHHwyBMScN/7gDwH3B0ojTgMemWy8OXIltCEUrt6qs8XxKOveQp7D@sU0WH3BkyhlXwqrCqj7GXoeGiVnwCKydv0TWZmizLzVNFpfPYlOdXCC/QJpp9i9XhC6xiFsQ@AME8b@EELMk2nbhJAwhmCKC1vSQ8rGRWG@70/CMRydY@yw3qJmnPCNo6U7J8ESV@/TnZN4q1uYfNPIZxmm/HfODIJATzbc@7AMrS@TKfj46bXO/gWndwc/E879/00ZvdXyKyzzxts3 "C++ (gcc) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
ƛ1⋎*›rṘ;fU?‹i
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C6%9B1%E2%8B%8E*%E2%80%BAr%E1%B9%98%3BfU%3F%E2%80%B9i&inputs=10&header=&footer=)
Messy port
] |
[Question]
[
### Challenge
Given a matrix **M** with **r** rows and **c** columns, and two Boolean lists **V** of length **r** and **H** of length **c**, calculate the partitioned cumulative vertical and horizontal sums.
### Rules
* **r** and **c** are greater than or equal to one
* **H** and **V** begin with a true value
* The values in **M** are within your language's reasonable numeric domain.
* Partitioning and summing begins in the top left corner.
### Walk through
Given **M**:
```
┌──────────────┐
│ 1 2 3 4 5│
│ 6 7 8 9 10│
│11 12 13 14 15│
│16 17 18 19 20│
└──────────────┘
```
**H**: `1 0 1 0 0`
**V**: `1 1 0 1`
Split **M** into groups of columns, beginning a new group at every true value of **H**
```
┌─────┬────────┐
│ 1 2│ 3 4 5│
│ 6 7│ 8 9 10│
│11 12│13 14 15│
│16 17│18 19 20│
└─────┴────────┘
```
Split each group of columns into groups of rows, beginning a new group at every true value of **V**:
```
┌─────┬────────┐
│ 1 2│ 3 4 5│
├─────┼────────┤
│ 6 7│ 8 9 10│
│11 12│13 14 15│
├─────┼────────┤
│16 17│18 19 20│
└─────┴────────┘
```
Cumulatively sum each cell horizontally:
```
┌─────┬────────┐
│ 1 3│ 3 7 12│
├─────┼────────┤
│ 6 13│ 8 17 27│
│11 23│13 27 42│
├─────┼────────┤
│16 33│18 37 57│
└─────┴────────┘
```
Cumulatively sum each cell vertically:
```
┌─────┬────────┐
│ 1 3│ 3 7 12│
├─────┼────────┤
│ 6 13│ 8 17 27│
│17 36│21 44 69│
├─────┼────────┤
│16 33│18 37 57│
└─────┴────────┘
```
Result:
```
┌──────────────┐
│ 1 3 3 7 12│
│ 6 13 8 17 27│
│17 36 21 44 69│
│16 33 18 37 57│
└──────────────┘
```
### Additional test cases
**M**:
```
┌───────────┐
│15 11 11 17│
│13 20 18 8│
└───────────┘
```
**H**: `1 0 0 1` **V**: `1 0`
Result:
```
┌───────────┐
│15 26 37 17│
│28 59 88 25│
└───────────┘
```
**M**:
```
┌─┐
│7│
└─┘
```
Result (**H** and **V** must be `1`):
```
┌─┐
│7│
└─┘
```
**M**:
```
┌──┐
│ 3│
│-1│
│ 4│
└──┘
```
**V**: `1 1 0` (**H** must be `1`)
Result:
```
┌──┐
│ 3│
│-1│
│ 3│
└──┘
```
**M**:
```
┌───────────────────────────────────────────────────────┐
│10 7.7 1.9 1.5 5.4 1.2 7.8 0.6 4.3 1.2 4.5 5.4 0.3│
│ 2.3 3.8 4.1 4.5 1 7.7 3 3.4 6.9 5.8 9.5 1.3 7.5│
│ 9.1 3.7 7.2 9.8 3.9 10 7.6 9.6 7.3 6.2 3.3 9.2 9.4│
│ 4.3 4.9 7.6 2 1.4 5.8 8.1 2.4 1.1 2.3 7.3 3.6 6 │
│ 9.3 10 5.8 9.6 5.7 8.1 2.1 3.9 4 1.3 6.3 3.1 9 │
│ 6.6 1.4 0.5 6.5 4.6 2.1 7.5 4.3 9 7.2 2.8 3.6 4.6│
│ 1.7 9.9 2.4 4.5 1.3 2.6 6.4 7.8 6.2 3.2 10 5.2 8.9│
│ 9.9 5.3 4.5 6.3 1.4 3.1 2.3 7.9 7.8 7.9 9.6 4 5.8│
└───────────────────────────────────────────────────────┘
```
**H**: `1 0 0 1 0 1 1 1 0 1 1 1 0`
**V**: `1 0 0 0 0 1 0 0`
Result:
```
┌────────────────────────────────────────────────────────────────┐
│10 17.7 19.6 1.5 6.9 1.2 7.8 0.6 4.9 1.2 4.5 5.4 5.7│
│12.3 23.8 29.8 6 12.4 8.9 10.8 4 15.2 7 14 6.7 14.5│
│21.4 36.6 49.8 15.8 26.1 18.9 18.4 13.6 32.1 13.2 17.3 15.9 33.1│
│25.7 45.8 66.6 17.8 29.5 24.7 26.5 16 35.6 15.5 24.6 19.5 42.7│
│35 65.1 91.7 27.4 44.8 32.8 28.6 19.9 43.5 16.8 30.9 22.6 54.8│
│ 6.6 8 8.5 6.5 11.1 2.1 7.5 4.3 13.3 7.2 2.8 3.6 8.2│
│ 8.3 19.6 22.5 11 16.9 4.7 13.9 12.1 27.3 10.4 12.8 8.8 22.3│
│18.2 34.8 42.2 17.3 24.6 7.8 16.2 20 43 18.3 22.4 12.8 32.1│
└────────────────────────────────────────────────────────────────┘
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
Zœṗ@+\€Ẏð/
```
[Try it online!](https://tio.run/##y0rNyan8/z/q6OSHO6c7aMc8alrzcFff4Q36////j46ONtQx0jHWMdExjdWJNtMx17HQsdQxNAByDA11DI10DI11DE10DEGyhmY6huY6hhY6hpY6RgaxIBEdAx0QBisHswxjYwE "Jelly – Try It Online") and [The Last Test Case](https://tio.run/##ZZE9TgQxDIV7TpGeKMRxfjYdHXcgpKRBewFaDkBDwSUotoUWcZDlIoFnewcQ0ijyxJ@fn5272/3@fq3rj6fj6/Pl@c3nw8vx7fH9cHG11hpjUAzRuxaadxQ6juJdCRlRQmLnXQzVuxzY7vKGxMDTu5GQYpA5kOVpk2VEDLyiQQHXFWEgBRIdhQy8oUUHxOLH/FVcVkQMoYQ0407oDA1xmFEkeEIhoa@03KFD0sEkYhNjwDVEtcGnluazImpbOZmtrOLiRTQIsGhU1JCupyBfgFerbvor1qNNm3RaWXKFBKFjRx8xnLdtJfWa7WFsD@nHc4LTrqPIstnKqz5fNq82fjchibo60Nnn9GfjG4zy0emk//Ef8Dce5/wC)
(With a `G` at the end for readability).
Input is taken as a list `[M, H, V]`.
## Explanation
```
Zœṗ@+\€Ẏð/ Input: [M, H, V]
ð/ Insert the previous (f) as a dyadic link
Forms f( f(M, H) , V)
For f(x, y):
Z Transpose x
œṗ@ Partition the rows of x^T at each true in y
+\€ Compute the cumulative sums in each partition
Ẏ Tighten (Joins all the lists at the next depth)
```
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 13 bytes
Takes ist of **V H M** as argument.
```
{⍉⊃,/+\¨⍺⊂⍵}/
```
[Try it online!](https://tio.run/##TVA7TkMxEOw5xZY8AY53/Xu@C00kBE0kaBGiIRISkZ7EMegogIYyR/FFwuzaiVDear0745lx1g@bq5vH9eb@7nC4ba/vT215a7vt5eriev/Rlt@2e2nLz/MKKJ0zMXniSU/ezh7nSKkt3235Ej@dGcsPRucKReCciNm@QhxIgM009wvTKGIQyxAZMqhg@0D7T6Z4tBi/Ywg@TUz8vwObYagJPBUHc1dRiZKL6ILdTN5lii7YHAfmMQsqAI@Obc@moLtIGToJWNU9eAW9ghfAKNCpwIJ6qW3GmNEDrgnWAbNSotlG0JQjEIomOkNILCBbiGJBMqlOUMnunNHLILO5RcuSjc5Uccom6pEuo6LaOLa0al0tq1jWbChDsUJJLFx/m6g1Zv2v@gOkhxCYV6Mne0cyazUMp@TVrhXjwUKjT38 "APL (Dyalog Unicode) – Try It Online")
`{`…`}/` insert (reduce by) the following anonymous function, where the term in the left is represented by ⍺ and the term on the right is represented by ⍵. Due to APL functions being right associative, this is therefore **V** *f* (**H** *f* **M**).
`⍺⊂⍵` partition ⍵ according to ⍺
`+\¨` cumulative sum of each part
`,/` reduce by concatenation (this encloses the result to reduce rank)
`⊃` disclose
`⍉` transpose
[Answer]
# [Python 2](https://docs.python.org/2/) + numpy, 143 138 117 115 110 108 bytes
-21 bytes thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m)!
```
lambda M,*L:reduce(lambda m,l:vstack(map(lambda p:cumsum(p,0),split(m,*where(l)))).T,L,M)
from numpy import*
```
[Try it online!](https://tio.run/##ZVPLjtpAELzzFS2fbDI78jxsY6Tc97Aol4gL8cGBcbCCwbJNIr6eTPe02Q2LhNVTVV1dPYb@Nh0vZ31vvv64n@ru56GGjVi@rQd3uO5dzFAnTus/41Tvf8dd3c9ov95fu/Haxb1IEzH2p3aKO7H8e3SD70z8R34Xb2KTLJrh0sH52vU3aLv@MkzL@8E1MLlxijcCXgVsk/UCmssArYAR2jM4L3dDPbk42rxuI6ShH9rz5OkvEK2jx3nHDtWurWZwwVz07TqhNJwaHLb16mTxJHuJYAkmneEFJauH@vzLxUqAVokc3HisexdbAVkiYOfhVEB4plUAGKuS2WCob/FupzIPKv4WpDXeFKUrAauqevejdj492xQsJP6ZNIi@EGc/6kKoT4lS6ScVsvC0LPHhI2bSYqWR8LlSmQuw0jBmH5JU0jCNlEGllYp59bA1WBmU5zggQ10ZJAYlGVqU2GhQXuCIEkWG8nC@HMEcK4NGGmmDGKktbYuAxSaSa2xUOJdGrnCCDotRZdjMoDiXaYhh5pGcM8eqeLQrjmWDOWUhD4Vi8sixR4XryZDPUJ5zdxGOFD3lbXXYli45p3eFE0ucQ4Ht47Z0yGr5xfA96PfMGpOWYRW6bMPteXh9lrPy@iUbUVWGBGH355/i/FSf6@qjMP3vz5Dc/wE "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œṗ+\€Ẏ
ḢçЀZð⁺
```
A dyadic link taking `H,V` on the left and `M` on the right and returning the resulting matrix.
**[Try it online!](https://tio.run/##y0rNyan8///o5Ic7p2vHPGpa83BXH9fDHYsOLz88AciLOrzhUeOu////R0cb6hjogLBBrA6QDebFxoLFjXSMdUx0TIHiZjrmOhY6ljqGYEVAVUY6hsY6hiY6hiBZQzMdQ3MdQwsdQ0sdI4PYWAA "Jelly – Try It Online")**
Alternatively as a single line also for 14: `Ḣœṗ+\€Ẏ$¥Ð€Zð⁺`
### How?
```
œṗ+\€Ẏ - Link 1: partition and cumSum: list of partition bools, list of values
œṗ - partition (the values) at truthy indexes (of the bools)
€ - for €ach part:
+\ - cumulative reduce by addition
Ẏ - tighten (flattens back into a list)
ḢçЀZð⁺ - Main link: list of lists, [H,V]; list of lists, M
⁺ - perform this twice:
ð - [it's a dyadic chain for the second pass, first pass is dyadic implicitly]
Ḣ - head, pop it & modify (so H the first time, V the second)
Ѐ - map across right: (M the first time, the intermediate result the second)
ç - the last link (1) as a dyad
Z - transpose the result (do the rows first time, and the columns the second)
```
---
Previous:
```
œṗ@+\€Ẏ
ç€Zç€⁵Z
```
A full program printing a representation of the result.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 19 bytes
```
,!ix"0GYs@12XQ!g]v!
```
Inputs are `M` (matrix), `H` (column vector), `V` (column vector). The row separator is `;`.
[Try it online!](https://tio.run/##LYo9D8IgAAV3f8XRuQMPKLRhcXPupiEMTsaknTTGf48fYXnJ3b39@txaG839PdjT5XGUO6/mVl@mtSIcnsCUiSRmFmQzEnLIo4C@TRElNKMFZ@uhKPO7/bdzV/UD "MATL – Try It Online") Or verify all test cases: [1](https://tio.run/##LYo9D8IgAAV3f8XRuQMPKLRhcXPupiEMTsaknTTGf48fYXnJ3b39@txaG839PdjT5XGUO6/mVl@mtSIcnsCUiSRmFmQzEnLIo4C@TRElNKMFZ@uhKPO7/bdzV/UD), [2](https://tio.run/##y00syfn/X0cxs0LJwD2y2MHQKCJQMT22TPH//2hDUwVDQzAyt1YwNFYwMlAwtFCwiOWKNrRWMAAjQygnFgA), [3](https://tio.run/##y00syfn/X0cxs0LJwD2y2MHQKCJQMT22TPH/f3MuQy5DAA), [4](https://tio.run/##y00syfn/X0cxs0LJwD2y2MHQKCJQMT22TPH//2hjawVdQ2sFk1guQ65oIAOIDGIB), [5](https://tio.run/##ZVA9SwUxEOz9FXnWErKbzeZCGjtrO@VxhZUIWikP//05O3fKA@Fy@zWZmc3Hy9f7tt2d3r5vy8Pz573o0@Ppdb2ctu0sJfXck@SB01LLhqjoLalkT5YraztmJdeZFM0KgGXhQEgRPUsOoobZiD5wPbeJQjDsKBT5ghxqIewoHbHinqJdUQfEJpUNuAApqIy0C5iUHoU2Oq148hCpQbqLO2I/0EI9ox0nXtKYSJ20BU4dx0Ioxy6N4oN2lXbjISAh4BzgCgd2LKihjjpebF9CdxsK@TGJb9ylUT0k65/7wXsRwzN3XG/OMlPhJ79/@Z9f467RZf0B).
### Explanation
This does the cumulative sum horizontally, then vertically.
```
, % Do the following twice
! % First time this inputs M implicitly. Transpose. Second time
% it transposes the result of the horizontal cumulative sum
ix % Input H (first time) or V (second time). Delete it; but gets
% copied into clipboard G
" % For each column of the matrix
0G % Push most recent input: H (first time) or V (second)
Ys % Cumulative sum. This produces a vector of integer values
% such that all columns (first time) or rows (second) of M
% with the same value in this vector should be cumulatively
% summed
@ % Push current column of M transposed (first time) or M after
% horizontal cumulative sum (second time)
12XQ % Cumulative sum. Gives a cell array of row vectors
!g % Join those vectors into one row vector
] % End
v % Concatenate the row vectors vertically into a matrix
! % Transpose. This corrects for the fact that each column vector
% of the matrix was cumulatively summed into a row vector
% Implicit end. Implicit display
```
[Answer]
# [J](http://jsoftware.com/), 20 bytes
```
;@(<@(+/\);.1|:)&.>/
```
[Try it online!](https://tio.run/##y/r/P03B1krB2kHDxkFDWz9G01rPsMZKU03PTp@LKzU5I18hTcEQCA2A2BpKGwChtYKCnZVCpp6CiYLp//8A "J – Try It Online")
Input is taken as an array of boxes containing `[V, H, M]`.
## Explanation
```
;@(<@(+/\);.1|:)&.>/ Input: [V H M]
( g ) / Insert g and reduce (right-to-left)
Forms V g H g M = V g (H g M)
& > Unbox each
|: Transpose the right arg
;.1 Partition
+/\ Reduce each prefix using addition (cumulative sum)
<@ Box each partition
;@ Raze (Concatenate the contents in each box)
&.> Box the result
```
[Answer]
# Mathematica, 212 bytes
```
(T=Transpose;A=AppendTo;J=Flatten;f[s_]:=Block[{},t=2;r=1;w={};While[t<=Length@s,If[s[[t]]==0,r++,w~A~r;r=1];t++];w~A~r];K[x_,y_]:=Accumulate/@#&/@(FoldPairList[TakeDrop,#,f@y]&/@x);d=J/@K[#,#2];T[J/@K[T@d,#3]])&
```
**input**
[M,H,V]
>
> [{{15, 11, 11, 17}, {13, 20, 18, 8}}, {1, 0, 0, 1}, {1, 0}]
>
>
>
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 164 bytes
```
(M,H,V)=>{int a=M.Length,b=M[0].Length,i,j;for(i=0;i<a;i++)for(j=0;j<b;j++)if(!H[j])M[i][j]+=M[i][j-1];for(i=0;i<a;i++)for(j=0;j<b;j++)if(!V[i])M[i][j]+=M[i-1][j];}
```
[Try it online!](https://tio.run/##jVRNb5tAEL37V0x9AmWDwGAwwliqeonUWqpSKT1QDtgGe5EBCYirKOK3uzO7YILrkOxhmJmd9@YDmG11vy3K@Ax4tseoquBnWezLKJuQ51VIOlUd1XwLp4LvYB3xXKnqkuf7IISo3FfqJa5H0Pn1UtVxpn3d1rzIl7vieXOMgzAIGWyK4tg/V5D4k7OyZg/sSfVXrzyvIfLX2o8439cHtvHXgR52FmeplxSlwn3d48vI43d3Ktkp2uly46Vo80T58hCkoboOeIjPO18q90b4KewTRg@wCETVa87eZNBh3xNk4EMe/0VtOAQ6rR8MnZHpaA4DQ3NJzBnMNQvdhjZjeLNgoGs2A0szmfSh2gXpmgkNe5ceZgQCk0gszWASafQ56Ravkcmm7HMKBFcEEdLR5qP0LnEi3qFQrMwlvCn6EI05VLhLwiE6W1RvkurKcGuUXrSM0mWSidBYGA1HVLqg9DOyDalRuMhkUrj9Qe1mV6YgE2XOqZWO12h7sWRaIrclOd64Y9w2cclKdRqmTcISTkHrSJvmIMc0EzeLtnCMHGM3RJEulSaaty7vC23qm5ziwxEDN0l0jc5oau74XFwxX7MltuV3Z4k3103Zke9k0WpyeFY7y2ZA3ngDU/7gcOh/DqjL55hBEh2r/jHwSeOtHL94J@fpg5wjFVxoB7yJkjE4MDip1xdFCQotLY4pcfKph9oSsnZloYV7ZYD4f0UIjpTwHqQExu1zwafX@NscdHhCNCvQ1W79fivyqjjG2u@S17EyZTBVvZvQm/GZ3II3IM3kUwTTP/l1wmYyGYE9xtHue/yivAHJVM35Hw "C# (.NET Core) – Try It Online")
Basically it does exactly as specified in the OP. It first iterates to sum horizontally and then it iterates again to sum vertically.
[Answer]
# [Haskell](https://www.haskell.org/), ~~129 bytes~~ 119 bytes
```
s m v=tail$scanl(\a(x,s)->if s then x else zipWith(+)a x)[](zip m v)
t=foldr(zipWith(:))$repeat[]
f m h v=t$s(t$s m v)h
```
[Try it online!](https://tio.run/##Zc8/a8MwEAXw3Z/iDR4keoVc@jcBd@zWrdBB1SAaGYnKjrHUYPrl3bNJKKWDEHr83okLLn/6lOY5o8OpKS6mOn@4Pql3pybK@voptsgowfeY4FP2@I7DWyxBXWmHSRurJFjauipNe0yHUV3EXut69IN3xdiqFROWP@qs5KyNMHcu9mhwOFZA8kXSBsYwYUu4IdwS7izB3BMeCI@EHYE3S8JiWBCLYmG8OhbIIlkoi91urD1PDsvk1/HLE56d7EH481iviz392n@NxXRueMEwxr5AnffS8w8 "Haskell – Try It Online")
*Saved 10 bytes thanks to @ceasedtoturncounterclockwis*
`t` (for transpose) switches rows and columns. A quick explanation:
```
foldr(zipWith(:))(repeat[])(r1,...,rn) =
zipWith(:) r1 (zipWith(:) r2 (... zipWith(:) rn (repeat [])))
```
Read from right to left: we browse rows from bottom to up, and push each value in its destination column.
`s` is basically a rolling sum of vectors, but resets when a True value arises in `v`
`f` sums the rows with `s` following `v` and do the same with the columns following `h`
[Answer]
## JavaScript (ES6), 88 bytes
```
(a,h,v)=>a.map(b=>b.map((e,i)=>t=h[i]?e:t+e)).map((b,j)=>t=v[j]?b:t.map((e,i)=>e+b[i]))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 31 bytes
```
+\€€
œṗḊZ€⁵œṗ$€Ḋ€Ç€ÇZ€€Z€;/€€;/
```
[Try it online!](https://tio.run/##JYw7DsJADER7zkHHSPFsQj7KTbJxSYNyAUpokGgpuAQtEtSIg4SLON6NZI3f2KM5HqbpZLYb/5enz@Z3nz@P@X0bkj@/st06@8n1e80yrOG0@mLlvjCzSBACqkXHgBIV9opYo0GLDhQ39FAAS7AC05c12IAt2CGIaqqRXCS6AA "Jelly – Try It Online")
Gah this is way too long for Jelly xD
BTW, 11/31 bytes in this program consists of euro characters. That's over a third of the program!
] |
[Question]
[
(via [chat](http://chat.stackexchange.com/transcript/message/30081079#30081079))
The OEIS entry [A123321](http://oeis.org/A123321) lists the sequence of numbers that are the product of seven distinct primes. For brevity, we'll call this a *7DP* number. The first few numbers and their corresponding divisors are below:
```
510510 = 2 * 3 * 5 * 7 * 11 * 13 * 17
570570 = 2 * 3 * 5 * 7 * 11 * 13 * 19
690690 = 2 * 3 * 5 * 7 * 11 * 13 * 23
746130 = 2 * 3 * 5 * 7 * 11 * 17 * 19
```
The challenge here will be to find the closest 7DP number, in terms of absolute distance, from a given input.
### Input
A single positive integer *n* in any [convenient format](https://codegolf.meta.stackexchange.com/q/2447/42963).
### Output
The closest 7DP number to *n*, again in any convenient format. If two 7DP numbers are tied for closest, you can output either or both.
### Rules
* Numbers can be assumed to fit in your language's default `[int]` datatype (or equivalent).
* Either a full program or a function are acceptable.
* [Standard loopholes](https://codegolf.meta.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 wins.
### Examples
```
5 -> 510510
860782 -> 870870
1425060 -> 1438710 (or 1411410, or both)
```
[Answer]
# Python, ~~89~~ ~~86~~ 85 bytes
```
f=lambda n,k=0:126^sum(1>>n%i<<7*(n/i%i<1)for i in range(2,n))and f(n+k,k%2*2+~k)or n
```
The algorithm is **O(scary)** to begin with and the recursion doesn't really help, but it works well as long as **n** is sufficiently close to a 7DP number.
*Thanks to @xnor for golfing off 3 bytes!*
Test it on [repl.it](https://repl.it/CYtD/4).
### How it works
Python has no primality or factorization built-ins, but we can identify 7DP numbers by the amount and nature of their divisors.
By the multiplication principle, the number of divisors of an integer can be computed as the product of the incremented exponents of its prime factorization. Thus, **σ0(n)** ([divisor function](https://en.wikipedia.org/wiki/Divisor_function)) is **2m** whenever **n** is a mDP number.
**σ0(n) = 128** is thus a necessary condition, but it is not sufficient; for example, **σ0(2127) = 128**, but **2127** is clearly not a 7DP number. However, if both **σ0(n) = 128** and no perfect square divides **n** evenly, then **n** is a 7DP number.
For the input **n**, the algorithm consists in inspecting the integers **n**, **n - 1**, **n + 1**, **n - 2**, **n + 2**, etc. and returning the first one that is a 7DP number.
When **f** is called with argument **n**, the following happens:
* The code
```
126^sum(1>>n%i<<7*(n/i%i<1)for i in range(2,n))
```
tests if **n** is *not* a 7DP number as follows.
For all integers **i** such that **1 < i < n**, `1>>n%i<<7*(n/i%i<1)` gets evaluated.
+ If **n** is divisible by **i** but not by **i2**, `1>>n%i` yields **1** and `(n/i%i<1)` yields **0**, resulting in
**1 · 27 · 0 = 1**.
+ If **n** is divisible by **i2**, `1>>n%i` and `(n/i%i<1)` both yield **1**, resulting in **1 · 27 · 1 = 128**.
+ If **n** not not divisible by **i**, `1>>n%i` yields **0**, resulting in **0 · 27 · x = 0**.
The sum of the resulting integers will be **2m - 2** if **n** is a mDP number (its **2m** divisors, excluding **1** and **n**) and a number greater than **127** if **n** has a perfect square factor. Thus, the sum will be **126** if and only if **n** is a 7DP number.
* For 7DP numbers, the sum is **126**, so XORing it with **126** yields **0**, which is falsy. Thus, the **or** part of the lambda is executed and **f** returns the current value of **n**.
* If **n** is not a 7DP number, XOR will return a non-zero, truthy value. Thus, the **and** part of the lambda is executed.
```
f(n+k,k%2*2+~k)
```
recursively calls **f** with updated values of **n** (the next potential 7DP number) and **k** (the difference between the the new candidate and the one after that).
If **k** is an even, non-negative integer, `k%2*2` yields **0** and `~k` yields **-(k + 1)**. The sum of both results is **-(k + 1)**, which is an odd, negative integer that is **1** greater in absolute value than **k**.
If **k** is an odd, negative integer, `k%2*2` yields **2** and `~k` yields **-(k + 1)**. The sum of both results is **2 - (k + 1) = -(k - 1)**, which is an even, non-negative integer that is **1** unit greater in absolute value than **k**.
This means that **k** takes the values **0, -1, 2, -3, 4, ⋯**.
When added cumulatively to **n0** (the initial value of **n**), the resulting integers are
+ **n0 + 0**
+ (**n0 + 0) - 1 = n0 - 1**
+ (**n0 - 1) + 2 = n0 + 1**
+ (**n0 + 1) - 3 = n0 - 2**
+ (**n0 - 2) + 4 = n0 + 2**
+ etc.
making sure the first 7DP number we encounter is as close to **n0** as possible.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~44~~ ~~40~~ 16 bytes
[Crossed out 44 is still regular 44 ;(](https://codegolf.stackexchange.com/questions/1576/compute-the-first-n-digits-of-e/79116#79116)
```
:I=+.>0,.$pPdPl7
```
Example:
```
?- run_from_atom(':I=+.>0,.$pPdPl7',1425060,Z).
Z = 1438710 .
```
Could it be that this language doesn't always suck? I beat Jelly and MATL!
The test case with `5` is the longest and takes about 10 seconds on my machine.
This would be 12 bytes if `$p` was not bugged (we wouldn't need the `>0,.` part)
### Explanation
Brachylog uses constraint logic programming by default for all integer arithmetic. Moreover, the labeling built-in `=` works on possibly infinite domains.
It successively unifies a variable with no constraints (i.e. in `(-inf, inf)`) as such: `0, 1, -1, 2, -2, 3, …`.
Therefore, we can get the closest 7DP number by looking for the first number `I` unified in `(-inf, inf)` (using automatic backtracking), for which `Input + I` is a 7DP number.
```
:I= Label variables in [Input, I]. I has no constraints and Input is known
+. Unify Output with Input + I
>0, Output > 0 (wouldn't be needed if $p failed for numbers less than 1)
.$pP Unify P with the list of prime factors of Output
dP Check that P with duplicates removed is still P
l7 Check that the length of P is 7
```
[Answer]
# Jelly, 17 bytes
```
Pµạ³,
×⁹ÆRœc7Ç€ṂṪ
```
Works in theory, but takes many years to complete.
---
Here is a version that actually works for the given inputs, but theoretically fails for large inputs:
```
Pµạ³,
50ÆRœc7Ç€ṂṪ
```
[Try it here.](http://jelly.tryitonline.net/#code=UMK14bqhwrMsCjYww4ZSxZNjN8OH4oKs4bmC4bmq&input=&args=ODYwNzgy) This generates all primes up to 50, then finds all 7-combinations of primes in that list, and then all their products. Finally, it simply finds the closest element from that list to the given argument.
Of course, once our 7DPs contain primes higher than 50, this will fail. The theoretical version generates all primes up to **256n** for an input **n**, but otherwise works the same way.
## Proof
Let `p(x)` denote the next prime after `x`. An (extremely loose) upper bound for the closest 7DP product to x is:
```
p(x) * p(p(x)) * p(p(p(x))) * ... * p(p(p(p(p(p(p(x)))))))
```
So we only need to check primes in **[2…p(p(p(p(p(p(p(x)))))))]**. [Bertrand's
postulate](https://en.wikipedia.org/wiki/Bertrand%27s_postulate) says that **p(x) ≤ 2x**, so it suffices to check all primes up to **128x**.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~21~~ ~~17~~ ~~16~~ ~~14~~ 13 bytes
*Thanks to Dennis for a suggestion that removed 4 bytes, and another that saved 1 more byte!*
```
t17*Zq7XN!pYk
```
This works in theory, but runs out of memory for inputs above `6` (online compiler).
A more efficient version uses **21 bytes**, and computes all test cases in about one second:
```
t3e4/k16+_YqZq7XN!pYk
```
Try it online!
* [Memory-inefficient version](http://matl.tryitonline.net/#code=dDE3KlpxN1hOIXBZaw&input=NQ)
* [Memory-efficient version](http://matl.tryitonline.net/#code=dDNlNC9rMTYrX1lxWnE3WE4hcFlr&input=ODYwNzgy)
* [Memory-efficient version, all test cases](http://matl.tryitonline.net/#code=YCAgICAgICAgICAgICAgICAgICAgICAgJSBJbmZpbml0ZSBsb29wCnQzZTQvMTYra19ZcVpxN1hOIXBZayAgICUgQWN0dWFsIGNvZGUuIFRha2VzIGlucHV0IGltcGxpY2l0bHkKRFQgICAgICAgICAgICAgICAgICAgICAgJSBEaXNwbGF5IGFuZCBlbmQgbG9vcA&input=NQo4NjA3ODIKMTQyNTA2MA)
## Explanation
### Memory-efficient version
Take input *N* = `860782` as an example. It suffices to consider primes up to *M* = `29`, which is the **first prime that multiplied by `2*3*5*7*11*13` exceeds N**. In this example, `2*3*5*7*11*13*29 = 870870`. The next prime is `31`. Any product involving that prime or greater will be at least `2*3*5*7*11*13*31 = 930930`, and so it's guaranteed **not** to be the solution, because it exceeds `870870` which exceeds *N*.
*M* is computed as the first prime greater than `max(N/(2*3*5*7*11*13), 16)`. The `max` function is used for ensuring that at least `17` is picked. To save a few bytes, the code replaces `2*3*5*7*11*13 = 30030` by `30000`, and function `max` by addition. These changes are valid because they give a larger value.
```
t % Take input implicitly. Duplicate
3e4/k % Divide input by 30000 and round down (rounding here is only needed
% due to a bug in the "next prime" function)
16+ % Add 16
_Yq % Next prime
Zq % Prime numbers up to that value
7XN % Combinations of those primes taken 7 at a time. Gives a 2D array
% with each combination on a different row
!p % Product of each row
Yk % Output product that is closest to the input. Implicitly display
```
### Memory-inefficient version
To further reduce the number of bytes the division can be removed; in fact, it suffices to multiply by `17` (thanks, @Dennis). This ensures that the next prime is included (by [Bertrand's postulate](https://en.wikipedia.org/wiki/Bertrand%27s_postulate)) and that the result is at least `17`. This works in theory, but runs out of memory for inputs larger than about `6`.
In the code, the section
```
3e4/k % Divide input by 30000 and round down (rounding here is only needed
% due to a bug in the "next prime" function)
16+ % Add 16
_Yq % Next prime
```
is replaced by
```
17* % Multiply by 17
```
[Answer]
## Pyke, 32 bytes
```
#PDl 7q.ID}lRlqi*(#)DF-X,)R],She
```
[Try it here!](http://pyke.catbus.co.uk/?code=%23PDl+7q.ID%7DlRlqi%2a%28%23%29DF-X%2C%29R%5D%2CShe&input=5&warnings=0)
Note this doesn't work online - it times out. [This Version](http://pyke.catbus.co.uk/?code=%23PDl+2q.ID%7DlRlqi%2a%28%23%29DF-X%2C%29R%5D%2CShe&input=12&warnings=0) only checks for 2 distinct primes and should work faster. When there are 2 numbers of the same distance away from the target, it chooses the lower one.
This goes through all the numbers until it finds one that is bigger than the input and is a 7DP. For each number, it gets rid of it if it isn't a 7DP. It then has a list of 7DPs up to the input with one that is bigger. It then picks the one that is closest to the input.
[Answer]
# Julia, 59 bytes
```
!n=sort(map(prod,combinations(17n|>primes,7))-n,by=abs)[]+n
```
This is *very* inefficient, but it works for the first test case in practice and for the others in theory.
At the cost of 5 more bytes – for a total of **64 bytes** – efficiency can be improved dramatically.
```
!n=sort(map(prod,combinations(n>>14+17|>primes,7))-n,by=abs)[]+n
```
[Try it online!](http://julia.tryitonline.net/#code=IW49c29ydChtYXAocHJvZCxjb21iaW5hdGlvbnMoMTdufD5wcmltZXMsNykpLW4sYnk9YWJzKVtdK24KCnByaW50bG4oITUpCgohbj1zb3J0KG1hcChwcm9kLGNvbWJpbmF0aW9ucyhuPj4xNCsxN3w-cHJpbWVzLDcpKS1uLGJ5PWFicylbXStuCgpwcmludGxuKCE4NjA3ODIpCnByaW50bG4oITE0MjUwNjAp&input=)
### Background
As mentioned in [@LuisMendo's answer](https://codegolf.stackexchange.com/a/82355), the set of primes we have to consider for the nearest 7DP number is quite small. It suffices for the set to contains a 7DP number that is bigger than the input **n**, which will be true if and only if it contains a prime **p ≥ 17** such that **30300p = 2·3·5·7·11·13·p ≥ n**.
In [On the interval containing at least one prime number](http://projecteuclid.org/euclid.pja/1195570997) proves that the interval **[x, 1.5x)** contains at least one prime number whenever **x ≥ 8**. Since **30030 / 16384 ≈ 1.83**, that means there must be a prime **p** in **(n/30030, n/16384)** whenever **n > 8 · 30300 = 242400**.
Finally, when **n < 510510**, **p = 17** is clearly sufficient, so we only need to consider primes up to **n/16384 + 17**.
At the cost of efficiency, we can consider primes up to **17n** instead. This works when **n = 1** and is vastly bigger than **n/16384 + 17** for larger values of **n**.
### How it works
`17n|>primes` and `n>>14+17|>primes` (the bitshift is equivalent to dividing by **214 = 16384**) compute the prime ranges mentioned in the previous paragraph. Then, `combinations(...,7)` computes all arrays of seven different prime numbers in that range, and mapping `prod` over those calculates their products, i.e., the 7DP numbers from which we'll choose the answer.
Next, `-n` subtracts **n** prom each 7DP number, then `sort(...,by=abs)` sorts those differences by their absolute values. Finally, we select the first difference with `[]` and compute the corresponding 7DP number by adding **n** with `+n`.
[Answer]
# Pyth, 30 bytes
```
L&{IPbq7lPby#.W!syMH,hhZa0teZ,
```
[Try it online!](http://pyth.herokuapp.com/?code=L%26%7BIPbq7lPby%23.W!syMH%2ChhZa0teZ%2C&input=860782&debug=0)
[Test suite.](http://pyth.herokuapp.com/?code=L%26%7BIPbq7lPby%23.W!syMH%2ChhZa0teZ%2C&test_suite=1&test_suite_input=860782%0A1425060&debug=0)
(5 takes too long to run)
### Explanation
```
L&{IPbq7lPby#.W!syMH,hhZa0teZ,
L&{IPbq7lPb Defines a function y, whose argument is b:
& Return if both the following are true:
{IPb the prime factorization contains no duplicate; and:
q7lPb the number of prime factors is 7
y#.W!syMH,hhZa0teZ, The main programme. Input as Q.
,QQ Implicit arguments, yield [Q,Q].
.W While
!syMH both numbers do not satisfy y:
,hhZ increment the first number
teZ and decrement the second number
a0 while making it non-negative.
```
[Answer]
# Mathematica ~~136 80~~ 75 bytes
This is a straightforward approach, working outwards from `n`.
`n` is a 7-distinct-prime product iff the number of prime factors is 7 (`PrimeNu@#==7`) and none of these factors appears more than once (`SquareFreeQ@#&`).
```
g@n_:=(k=1;While[!(PrimeNu@#==7&&SquareFreeQ@#&)⌊z=n-⌊k/2](-1)^k⌋,k++];z)
```
My earlier submission (136 bytes) found both the first 7-distinct-prime product above `n` and, if it exists, the first 7-distinct-prime product below `n`. It then simply determined which was closer to `n`. If the products were equidistant, it returned both.
The current version checks n-1,n+1,n-2,n+2... until it reaches the first 7-distinct-prime product. This more efficient version adopts the approach Dennis took.
The key advance was in using `⌊k/2](-1)^k⌋` to return the series, 0, 1, -1, 2, -2... The zero is used to check whether `n` is itself a 7-distinct-prime product. For this reason, `Floor`(that is, `⌊...⌋`) is used instead of `Ceiling`.
---
```
g[5]
g[860782]
g[1425060]
```
510510
870870
1438710
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
°Åp7.ÆPs.x
```
[Try it online!](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX1n5/9CGw60F5nqH2wKK9Sr@6/w3BAA "05AB1E – Try It Online")
Tries all combinations of 7 of the first 10\*\*input primes. Runs out of memory for inputs greater than 1.
Considerably more efficient 14 bytes version:
```
5°/7+Åp7.ÆPs.x
```
[Try it online!](https://tio.run/##yy9OTMpM/V9TVmmvpKBrp6BkX1n53/TQBn1z7cOtBeZ6h9sCivUq/uv8N@Qy5TI1MQAiCGXIZWFmYG5hxGVoYmRqYGYAAA "05AB1E – Try It Online")
Uses the first (input / 100000 + 7) primes.
] |
[Question]
[
# Merge Sort
In this challenge, you will implement the merge subroutine of merge sort. Specifically, you must create a function or program or verb or similar which takes two lists, each sorted in increasing order, and combines them into one list sorted in increasing order.
Requirements:
# - Your algorithm must take an asymptotically linear amount of time in the size of the input. Please stop giving O(n^2) solutions.
* You may not use any built-in functions capable of sorting a list, or merging a list, or anything like that. Author's discretion.
* The code should be able to handle repeated elements.
* Don't worry about empty lists.
# Examples:
```
merge([1],[0,2,3,4])
[0,1,2,3,4]
merge([1,5,10,17,19],[2,5,9,11,13,20])
[1, 2, 5, 5, 9, 10, 11, 13, 17, 19, 20]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest code win!
[Answer]
# Rebmu (35 32 chars)
```
u[iG^aNXa[rvA]apGtkFaM?fA]apGscA
```
**Test**
```
>> rebmu/args [u[iG^aNXa[rvA]apGtkFaM?fA]apGscA] [[1 5 10 17 19] [2 5 9 11 13 20]]
== [1 2 5 5 9 10 11 13 17 19 20]
>> rebmu/args [u[iG^aNXa[rvA]apGtkFaM?fA]apGscA] [[2 5 9 11 13 20] [1 5 10 17 19]]
== [1 2 5 5 9 10 11 13 17 19 20]
```
**About**
[Rebmu](http://rebmu.hostilefork.com/) is a dialect of Rebol that permits 'mushing' of regular code for situations that require brevity. Unmushed, the code works somewhat like:
```
u [ ; until
i g^ a nx a [ ; if greater? args next args
rv a ; reverse args
] ; (we want the block containing the next value first)
ap g tk f a ; append output take first args
m? f a ; empty? first args
] ; (first block is now empty)
ap g sc a ; append output second args
; (add the remainder of the second)
```
I believe this satisfies the **O(n)** requirement as the until block is at most looped as many times as the length of the input (and the `reverse` only switches the order of the container of the input blocks, not the blocks themselves). Using `take` is perhaps a liberty, but is still a minor efficiency hit.
# Rebol (83 75 chars)
Just a wee bit different: in Rebol, paths are a shorter expression than `first` or `second`. `a` is the input block containing the two blocks:
```
until[if a/2/1 < a/1/1[reverse a]append o:[]take a/1 tail? a/1]append o a/2
```
[Answer]
# OP's solutions:
# Haskell 49 44 40
```
k@(p:r)%l@(q:s)|p>=q=q:k%s|0<1=l%k
a%_=a
```
# Python 131 105 101 99 93
With thanks to @Evpok:
```
f=lambda u,v:v and(v[-1]<u[-1]and f(v,u)or[b.append(a)for a,b in[(v.pop(),f(u,v))]]and b)or u
```
[Answer]
# Python (79)
```
from itertools import*
def m(*a):
while any(a):yield min(compress(a,a)).pop(0)
```
## Python (95, if we're not allowed to return a generator)
```
from itertools import*
def m(*a):
r=[]
while any(a):r+=[min(compress(a,a)).pop(0)]
return r
```
Itertools is the solution for all worldy problems.
Bonus: the two of these work on an arbitrary number of lists, and DO worry about empty lists (as in, they'll happily take 2 empty lists, and return an empty list, or take 1 empty and 1 non-empty list, and they'll return the non-empty one. Another added feature of the 2 non-yielded ones: they'll also run with no arguments, and just return an empty list.)
Ungolfed:
```
from itertools import * # Import all items from itertools
def m(*a): # Define the function m, that takes any number of arguments,
# and stores those arguments in list a
r=[] # Create an empty list r
while any(a): # While any element in a returns True as value:
b=compress(a,a) # Remove any element from a that isn't True (empty lists)
# The example in the official documentation is this one:
# compress('ABCDEF', [1,0,1,0,1,1]) --> A C E F
c=min(b) # Sort the lists by first value, and take the first one of these.
d=c.pop(0) # Take the first element from c
r.append(d) # Append this first element to r
return r # Gives back r
```
[Answer]
# C - 75
This operates on `NULL` terminated arrays of `int *`, though it would work equally well for pointers to other types by substituting the appropriate comparison function for `**b < **a` (e.g., `strcmp(*b, *a) < 0`).
```
void m(int**a,int**b,int**c){while(*a||*b)*c++=!*a||*b&&**b<**a?*b++:*a++;}
```
Ungolfed:
```
void merge(int **a, int **b, int **c)
{
while(*a || *b)
*c++ = !*a || *b && **b < **a
? *b++
: *a++;
}
```
[Answer]
# Golfscript, ~~29~~ ~~27~~ ~~30~~ ~~29~~ 26 bytes
```
~{[[email protected]](/cdn-cgi/l/email-protection)=@<{}{\}if(@@.}do;~]p
```
or
```
~{[[email protected]](/cdn-cgi/l/email-protection)=@>{\}*(@@.}do;~]p
```
### How it works
The command
```
golfscript merge.gs <<< '[2 3] [1 4]'
```
will get processed as follows:
```
~ # Interpret the input string.
#
# STACK: [2 3] [1 4]
{ #
.@=0.@=0 # Duplicate the two topmost arrays of the stack and extract their first
# elements. This reverses the original order of the first copy.
#
# STACK: [1 4] [2 3] 2 1
#
> # Check if the respective first elements of the arrays are ordered.
#
# STACK: [1 4] [2 3] 1
#
{\}* # If they are not, swap the arrays. This brings the array with the smallest
# element to the top of the stack.
#
# STACK: [2 3] [1 4]
#
(@@ # Shift the first element of the array on top of the stack and rotate it
# behind the arrays.
#
# STACK: 1 [2 3] [4]
#
. # Duplicate the topmost array.
#
# STACK: 1 [2 3] [4] [4]
#
}do # Repeat this process if the array is non-empty.
#
# STACK: 1 [2 3] [4] -> 1 2 [4] [3] -> 1 2 3 [4] []
#
;~ # Delete the empty array from the stack and dump the non-empty array.
#
# STACK: 1 2 3 4
#
]p # Combine all elements on the stack into a single array, the to a string and
# print.
```
The output is:
```
[1 2 3 4]
```
[Answer]
# Python (63)(69)(71)
```
def m(a,b):
if a[0]>b[0]:a,b=b,a
return[a.pop(0)]+(m(a,b)if a else b)
```
I wrote this before seeing OP's comments on runtimes of other answers, so this is another solution that's O(n) in algorithm but not implementation.
[Answer]
## J - ~~42~~ 33
Modified version from [here](http://rosettacode.org/wiki/Sorting_algorithms/Merge_sort#J) + the comment of @algorithmshark
```
k=:(m}.),~0{]
m=:k~`k@.(>&{.) ::,
```
`k` prepends the head of the right array to the merged tails of both arrays. `k~` is the same, but with arrays flipped. `(>&{.)` is comparing the heads. The code will throw an error if one of the arrays is empty, in that case we return just their concatenation `,`.
[Answer]
# JavaScript (ES6), ~~69~~ 79 bytes
```
f=(a,b,c=[])=>(x=a[0]<b[0]?a:b).length?f(a,b,c.concat(x.shift())):c.concat(a,b)
```
### How it works
```
f = (a, b, c = []) => // `f' is a function that takes arguments `a', `b' and `c' -
// `c' defaults to `[]' - which returns the following
// expression:
//
(x = a[0] < b[0] ? a : b) // Store the array among `a' and `b' with the smaller first
// element in `x'.
//
.length ? // If it's non-empty,
//
f(a, b, c.concat(x.shift())) // append the first element of array `x' to array `c' and run
// `f' again;
//
: c.concat(a,b) // otherwise, append the arrays `a' and `b' to `c'.
//
)
```
[Answer]
# Haskell, 35 bytes
```
a#b@(c:d)|a<[c]=b#a|0<1=c:a#d
a#_=a
```
### Haskell, 30 bytes (non-competing)
This non-competing version only guarantees linear runtime if `a` and `b` have disjoint elements; otherwise it still runs correctly but may use quadratic time.
```
a#b|a<b=b#a|c:d<-b=c:a#d
a#_=a
```
[Answer]
# PHP ~~91 98~~ 91 bytes
edit #1: Empty `$b` requires an addional condition in the curly braces (+7).
edit #2: minor golfings
edit #3: added second version
pretty straight forward. The nicest part is the ternary inside the `array_shift`
(which fails if you try it without the curlys)
```
function m($a,$b){for($c=[];$a|$b;)$c[]=array_shift(${$a&(!$b|$a[0]<$b[0])?a:b});return$c;}
```
or
```
function m($a,$b){for($c=[];$a|$b;)$c[]=array_shift(${$a?!$b|$a[0]<$b[0]?a:b:b});return$c;}
```
**ungolfed**
```
function m($a,$b)
{
$c=[];
while($a||$b)
{
$c[] = array_shift(${
$a&&(!$b||$a[0]<$b[0])
?a
:b
});
# echo '<br>', outA($a), ' / ', outA($b) , ' -> ', outA($c);
}
return $c;
}
```
**test**
```
$cases = array (
[1],[0,2,3,4], [0,1,2,3,4],
[1,5,10,17,19],[2,5,9,11,13,20], [1, 2, 5, 5, 9, 10, 11, 13, 17, 19, 20],
[1,2,3],[], [1,2,3],
[],[4,5,6], [4,5,6],
);
function outA($a) { return '['. implode(',',$a). ']'; }
echo '<table border=1><tr><th>A</th><th>B</th><th>expected</th><th>actual result</th></tr>';
while ($cases)
{
$a = array_shift($cases);
$b = array_shift($cases);
# echo '<hr>', outA($a), ' / ', outA($b) , ' -> ', outA($c);
$expect = array_shift($cases);
$result=m($a,$b);
echo '<tr><td>',outA($a),'</td><td>',outA($b),'</td><td>', outA($expect), '</td><td>', outA($result),'</td></tr>';
}
echo '</table>';
```
[Answer]
## Go, 124 chars
```
func m(a,b[]int)(r[]int){for len(a)>0{if len(b)==0||a[0]>b[0]{a,b=b,a}else{r=append(r,a[0]);a=a[1:]}};return append(r,b...)}
```
[Answer]
# JavaScript - 133
```
function m(a,b){c=[];for(i=j=0;i<a.length&j<b.length;)c.push(a[i]<b[j]?a[i++]:b[j++]);return c.concat(a.slice(i)).concat(b.slice(j))}
```
Same sort of approach as OP's.
[Answer]
# perl, 87 chars / perl 5.14, 78+1=79 chars
This implementation clobbers the input array references. Other than that, it's pretty straight-forward: while both arrays have something, shift off the lower of the two. Then return the merged bit joined with any remaining bits (only one of @$x or @$y will remain). Straight-up perl5, 87 chars:
```
sub M{($x,$y,@o)=@_;push@o,$$x[0]>$$y[0]?shift@$y:shift@$x while@$x&&@$y;@o,@$x,@$y}
```
Using perl 5.14.0 and its newfangled arrayref shift: 78 chars + 1 char penalty = 79 chars:
```
sub M{($x,$y,@o)=@_;push@o,shift($$x[0]>$$y[0]?$y:$x)while@$x&&@$y;@o,@$x,@$y}
```
[Answer]
# Java: 144
This is pretty straightforward. A function that takes two arrays and returns one, the merged version, golfed and without compilation wrapper:
```
int[]m(int[]a,int[]b){int A=a.length,B=b.length,i,j;int[]c=new int[A+B];for(i=j=0;i+j<A+B;c[i+j]=j==B||i<A&&a[i]<b[j]?a[i++]:b[j++]);return c;}
```
Ungolfed (with compile-able and runnable wrapper):
```
class M{
public static void main(String[]args){
int[]a=new int[args[0].split(",").length];
int i=0;
for(String arg:args[0].split(","))
a[i++]=Integer.valueOf(arg);
int[]b=new int[args[1].split(",").length];
int j=0;
for(String arg:args[1].split(","))
b[j++]=Integer.valueOf(arg);
int[]c=(new M()).m(a,b);
for(int d:c)
System.out.printf(" %d",d);
System.out.println();
}
int[]m(int[]a,int[]b){
int A=a.length,B=b.length,i,j;
int[]c=new int[A+B];
for(i=j=0;i+j<A+B;c[i+j]=j==B||i<A&&a[i]<b[j]?a[i++]:b[j++]);
return c;
}
}
```
Example executions:
```
$ javac M.java
$ java M 10,11,12 0,1,2,20,30
0 1 2 10 11 12 20 30
$ java M 10,11,12,25,26 0,1,2,20,30
0 1 2 10 11 12 20 25 26 30
```
Any tips to shorten would be appreciated.
[Answer]
# Scala, 97 bytes
Recursive solution with O(n). To shorten the code, sometimes an operation is done by switching the 2 interchangeable parameters, i.e. f(a,b) calls f(b,a).
```
type L=List[Int];def f(a:L,b:L):L=if(a==Nil)b else if(a(0)<=b(0))a(0)::f(a.drop(1),b) else f(b,a)
```
Ungolfed:
```
type L=List[Int]
def f(a:L, b:L) : L =
if (a == Nil)
b
else
if (a(0) <= b(0))
a(0) :: f(a.drop(1), b)
else
f(b,a)
```
[Answer]
## APL (32)
```
{⍺⍵∊⍨⊂⍬:⍺,⍵⋄g[⍋g←⊃¨⍺⍵],⊃∇/1↓¨⍺⍵}
```
Explanation:
```
{⍺⍵∊⍨⊂⍬ if one or both of the arrays are empty
:⍺,⍵ then return the concatenation of the arrays
⋄g[⍋g←⊃¨⍺⍵] otherwise return the sorted first elements of both arrays
,⊃∇/ followed by the result of running the function with
1↓¨⍺⍵} both arrays minus their first element
```
[Answer]
## LISP, 117 bytes
The algorithm ends in `n + 1` iterations, where `n` is the length of the shortest list in input.
```
(defun o(a b)(let((c(car a))(d(car b)))(if(null a)b(if(null b)a(if(< c d)(cons c(o(cdr a)b))(cons d(o a(cdr b))))))))
```
[Answer]
# [PYG](https://gist.github.com/Synthetica9/9796173) (50)
```
def m(*a):
while An(a):yield Mn(ItCo(a,a)).pop(0)
```
## [PYG](https://gist.github.com/Synthetica9/9796173) (64, again, if no generators are allowed.):
```
def m(*a):
r=[]
while An(a):r+=[(Mn(ItCo(a,a)).pop(0)]
return r
```
An adaptation of [my Python answer](https://codegolf.stackexchange.com/questions/25461/merge-two-sorted-lists/25480#25480).
[Answer]
# Python – 69 bytes
```
def m(A,B):
C=[]
while A and B:C+=[[A,B][A>B].pop(0)]
return C+A+B
```
If the order of input and output were descending, this could be shortened to **61 bytes**:
```
def m(A,B):
C=[]
while A+B:C+=[[A,B][A<B].pop(0)]
return C
```
And further down to **45 bytes** if generators are allowed:
```
def m(A,B):
while A+B:yield[A,B][A<B].pop(0)
```
[Answer]
# Perl 6: 53 characters
```
sub M(\a,\b){{shift a[0]>b[0]??b!!a}...{a^b},a[],b[]}
```
Shift from whichever of `a` or `b` has the smaller value, until `a` XOR `b` (`a^b`) is true. Then return whatever is left, flattening (`[]`) the arrays into the list (`a[],b[]`).
Assuming shifting from the start of an array is O(n), the worst case is two comparisons and one shift per element, so the algorithm is O(n).
[Answer]
# JavaScript (ES5) 90 86 90 bytes
```
function f(a,b){for(o=[];(x=a[0]<b[0]?a:b).length;)o.push(x.shift());return o.concat(a,b)}
```
**edit:** (90 - >86) Moved the ternary into the for loop condition. Idea stolen from Dennis.
**edit:** (86 -> 90) Removed Array to String cast, as it breaks the *O(n)* requirement.
[Answer]
# Mathematica, 137 135
```
m[a_,b_]:=(l=a;Do[Do[If[b[[f]]<=l[[s]],(l=Insert[l,b[[f]],s];Break[]),If[s==Length@l,l=l~Append~b[[f]]]],{s,Length@l}],{f,Length@b}];l)
```
Input:
```
m[{2,2,4,6,7,11},{1,2,3,3,3,3,7}]
```
Output:
```
{1, 2, 2, 2, 3, 3, 3, 3, 4, 6, 7, 7, 11}
```
Ungolfed:
```
mergeList[a_, b_] := (
list = a;
Do[
Do[(
If[
b[[f]] <= list[[s]],
(list = Insert[list, b[[f]], s]; Break[]),
If[
s == Length@list,
list = list~Append~b[[f]]
]
]),
{s, Length@list}
],
{f, Length@b}
];
list
)
```
Could probably do better.
[Answer]
# R, 80
Same solution as in Scala and other languages. I am not so sure about x[-1] is O(1).
```
f=function(a,b)if(length(a)){if(a[1]<=b[1])c(a[1],f(a[-1],b))else f(b,a)}else b
```
[Answer]
## Mathematica, 104 bytes
```
Reap[{m,n}=Length/@{##};i=k=1;Do[If[k>n||TrueQ[#[[i]]<#2[[k]]],Sow@#[[i++]],Sow@#2[[k++]]],n+m]][[2,1]]&
```
Anonymous function, stores the length of the two input lists in the variables `m` and `n`, then each iteration of the `Do` loop `Sow`s an element of one the lists incrementing the counter for that list (`i` for the first, `k` for the second) by one. If one of the counters exceeds the length of the list, the `If` statement will always `Sow` the element from the other list. After `n+m` operations, all the elements have been taken care of. `Reap` or rather part `[[2,1]]` of its output is a list of elements in the order they have been `Sow`n.
I'm not sure of the internals (is accessing a part of a list a `O(1)` operation or not), but timings looked quite linear on my machine with respect to input list length.
] |
[Question]
[
Braille Patterns in Unicode contains 8 dots(`⣿`) and occupy area U+2800-U+28FF. Given a Braille Pattern character, where the bottom two dots are not used(aka. U+2800-U+283F), shift it down by one dot.
Test cases:
```
⠀ => ⠀ (U+2800 -> U+2800)
⠅ => ⡂
⠕ => ⡢
⠿ => ⣶
```
Shortest code wins.
[Answer]
# [Python](https://www.python.org), 44 bytes
```
lambda c:chr((d:=ord(c))+d%64+14*(d&36)%192)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3dXISc5NSEhWSrZIzijQ0Uqxs84tSNJI1NbVTVM1MtA1NtDRS1IzNNFUNLY00oXrM0_KLFJIVMvMUihLz0lM1DCqMLAwMdECUiYGmFZdCQVFmXokGyMBkTZ00KEMTqn3BAggNAA)
Takes and returns a Unicode character.
# [Python](https://www.python.org), 29 bytes
```
lambda c:c+c%64+14*(c&36)%192
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhZ7cxJzk1ISFZKtkrWTVc1MtA1NtDSS1YzNNFUNLY0gam6ap-UXKSQrZOYpFCXmpadqGFQYWRgY6IAoEwNNKy6FgqLMvBKN5IwijWRNHRCVBmRoakK0L1gAoQE)
Takes and returns a code point.
### [Python](https://www.python.org), 33 bytes
```
lambda c:c+c%64+2*(c&32)+14*(c&4)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3FXMSc5NSEhWSrZK1k1XNTLSNtDSS1YyNNLUNTUAsE02oQvO0_CKFZIXMPIWixLz0VA2DCiMLAwMdEGVioGnFpVBQlJlXopGcUaSRrKkDotKADE2o9gULIDQA)
Takes and returns a code point.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 7 bytes
```
B⁽1¢œ?Ḅ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCJC4oG9McKixZM/4biEIiwi4biiT8OH4buMIiwiIixbIuKgtSJdXQ==)
I/O via unicode codepoints.
## Explanation
```
B⁽1¢œ?Ḅ Main Link
B Convert to binary
⁽1¢œ? Take the 13252nd permutation, which shuffles the last 8 bits into place
Ḅ Convert from binary
```
My original idea was to chop off the first 7 bits to apply permutation and then add 10240, but Lynn made the clever observation that permutation number 13252 only modifies the last 8 bits so it's not needed to do those precomputation and postcomputation steps.
-5 bytes thanks to emanresu A and Jonathan Allan by using a more convenient input format.
-6 bytes thanks to Lynn by noticing that removing and re-adding the first 7 bits is not needed
[Answer]
# JavaScript (ES6), 25 bytes
Expects and returns a code point.
```
n=>n+n%64+((n/4&9)+3^3)*8
```
[Try it online!](https://tio.run/##Jc5BDoIwEIXhPaeYjTJjESsQgkHccATj1oRoixicktIYEuPZK@ru@/M27948m/Fiu8Gt2VyV15Xn6sCCF3kmEHmTLXck0nNKq8JrY7FXDhgqkFNSSFnO3v@cfS0EwSsAuBgeTa/i3rQYyikEARw7c3S24xa3Oc1xGgZl62ZUSBH8l1hb86hvja3nK8gRpEkEGpmIyuDtPw "JavaScript (Node.js) – Try It Online")
### 23 bytes
A port of [loopy walt's solution](https://codegolf.stackexchange.com/a/264063/58563) is shorter.
```
n=>n+n%64+14*(n&36)%192
```
[Try it online!](https://tio.run/##Jc5LDoIwFIXhOau4E6S1SMojRIM4YQnGBTTYIqbeS0pjSIxrr6iz78@ZnLt6qrl34@R3SFcdTBuwPaHAuK5EXm0Zbsqax/mhCIYcs9oDQgtyKfZSNquPP1dfC8HhFQH0hDNZnVkaWCKXBARg5uns3YgDy2u@xmWatOvUrBlP4b9kxtGjuynXrUcYplAWKRiGnPMmeocP "JavaScript (Node.js) – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~178~~ ~~163~~ 150 bytes
```
.
255*x
Y`x`⠁-⣿
~)`.+
Y`$0`$-1
~(K`T`⠂⣿`⠂⠆⡀⡆⠐⠖⡐⡖⠠⠦⡠⡦⠰⠶⡰⡶⢀⢆⣀⣆⢐⢖⣐⣖⢠⢦⣠⣦⢰⢶⣰⣶
-
```
[Try it online!](https://tio.run/##Hc@3TsRQFITh3k9BQUHQrlikfQpaGjpTUNBQIIqtViaZDCaZDHPvBZPBJJPZd/lfxNiujnSmmG8mx6bGJ0YbeV73BpvNvpY34rd8NF3DdTyvy2v3@vX@4tk94HfXGl67Z8gfLvKZIq6OQkyACVGEYkyEiZFQghEmQSnKMCkmwwbYEBfgQmyEjXERLsYKm@CES7ApNsOluMzzanmOgoJTVc2iOTRfdmoBLaIltIxW0CpaQ@too4Jsoi20jXbQbunSHtpHB@gQHaFjdIJO0VmFNcgih87RRWnXJbpC1@gG3aI7dI8e0GM16Ak9oxf0it7KfXpHH@gTfaFv9IN@0R/q/AM "Retina – Try It Online")
*-15 with another eval stage*
*-6 directly thanks to Neil and -7 extrapolating from his suggestions*
Shaves a few bytes off [direct transliteration](https://codegolf.stackexchange.com/a/264078/85334) by spending 40 on an incredibly convoluted way of "doubling" the input so the final transliteration stage can use more ranges. The doubling is necessary because every possible output is even; if the bits in a byte are `76543210` then the dots in the corresponding Braille character are
```
0 3
1 4
2 5
6 7
```
(Although this handles longer inputs fine, in the explanation I'll assume only the single character input required by the challenge for the sake of simplicity.)
# Explanation:
The entire program consists of two eval stages, which construct then run Retina programs:
## Eval stage 1
```
.
255*x
```
Replace any and all characters in the input with 255 copies of the letter `x`.
```
Y`x`⠁-⣿
```
Cycling transliterate those into the range of all 255 nonzero Braille characters. This creates that range as a string.
```
```
Replace the empty string with a space, prepending a space to every character in the range and appending another to the end.
```
.+
Y`$0`$-1
```
Interpolate the spaced range and the unspaced range into the string representation of a cyclic transliterate.
## Eval stage 2
```
K`T`⠂⣿`⠂⠆⡀⡆⠐⠖⡐⡖⠠⠦⡠⡦⠰⠶⡰⡶⢀⢆⣀⣆⢐⢖⣐⣖⢠⢦⣠⣦⢰⢶⣰⣶
```
The literal string `T`⠂⣿`⠂⠆⡀⡆⠐⠖⡐⡖⠠⠦⡠⡦⠰⠶⡰⡶⢀⢆⣀⣆⢐⢖⣐⣖⢠⢦⣠⣦⢰⢶⣰⣶`.
```
-
```
Replace the empty string with a hyphen, prepending a hyphen to every character in the string and appending another to the end.
## What actually gets run on the input
```
Y` ⠁ ⠂ ⠃ ⠄ ⠅ ⠆ ⠇ ⠈ ⠉ ⠊ ⠋ ⠌ ⠍ ⠎ ⠏ ⠐ ⠑ ⠒ ⠓ ⠔ ⠕ ⠖ ⠗ ⠘ ⠙ ⠚ ⠛ ⠜ ⠝ ⠞ ⠟ ⠠ ⠡ ⠢ ⠣ ⠤ ⠥ ⠦ ⠧ ⠨ ⠩ ⠪ ⠫ ⠬ ⠭ ⠮ ⠯ ⠰ ⠱ ⠲ ⠳ ⠴ ⠵ ⠶ ⠷ ⠸ ⠹ ⠺ ⠻ ⠼ ⠽ ⠾ ⠿ ⡀ ⡁ ⡂ ⡃ ⡄ ⡅ ⡆ ⡇ ⡈ ⡉ ⡊ ⡋ ⡌ ⡍ ⡎ ⡏ ⡐ ⡑ ⡒ ⡓ ⡔ ⡕ ⡖ ⡗ ⡘ ⡙ ⡚ ⡛ ⡜ ⡝ ⡞ ⡟ ⡠ ⡡ ⡢ ⡣ ⡤ ⡥ ⡦ ⡧ ⡨ ⡩ ⡪ ⡫ ⡬ ⡭ ⡮ ⡯ ⡰ ⡱ ⡲ ⡳ ⡴ ⡵ ⡶ ⡷ ⡸ ⡹ ⡺ ⡻ ⡼ ⡽ ⡾ ⡿ ⢀ ⢁ ⢂ ⢃ ⢄ ⢅ ⢆ ⢇ ⢈ ⢉ ⢊ ⢋ ⢌ ⢍ ⢎ ⢏ ⢐ ⢑ ⢒ ⢓ ⢔ ⢕ ⢖ ⢗ ⢘ ⢙ ⢚ ⢛ ⢜ ⢝ ⢞ ⢟ ⢠ ⢡ ⢢ ⢣ ⢤ ⢥ ⢦ ⢧ ⢨ ⢩ ⢪ ⢫ ⢬ ⢭ ⢮ ⢯ ⢰ ⢱ ⢲ ⢳ ⢴ ⢵ ⢶ ⢷ ⢸ ⢹ ⢺ ⢻ ⢼ ⢽ ⢾ ⢿ ⣀ ⣁ ⣂ ⣃ ⣄ ⣅ ⣆ ⣇ ⣈ ⣉ ⣊ ⣋ ⣌ ⣍ ⣎ ⣏ ⣐ ⣑ ⣒ ⣓ ⣔ ⣕ ⣖ ⣗ ⣘ ⣙ ⣚ ⣛ ⣜ ⣝ ⣞ ⣟ ⣠ ⣡ ⣢ ⣣ ⣤ ⣥ ⣦ ⣧ ⣨ ⣩ ⣪ ⣫ ⣬ ⣭ ⣮ ⣯ ⣰ ⣱ ⣲ ⣳ ⣴ ⣵ ⣶ ⣷ ⣸ ⣹ ⣺ ⣻ ⣼ ⣽ ⣾ ⣿`⠁⠂⠃⠄⠅⠆⠇⠈⠉⠊⠋⠌⠍⠎⠏⠐⠑⠒⠓⠔⠕⠖⠗⠘⠙⠚⠛⠜⠝⠞⠟⠠⠡⠢⠣⠤⠥⠦⠧⠨⠩⠪⠫⠬⠭⠮⠯⠰⠱⠲⠳⠴⠵⠶⠷⠸⠹⠺⠻⠼⠽⠾⠿⡀⡁⡂⡃⡄⡅⡆⡇⡈⡉⡊⡋⡌⡍⡎⡏⡐⡑⡒⡓⡔⡕⡖⡗⡘⡙⡚⡛⡜⡝⡞⡟⡠⡡⡢⡣⡤⡥⡦⡧⡨⡩⡪⡫⡬⡭⡮⡯⡰⡱⡲⡳⡴⡵⡶⡷⡸⡹⡺⡻⡼⡽⡾⡿⢀⢁⢂⢃⢄⢅⢆⢇⢈⢉⢊⢋⢌⢍⢎⢏⢐⢑⢒⢓⢔⢕⢖⢗⢘⢙⢚⢛⢜⢝⢞⢟⢠⢡⢢⢣⢤⢥⢦⢧⢨⢩⢪⢫⢬⢭⢮⢯⢰⢱⢲⢳⢴⢵⢶⢷⢸⢹⢺⢻⢼⢽⢾⢿⣀⣁⣂⣃⣄⣅⣆⣇⣈⣉⣊⣋⣌⣍⣎⣏⣐⣑⣒⣓⣔⣕⣖⣗⣘⣙⣚⣛⣜⣝⣞⣟⣠⣡⣢⣣⣤⣥⣦⣧⣨⣩⣪⣫⣬⣭⣮⣯⣰⣱⣲⣳⣴⣵⣶⣷⣸⣹⣺⣻⣼⣽⣾⣿
```
The program generated and run in eval stage 1. Transliterates the input to the character at twice its index in the Braille range, "doubling" it.
```
-T-`-⠂-⣿-`-⠂-⠆-⡀-⡆-⠐-⠖-⡐-⡖-⠠-⠦-⡠-⡦-⠰-⠶-⡰-⡶-⢀-⢆-⣀-⣆-⢐-⢖-⣐-⣖-⢠-⢦-⣠-⣦-⢰-⢶-⣰-⣶-
```
The program generated and run in eval stage 2. Transliterates the doubled input into a bunch of smaller ranges.
The ranges are non-overlapping pairs of non-hyphens in the `to` section after the rightmost backtick; the hyphens not inside those pairs parse as literal hyphens which are used for alignment (as the whole point of this is that the `from` range, between the backticks, is not doubled.) The final hyphen in both the `from` and `to` sections is completely irrelevant and the leading hyphens cancel each other out; the extra hyphens before the first backtick are just ignored.
[Answer]
# [Go](https://golang.org/), 45 bytes
```
func(c rune)rune{return c+c%64+14*(c&36)%192}
```
[Try it online!](https://tio.run/##LY1BCoMwFET3OcUgpCSNFLUiba136AG6CR8jUhIlxCKIZ7cauhnewGOmG7ZR00d3LazuHevtOPiAxNiQMPbVHgbNZiZHguAn18ojFt@GyTuQIl6VKi/Pgk7XSvL8XqzRjmsQEgsDzOAx49Egm4tbltV7eUYuD1YqSrtmw@XlexeMSDiB09slaTwVs0xhxB@lrHd/Zev2Aw "Go – Try It Online")
Port of loopy walt's Python answer.
[Answer]
# [Python](https://www.python.org), ~~77~~ 64 bytes
*-2 bytes thanks to l4m2*
```
lambda c:[c&32and(c:=c&~32|64),c&4and(c:=c&~4|32),c*2-0x2800][2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3HXISc5NSEhWSraKT1YyNEvNSNJKtbJPV6oyNasxMNHWS1UwQYiY1xkZAIS0jXYMKIwsDg9hoo1ioOTUlqcUlyYnFqcUKtgrR0UqPFjQo6YDJWB0QrxXEW9gE5U0F8xZBeftBvMXblGJjudLyixQydfIVMvMU4AZacSkAQUFRZl6JBlBOJzmjSCNNI78oRSNTU1PT1jZfE-KGBQsgNAA)
Input/output in Unicode codepoints.
## Ungolfed
```
def f(c):
# fix exceptions (Historical Reasons™)
if c & 32: # change bit 7 set to bit 8 set
c &= ~32
c |= 64
if c & 4: # change bit 4 set to bit 7 set
c &= ~4
c |= 32
return (c << 1) - 0x2800
```
See <https://en.wikipedia.org/wiki/Braille_Patterns#Identifying,_naming_and_ordering>
for more info.
[Answer]
# [J](https://www.jsoftware.com), 12 bytes
```
13251#.@A.#:
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxxtDYyNRQWc_BUU_ZCiJ0M06TKzU5I1_BQqHUSskwVsFEwdBMBUiWWmmkpGUoqBtZGBioaypoK2TqKZiZ4FKrkKZmp4BNA8SWBQsgNAA)
Apparently converged at the same algorithm as [Jelly](https://codegolf.stackexchange.com/a/264059/78410), because both have the "nth permutation" built-in. (This is not magically winning against Jelly; the direct translation is Lynn's 7-byter in the comments.)
Looking at the lower 8 bits of a Braille's codepoint (highest bit first), the main task is to permute the first into the second:
```
0 0 b2 b3 b4 b5 b6 b7
b2 b5 b3 b4 0 b6 b7 0
```
It doesn't matter which of the two guaranteed zeros go first, so 13257 also works in place of 13251. Jelly uses 13252 instead because its built-in is 1-indexed instead of 0-indexed.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 23 bytes
```
℅Σ⟦℅θ&℅θ⁶³×¹⁴&℅θ⁴⊗&℅θ³²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMZyE9MLkkt0gguzdWI9i9KycxLzNEo1NRRcMosKc8sTnXMS9FAFjYzBhIhmbmpxRqGJjhVmWgCCZf80qSc1BQNHGqMjTQ1YzU1Na3//3@0YOp/3bIcAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @loopywalt's original Python answer.
```
θ Input character
℅ Code of character
θ Input character
℅ Code of character
& Bitwise And
⁶³ Literal integer `63`
θ Input character
℅ Code of character
& Bitwise And
⁴ Literal integer `4`
× Multiplied by
¹⁴ Literal integer `14`
θ Input character
℅ Code of character
& Bitwise And
³² Literal integer `32`
⊗ Doubled
⟦ Make into list
Σ Take the sum
℅ Character with code
Implicitly print
```
Alternative version, also 23 bytes:
```
≔℅Sθ℅Σ⟦θ&θ⁶³×¹⁴&θ⁴⊗&θ³²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DvyglMy8xR8Mzr6C0JLikKDMvXUNTU0ehUNOaKwDIK9FwBmpJTC5JLdIILs3ViC7UUXDKLCnPLE51zEvRAPLMjIHKQzJzU4s1DE3QJU1AZrnklyblpKZooEoZG2lqxmpqalr///9owdT/umU5AA "Charcoal – Try It Online") Link is to verbose version of code.
24 bytes for a whole string at once:
```
⭆ES℅ι℅Σ⟦ι&ι⁶³×¹⁴&ι⁴⊗&ι³²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaICwZ15BaQlESENTR8G/KCUzLzFHI1MTyHEG6kxMLkkt0gguzdWIztRRcMosKc8sTnXMS9EA8syMgYpCMnNTizUMTdAlTUAmuOSXJuWkpmigShkbaWrGaoKA9f//jxY0PFrQ@mjB1EcL9v/XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 199 bytes
```
T`⠁-⠿`⠂⠄⠆⡀⡂⡄⡆⠐⠒⠔⠖⡐⡒⡔⡖⠠⠢⠤⠦⡠⡢⡤⡦⠰⠲⠴⠶⡰⡲⡴⡶⢀⢂⢄⢆⣀⣂⣄⣆⢐⢒⢔⢖⣐⣒⣔⣖⢠⢢⢤⢦⣠⣢⣤⣦⢰⢲⢴⢶⣰⣲⣴⣶
```
[Try it online!](https://tio.run/##Dc@xDYJgFIXRidzGAbSwsLEwDoAEqf8QpL7vPkJNCKF1l28RpDr1ed5e98d1388X9D6h32GNGtQSFVETDdGigjrUo4EoREf0xICEjEY0ESJMjMSEZrSgFW3ETCzESmy4wjVucEtWZE02ZIsL7nCPB7KQHdmTAxY2HvFEijQ5khOe8YJXvJEzuZArue07qtAHfY/LHw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Unfortunately there doesn't seem to be a good way to encode the destination characters as their codes jump all over the place. I looked into shifting the codes into the ASCII range to do the transliteration but that looks as if it will take 239 bytes.
[Answer]
# [Scala 3](https://www.scala-lang.org/), 48 bytes
Port of [@loopy walt's Python answer](https://codegolf.stackexchange.com/a/264063/110802) in Scala.
---
```
c=>{val d=c.toInt;(d+d%64+14*(d&36)%192).toChar}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NU1NCoJAGN17ikdkzCTGlCL9KUSrFq06wTSjZMgoOoYgnqSNm7pTt0lLv8X7eLy_57sQPOFO-2Hp9R4KjTOPFcJKh0oWOGQZasMAHjxBtD3eeO4HPcLHq9SRvf4w4Qd1L0tfLHR6UnpHpCVNz7WW7pzImeNRc7lZ0U7sk82QuwBRmoMI7G2warVmDKXScfIjLqPdMLrL8ljpRJFiMq3F2IFpHZGR0WZCO2tjDNVt-_9f)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
bœŽp÷èC
```
Port of [*@hyper-neutrino♦*'s Jelly answer](https://codegolf.stackexchange.com/a/264059/52210), so make sure to upvote that answer as well!
I/O as codepoint integers.
No TIO, since it's way too slow (it'll get a list of all binary-permutations and indexes into it).
**Much faster version which does finish - 11 (or 9*†*) [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage):**
*†: Should have been 9 bytes without the `ƶ` and `Ā`, but apparently there is [a bug with the \$n^{th}\$ permutation builtin `.I` and bit-lists](https://github.com/Adriandmen/05AB1E/issues/204)..*
```
2вƶŽp÷.IĀ2β
```
I/O as codepoint integers.
[Try it online](https://tio.run/##yy9OTMpM/X@4PcHl6AKlw/sVNA7v11R41DZJQan4v9GFTce2Hd1bcHi7nueRBqNzm/67HF5eDFOl5GX//9GC6QA) or [verify all test cases](https://tio.run/##Nco3TsNgAIDRq1ieQEIMuQCLF24BSAxMIEVCYqMmQKih948aejGQ0IKHnzAizvBdxEy8@Q0We/sG@vPhkSSUe5IWcciitpC1R5aqUdyVF37T73qrORQand1fo4WfNE9Crfi/4o5cxmRcJmRSpqQkZZmWGZmViszJvCzIoizJslRlRVZlTdZlQzZlS7ZlR3ZlT/blQJBDOZJjOZFTOZOanMuFXMqVXMuN3Mqd3MuDpPIoT/IsdWnIi7zKm7zLhzTlU7I/).
**Explanation:**
```
b # Convert the (implicit) input-integer to a binary-string
œ # Get all permutations of this binary-string
Žp÷ # Push compressed integer 13251
è # Index it into the list of permutations
C # Convert this permuted binary-string back to a (base-10) integer
# (which is output implicitly as result)
```
```
2в # Convert the (implicit) input-integer to a binary-list
ƶ # Multiply each 1 to its 1-based index (bug workaround part 1 of 2)
Žp÷ # Push compressed integer 13251
.I # Get the 0-based 13251st permutation of the list
Ā # Convert each positive integer back to 1s (bug workaround part 2 of 2)
2β # Convert this permuted binary-list back to a (base-10) integer
# (which is output implicitly as result)
```
Note: `.I` only works with lists and not with strings.
[See this 05AB1E tip of mine (section *How to compress large integers?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `Žp÷` is `13251`.
[Answer]
# Java, 23 bytes
```
c->c+c%64+(c&36)*14%192
```
Another port of [*@loopyWalt*'s Python answer](https://codegolf.stackexchange.com/a/264063/52210).
I/O as codepoint-integers.
[Try it online.](https://tio.run/##LZFHSwNhEIbv/oqPhciuSxYsCCoRxLNePIqHzy@Jria7slkFkRzsvff@2nvv/b@8fyTuJpnDDPMyhXmmS/bJaFe8O6dSMpMRTdJ2BkqEsB0/4SWlSojmMM0LIqmHXhl1gZItCVzGl76tRLNwRCynovXKVJHqKlNXpZXVRll5VaS8piJXF1b29LangspiQ59rx0U6WKW3@J7tdLS2SaOwJul6uuqUnlC1GjFIDBHDxAgxSowR48QEMUlMEdPEDDFLzBHzxAKxSCwRy8QKsUqsEevEBrFJbBHbxA6xS@wR@wSIA@KQOCKOiRPilDgjzokL4pK4Iq6JG@KWuCPuiQfikXginokX4pV4I96JD@KT@CK@iR/il/jTLN9tDA5p8DzZrxvF8wocvZhjJfUCx9Ba@jN@Im25vb7VE@DwU44ekjaUqQldM8PAsSWhmV5ByBMygsTQijOy@Y9kc/8)
With characters as I/O, it would be 1 byte longer:
```
c->c+=c%64+(c&36)*14%192
```
[Try it online.](https://tio.run/##LZBHSwNRFIX3@RWPQGTGkICFgEoEca0bl@Li@ZLoaDITJi@CiAt77y32Y@@99/9y/sg4xmzu5R7O5fCdLtkjI12Jbk@lZS4nmqRl9wWEsGyddFNSJUXz3ymE6pSuSBnFpcw6X@sP@COnpbaUaBa2iHsqUq/CcRWKVYcNVVYVM8srqkMVNZVe3Z81m29P@9bSR49jJUTGTzNatGvZHa1t0vxPSjluKaY2SAwQg8QQMUyMEKPEGDFOTBCTxBQxTcwQs8QcMU8sEIvEErFMrBCrxBpRINaJDWKT2CK2iR1ilwCxR@wTB8QhcUQcEyfEKXFGnBMXxCVxRVwTN8QtcUfcEw/EI/FEPBMvxCvxRrwTH8Qn8UV8Ez/BqHYafZAG15W9hmkW6YRo6c3pZCbq5HU065PrtG2ocFBwtCCCYTvqd2yW@u33fgE)
**Explanation (of the character I/O lambda function):**
```
c-> // Method with character as both parameter and return-type
c+= // Add to the current codepoint-integer, without changing its type:
c%64 // The input-codepoint modulo-64
+ // As well as:
(c&36) // The input-codepoint basewise-AND with 36
*14 // Then multiplied by 14
%192 // And then modulo-192
```
] |
[Question]
[
[Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)'s 2D programming language [Alice](https://github.com/m-ender/alice) has two different modes depending on what orientation the IP has: orthogonal (Cardinal mode) or diagonal (Ordinal mode). Commands in Alice change their meaning depending on which mode the program is in when they're executed. One especially interesting implementation of this is Alice's `Z`, or "pack", command. For strings in Ordinal mode, this simply takes two strings **a** and **b** and interleaves (also known as "zip") them. For example:
```
a = "Hello"
b = "World"
Z -> "HWeolrllod"
```
However, while in Cardinal mode, `Z` pops two integers \$n\$ and \$m\$ and returns \$\pi(n,m)\$\*, the [Cantor pairing function](https://en.wikipedia.org/wiki/Pairing_function#Cantor_pairing_function). For example, for \$n = 2, m = 3\$, `Z` returns \$\pi(2, 3) = 18\$. The reasoning behind this is explained in [this](https://codegolf.stackexchange.com/a/147028/66833) answer.
For clarity, the Cantor pairing function uses the following formula:
$$\pi(n,m) = \frac12(n+m)(n+m+1)+m$$
---
You are to write two **non-identical** programs that implement the two modes of `Z`. More specifically:
* The first should take two non-empty strings containing only printable ASCII (`0x20` to `0x7e`) of the same length\* and output these strings zipped/interleaved together
* The second should take two non-negative integers \$x\$ and \$y\$ and should output \$\pi(x, y)\$ as specified above.
\*: This isn't *technically* how the `Z` command works, read the Alice docs for more
You may input and output in any [accepted method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and you may assume all inputs are reasonable for your language.
Your score is the [Levenshtein distance](https://en.wikipedia.org/wiki/Levenshtein_distance) between your two programs multiplied by the sum of the program lengths, aiming for a lower score. You can use [this](https://planetcalc.com/1721/) website to calculate Levenshtein distance.
## Test Cases
For the first program:
```
a, b -> Z
"a", "b" -> "ab"
"Hello,", "World!" -> "HWeolrllod,!"
"World!", "Hello," -> "WHoerllldo!,"
"Alice", " " -> "A l i c e "
```
The second program:
```
n, m -> π(n, m)
2, 3 -> 18
5, 5 -> 60
0, 1 -> 2
1, 0 -> 1
100, 75 -> 15475
```
[Answer]
# Jelly, Score 1 \* 8 bytes = 8
String zip:
```
+Ẇɼ+
```
[Try it online!](https://tio.run/##y0rNyan8/1/74a62k3u0////7wEUyP8fnl@UkwIA "Jelly – Try It Online")
Cantor pairing function:
```
+ẆL+
```
[Try it online!](https://tio.run/##y0rNyan8/1/74a42H@3///8bGhj8NzcFAA "Jelly – Try It Online")
We use the fact that the Cantor pairing is equal to
$$ {n + m + 1 \choose 2} + m $$
Where the left term just happens to be the number of nonempty contiguous slices of \$m+n\$. This saves two bytes per program over the naive `+‘×+H+`, and one byte over the (less naive) `+‘c2+`.
Conveniently, in Jelly `+` zips strings (I had no idea!).
Explanations:
```
Implicit input: strings s1, s2
+ Zip s1, s2.
Ẇ All nonempty slices.
ɼ Save the result to register (ignore previous 2).
+ Zip s1, s2.
```
```
Implicit input: numbers n, m
+ Compute m+n.
Ẇ All nonempty slices of implicit range m+n.
L Length.
+ Add m.
```
---
Note that there are many ways to get 4 for the pairing function (`+R;S`, `+R+ƒ`, etc)
[Answer]
# [Python 3](https://docs.python.org/3/), 1 \* (50 + 50) = 100
-2 bytes thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!
**First function**:
Output is a tuple of characters.
```
lambda a,b:1and sum(zip(a,b),())or(a+b)*(a-~b)/2+b
```
[Try it online!](https://tio.run/##Lc6xDsIgFAXQvV/xZCm0GKNuTTp08w8ctMPD0khCgQAOOvjrCLVvujk3uXnuHZ/WnNPc35PGRUwIyEV3RDNBeC30oxzNwDhlzHqKrWANxf1XsMOpFSnKEAP0cCNIOBBBRp7zRWpteYGr9Xra/XXLWbd@1UGrhywI5chYzdbnF0CAMrDOdxWA88pE2sy0NIxDkK6va5Z@ "Python 3 – Try It Online")
**Second function**:
```
lambda a,b:0and sum(zip(a,b),())or(a+b)*(a-~b)/2+b
```
[Try it online!](https://tio.run/##HcvBCoMwEIThu08xx9260qiEguCTWA8JVhqoUZL00B766ql6@uAfZvuk5@rbPPf3/DKLnQyM2E4ZPyG@F/q6jfbAQsxrIFNavpCpfpavTWlzesQU0WNoBO0oGLRAHypBfVgL1Knay02PxbwGeMEC53G@uwLYgvOJZjoG5vwH "Python 3 – Try It Online")
[Answer]
# Haskell, score 1×(43+43)=86
One program is:
```
a!b=sum[1..a+b]+b
(a:b)%(c:d)=a:c:b%d;a%b=b
```
It defines `a!b` = π(a, b), and an unused “helper function” `(%)`.
The other program is the same, but with a semicolon instead of a newline.
It defines `x%y` = Z(x, y), and an unused “helper function” `(!)`.
[Answer]
# [Husk](https://github.com/barbuz/Husk), score 1 × 12 bytes = 12
First program:
```
₅
+¹Σ+
```
[Try it online!](https://tio.run/##yygtzv7//1FTK5f2oZ3nFmv////f0MDgv7kpAA "Husk – Try It Online") It takes \$n\$ and \$m\$ as two separate arguments.
Second program:
```
Ξ
+¹Σ+
```
[Try it online!](https://tio.run/##yygtzv7//9w8Lu1DO88t1v7//3@0kkdqTk6@jpKOUnh@UU6KolIsAA "Husk – Try It Online") It takes the two strings in a list.
In the first program, the main function just calls the auxiliary function with its arguments flipped, and in the second program, the auxiliary function is ignored altogether.
[Answer]
# JavaScript (ES6), 1 \* 102 bytes = 102
Doing it the [@ovs way](https://codegolf.stackexchange.com/a/213735/58563).
### Ordinal mode, 51 bytes
```
a=>b=>1?b.replace(/./g,(c,i)=>a[i]+c):b-(a+=b)*~a/2
```
[Try it online!](https://tio.run/##BcExDsIwDADAt5DJpmkiGJGcrvyAATE4qVsFWXWVIka@Hu7e/OWjtLp/xs1m6Qt1ppQpXaYcmuzKRSCGuHooviIlftbXUPCWR@CBMp5/HK@92HaYSlBbYQF3F1XzDsE9rOl8coj9Dw "JavaScript (Node.js) – Try It Online")
### Cardinal mode, 51 bytes
```
a=>b=>0?b.replace(/./g,(c,i)=>a[i]+c):b-(a+=b)*~a/2
```
[Try it online!](https://tio.run/##BcFbCoAgEADA6@z2UAsiCNYOEn2sm4UhGRV9dnWb2fnlW65wPvWRFp9XykzWkTWjU5c/I4sHrfRWgVQByfIU5lJwcDVwSQ6Lj3WbJR13il7FtMEKjTEIfYeYfw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 13 \* 70 bytes = 910
### Ordinal mode, 35 bytes
```
e=>l=>l.replace(/./g,(l,i)=>e[i]+l)
```
[Try it online!](https://tio.run/##DcJBCoAgEAXQs@RqhsxOYOtu0CJaiI1ifJqw6PrW4x3hDXes5XqGU3dpyTfxE/6uyoUQhUY3Zkuwhf0ka9l6cIt63gpx0EyJzCyAWsNkFq3YO8PcPg "JavaScript (Node.js) – Try It Online")
### Cardinal mode, 35 bytes
```
e=>l=>l+(e,l-~e)/2*(((l,i)=>e,e)+l)
```
[Try it online!](https://tio.run/##DcJRCoAgDADQ62ypZUH0pXeRmmEMFxl9dvXV4x3pSW29ynm7KhtpDkoh8t8AWXYv4TB1AMC2YIhkCQ2jrlKbMPUsO2QYvUdYZkT9AA "JavaScript (Node.js) – Try It Online")
```
e=>l=>l.replace(/./g,(l,i)=>e[i]+l)
## # ## # #### ### // 13 differences
e=>l=>l+(e,l-~e)/2*(((l,i)=>e,e)+l)
e=>l=> // given e and l,
l+( // compute l +
e, // (meaningless filler)
l-~e)/2*(( // (l + e + 1) / 2 *
(l,i)=>e, // (meaningless filler)
e)+l) // (e + l)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), score ~~200~~ ~~44~~ 1 \* 42 bytes = 42
[crossed out 44 is still regular 44](https://codegolf.stackexchange.com/a/195414/17602)
First program:
```
¿¹⭆§θ⁰⭆θ§λκI⁺Σ…·⁰Σθ⊟θ
```
Second program:
```
¿⁰⭆§θ⁰⭆θ§λκI⁺Σ…·⁰Σθ⊟θ
```
Explanation: Port of @ovs's approach. An `if` statement at the start is used to select the desired code, thus the distance between the two programs is one byte. Since one program has string output and the other has numeric output it's not possible to share code between the two. See the original answer that scored 10 \* ~~20~~ 19 bytes = ~~200~~ 190 below for how each branch of the `if` works:
First program:
```
⭆§θ⁰⭆θ§λκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaDiWeOalpFZoFOooGGjqKCAkgAIwuRwdhWxNILD@/z86WskjNScnX0dJR0EpPL8oJ0VRKTb2v25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of two strings. Explanation:
```
θ Input array
§ ⁰ First element
⭆ Map over characters and join
θ Input array
⭆ Map over strings and join
λ Current string
§ Indexed by
κ Outer index
Implicitly print
```
Second program:
```
I⁺Σ…·⁰Σθ⊟θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyCntFgjuDRXwzMvGcjMLEsNSsxLT9Uw0FEAiRZqamrqKATkF4BZmtb//0dHG@koGMfG/tctywEA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as an array of two integers. Explanation:
```
⁰ Literal `0`
θ Input array
Σ Sum
…· Inclusive range
Σ Sum
⁺ Plus
⊟ Last element of
θ Input array
I Cast to string
Implicitly print
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 4dist(2 + 6 4) = 48 24 scored
*-24 points thanks to @ovs!*
I am sure that the programs can be heavily improved.
**Ordinal mode:**
```
.ι
```
Outputs the zipped string as a list of characters.
Also takes in input swapped, so `"Hello,", "World!" -> "WHoerllldo!,"` and `"World!", "Hello," -> "HWeolrllod,!".`
## How?
```
.ι # Interleave the two inputs, then output implicitly
```
[Try it online!](https://tio.run/##yy9OTMpM/f9f79zO//89UnNy8nW4wvOLclIUAQ)
**Cardinal mode:**
```
+LO+
```
Takes in input in the right order this time!
## How?
```
+ # Add m and n
LO # Summation of all numbers in range [1...m+n]
+ # Add m (which is still surviving in the stack) to the result and output implicitly
```
[Try it online again!](https://tio.run/##yy9OTMpM/f9f28df@/9/Uy4zAA)
[Answer]
# [R](https://www.r-project.org/), 1×(76+76) = 152
Ordinal mode:
```
function(a,`^`=Reduce,p=paste0)`if`(F,sum(1:sum(a),a[2]),p^p^strsplit(a,""))
```
[Try it online!](https://tio.run/##PYy7DgIhEEV7vwKngmQK19KEwsZYb2NhloAsJCS4EB7fj2BWp5jk3DNzU7OEk2brposLG1UoheSzWas2GHlUuZgTk85KesNc33S6jK0Yqud5YRhFFLmkHL0r/RmAsWappqAACbw6Hr54N94HHNkjJL8e/2LHLvaTn7h6p83IyZjR@wE "R – Try It Online")
Cardinal mode:
```
function(a,`^`=Reduce,p=paste0)`if`(T,sum(1:sum(a),a[2]),p^p^strsplit(a,""))
```
[Try it online!](https://tio.run/##NcvBCsMgEATQe79iyWkX9qApoVDwJ0pvpaJYBaFNl6jfbw2kl@ExzGw9gYGe2hpq/q7o2VlnbvHVQmQx4kuNilxODu9c2gf1dU9P7B/zk1is2FK3Iu9cx3maiHrCgDPDmei0c2FYDioGfVAzqD/V6C9j038 "R – Try It Online")
Input is as a length-2 vector.
The only difference between the two functions is the 37th character, which flips between `F` and `T`. Either the second or the third argument of `if` is therefore executed. For the ordinal mode (interleaving), I relied on [this tip](https://codegolf.stackexchange.com/a/171759/86301) by J.Doe.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 2x(6+6)=24
Ordinal mode:
```
Đ←+⇹ŕǰ
```
Requires strings to be passed in as arrays of characters
[Try it online!](https://tio.run/##K6gs@f//yIRHbRO0H7XvPDr1@Ib//6OVwpV0lPKBuAiIc4A4RSmWK1rJA8hKhYrkgFXEAgA "Pyt – Try It Online")
```
Đ implicit input; duplicate string
← get second input
+ element-wise string addition
⇹ŕ flip the stack and remove the top
ǰ join the list of strings into one string; implicit print
```
Cardinal mode:
```
Đ←+△+ǰ
```
[Try it online!](https://tio.run/##K6gs@f//yIRHbRO0H03brH18w///xlxGAA "Pyt – Try It Online")
```
Đ implicit input (m); duplicate top of stack
← get input (n)
+ add the top two items on the stack (yielding n+m)
△ get the (n+m)th triangle number
+ add the top two items on the stack (yielding 1/2*(n+m)*(n+m+1)+m)
ǰ join the stack as strings (essentially a no-op here)
```
] |
[Question]
[
Consider the following sequence:
```
1, 0, 1, 2, 4, 1, 6, 8, 0, 1, 2, 4, 6, 8, 1, 0, 2, 4, 6, 8, 1, 0, 2, 4, 6, 8, 0, 1, ...
```
The even digits start from **0** and are grouped into runs of increasing length. They are arranged cyclically, meaning that they are sorted in ascending order until **8** is reached, and then cycled back from **0**. **1** separates the runs of even digits, and it also starts the sequence. Let's visualize how this sequence is formed:
```
1, 0, 1, 2, 4, 1, 6, 8, 0, 1, 2, 4, 6, 8, 1, 0, 2, 4, 6, 8, 1, ...
- ---- ------- ---------- -------------
run length: 1 2 3 4 5 ...
position of 1: X X X X X X ...
even sequence: 0, 2, 4, 6, 8, 0, 2, 4, 6, 8, 0, 2, 4, 6, 8 ...
```
---
Acceptable Input and Output methods:
* Receive an integer **N** as input and output the **N**th term of this sequence.
* Receive an integer **N** as input and output the first **N** terms of this sequence.
* Print the sequence indefinitely.
You can choose either 0 or 1-indexing for the first two methods.
You can compete in any [programming language](https://codegolf.meta.stackexchange.com/questions/2028/what-are-programming-languages/2073#2073), while using the [standard input and output methods](http://meta.codegolf.stackexchange.com/a/2422/36398). [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in each language wins.
[Answer]
# [Haskell](https://www.haskell.org/), ~~50~~ 46 bytes
```
1#cycle[0,2..8]
n#r=1:take n r++(n+1)#drop n r
```
[Try it online!](https://tio.run/##y0gszk7NyflfbBvz31A5uTI5JzXaQMdIT88ilitPucjW0KokMTtVIU@hSFtbI0/bUFM5pSi/AMT/n5uYmadgq1BQlJlXoqCiAFZnaGCgUPz/X3JaTmJ68X/d5IICAA "Haskell – Try It Online")
`1#cycle[0,2..8]` returns the sequence as infinite list.
*-4 bytes thanks to Ørjan Johansen!*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
5ḶḤṁR€1pFḣ
```
Returns the first **n** items of the sequence.
[Try it online!](https://tio.run/##y0rNyan8/9/04Y5tD3csebizMehR0xrDAreHOxb/BwobAAA "Jelly – Try It Online")
### How it works
```
5ḶḤṁR€1pFḣ Main libk. Argument: n
5 Set the return value to 5.
Ḷ Unlength; yield [0, 1, 2, 3, 4].
Ḥ Unhalve; yield [0, 2, 4, 6, 8].
R€ Range each; yield [[1], [1, 2], [1, 2, 3], ..., [1, ..., n]].
ṁ Mold; in the result to the left, replace [1] with [0], [1, 2] with
[2, 4], [1, 2, 3] with [6, 8, 0], and so forth.
1p Take the Cartesian product of [1] and the result.
F Flatten the result.
ḣ Head; take the first n items of the result.
```
[Answer]
## [Husk](https://github.com/barbuz/Husk), ~~12~~ ~~11~~ 10 bytes
```
ṁ:1CN¢mDŀ5
```
[Try it online!](https://tio.run/##yygtzv7//@HORitDZ79Di3JdjjaY/v8PAA "Husk – Try It Online")
Prints the sequence indefinitely.
Alternatively:
```
J1CΘN¢mDŀ5
```
[Try it online!](https://tio.run/##yygtzv7/38vQ@dwMv0OLcl2ONpj@/w8A "Husk – Try It Online")
### Explanation
```
ŀ5 Start from [0, 1, 2, 3, 4]
mD Double each value to get [0, 2, 4, 6, 8]
¢ Repeat this list indefinitely, [0, 2, 4, 6, 8, 0, 2, ...]
CN Cut it into chunks of increasing lengths,
[[0], [2, 4], [6, 8, 0], ...]
ṁ:1 Prepend 1 to each sublist and concate the resulting lists.
```
For the alternative solution:
```
¢mDŀ5 Again, get [0, 2, 4, 6, 8, 0, 2, ...].
CΘN This time we prepend a zero to the natural numbers, which
prepends an empty list to the resulting chunks.
J1 Join all the sublists with 1.
```
We could also do `...ΘCN...`, because `Θ` does "prepend default element", which prepends a zero for lists of integers and an empty list for lists of lists.
[Answer]
# [Python 3](https://docs.python.org/3/), 52 bytes
```
def f(n):t=(8*n+1)**.5+1;return 0==t%1or(n-t//2)%5*2
```
Takes a 1-based index and returns *True* or an integral *float*.
[Try it online!](https://tio.run/##HcxBDoIwEAXQNZzibxpmCojFNDGYehcTQdkMZJguPH01Jm/99o@9N7mU8pwXLCQ8WaKrlzaw96fYhpvOllVwTslc2JSkt2EY2UU/lmVTCFaBPuQ1U@gQA091pUj/rK52XcWocWNGf4fLIHdwAweSDvrDXL4 "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 51 bytes
```
k=n=0
while 1:print 1;k+=1;exec'print n%10;n+=2;'*k
```
Prints the whole sequence.
[Try it online!](https://tio.run/##K6gsycjPM/r/P9s2z9aAqzwjMydVwdCqoCgzr0TB0Dpb29bQOrUiNVkdIpKnamhgnadta2StrpX9/z8A "Python 2 – Try It Online")
[Answer]
# APL, 25 bytes
Returns nth term.
```
1,(⌽n↑⌽(+/⍳n←⎕)⍴0,2×⍳4),1
```
Explanation
```
n←⎕ Prompts for screen input of integer
+/⍳ Creates a vector of integers of 1 to n and sums
⍴0,2×⍳4 Creates a vector by replicating 0 2 4 6 8 to the length of sum
⌽n↑⌽ Rotates the vector, selects first n elements and rotates result
(selects last n elements}
1,...,1 Concatenates 1s in front and behind result
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~52~~ ~~59~~ 56 bytes
```
r←c k
r←~n←0
:For j :In ⍳k
n+←j-1
r,←1,⍨j⍴n⌽0,2×⍳4
:End
r←k⍴r
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO96FHbhGSF7P8gui4PSBhwWbnlFylkKVh55ik86t2czZWnDRTO0jXkKtIBMgx1HvWuyHrUuyXvUc9eAx2jw9OBiky4rFzzUrhAhmQDpYpAJv9PVjA2BQA "APL (Dyalog Unicode) – Try It Online")
This is a tradfn (**trad**itional **f**unctio**n**) taking one argument `k` and returning the first `k` items of the sequence.
Thanks to @GalenIvanov for pointing out an error in the function.
Thanks to @Adám for 3 bytes.
### How it works:
```
r←c k ⍝ The function c takes the argument k and results in r
r n←1 0 ⍝ Initializing the variables r and n, and setting them to 1 and 0, respectively.
:For j :In ⍳k ⍝ For loop. ⍳k yields [1, 2, 3, ..., k], and j is the control variable.
n+←j-1 ⍝ Accumulates j-1 into n, so it follows the progression (0, 1, 3, 6, 10, 15...)
r,←1,⍨j⍴n⌽0,2×⍳4 ⍝ This line is explained below.
:End ⍝ Ends the loop
r←k⍴r ⍝ return the first k items of r.
⍝ ⍴ actually reshapes the vector r to the shape of k;
⍝ since k is a scalar, ⍴ reshapes r to a vector with k items.
2×⍳4 ⍝ APL is 1-indexed by default, so this yields the vector 2 4 6 8
0, ⍝ Prepend a 0 to it. We now have 0 2 4 6 8
n⌽ ⍝ Rotate the vector n times to the left.
j⍴ ⍝ Reshape it to have j items, which cycles the vector.
1,⍨ ⍝ Append a 1, then
r,← ⍝ Append everything to r.
```
Below are a `Dfn`(**d**irect **f**unctio**n**) and a tacit function that also solve the challenge, both kindly provided by @Adám.
* Dfn: `{⍵⍴1,∊1,⍨¨j⍴¨(+\¯1+j←⍳⍵)⌽¨⊂0,2×⍳4}` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBNWPerc@6t1iqPOoowtI9K44tCILyD@0QkM75tB6Q@2sR20THvVuBqrSfNSz99CKR11NBjpGh6cDxUxqjU0B "APL (Dyalog Unicode) – Try It Online")
* Tacit: `⊢⍴1,∘∊1,⍨¨⍳⍴¨(⊂0,2×⍳4)⌽⍨¨(+\¯1+⍳)` [Try it online!](https://tio.run/##SyzI0U2pTMzJT/8PBBqPuhY96t1iqPOoY8ajji4g3bvi0IpHvZuBgodWAGWbDHSMDk8HCphoPurZC5bV0I45tN5QGyimqWlsCgA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# JavaScript (ES6), ~~62~~ ~~54~~ 52 bytes
Returns the **N**th term of the sequence, 0-indexed.
```
n=>(g=e=>n--?g(e+=k++<l?2:k=!++l):k<l?e%10:1)(k=l=0)
```
### Demo
```
let f =
n=>(g=e=>n--?g(e+=k++<l?2:k=!++l):k<l?e%10:1)(k=l=0)
for(n = 0; n < 30; n++) {
console.log('a(' + n + ') = ' + f(n))
}
```
[Answer]
# C (gcc), 84 bytes
```
i;j;f(){for(i=1;;i++){printf("%d ",1);for(j=0;j<i;)printf("%d ",(2*j+++i*i-i)%10);}}
```
[Try it online!](https://tio.run/##Vc0xCsMwDIXhuTmFCAQkK4G4q5rDGBWnMjQtpnQxPrvrjN3ezzc8XXbV1kySRKQSXxlt8yLGTOWd7fhEHKc7jLMnOTVtq6SbCf0hXl1iZnO2GE1@Jam1dYdnsAPPEfKuM@gjZHCux5egDJf@KUNtPw "C (gcc) – Try It Online")
A function (`f()`) that prints the sequence infinitely, separated by spaces.
`i` is the length of the current even-run.
`j` is the index in the current even-run
`(2*j+++i*i-i)%10` gives the correct even number, given i and j (and increments j), equivalent to ((j+Tr(i))%5)\*2, where Tr(x) is the xth triangular number (which is the number of even numbers that have been printed before the current even run;
[Answer]
# Java 8, 96 bytes
```
v->{for(int i=0,j=-2,k;;i++,System.out.println(1))for(k=0;k++<i;System.out.println(j%=10))j+=2;}
```
Prints indefinitely, each number on a new line.
**Explanation:**
[Try it here.](https://tio.run/##bY7BCoMwEETv/Yq9FBKiol7T9A/qReil9JBGLYkxiomBIn67jdVjYZdllhnmKe553A@1UVW7Cs2thRuXZj4BSOPqseGihmKTAL6XFQh0347HNPyWsGGs404KKMAAg9XH17npRxTyIFkaKRbnUUupJCQqP9bVXdJPLhnGYNAGZRhv7paltCXkIukfjzqzLMVYEZbTZaV76zC9dGg9yn9wXUBHpQup9@MJHO/cJhHITFofyMv6BQ)
```
v->{ // Method with empty unused parameter and no return-type
for(int i=0, // Index integer, starting at 1
j=-2, // Even index integer, starting at -2
k; // Inner index integer
; // Loop (1) indefinitely
// After every iteration:
i++, // Increase index `i` by 1
System.out.println(1)) // And print a 1
for(k=0; // Reset index `k` to 0
k++<i; // Inner loop (2) from 0 to `i`
// After every iteration:
System.out.println(j%=10)) // Set `j` to `j` modulo-10, and print it
j+=2; // Increase `j` by 2
// End of inner loop (2) (implicit / single-line body)
// End of loop (1) (implicit / single-line body)
} // End of method
```
[Answer]
## Batch, 85 bytes
```
@set/an=%2+1,t=n*-~n/2
@if %t% lss %1 %0 %1 %n%
@cmd/cset/a(%1-n)%%5*2*!!(t-=%1)+!t
```
Outputs the Nth term of the sequence. Works by calculating the next triangular number.
[Answer]
# [Perl 5](https://www.perl.org/), 44 bytes
```
do{say 1;map{say(($r+=2)%10)}0..$i++}while 1
```
[Try it online!](https://tio.run/##K0gtyjH9/z8lv7o4sVLB0Do3sQDE0tBQKdK2NdJUNTTQrDXQ01PJ1NauLc/IzElVMPz//19@QUlmfl7xf11fUz0DQwMA "Perl 5 – Try It Online")
Infinite output
[Answer]
# [J](http://jsoftware.com/), 46 42 40 bytes
-6 bytes thanks to cole
```
{.({.[:;[:#:&.>2^i.);@(1,&.><;.1)10|2*i.
```
Outputs the first N terms of this sequence.
How it works:
`10|[:+:i.` - generates a list of length N of 0 2 4 6 8 0 2 4... It simply takes mod 10 of the doubled items of a list of integers starting at 0.
`[:;[:#:&.>2^i.` - generates a bit mask for cutting the above list.
(1 means start): 1 1 0 1 0 0 1 0 0 0 1 0 0 0 0 1 0 0 0 0 ... It finds 2 to the power of the consecutive non-negative integers, converts them into binary, flattens the list and takes only the first N items, so that the length of the both lists is the same.
`;@(1,&.><;.1)` - splits (cuts) the list of the even digits into sublistsaccording to the map of ones and zeroes, appends the sublist to 1 and finally flattens the resulting list
`]{.` - takes only the first N items, getting rid of the additional numbers in the list due to the added 1s.
[Try it online!](https://tio.run/##y/qfVqxgq6dgoGClYPC/Wk@jWi/ayjraStlKTc/OKC5TT9PaQcNQB8ixsdYz1DQ0qDHSytT7r8mlpKegnmZrpa6go1BrpZBWzJWanJGvkKZgZvD/PwA "J – Try It Online")
[Answer]
# Common Lisp, 74 bytes
```
(do((b 1(1+ b))(k -2))(())(print 1)(dotimes(m b)(print(mod(incf k 2)10))))
```
[Try it online!](https://tio.run/##JYpbCoAwDASvks8NIpgeqa1C6BPb@8eAA8vAMqnqmmbIA4gkkIMiMwqdwQXffLVvEvZka7sXmhf/izYytKeHCgWWix2zDw)
Prints the sequence indefinitely.
[Answer]
# Perl 5, 35 bytes
```
{say$i--?$r++%5*2:($i=++$j)>0;redo}
```
[try it online](https://tio.run/##K0gtyjH9/7@6OLFSJVNX116lSFtb1VTLyEpDJdNWW1slS9POwLooNSW/9v//f/kFJZn5ecX/dX1N9QwMDQA)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
9Ḷm2ẋ⁸ṁJR$$j1 1;ḣ
```
[Try it online!](https://tio.run/##ASgA1/9qZWxsef//OeG4tm0y4bqL4oG44bmBSlIkJGoxIDE74bij////MTAw "Jelly – Try It Online")
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 55 bytes
```
i=0 j=-2while1{for k:0..i print(j=(j+2)%10)print(1)i++}
```
[Try it online!](https://tio.run/##KyjKL8nP@/8/09ZAIctW16g8IzMn1bA6Lb9IIdvKQE8vU6GgKDOvRCPLViNL20hT1dBAEyJgqJmprV37/z8A "Proton – Try It Online")
Prints the sequence indefinitely
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 107 bytes
```
i->{String b="";for(int l=i,r=0,z=0;i>0;b+=l-i--==r?(l=i)<1+r++*0?"1":"1":"02468".charAt(z++%5));return b;}
```
[Try it online!](https://tio.run/##VY9Ba4NAEIXv@RWDUNCsLhraUrpZQw8t9FB6yLH0sK4mHau7so4BE/ztdkm8dGAu781jvlerk0psV5m6/J2x7awjqL3GB8KGHwajCa3ha7HqhqJBDbpRfQ8fCg1cVj0p8trbcrZ9N1QdKxfDnhyaYw561D70eqrMZ1mChBmT/HIzoZBBIA7WhWgIGomxk2l8lqnAPBUFk02CSSKl24XejLYZc4yt012QBc/XTTf3j08B1z/KvVB4ZuzuIYqEq2hwBgoxzWJBXihPFktoPXh4A/j6BhX5ErDMfuyparkdiHfep/AfPFdd14xhtvE/rpFpmv8A "Java (OpenJDK 8) – Try It Online")
[Answer]
# Mathematica, 68 bytes
Returns the Nth term
```
Insert[Join@@Table[{0,2,4,6,8},#^2],1,Array[{(2-#+#^2)/2}&,#]][[#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfM684tagk2is/M8/BISQxKSc1utpAx0jHRMdMx6JWRznOKFbHUMexqCixMrpaw0hXWRsopKlvVKumoxwbGx0NJNT@BxRl5pU4pEUbGhgYxP4HAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 61 bytes
```
Flatten[TakeList[2Mod[r=0~Range~#,5],UpTo/@r]~Riffle~1][[#]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/DfLSexpCQ1LzokMTvVJ7O4JNrINz8lusjWoC4oMS89tU5ZxzRWJ7QgJF/foSi2LigzLS0ntc4wNjpaOTZWDWhEnYJjUVFiJZA2NDBQ0NdXCCjKzCv5DwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# JavaScript, 45 bytes
1 indexed:
```
f=(x,t=0,p=0)=>p<x?f(x-1,t+1,p+t):x-p?x%5*2:1
```
0 indexed:
```
g=(x,p=0)=>p<x?g(x-1,p?++t+p:t=1):x-p?x%5*2:1
```
```
f=(x,t=0,p=0)=>p<x?f(x-1,t+1,p+t):x-p?x%5*2:1
g=(x,p=0)=>p<x?g(x-1,p?++t+p:t=1):x-p?x%5*2:1
a.value=[...Array(100)].map((_,i)=>f(i+1))
b.value=[...Array(100)].map((_,i)=>g(i))
```
```
<output id=a></output>
<output id=b></output>
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~48~~ 46 bytes
```
a=b=c=0;loop{a>b&&(p 2*b%10;b+=1)||a+=c+=p(1)}
```
[Try it online!](https://tio.run/##KypNqvz/P9E2yTbZ1sA6Jz@/oDrRLklNTaNAwUgrSdXQwDpJ29ZQs6YmUds2Wdu2QMNQs/b/fwA "Ruby – Try It Online")
Print the sequence indefinitely
[Answer]
# bash, 42 bytes
```
for((;;)){ echo $[i--?r++%5*2:(i=++j)>0];}
```
or 34 if valid
```
echo $[i--?r++%5*2:(i=++j)>0];. $0
```
[try it online](https://tio.run/##S0oszvj/Py2/SEPD2lpTs1ohNTkjX0ElOlNX175IW1vVVMvISiPTVls7S9POINa69v9/AA)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 15 bytes
```
W P1L UiP2*Uv%t
```
Prints indefinitely. [Try it here!](https://replit.com/@dloscutoff/pip) Or, here's a 16-byte equivalent in Pip Classic: [Try it online!](https://tio.run/##K8gs@P8/XCHA0EdbOzPASEtbu0y15P///7o5AA "Pip – Try It Online")
### Explanation
```
W While this expression is truthy--
P1 print 1 (evaluates to 1, which is truthy)
--loop:
Ui Increment i (initially 0)
L and loop that many times:
Uv Increment v (initially -1)
2* Multiply by 2
%t Mod 10
P Print
```
] |
[Question]
[
Let's say you have a positive integer *N*. First, build a **regular** polygon, that has *N* vertices, with the distance between neighbouring vertices being 1. Then connect lines from every vertex, to every other vertex. Lastly, calculate the length of all lines summed up together.
# Example
Given the input ***N = 6***, build a **hexagon** with lines connecting every vertex with the other vertices.
[](https://i.stack.imgur.com/ZXclz.png)
As you can see, there are a total of 6 border lines (length=1), 3 lines that have double the border length (length=2) and 6 other lines that we, by using the Pythagoras Theorem, can calculate the length for, which is
If we add the lengths of the lines together we get *(6 \* 1) + (3 \* 2) + (6 \* 1.732) = **22.392***.
## Additional Information
As structures with 2 or less vertices are not being considered polygons, output 0 (or `NaN`, since distance between a single vertex doesn't make much sense) for N = 1, since a single vertice cannot be connected to other vertices, and 1 for N = 2, since two vertices are connected by a single line.
## Input
An integer N, in any reasonable format.
## Output
The length of all the lines summed up together, accurate to at least 3 decimal places, either as a function return or directly printed to `stdout`.
## Rules
* Standard loopholes are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes, in any language, wins.
## Good luck!
# Test Cases
```
(Input) -> (Output)
1 -> 0 or NaN
2 -> 1
3 -> 3
5 -> 13.091
6 -> 22.392
```
[Answer]
# [Python 3](https://docs.python.org/3/) ~~(with [sympy](http://www.sympy.org/en/index.html))~~, ~~61 60 58 54~~ 48 bytes
-6 (maybe even -10 if we do not need to handle `n=1`) thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor) (further trigonometric simplification plus further golfing to handle edge case of 1 and save parentheses by moving a (now unnecessary) `float` cast).
~~Hopefully~~ beatable with no ~~3rd party~~ libraries? [Yes!!](https://codegolf.stackexchange.com/a/146144/53748) ~~but~~ Lets get things rolling...
```
lambda n:1%n*n/2/(1-cos(pi/n))
from math import*
```
**[Try it online!](https://tio.run/##DctBDoIwEAXQtZxiNoQpKanVHYmehE0FKk3sn2bshtNX3/6Vsx6Ce4uPpX1Cfm2BMPseI9zNsZ9W@XJJDsZ0USVTDvWglItoHVsUJVACacB7Z2/JX83cXYomVIalYXoOliL/e/sB "Python 3 – Try It Online")**
This uses a formula for the sum of the lengths if a polygon is inscribed inside a unit circle, `n*cot(pi/2/n)/2` and adjusts the result to one for the side length being one by dividing by the sin of that cord length `sin(pi/n)`.
The first formula is acquired by considering the `n-1` cord lengths of all the diagonals emanating from one corner which are of lengths `sin(pi/n)` (again), `sin(2*pi/n)`, ..., `sin((n-1)pi/n)`. The sum of this is `cot(pi/2/n)`, there are `n` corners so we multiply by `n`, but then we've double counted all the cords, so we divide by two.
The resulting `n*cot(pi/2/n)/2/sin(pi/n)` was then simplified by xnor to `n/2/(1-cos(pi/n))` (holding for `n>1`)
...this (so long as the accuracy is acceptable) now no longer requires `sympy` over the built-in `math` module (`math.pi=3.141592653589793`).
[Answer]
# [Python](https://docs.python.org/3/), 34 bytes
```
lambda n:1%n*n/abs(1-1j**(2/n))**2
```
[Try it online!](https://tio.run/##DcpNDkAwEAbQq8xGMp1Uatg1cRObCvUTPlLdOH1563e/eb3QldgP5QjnOAWC1woCF8aHtdZdhFsHY0TaEq9EoA2UApaZ1ZI2avydNmSGjfy/8gE "Python 3 – Try It Online")
Uses the formula `n/2/(1-cos(pi/n))` simplified [from Jonathan Allan](https://codegolf.stackexchange.com/a/146126/20260). Neil saved 10 bytes by noting that Python can compute roots of unity as fractional powers of `1j`.
Python without imports doesn't have built-in trigonometric functions, `pi`, or `e`. To make `n=1` give `0` rather than `0.25`, we prepend `1%n*`.
A longer version using only natural-number powers:
```
lambda n:1%n*n/abs(1-(1+1e-8j/n)**314159265)**2
```
[Try it online!](https://tio.run/##DcbBDkNAFAXQX3mbJm@mRC8lKvEnNiOMEi6Z2vj6qbM6x3V@dxbRt11c3dYPTtjgQcvM9T9FqnhiTOslo7G2wBvlJ6/K@3n0exDKTAmO06hIBC@Y5ggzT2XilcbEPw "Python 3 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~16~~ 15 bytes
```
t:=ZF&-|Rst2)/s
```
[Try it online!](https://tio.run/##y00syfn/v8TKNspNTbcmqLjESFO/@P9/MwA "MATL – Try It Online") Or [verify all test cases](https://tio.run/##y00syfmf8L/EyjbKTU23Jqi4xEhTv/i/S8h/Qy4jLmMuUy4zAA).
This uses a [commit](https://github.com/lmendo/MATL/commit/dbb4bdca5239b74e6c9cfe9ad650d8ae056d3cdf) which introduced the FFT (Fast Fourier Transform) function, and which predates the challenge by 8 days.
### Explanation
The code uses [this trick](https://codegolf.stackexchange.com/a/145404/36398) (adapted to MATL) to generate the roots of unity. These give the positions of the vertices as complex numbers, except that the distance between consecutive vertices is not normalized to 1. To solve that, after computing all pairwise distances, the program divides them by the distance between consecutive vertices.
```
t % Implicit input, n. Duplicate
: % Range: [1 2 ... n-1 n]
= % Isequal, element-wise. Gives [0 0 ... 0 1]
ZF % FFT. Gives the n complex n-th roots of unity
&-| % Matrix of pairwise absolute differences
R % Upper triangular matrix. This avoids counting each line twice.
s % Sum of each column. The second entry gives the distance between
% consecutive vertices
t2)/ % Divide all entries by the second entry
s % Sum. Implicit display
```
[Answer]
# Grasshopper, 25 primitives (11 components, 14 wires)
I read a meta post about programs in GH and LabVIEW, and follow similar instructions to measure a visual language.
[](https://i.stack.imgur.com/RWJek.png)
Print `<null>` for N = `0, 1, 2`,because `Polygon Primitive` cannot generate a polygon with 2 or fewer edges and you will get an empty list of lines.
Components from left to right:
* `Side count` slider: input
* Polygon Primitive: draw a polygon on canvas
* Explode: Explode a polyline into segements and vertices
* Cross reference: build holistic cross reference between all vertices
* Line: draw a line between all pairs
* Delete Duplicate Lines
* Length of curve
* (upper) Sum
* (lower) Division: because `Polygon Primitive` draws polygon based on radius, we need to scale the shape
* Multipication
* Panel: output
[](https://i.stack.imgur.com/o8eLi.jpg)
[Answer]
# Mathematica, 26 bytes
uses @Jonathan Allan's formula
```
N@Cot[Pi/2/#]/2Csc[Pi/#]#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zgq/Dfz8E5vyQ6IFPfSF85Vt/IuTgZxFGOVVb7H1CUmVei4JAWbRb7HwA "Wolfram Language (Mathematica) – Try It Online")
-1 byte junghwan min
[Answer]
# [Haskell](https://www.haskell.org/), 27 bytes
```
f 1=0
f n=n/2/(1-cos(pi/n))
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P03B0NaAK00hzzZP30hfw1A3Ob9YoyBTP09T839uYmaegq1CbmKBr4JGQVFmXomCnkKapkK0oZ6eoUHsfwA "Haskell – Try It Online")
I just dove into Haskell, so this turns out to be a fair beginner golf (that is, copying the formula from other answers).
I've also tried hard to put `$` somewhere but the compiler keeps yelling at me, so this is the best I've got. :P
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~13~~ ~~12~~ 11 bytes
Uses Jonathan Allan's formula (and thanks to him for saving 2 bytes)
```
ØP÷ÆẠCḤɓ’ȧ÷
```
[Try it online!](https://tio.run/##ASIA3f9qZWxsef//w5hQw7fDhuG6oEPhuKTJk@KAmcinw7f///82 "Jelly – Try It Online")
I've always been pretty fascinated with Jelly, but haven't used it much, so this might not be the simplest form.
[Answer]
# Javascript (ES6), 36 bytes
```
n=>1%n*n/2/(1-Math.cos(Math.PI/n))
```
Port of @JonathanAllan's Python 3 answer
```
f=n=>1%n*n/2/(1-Math.cos(Math.PI/n))
```
```
<input id=i type=number oninput="o.innerText=f(i.value)" /><pre id=o>
```
] |
[Question]
[
*Inspired by [this](https://chat.stackexchange.com/transcript/message/39979766#39979766) CMC*
Given a positive integer greater than 0, perform the following operation on it:
* If all ten single digits (`1234567890`) are in the number at least once, output the count and exit the program
* Otherwise, double the number and repeat, incrementing the count.
The count starts at 0 and is the number of times the input was doubled. For example, if the input were 617283945, it would need to be doubled once because 1234567890 has all 10 digits in it.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code wins. Input may be taken as a string, if you want.
## Test cases
```
input => output
617283945 => 1
2 => 67
66833 => 44
1234567890 => 0
100 => 51
42 => 55
```
[Answer]
# [Python 3](https://docs.python.org/3/), 39 bytes
```
f=lambda n:len({*str(n)})<10and-~f(n*2)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRIc8qJzVPo1qruKRII0@zVtPG0CAxL0W3Lk0jT8tI839BUWZeiUaahpmhuZGFsaWJqaYmF0zMCIltZmZhbIzENzQyNjE1M7ewNEAWNEDmmQD1/wcA "Python 3 – Try It Online")
Outputs `False` for `0`.
[Answer]
# [J](http://jsoftware.com/), ~~24~~ 23 bytes
```
(]1&(+$:)2**)10>#@~.@":
```
[Try it online!](https://tio.run/##BcFBCoAgEAXQfaf4WIRaxMxoZkLhRVpFEW3aturq9t5dyoklQW/c6q5JRqw1TGudvyGrVFXHfj3Q/WkU4U0IPEl0sx8hCCE6BxbnxzDFmcBE8FLKDw)
## Explanation
```
(]1&(+$:)2**)10>#@~.@": Input: integer n
": Format as string
~.@ Unique
#@ Length
10> Less than 10
* Multiply, gives n if previous was true, else 0
2* Multiply by 2
] Get the previous condition
1&( ) Execute this if true on 2n, else return 0
$: Recurse
1 + Add 1
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~11~~ 10 bytes
-1 byte thanks to [scottinet](https://codegolf.stackexchange.com/users/73296/scottinet)
```
[D9ÝåË#·]N
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2sXy8NzDSw93Kx/aHuv3/7@ZmYWxMQA "05AB1E – Try It Online") or as a [Test Suite](https://tio.run/##MzBNTDJM/V9TVvk/2sXy8NzDSw93Kx/aHuv3v1Lp8H4rBSV7nf@GRsYmpmbmFpYGXGaG5kYWxpYmplxmZhbGxgpcRlyGBgZcJkYA "05AB1E – Try It Online")
```
[ // Start infinity loop
D // Duplicate current value (or input)
9Ý // Push [0,1,2,3,4,5,6,7,8,9]
å // Does each exist in the current value
Ë# // Break if all equal (if every digit exists)
· // Else double the current value
]N // End loop and print the number of times through the loop
```
[Answer]
# [Perl 6](https://perl6.org), ~~31~~ 28 bytes (27 chars)
*-3 bytes thanks to @Joshua*
```
{($_,2×*...*.comb.Set>9)-1}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKvwv1pDJV7H6PB0LT09PS295PzcJL3g1BI7S01dw9r/1lzFiSCFGkaa1v8B "Perl 6 – Try It Online")
**Explanation:** Still the same construct to recursively generate lists. The first element is the given number (`$_`), each next element is 2 times the previous (`2×*` — we use ×, because, although 2 byte character, it's still 1 byte cheaper than `2 * *`), and we do this until the end condition of `*.comb.unique>9` is satisfied, i. e. when there is more than 9 unique characters in the number. (Technically, we break the string down to a list of characters with `.comb`, force it to a set with `.Set` (of course, Sets contain each element only once), and compare with 9, which forces the set into numerical context, which in turn gives its number of elements.)
Finally, we subtract 1 from this list. Again, the list is forced into numerical context, so what we return is 1 less than the length of that list.
[Answer]
# JavaScript (ES6) + [big.js](https://github.com/MikeMcl/big.js/), ~~84~~ ~~74~~ ~~73~~ 70 bytes
*Thanks [@ConorO'Brien](https://codegolf.stackexchange.com/users/31957/conor-obrien) for saving 10 bytes by suggesting [big.js](https://github.com/MikeMcl/big.js/) instead of bignumber.js*
*Thanks to [@Rick Hitchcock](https://codegolf.stackexchange.com/users/42260/rick-hitchcock) for -1 byte*
*Thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy) for -3 bytes*
```
f=n=>[..."4"+2**29].every(d=>RegExp(d).test(c=Big(n)))?0:1+f(c.mul(2))
```
Takes input as string; supports up to around 269 due to automatic scientific notation conversion occurring beyond that point.
## Test Snippet
```
f=n=>[..."4"+2**29].every(d=>RegExp(d).test(c=Big(n)))?0:1+f(c.mul(2))
;[617283945, 2, 66833, 1234567890, 100, 42].forEach(t=>console.log(`f(${t}) = `+f(t)))
```
```
<script src="https://cdn.rawgit.com/MikeMcl/big.js/c6fadd08/big.min.js"></script>
```
## Infinite range, ~~106~~ ~~88~~ ~~87~~ 84 bytes
By using the config option to effectively disable scientific notation when converting numbers to strings, we can have nearly infinite range.
```
f=n=>[..."4"+2**29].every(d=>RegExp(d).test(c=Big(n)),Big.E_POS=1e9)?0:1+f(c.mul(2))
let num = `${Math.random()*1e6|0}`.repeat(100)
O.innerText=`f(\n${num}\n) = ${f(num)}`
```
```
<script src="https://cdn.rawgit.com/MikeMcl/big.js/c6fadd08/big.min.js"></script>
<pre id=O style="width:100%;white-space:normal;overflow-wrap:break-word"></pre>
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~12~~, 11 bytes
```
QLn⁵
ḤÇпL’
```
[Try it online!](https://tio.run/##ASAA3/9qZWxsef//UUxu4oG1CuG4pMOHw5DCv0zigJn///80Mg "Jelly – Try It Online")
>
> *Gotta go fast!*
>
>
>
Explanation:
```
# Helper link, takes one argument 'z'
Q # The unique digits of 'z'
L # Length
n # Does not equal
⁵ # 10
#
# Main link
п # While <condition> is true, run <body> and return all intermediate results
# Condition:
Ç # The helper link
# Body:
Ḥ # Double the input
# Now we have a list of all the 'z's that we passed to the helper link
L # Return it's length
’ # minus one
```
[Answer]
# [Haskell](https://www.haskell.org/), 46 bytes
```
f n|all(`elem`show n)['0'..'9']=0|1<3=1+f(2*n)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hryYxJ0cjITUnNTehOCO/XCFPM1rdQF1PT91SPdbWoMbQxtjWUDtNw0grT/N/bmJmnoKtQkFRZl6JgopCmoKJ0X8A "Haskell – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 43 bytes
```
f=:(,$:@+:@{.)`[@.(9<[:#@~.10&#.inv)
<:@#@f
```
[Try it online!](https://tio.run/##y/qvnqiQpK5ga6VgY60Xb6jg46ajUGulYKAAxP/TbK00dFSsHLStHKr1NBOiHfQ0LG2irZQd6vQMDdSU9TLzyjS5bKwclB3S/mtyKeklArF6uq2Vuk4SV2pyRr5CuoKJ0X8A "J – Try It Online")
Defines an anonymous function. Collects results quite suboptimally. Check out [miles's superior answer here!](https://codegolf.stackexchange.com/a/142781/31957)
[Answer]
## Haskell, 44 bytes
```
until(\c->all(`elem`show(n*2^c))['0'..'9'])(+1)0
```
[Answer]
# Clojure, ~~115~~ ~~89~~ 82 bytes
-26 bytes by just using a string to represent the list of characters (duh, in retrospect), and changing from using recursion to `loop`, which allowed me to make a couple of optimizations.
-7 bytes by getting rid of the call to `bigint`. Apparently we only need to handle input that won't cause an overflow.
```
#(loop[n % c 0](if(empty?(remove(set(str n))"1234567890"))c(recur(* 2 n)(inc c))))
```
Pregolfed:
```
(defn pan [num]
(loop [n num
cnt 0]
; Remove all the characters from the stringified input
; that are numeric. If the result is an empty list, all
; the numbers were present.
(if (empty? (remove (set (str n)) "1234567890"))
cnt
(recur (* 2 n) (inc cnt)))))
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 85 bytes
```
^\d*
$&¶$&
D`.(?=.*¶)
\d{10}¶\d+|\d*¶
[5-9]
#$&
T`d`EE
T`_d#`d_`\d#
#
1
}`\d\b
$&@
@
```
[Try it online!](https://tio.run/##DYy7DcIwGAb7bw2HKAQR@RXHLhApiFiADkMM@iloKBAdZC0P4MWMq7vidO/H5/m65VXTHEO@empR1SlWNQ6ha/a7rk1xDU9fwZcUPW1@JUkROPdbdwEr4SlQmKaCmVigOXhiYBBYivl72Y0YczZikFY53UPCGKsUhFS6N4N1HIJzaPkH "Retina – Try It Online") Link includes test cases. Slightly optimised for run time. Explanation:
```
^\d*
$&¶$&
```
Duplicate the input number.
```
D`.(?=.*¶)
```
Deduplicate the digits in the first copy.
```
\d{10}¶\d+|\d*¶
```
If 10 digits remain, delete both numbers, otherwise just delete the first copy. Note that deleting both numbers causes the rest of the loop to no-op.
```
[5-9]
#$&
```
Place a `#` before large digits.
```
T`d`EE
```
Double each digit.
```
T`_d#`d_`\d#
```
Add in the carries.
```
#
1
```
Deal with a leading carry.
```
}`\d\b
$&@
```
Append an `@` and loop until all 10 digits are found.
```
@
```
Print the number of `@`s added.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 19 + 2 = 21 bytes
```
0∘{∧/⎕D∊⍕⍵:⍺⋄⍺+1∇2×⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HfVLegR20TDI0szLmAnIAAIMfYhCsNSFU/6liuDxRzedTR9ah36qPerVaPenc96m4BktqGjzrajQ5PBwrW/v9voJCmYGZobmRhbGliygXiGYFJMzMLY2Mwy9DI2MTUzNzC0gDCNYDQJkYA "APL (Dyalog Unicode) – Try It Online")
This is a dyadic `Dfn` (**d**irect **f**unctio**n**), taking 0 as its left argument and the integer as the right. Since the input is supposed to be only the integer, I added 2 bytes for the argument `0∘` to the byte count.
`f←` is not included in the byte count, since it's not *necessary*. It just makes it easier to build the test cases.
### How it works:
**The headers:**
I removed those from the byte count after some chatting in the APL room, since the function does what it's supposed to do and the results are only incorrect because of the default settings of APL's REPL.
`⎕FR←1287` Sets the **F**loat **R**epresentation to 128-bit decimal (7 is the code for decimal in APL's REPL).
`⎕PP←34` Sets the **P**rint **P**recision to 34 digits.
Both of these are needed, since APL's default representation for big numbers transforms them to scientific notation (e.g. 3.14159265359E15) which messes up the code big time.
```
0∘{∧/⎕D∊⍕⍵:⍺⋄⍺+1∇2×⍵} ⍝ Dyadic Dfn
0∘ ⍝ Fixes 0 as the left argument
: ⍝ If
⎕D ⍝ String representation of all digits [0, 9]
∊ ⍝ "is in"
⍕⍵ ⍝ String representation of the input
∧/ ⍝ AND-reduction. Yields 1 (true) iff all digits are in the right argument.
⍺ ⍝ return the left argument
⋄ ⍝ Else
2×⍵ ⍝ Double the right arg
⍺+1 ⍝ increment the left arg
∇ ⍝ Recursively call this function with the new arguments.
```
[Answer]
# Java 8, ~~132~~ ~~110~~ ~~87~~ 74 bytes
```
n->{int c=0;for(;(n+"").chars().distinct().count()!=10;n*=2)c++;return c;}
```
-57 bytes thanks to *@OlivierGrégoire*.
**Explanation:**
[Try it here.](https://tio.run/##hY5NbsMgEEb3OcU0K6gV4r84jpB7g2aTZdUFxSQltQcLcKoq8tld7LbLyhJo@EZvhncVN7ExncJr/THKRjgHz0LjfQWg0St7FlLBcYpzAyRpDF4AKQ@tIdxwjoBQwYibp/uMVDE/G0s4wWi9pky@C@sIZbV2XqP04SlNj6E@VEnM8bFKqYwibpXvLYLkwzgt7/q3RktwXvhQbkbX0AYzcvJW4@XlFQT90Zp8oQ0GqD7nQGY5gNOX86plpvesCzO@QdIyZJIkaZbvin15iOkSWiT7tMwO@W6ZLMosW6SSePnPPP1Dttt/oV9mWA3jNw) (Note: test case for `2` is disabled because it should stop at 268, but the size of `long` is limited to 263-1.)
```
n-> // Method with long parameter and integer return-type
int c=0; // Count-integer, starting at 0
for(;(n+"").chars().distinct().count()!=10;
// Loop (1) as long as the unique amount of digits in the number are not 10
n*=2) // After every iteration: multiply the input by 2
c++; // Increase the count by 1
// End of loop (1) (implicit / single-line body)
return c; // Return the counter
} // End of method
```
---
Old **132 bytes** answer using a `String` input and regex:
```
n->f(n,0)int f(String n,int c){String t="";for(int i=0;i<10;t+="(?=.*"+i+++")");return n.matches(t+".*")?c:f(new Long(n)*2+"",c+1);}
```
[Try it here.](https://tio.run/##jZDLbsIwFET3@Yorr2wMefJsmvIDLRuWVRfGOGBK7Ci5oUIo3546lLKrimTLmtHx@I4P4iRGtlTmsP3s5FHUNbwJbS4egDaoqlxIBateXg2QdI2VNjswLHVm67ZbKzCQQWdGLzk1w5B5qcODAFYWoRQVgs0B9wo2Z1QjaRuDXh@W38OG12x2uWnMCElzW9He1lmY6ucoTJFnhC4zf0C45pwTRlhaKWwqA8YvBMq9qily4gC2lE9uFPUFr9bsqGGDmBMylDxiadsBlM3mqCXUKNAdJ6u3ULjat3neP0Cwn879Z0DhyvVZvaDX3gDrc42q8G2Dfunu4NHQwje@pCSKk/FkOpsvQsL@hafRLJ4ni/HkEXY6T5IHuCh85OVxfIeC4G/sl2q9tvsG) (Note: test case for `2` is disabled because it causes a StackOverflowException due to slightly too much recursion.)
The total regex to check if the String contains all 9 digits becomes `^(?=.*0)(?=.*1)(?=.*2)(?=.*3)(?=.*4)(?=.*5)(?=.*6)(?=.*7)(?=.*8)(?=.*9).*$`, which uses a positive look-ahead for the entire String.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
←Vö>9Lud¡D
```
[Try it online!](https://tio.run/##AUUAuv9odXNr/yBtyK9z4oKBcsK2/@KGkFbDtj45THVkwqFE////NjE3MjgzOTQ1CjIKNjY4MzMKMTIzNDU2Nzg5MAoxMDAKNDI "Husk – Try It Online")
### Explanation
```
¡D Repeatedly double the input, collecting results in a list
V Return the first index where the following is true
L The length of
d the digits
u with duplicates removed
ö>9 is greater than 9
← Decrement (as Husk uses 1-indexing)
```
[Answer]
# Mathematica, ~~59~~ ~~48~~ ~~47~~ ~~46~~ 38 bytes
*-9 bytes thanks to Jenny\_mathy.*
```
If[!FreeQ[DigitCount@#,0],#0[2#]+1,0]&
```
[Try it online using Mathics!](https://tio.run/##JYw9C8JAEET7/IqVgE22uI/kcgEDghIQLLRerhC5JFeYQLJW4m8/T51ieDyYedx4DPc19m089bTpFu@vdAxD4MP8nHifo3CYC1K5K2TibWS/8gotvIysldVNWSEoBGOs1ghS6bIytW1EYpGqVO8s6@aFQtpIhAC7Fs5@Gnik35VLrigQLkuYmPq/JArum/gB "Mathics – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 74 bytes
```
function(x){while(!all(0:9%in%el(strsplit(c(x,""),"")))){F=F+1;x=2*x};F*1}
```
[Try it online!](https://tio.run/##HYxNCoMwGET3PUUrCF9sF@bHaCrZeg9rDQbSWJKUpohnT9WB4c3bjEtGP1zvfvAawzQ/PTqps0zqY4egZwsRLd9JmxEuvTFQ3kWubT4a8MH5t9EBBoi3LEN7tyyd7K64jZIUcW27Aq9JAcc1aahg1fYNnDeU7gMTyipeN6I8rDzACEp/ "R – Try It Online") Note that R will give the wrong answer to `f(2)` due to limitations of how the language stores large integers.
Explanation: For the test of pandigitality, the input is coerced to a character vector by joining with an empty string and then split into individual digits. We then check whether all of 0:9 are present in the resulting vector; if not, we increment the counter, double the input and repeat.
The counter uses F which initialises as FALSE. To make sure it is coerced to numeric, we multiply by one before returning.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~70~~ 69 bytes
```
for($n=[bigint]$args[0];([char[]]"$n"|group).count-le9;$n*=2){$i++}$i
```
[Try it online!](https://tio.run/##BcFBCoAgEADAv8QeMikiuoT4EvFgYSbIGmvSoXr7NnPm21M5fErMe6YWUJs1hoiXBUehmNGq1myHI2NtA9i8gXI9xbDlilef/KIAOz2JB6KUH0Rmnqcf "PowerShell – Try It Online")
*(Nearly twice as long as the Python answer :-\ )*
Takes input `$args[0]`, casts it as a `[bigint]`, saves it to `$n`. Enters a `for` loop. Each iteration we check against whether the `$n`umber converted to a string then to a `char`-array, when `Group-Object`'d together, has a `.count` `-l`ess than or `e`qual to `9`. Meaning, the only way that it equals 10 is if at least one digit of every number `1234567890` is present. If yes, we exit the loop. If not, we `$n*=2` and continue. Each iteration inside the loop, we're simply incrementing `$i`. When we exit the loop, we simply output `$i`.
Note that for input like `1234567890` where every digit is already accounted for, this will output nothing, which is a falsey value in PowerShell, and equivalent to `0` when cast as an `[int]`. If that's not OK, we can simply put a `+` in front of the output `$i` to explicitly cast it as an integer.
*Saved a byte thanks to Roland Heath.*
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 11 bytes
```
f>l{`.<QT9Z
```
[Test suite](https://pyth.herokuapp.com/?code=f%3El%7B%60.%3CQT9Z&test_suite=1&test_suite_input=617283945%0A2%0A66833%0A1234567890%0A100%0A42&debug=0).
First natural number `T` where `input << T` meets the requirement.
[Answer]
# [Perl 5](https://www.perl.org/), 52 + 1 (-p) = 53 bytes
```
$/=10;for$i(0..9){$/-=/$i/}$_*=2;++$\;$/&&redo}{$\--
```
[Try it online!](https://tio.run/##BcFBCoAgEADAzyxSyboqdQjxCf1A6JKBECnWTfx620yJ9VqYgbzR7swV0qCVWscGhJ4gUYd98tZJCcEBCVHjkXuDgMg82y@XN@X7YdwWpY1mLD8 "Perl 5 – Try It Online")
[Answer]
# Perl, 43 + 1 bytes
```
for$x(0..9){$_*=2,++$\,redo LINE if!/$x/}}{
```
Using the `-p` flag. This builds on the solution provided by Xcali above.
[Answer]
# **Swift 4**, 111 bytes
```
func p(_ x:Int,_ c:Int=0)->Int{if !(String(Set(String(x)).sorted())=="0123456789"){return p(x*2,c+1)};return c}
```
Note: Won't work for x = 2, because of overflow.
Explanation - Input x is first typecasted to string. Then Set() removes the repeating characters. Then it is sorted to match the result. If it doesn't match, x is doubles and counter is incremented.
[Answer]
# Ruby, ~~46~~ ~~45~~ ~~39~~ 38 bytes
```
def f n;n.digits.uniq[9]?0:1+f(n*2)end
```
[Try it online!](https://tio.run/##KypNqvz/PyU1TSFNIc86Ty8lMz2zpFivNC@zMNoy1t7AylA7TSNPy0gzNS/lf0FpSbFGmoaZobmRhbGliammJhdUyAjBNDOzMDZGcA2NjE1MzcwtLA2QxAyQOCZAvf8B "Ruby – Try It Online")
Updates:
1. -1 by using `def f n;` instead of `def f(n);`.
2. -6 by using `…[9]` instead of `….size==10`
3. -1 by removing a semicolon
[Answer]
# [Japt](https://ethproductions.github.io/japt/), 15 bytes
```
LÆ*2pXÃbì_â Ê¥A
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=TMYqMnBYw2LsX+IgyqVB&input=NDI=)
---
## Explanation
Implicit input of integer `U`.
```
LÆ Ã
```
Create an array of integers from `0` to `99` and pass each through a function where `X` is the current element.
```
*2pX
```
`U` multiplied by 2 raised to the power of `X`.
```
b
```
Get the index of the first element thay returns true when passed through the following function.
```
ì_â
```
Split to an array of digits and remove the duplicates.
```
Ê¥A
```
Get the length of the array and check for equality with `10`.
---
## Alternative, 15 bytes
```
@*2pX)ìâ sÊ¥A}a
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=QCoycFgp7OIgc8qlQX1h&input=NDI=)
---
### Explanation
Implicit input of integer `U`.
```
@ }a
```
Starting with `0`, return the first number that returns true when passed through the following function, with `X` being the current number.
```
*2pX)
```
As above, multiply `U` by 2 to the power of `X`.
```
ìâ
```
Split to an array of digits, remove duplicates and rejoin to an integer.
```
sÊ
```
Convert to a string, get the length and convert back to an integer.
```
¥A
```
Check for equality with `10`.
[Answer]
# GNU dc, 61 bytes
Input is copied from top of stack (which must be otherwise empty); output is pushed to top of stack.
```
[I~1r:ad0<s]ss[d1+r;a1=p]sp[d2*lfx]sh[0Sadlsxlpx11!=h]dsfxz1-
```
## Explanation
We use the array variable `a`, storing a 1 in `a[d]` if digit `d` is present, otherwise falling back to 0 there. We use the GNU extension `~` to obtain quotient and remainder in a single command.
```
# populate a[0-9] from the digits
[I~1r:ad0<s]ss
# check pandigit
# return 1 more than lowest unset element of a[]
# start with stack=0
[d1+r;a1=p]sp
# Test for pandigit; double and repeat if needed
[dd+lfx]sh
[0Sadlsxlpx11!=h]dsfx
# We left one value on the stack for each doubling, plus the original
z1-
```
As a bonus, this will work in arbitrary number bases (not only decimal): simply set the input radix as required (the constant `11` in the definition of `f` will be read using that number base, so is automatically correct).
## Test
```
for i in 617283945 2 66833 1234567890 100 42
do
printf '%s => ' $i
dc -e $i \
-e '[I~1r:ad0<s]ss[d1+r;a1=p]sp[dd+lfx]sh[0Sadlsxlpx11!=h]dsfxz1-' \
-e p
done
```
```
617283945 => 1
2 => 67
66833 => 44
1234567890 => 0
100 => 51
42 => 55
```
[Answer]
## REXX, 57 bytes
```
arg n
do b=0 while verify(0123456789,n)>0
n=n*2
end
say b
```
[Answer]
# [q/kdb+](http://kx.com/download), 33 bytes
**Solution:**
```
(#)1_{x*2 1 min!:[10]in 10 vs x}\
```
**Examples:**
```
q)(#)1_{x*2 1 min!:[10]in 10 vs x}\[100]
51
q)(#)1_{x*2 1 min!:[10]in 10 vs x}\[1234567890]
0
q)(#)1_{x*2 1 min!:[10]in 10 vs x}\[42]
55
```
**Explanation:**
All the bytes are in the equality, might be able to golf this one down a little further. Utilises q's `scan` adverb:
```
count 1_{x*2 1 min til[10] in 10 vs x}\ / ungolfed solution
{ }\ / scan over this lambda until it yields same result
10 vs x / convert to base 10
in / left list in right list, returns boolean list
til[10] / range 0..9
min / return the minimum of the list, 0 or 1
2 1 / list (2;1) indexed into with 0 or 1
x* / return x multiplied by either 2 or 1
1_ / 1 drop, drop one element from front of list
count / count the length of the list
```
**Notes:**
If we drop to the `k` prompt then we can have a 25 byte solution. Converts the number to a list of characters:
```
q)\
#1_{x*2 1@&/($!10)in$$x}\[100]
51
```
] |
[Question]
[
[Keep Talking and Nobody Explodes](http://www.keeptalkinggame.com/) is a local multiplayer game where one player has control over a virtual "bomb", and has to be guided by another player, the "expert", who has access to a bomb defusal manual. One of the modules to be disarmed in the game is the keypad module, which is what we'll be dealing with in this challenge.
## The task
Input will start with a single line of printable ASCII characters except space (0x21 to 0x7E). These represent the keypad buttons visible to you.
The next few lines will represent "keys" – only one line will contain all of the characters of the first line, not necessarily in order. Your task is to output the keypad characters, in the order of the matching key line.
For example, if the input was
```
5~Fy
HrD7K!#}
Ui%^fHnF
)Tf;y~I5
~Fi(&5gy
,'Xd#5fZ
```
then the keypad buttons are `5`, `~`, `F` and `y`. Only the 4th key line `~Fi(&5gy` contains all of these characters, so we output the keypad characters in the order in which they appear, i.e. `~F5y`.
## Rules and clarifications
* Input must be a single multiline string, with the keypad buttons and key lines on separate lines.
* There will be exactly one key line which contains all of the keypad characters.
* Every line, i.e. the initial keypad line and following key lines, will have no duplicate characters.
* Unlike the game, you may not assume anything about the number of keypad characters, the length of each key line or the number of key lines. However, all key lines are guaranteed to be the same length.
* The output may contain a single optional trailing newline. Similarly you may assume either way about an optional trailing newline in the input, but please specify in your answer if you need the assumption.
* Although this already seems to be [common practice](https://codegolf.meta.stackexchange.com/a/4781/21487), I'll state explicitly: terminating with an error is okay for this challenge, as long as STDOUT output is correct (if this is your chosen form of output). Hopefully this will make handling input easier.
## Test cases
```
7
4?j01C3"ch
KP.OG>QB)[
z#)Kn"I2&.
]#,D|sBFy5
Qzj*+~7DLP
```
**Output:** `7`. Only the last line contains a `7`.
```
0b~
Ob+hy{M|?;>=dtszPAR5
*8rCfsw|3O9.7Yv^x>Hq
$ip.V@n}|La:TbIt^AOF
jZ[Ec4s0|%b*$id',~J6
z*#b}-x$Ua&!O2;['T+?
NVj_X8rlhxfnS\.z}];c
bykscf.w^dnWj+}-*2g_
VP`AJH|&j5Yqmw/"9IMc
```
**Output**: `0b~`. The 4th key line already contains the characters in the right order.
```
MTuz
bIAr>1ZUK`s9c[tyO]~W
oMGIi/H&V"BeNLua%El=
j*uYbplT:~);BM|_mPZt
Q}z5TC@=6pgr<[&uJnM%
YOA(F~_nH6T{%B7[\u#5
y&t"8zQn{wo5[Idu4g:?
[0tZG"-fm!]/|nqk,_2h
dA&C.+(byo6{7,?I}D@w
```
**Output**: `zTuM`. The key line is the 4th one, although the 3rd key line is a close miss.
```
o@nj<G1
f]?-<I6h2vS*%l=:}c8>LK5rMdyeon,;sE[@m(73
ibhp+2Hq6yKzIf_Zo}EO3-[*0/e&Fvd]wQU=|%`C
;}>d'cg~CPtQG&%L\)MUl419bkTZ7@]:[*H"RyYj
L^<:zXJ#kj$EFlwN%B`Dd,Cs?]xRZ*K9-uQ.@&f+
i1v'7:90R-l}FMxj`,DTWK+(n32Z4Vs[p@%*eS!d
B|^Ti/ZG$}ufL9*wE[AVt]P7CrX-)2JpD<sYxd6O
ex.$4#KarS^j+'_!B"]H[\83:(DCXUgI*Lct?qAR
^GXQoy*KW&v}n']Em~\N9)fxP(qC=7#4sRdcD6%5
;inr[&$1j_!F~@pzo#blv]}<'|fRds6OW%tEg"G2
e;0T#gfo^+!:xHDN&4V=In?AwhEv$2Fd~ZLz_\81
```
**Output**: `n1j@o<G`. The key line is the second last line.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code in the fewest bytes wins.
[Answer]
## CJam, ~~13~~ 12 bytes
```
qN/(f&{,}$W=
```
[Test it here.](http://cjam.aditsu.net/#code=qN%2F(f%26%7B%2C%7D%24W%3D&input=5~Fy%0AHrD7K!%23%7D%0AUi%25%5EfHnF%0A)Tf%3By~I5%0A~Fi(%265gy%0A%2C'Xd%235fZ)
### Explanation
```
q e# Read all input.
N/ e# Split into lines.
( e# Pull off the keypad buttons.
f& e# Take the set intersection of each key line with the keypad, preserving the order
e# order in the key line.
{,}$ e# Sort the results by length.
W= e# Pick the last (longest) one.
```
[Answer]
# Pyth, 10
```
@zhf!-zT.z
```
[Try it online](http://pyth.herokuapp.com/?code=%40zhf%21-zT.z&input=MTuz%0AbIAr%3E1ZUK%60s9c%5BtyO%5D~W%0AoMGIi%2FH%26V%22BeNLua%25El%3D%0Aj%2AuYbplT%3A~%29%3BBM%7C_mPZt%0AQ%7Dz5TC%40%3D6pgr%3C%5B%26uJnM%25%0AYOA%28F~_nH6T%7B%25B7%5B%5Cu%235%0Ay%26t%228zQn%7Bwo5%5BIdu4g%3A%3F%0A%5B0tZG%22-fm%21%5D%2F%7Cnqk%2C_2h%0AdA%26C.%2B%28byo6%7B7%2C%3FI%7DD%40w&debug=0)
### Explanation
```
@zhf!-zT.z ## z = first line of input, .z = list of rest of lines
f .z ## Filter .z as T based on
!-zT ## Whether removing all the letters from z that appear in T leaves an
## Empty string or not (keep the ones that give empty strings)
h ## Take the first such line (necessary indexing, shouldn't ever matter)
@z ## @ is setwise intersection. Pyth implements this by iterating over
## each element of the second argument and keeping values that appear
## in the first argument, which gives the intended result
```
[Answer]
# Pyth, 9 bytes
```
[[email protected]](/cdn-cgi/l/email-protection)
```
[Demonstration](https://pyth.herokuapp.com/?code=eolN%40Lz.z&input=o%40nj%3CG1%0Af%5D%3F-%3CI6h2vS%2a%25l%3D%3A%7Dc8%3ELK5rMdyeon%2C%3BsE%5B%40m%2873%0Aibhp%2B2Hq6yKzIf_Zo%7DEO3-%5B%2a0%2Fe%26Fvd%5DwQU%3D%7C%25%60C%0A%3B%7D%3Ed%27cg~CPtQG%26%25L%5C%29MUl419bkTZ7%40%5D%3A%5B%2aH%22RyYj%0AL%5E%3C%3AzXJ%23kj%24EFlwN%25B%60Dd%2CCs%3F%5DxRZ%2aK9-uQ.%40%26f%2B%0Ai1v%277%3A90R-l%7DFMxj%60%2CDTWK%2B%28n32Z4Vs%5Bp%40%25%2aeS%21d%0AB%7C%5ETi%2FZG%24%7DufL9%2awE%5BAVt%5DP7CrX-%292JpD%3CsYxd6O%0Aex.%244%23KarS%5Ej%2B%27_%21B%22%5DH%5B%5C83%3A%28DCXUgI%2aLct%3FqAR%0A%5EGXQoy%2aKW%26v%7Dn%27%5DEm~%5CN9%29fxP%28qC%3D7%234sRdcD6%255%0A%3Binr%5B%26%241j_%21F~%40pzo%23blv%5D%7D%3C%27%7CfRds6OW%25tEg%22G2%0Ae%3B0T%23gfo%5E%2B%21%3AxHDN%264V%3DIn%3FAwhEv%242Fd~ZLz_%5C81&debug=0)
`@Lz.z`: Filter all lines for the intersection with the first line.
`olN`: Order by length
`e`: Take the longest.
[Answer]
## Haskell, 49 bytes
```
g(!)(a:b)=[c|d<-b,all(!d)a,c<-d,c!a]
g elem.lines
```
The first line defines a helper function `g`, the unnamed function on the second line is my answer.
## Explanation
The algorithm is the obvious one: split input into lines, find the line that contains all characters of the first line, and filter out all the other characters on that line.
```
g(!)(a:b)= -- g gets a binary function ! and list of strings a:b
[c| -- and returns the string of characters c where
d<-b,all(!d)a, -- d is drawn from b and x!d holds for all x in a,
c<-d,c!a] -- and c is drawn from d and c!a holds.
g elem.lines -- The input is split into lines and fed to g elem;
-- then x!d means x `elem` d in the above.
```
[Answer]
# Prolog, ~~204~~ 190 bytes
This could have been a nice challenge for Prolog if it hadn't been for the combined requirements of multiline input and unescaped characters ' and " in the input. A big chunk of the code (p and r) exist to read a file as character codes which is what I had to do to take unescaped input on several lines.
If only ' existed as an unescaped character, I could read input as a string.
If only " existed as an unescaped character, I could read input as an atom.
If input wasn't multiline, say separated by space instead, I could read it as one line to codes.
```
r(I,[H|T]):-read_line_to_codes(I,H),H\=end_of_file,r(I,T).
r(_,[]).
q(_,[]).
q(E,[H|T]):-subset(E,H),intersection(H,E,X),writef("%s",[X]);q(E,T).
p:-open("t",read,I),r(I,[H|T]),q(H,T),!.
```
**How it functions**
1. Opens file t (which contains all input) to read
2. Read all lines as character codes and place in a list of lists (1 list per row)
3. Recurses over tail lists and checks if head list exist as a subset of that list
4. Intersects matched list with head to get wanted characters in the correct order
5. Prints solution
**How to run**
Program is run with command:
p.
File namned t containing input has to be in the same directory.
**Edit:** Saved 14 bytes by unifying 2 q-clauses with OR.
[Answer]
## MATLAB, 107 bytes
```
b=char(strsplit(char(inputdlg),' '));[~,x]=ismember(b,b(1,:));[~,f]=min(abs(1./sum(~x')-1));b(f,(~~x(f,:)))
```
This ended up being a very sloppy piece of code...
When being run, an input dialog is opened where a multi-line string can be pasted into (newlines are converted to spaces and the output will be a cell with 1 very long string). I chose to convert the resulting cell to a char which makes it possible to split at the spaces (result is a cell array) and then again convert to char to retrieve the intended shape. MATLAB's built-in **ismember** function does a good job here in comparing our first line to the other lines.
After that it gets nasty... I've tried a lot of ways to exclude the first line from my 'best match' check and ended up with this. We look for the line and then use this information to grab the indices (by converting our **ismember** output to logicals) that we want our output characters from.
[Answer]
# Wolfram Language 106 bytes
```
c=Characters[InputString[]~StringSplit~"\n"];o=c[[1]];t=Select;t[t[Rest@c,#~SubsetQ~o&][[1]],o~MemberQ~#&]
```
Example input:

Output:

Explanation of the code : First with InputString we get the full string of input, then we get the first set of letters by splitting the string by newline, and saving all the characters of the first one in variable o. Next, we select from the rest of the input lines those lines that have the first line's characters (saved as variable o) as a subset. Then with that line selected, we grab the members of that line that are in the original set.
Edit : Thanks to Martin Büttner for the tips on using infix notation and my unnecessary variables
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-h`](https://codegolf.meta.stackexchange.com/a/14339/), ~~6~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
~~Takes the keypad as an array of lines. The buttons can be either a string or a character array.~~ +2 bytes to accommodate the cumbersome input format.
```
·ËoFgÃñl
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=t8tvRmfD8Ww&input=IjV%2bRnkKSHJEN0shI30KVWklXmZIbkYKKVRmO3l%2bSTUKfkZpKCY1Z3kKLCdYZCM1Zloi)
```
·ËoFgÃñl :Implicit input of multi-line string
· :Split on newlines
Ë :Map each element in array F
o : Remove characters not contained in
Fg : First element of F
à :End map
ñ :Sort by
l : Length
:Implicit output of last element
```
[Answer]
# Python 2, 112 bytes
```
import sys
i=sys.stdin.readlines()
print[''.join(c for c in l if c in i[0])for l in i[1:]if set(i[0])<set(l)][0]
```
Example run: [Ideone](https://ideone.com/plM59N)
[Answer]
# Javascript (ES6), 107 104 102 bytes
Snippet demo for supporting browsers.
```
f=x=>([a]=x.split`
`).map(y=>[...y].filter(z=>~a.indexOf(z)-x).join(x='')).find(z=>z.length==a.length)
```
```
<textarea id="i" rows="6" cols="45">o@nj<G1
f]?-<I6h2vS*%l=:}c8>LK5rMdyeon,;sE[@m(73
ibhp+2Hq6yKzIf_Zo}EO3-[*0/e&Fvd]wQU=|%`C
;}>d'cg~CPtQG&%L\)MUl419bkTZ7@]:[*H"RyYj
L^<:zXJ#kj$EFlwN%B`Dd,Cs?]xRZ*K9-uQ.@&f+
i1v'7:90R-l}FMxj`,DTWK+(n32Z4Vs[p@%*eS!d
B|^Ti/ZG$}ufL9*wE[AVt]P7CrX-)2JpD<sYxd6O
ex.$4#KarS^j+'_!B"]H[\83:(DCXUgI*Lct?qAR
^GXQoy*KW&v}n']Em~\N9)fxP(qC=7#4sRdcD6%5
;inr[&$1j_!F~@pzo#blv]}<'|fRds6OW%tEg"G2
e;0T#gfo^+!:xHDN&4V=In?AwhEv$2Fd~ZLz_\81</textarea><br /><input type="button" onclick="o.value=f(i.value)" value="Run"> Output: <input type="text" id="o" readonly />
```
**Commented:**
```
f=x=>
([a]=x.split('\n')) // split input by newlines, assign first value to a
.map(y=> // map function to each line
[...y].filter(z=> // filter characters
~a.indexOf(z)-x // a has character z and not the first item (x is still set)
).join(x='') // join characters with empty string, reset x flag
).find(z=>z.length==a.length) // return string with same length as a
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~96~~ ~~71~~ 63 bytes
-8 bytes thanks to [south](https://codegolf.stackexchange.com/users/110888/south)
Inspired by [Shaggy’s Japt solution](https://codegolf.stackexchange.com/a/254124/11261). Requires a trailing newline in the input.
```
->s{a,b=s.split$/,2
b.gsub(/./){a[$&]&&$&}.lines.max_by &:size}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=Lc7PUoJAAIDx-z6FFa6KsDiUpTJiThOjToZTZhmJsSgKKYMsJP_WF-niNPUMPUtv08FO3-0338eXH-J4_6k0v8PA4mu_LV4mqcHhJkHEW9kBI3AiwGhBQlwUkFBKDY2BEwgZSNHKducErY1oiuMcbBA7mdN_5scLA5JTtHyxgndAxeVlnPazliQ3ZwFJBu27KmBr_pVFttmpWkcX43c9kjsbwNgeGl26NLsxGkPcDfS2qgDnWbs2z0gly2OWsWcFbtc7Bwl7gikfMQ8GPFJFSSsMyy1wO3KmTzV_tYws9_4FJXQimQDHb8S00FafuY9OmfKsuJiC0eC13etk0KmON-utcFzv9k1Qmhz29_tD_wA)
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~8~~ 7 bytes (14 nibbles)
```
/\+=~.;@`&$;$,
```
```
. # map over
;@ # all lines of input
`& # getting list intersection
$ # of each line
;$ # with the first line of input;
=~ # now group intersections by
, # length,
+ # flatten the list-of-groups,
\ # reverse it
# (so the 'found' keys are now first,
# and the input is second),
/ # finally, fold from right
# returning the (implicit) right argument
# at each step
# (so returning the first element)
```
[](https://i.stack.imgur.com/kzVok.png)
] |
[Question]
[
Inspired by [this link I found on Reddit](http://blog.amjith.com/fuzzyfinder-in-10-lines-of-python).
A FuzzyFinder is a feature of many text editors. As you start to type a file path `S`, the FuzzyFinder kicks in and shows you all files in the current directory containing the string you entered, sorted by the position of `S` in the file.
Your task is to implement a fuzzy finder. It should be program or function that takes (via stdin, function argument, or command line) a string `S` and a list of strings `L`, formatted however you wish, and returns or prints the result of running the fuzzy finder. The search should be case-sensitive. Results where `S` is in the same position in multiple strings may be sorted however you wish.
Example:
```
Input: mig, [imig, mig, migd, do, Mig]
Output:
[mig, migd, imig]
OR
[migd, mig, imig]
```
This is code golf, so the shortest solution wins.
[Answer]
# Pyth, 9 bytes
```
oxNzf}zTQ
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=oxNzf%7DzTQ&input=mig%0A%5B%22imig%22%2C%20%22mig%22%2C%20%22migd%22%2C%20%22do%22%2C%20%22Mig%22%5D&debug=0)
### Explanation:
```
implicit: z = input string, Q = input list
f Q filter Q for elements T, which satisfy:
}zT z is substring of T
o order the remaining strings N by:
xNz the index of z in N
```
[Answer]
## Python 2, 65
```
def f(s,l):g=lambda x:x.find(s)+1;print sorted(filter(g,l),key=g)
```
The expression `x.find(s)` returns the position of the first occurrence of `s` in `x`, giving `-1` for no match. We add `1` to the result to that no-match corresponds to `0`, letting us `filter` them out. We then sort by the match position, which is unaffected by shifting by 1.
[Answer]
# CJam, ~~18~~ 15 bytes
```
{1$#)}q~2$,@$p;
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=%7B1%24%23)%7Dq~2%24%2C%40%24p%3B&input=%22mig%22%20%5B%22imig%22%20%22mig%22%20%22migd%22%20%22do%22%20%22Mig%22%5D).
### I/O
Input:
```
"mig" ["imig" "mig" "migd" "do" "Mig"]
```
Output:
```
["mig" "migd" "imig"]
```
### How it works
```
q~ e# Read and evaluate the input from STDIN.
e# Pushes a needle and an array of haystacks.
{ } e# Define a code block:
1$ e# Copy the needle.
# e# Compute the index of the needle in the haystack.
) e# Add 1 to the index.
2$ e# Copy the block.
, e# Filter: Keep only haystacks for which the code block
e# pushed a non-zero value.
@ e# Rotate the block on top of the stack.
$ e# Sort: Arrange the haystacks according to the values
e# pushed by the code block.
p e# Print the filtered and sorted haystacks.
; e# Discard the needle.
```
[Answer]
# GolfScript, 13 bytes
```
~{?)}+\1$,\$`
```
This is one of those rare occasions where GolfScript can beat CJam, by using block concatenation and taking a few liberties with the input which can be *formatted however you wish*.
Try it online in [Web GolfScript](http://golfscript.apphb.com/?c=OydbImltaWciICJtaWciICJtaWdkIiAiZG8iICJNaWciXSB7Im1pZyJ9JyAjIFNpbXVsYXRlIGlucHV0IGZyb20gU1RESU4uCgp%2Bez8pfStcMSQsXCRg).
### I/O
Input
```
["imig" "mig" "migd" "do" "Mig"] {"mig"}
```
Output
```
["migd" "mig" "imig"]
```
### How it works
```
~ # Evaluate the input from STDIN.
# Pushes an array of haystacks and a needle in a block.
{?)} # Push a code block that computes an index and increments it.
+ # Concatenate that block with the needle block.
\1$ # Swap the block with the arrays of haystacks and copy the block.
, # Filter: Keep only haystacks for which the code block
# pushed a non-zero value.
\ # Swap the array of haystacks with the code block.
$ # Sort: Arrange the haystacks according to the values
# pushed by the code block.
` # Inspect: Format the array for pretty printing.
```
[Answer]
# JavaScript ES6, 68 bytes
```
(s,l,f=j=>j.indexOf(s))=>l.filter(w=>~f(w)).sort((a,b)=>f(a)>f(b))
```
This is an anonymous function that takes parameters `s` (file path string) and `l` (array of strings). The Stack Snippet below contains ungolfed code converted to ES5 so more people can test it easily. (If you have Firefox, you can use edc65's prettier test suite found in his answer.)
```
f=function(s,l){
g=function(j){
return j.search(s)
}
return l.filter(function(w){
return ~g(w)
}).sort(function(a,b){
return g(a)>g(b)
})
}
id=document.getElementById;run=function(){document.getElementById('output').innerHTML=f(document.getElementById('s').value,document.getElementById('l').value.split(', ')).join(', ')};document.getElementById('run').onclick=run;run()
```
```
<label>File path: <input type="text" id="s" value="mig" /></label><br />
<label>Files: <input type="text" id="l" value="imig, mig, migd, do, Mig" /></label><br />
<button id="run">Run</button><br />
Output: <output id="output"></output>
```
[Answer]
# [Hold] Pyth, 24 Bytes
```
JwKcwdVlK=G.)KI}JGaYG))Y
```
Try is [here](https://pyth.herokuapp.com/?code=JwKcwdVlK%3DG.)KI%7DJGaYG))Y&input=mig%0Aimig+mig+migd+do+Mig&debug=1)
I'm pretty new at Code Golfing/Pyth so I'm not sure it's optimal, but I'm working on it!
**Update:** I don't think I'm actually sorting correctly, and I can't seem to get it to work. I know that `o` is order-by, and I need to sort by position of S so I am using `.:GlJ` in order to find all the substrings of the length of S for the current element `G` and then `x` in order to find the index of the first occurrence of S, but I can't seem to set lambda correctly.
[Answer]
# JavaScript (*ES6*), 68
**That's almost the same of @NBM answer (even if it's not copied), so I don't expect upvotes. Enjoy the snippet anyway**
A function with a string and a string array arguments, return a string array. Filter then sort.
Test runnign the snippet below (being EcmaScript 6, Firefox only)
```
f=(s,l,i=t=>t.indexOf(s))=>l.filter(t=>~i(t)).sort((t,u)=>i(t)-i(u))
$(function(){
$("#S,#L").on("keyup",
function() {
$('#O').val(f(S.value,L.value.split('\n')).join('\n'))
} );
$("#S").trigger('keyup');
})
```
```
#S,#L,#O { width: 400px }
#L,#O { height: 100px }
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Input String<br><input id=S value='mig'><br>
Input List<br><textarea id=L>
imig
mig
migd
do
Mig
</textarea><br>
Output List<br><textarea id=O readonly></textarea>
```
[Answer]
**ORACLE, 60**
Does this count?
`select * from t where a like '%mig%' order by instr(a,'mig')`
[Answer]
# Haskell, ~~129~~ 116
116 (Thanks to Franky):
```
import Data.List
h s=map snd.sort.map(\x->((head[c|c<-[0..length x],isPrefixOf s(drop c x)]),x)).filter(isInfixOf s)
```
---
129:
```
import Data.List
f s n=map snd(sort(map(\x->((head [c|c<-[0..length x],isPrefixOf s(drop c x)]),x))(filter(\x->isInfixOf s x)n)))
```
Well, it's pretty long, maybe I'll find how to short it up a bit...
[Answer]
# Python 2, ~~69~~ ~~68~~ 66 Bytes
I just created a function which takes `s` as the string to match in a list of strings `n`
*Edit 1: Thanks to Jakube for golfing off a byte.*
```
lambda s,n:sorted([x for x in n if s in x],key=lambda x:x.find(s))
```
[Check it out here.](http://ideone.com/dpL0sA)
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `r`, ~~7~~ 6 bytes
*-1 byte because I is big dumb and forgot about multi-byte lambda thingies.*
```
‡⁰e~Fṡ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=r&code=%E2%80%A1%E2%81%B0e%7EF%E1%B9%A1&inputs=%5B%22imig%22%2C%20%22mig%22%2C%20%22migd%22%2C%20%22Rick%20Astley%22%2C%20%22Mig%22%5D%0A%22mig%22&header=&footer=)
Explanation:
```
# Implicit input - List of strings
‡ # Define lambda:
⁰ # Get last input - Search string
e # Regex span - Returns empty list for no match
~F # Filter list by lambda without popping lambda
ṡ # Sort filtered list by lambda
# Implicit output
```
[Answer]
## Ruby, 63
```
p=->(w,l){l.find_all{|x|x[w]}.sort{|a,b|a.index(w)-b.index(w)}}
```
Run
```
irb(main):022:0> p["mig", ["imig", "mig", "migd", "do", "Mig"]]
=> ["migd", "mig", "imig"]
```
Notes
1. First find all matching words with `find_all`
2. Sort by index position of word to be searched.
Edit (by daneiro)
## Ruby, 49
```
p=->w,l{l.select{|x|x[w]}.sort_by{|e|e.index(w)}}
```
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 15 bytes
14 bytes of code, +1 for `-p` flag.
```
Yq_@?ySKyN_FIg
```
Takes the list as command-line args and the string from stdin. [Try it online!](http://pip.tryitonline.net/#code=WXFfQD95U0t5Tl9GSWc&input=bWln&args=LXA+aW1pZw+bWln+bWlnZA+ZG8+TWln)
### Explanation
```
Yq Yank a line of stdin into y
FIg Filter array of cmdline args by this function:
yN_ Count occurrences of y in arg
SK Sort the resulting list using this key function:
_@?y Index of y in arg
Print the Pip representation of the list (implicit, -p flag)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
føV ñbV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=ZvhWIPFiVg&input=WyJpbWlnIiwibWlnIiwibWlnZCIsImRvIiwiTWlnIl0KIm1pZyI)
```
føV ñbV :Implicit input of array U and string V
f :Filter U by
øV : Contains V?
ñ :Sort by
bV : First index of V
```
[Answer]
## Racket 46 bytes
```
(for/list((i l)#:when(string-contains? i s))i)
```
Usage:
```
(define (f s l)
(for/list((i l)#:when(string-contains? i s))i))
```
Testing:
```
(f "mig" '["imig" "mig" "migd" "do" "Mig"])
```
Output:
```
'("imig" "mig" "migd")
```
[Answer]
# Groovy, 32 bytes
```
{a,b->a.findAll{it.contains(b)}}
```
] |
[Question]
[
Produce the shortest program which takes two signed integers as input (through stdin or as arguments) and displays 3 different outputs depending upon whether the first number is (1) greater than, (2) smaller than, or (3) equal to the second number.
**The Catch**
You cannot use any of the following in your program:
* The standard comparison operators: `<`, `>`, `<=`, `>=`, `==`, `!=`.
* Any library file apart from `conio`, `stdio`, or `iostream`.
* Any non-ASCII or non-printable ASCII character.
**The Winner**
The program with the shortest number of characters wins.
[Answer]
Maybe I'm missing something in the rules, but...
# 81 bytes
```
main(a,b){scanf("%d%d",&a,&b);long long l=a;l-=b;printf("%lld%d",--l>>63,l>>63);}
```
Ouputs `00` if `a > b`, `-10` if `a == b`, and `-1-1` if `a < b`.
[Answer]
## 90 bytes
If we can use `stdio`, why not use its formatting capabilities to perform comparison?
```
main(a,b){scanf("%d%d",&a,&b);snprintf(&a,2,"%d",b-a);a&=63;putchar(51-!(a-45)-!!(a-48));}
```
Assumes ASCII-compatible encoding and little-endianness.
## 72 bytes
Quotients are rounded toward zero but right-shifts are (in practice) "rounded down". That's a dead giveaway.
```
main(a,b){scanf("%d%d",&a,&b);a-=b;putchar(a?a|=1,a/2-(a>>1)?60:62:61);}
```
## ~~65~~ 79 bytes
Another distinguishing property of negative numbers is that they produce negative modulo.
This one doesn't depend on integer representation at all; it even works on my 8-bit excess-127 toaster!
Oh, and since we can use `conio`, why not save two bytes with `putch`? Now, if I could only find my copy of TurboC...
```
main(a,b){scanf("%d%d",&a,&b);long long d=a;d-=b;putch(d?d|=1,d%2-1?60:62:61);}
```
**EDIT**: Handle large differences assuming `long long` is wider than `int`.
[Answer]
# ~~64~~ 61 characters
```
main(a,b){scanf("%d%d",&a,&b);for(a-=b;a/2;a/=2);putchar(a);}
```
Prints the character values of -1, 0, and 1 for less than, equal to, or greater than, respectively.
This implementation relies on undefined behavior for `b` being of type `int` and for inputs outside the range `INT_MIN / 2` to `INT_MAX / 2`. On platforms where signed overflow wraps around, whether 2s-complement (basically all of them) or sign-magnitude, it will fail for 25% of possible pairs of valid `int`. Interestingly (to me anyway), it will work correctly on platforms where signed overflow saturates.
[Answer]
## ~~59~~ 54 characters
54 charcters with a compiler like gcc which doesn't balk at `main(x,y)`:
```
main(x,y){scanf("%d%d",&x,&y);y-=x;putchar(y>>31|!y);}
```
59 characters otherwise:
```
main(){int x,y;scanf("%d%d",&x,&y);y-=x;putchar(y>>31|!y);}
```
Output:
* ASCII code 0x00 if x < y
* ASCII code 0xFF if x > y
* ASCII code 0x01 if x == y
[Answer]
## ~~66~~ 102 bytes
```
main(a,b,c,d,e){scanf("%d %d",&a,&b);e=1<<31;c=a&e;d=b&e;putchar(a-b?c&~d?48:d&~c?49:a-b&e?48:49:50);}
```
Reads the integers from STDIN and prints `0` (a < b), `1` (a > b) or `2` (a == b).
**Edit:** Now it should also work for differences which are too large to fit into a 32-bit integer. I'm sure That nested ternary can be shortened with some more bit-magic.
[Answer]
# 52 bytes
Sadly this one only works for positive integers, but I thought the concept of using purely arithmetic operators was interesting:
```
main(a,b){scanf("%d%d",&a,&b);putchar(b%a/b-a%b/a);}
```
### Outputs:
* ASCII code 0xFF: a less than b
* ASCII code 0x00: a equal to b
* ASCII code 0x01: a greater than b
[Answer]
# 53 bytes
```
main(a,b){scanf("%d%d",&a,&b);printf("%ld",0l+a-b);}
```
Only the first character of the output is relevant. The three different outputs are:
1. '-' if b > a
2. '0' if a == b
3. any other character if a > b
It works for the full input range of int on all platforms where sizeof(long) > sizeof(int).
Edit: it costs one extra character to make case 3 print a '+' uniquely instead:
```
main(a,b){scanf("%d%d",&a,&b);printf("%+ld",0l+a-b);}
```
[Answer]
# 66 bytes
```
main(a,b){scanf("%d%d",&a,&b);putchar((0l+b-a>>63)-(0l+a-b>>63));}
```
Prints the byte 0x00 if `a == b`, 0x01 if `a < b` and 0xff if `a > b`.
Since *non-ASCII or non-printable ASCII character in [my] program* and *if anything is not explicitly forbidden in the question, then it is permitted*, unprintable character in the **output** should be completely fine.
[Answer]
# 87 characters
```
main(a,b,c){scanf("%d%d",&a,&b);c=1<<31;a+=c;b+=c;puts(a^b?(unsigned)a/b?">":"<":"=");}
```
Using the 2^31 trick to convert to unsigned int's
Casting the division to unsigned to handle the upper bit as data, not sign
Using ^ to XOR a and b, when they are equal this returns 0
Using nested conditionals (?) to get "<",">", or "=" to feed to puts()
[Answer]
In 64 chars without stdio.h
`a,b;main(){scanf("%d%d",&a,&b);puts((a-b)>>31?"<":a^b?">":"=");}`
prints '>' if a > b, '<' if a < b, '=' if a == b
int overflow is UB. Just don't overflow.
```
// declare a and b as ints
a,b;
// defaults to int
main()
{
scanf("%d%d",&a,&b);
/*
* (a-b)>>31 signbit of a-b
* a^b a xor b -> 0 if they are equal
*/
puts(((a-b)>>31) ? "<" : (a^b) ? ">" : "=");
}
```
[Answer]
## 71 bytes
```
main(x,y,z){scanf("%d%d",&x,&y);putchar((z=x-y)?(z&(z>>31))?50:49:51);}
```
<http://ideone.com/uvXm6c>
[Answer]
## 68 characters
```
int main(a,b){scanf("%d%d",&a,&b);putchar(a-b?((unsigned)a-b)>>31:2);}
```
Puts ASCII character 1, 2 or 3 for less than, greater than or equal, respectively.
[Answer]
# ~~88~~ 89 bytes
```
main(a,b){scanf("%d%d",&a,&b);a+=1<<31;b+=1<<31;for(;a&&b;a--)b--;putchar(a?b?48:49:50);}
```
This starts by adding `1<<31` (`INT_MIN`) to a and b, so that 0 now corresponds `INT_MIN`. Then loops and decrements a and b every loop until either is 0, then prints 0, 1 or 2
depending on whether a, b or both are 0.
# ~~120~~ 119 bytes
```
main(a,b,c){scanf("%d%d",&a,&b);c=1<<31;a^=c;b^=c;for(c~=c;!c;c/=2)if(a&c^b&c){putchar(a?48:49);return;}putchar(50);}
```
It's not the shortest solution as it is but might be golfed down a bit by better golfer than me. (Or just people with more knowledge of C than me)
The idea is to mask each bit, starting from the left one and checking for inequality. The rest should explain itself. Since negative numbers start with a 1 bit, I first invert the first bit with `a^=1<<31`.
[Answer]
I think I'm not even going to try at writing short code. What I will attempt is to perform this comparison in a way that is portable per the C99 spec.
```
int a, b; // Let's assume these are initialized
int sign_a = a ? ((a|7)^2)%2 + ((a|7)^3)%2 : 0;
```
The modulo operator preserves sign, but it may well produce a zero (including negative zero), so we ensure we have both an odd and even value for it to check (even without knowing if we are using ones complement). Arithmetic operations may overflow, but bitwise will not, and by ensuring there are bits both set and cleared we avoid inadvertently converting our number into negative zero or a trap value. The fact that two operations are required to do so oddly should not matter, because the possible trap representation doesn't cause undefined behaviour until put in an lvalue. Doing the operation with bit 0 toggled ensures we get exactly one non-zero remainder. Armed with the knowledge of both signs, we can decide how to proceed with the comparison.
```
char result="\0<<>=<>>\0"[4+3*sign_a+sign_b]
if (!result) { // signs matching means subtraction won't overflow
int diff=a-b;
int sign_diff=diff ? (diff|7^2)%2 + (diff|7^3)%2 : 0;
result = ">=<"[1-sign_diff];
}
```
This method may be one of a few that permit extracting the sign of an integer negative zero. We solve that by explicitly checking for zero. If we were golfing for real, we could of course allow the comparison of two zeros to also perform the subtraction.
[Answer]
## C 80 chars
```
a,b,c=1<<31;main(){scanf("%d%d",&a,&b);putchar(a^b?(a&c^b&c?a:a-b)&c?60:62:61);}
```
It prints '<', '>' or '=', as it should.
## C 63 chars
A new approach:
```
a;main(b){scanf("%d%d",&a,&b);putchar(50+(0L+a-b>>42)+!(a-b));}
```
Prints '1', '2' or '3'.
] |
[Question]
[
Discussion in courtrooms often occurs at a high speed and needs to be accurately transcribed in case the text of the decision is needed in future cases. For this purpose, the stenographers who transcribe court discussions use specially designed keyboards with a small set of buttons, which are pressed in groups to spell out words with a single motion. For this challenge, you will write a program that does something quite similar.
## The Challenge
Given a list composed of sequences of three letters, as well as another list of dictionary words, return the shortest word containing all of them in sequence without overlaps. If there are multiple shortest words, you may return any of them. Your program may accept the dictionary and letter sequences in any format conforming to [the I/O rules](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
## Examples
```
[dic, ion, ary]: dictionary
[tra, scr, ber]: transcriber
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins!
*The dictionary used to check answers should be [the SCOWL word list](http://wordlist.aspell.net/), usually available as `/usr/share/dict/words` on Debian GNU/Linux systems.*
[Answer]
# [Ruby](https://www.ruby-lang.org/), 40 bytes
-1 byte thanks to [Dingus](https://codegolf.stackexchange.com/users/92901/dingus)
```
->d,a{d.grep(/#{a*".*"}/).min_by &:size}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY9BasMwEEX3OcWg0pIGx9mWQrLMJYwIY2vsDMSyGUkUN-Qk2ZiSHKrrXqSSXcimq_8f82aErjcJ5TB-7bf34Ov12_dyvTMZnk3eCPXLzdMZVypfqcvmNW_ZHsoBXt4df9Llz_8xXHnuLMoAWygUtsGRykCVgk3KqjM0Z3BsU3tsTCTk4mBya2z5xCipN92pTnkMPkVLNi2l2gtVZCInEEIz3fFHFufnKmhdJVySKL1Y9LAvHm9m8PxRRAOiAdHQ-j8hIkSEyFrPXx3HOX8B)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ñÊfèVq*i.
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=8cpm6FZxKmku&input=WyJkaWN0aW9uYXJ5IiwidHJhbnNjcmliZXIiXQpbImRpYyIsImlvbiIsImFyeSJd)
```
ñÊfèVq*i. :Implicit input of arrays U=dictionary & V=substrings
ñ :Sort U by
Ê : Length
f :Filter by
è : Count occurrences of
Vq : Join V with
*i. : "*" prepended with "."
:Implicit output of first element
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~76~~ 75 bytes
*-1 bytes thanks to @m90*
```
lambda x,d:min(filter(re.compile('.*'.join(x)).search,d),key=len)
import re
```
[Try it online!](https://tio.run/##TY69DsIwDIR3nqKbExRlYUFIfRLoEBpXNeRPbiTapw/mRwgPPt93N7hsdc7pcCzcpv7SgotX77rV@FOkpCYKFVkx2jHHQgEV2D3YW5Zs1dou6HicjdfmjlsfMOkdxZK5doytMKWqJnUGTyMYoJxkO95gMG9WhbysgcqIIj9GuIhldP5LReSXgCzHI7P/L2@fgUHr9gQ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [J-uby](https://github.com/cyoce/J-uby), 45 bytes
Port of [my Ruby answer](https://codegolf.stackexchange.com/a/252939/11261). Unfortunately lost a few bytes by having to call `Regexp.new` manually instead of using a Regexp literal and interpolation.
```
(:grep|:min_by+:+@)%(~:*&".*"|~(:new&Regexp))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bY9LCsIwFEXnruIRUFp_YwkIjlyA0xIkbV9rxKblJUEL4kacFMFFOXYjJq3gxNG5h9ybkPvzuHdp2z2266ezxWL1WkS8JGyuvFJ6n7YzPtvE4-jGpxO2nLLrLeIaz5Mdlnhp4vg7eucqs6rWklpYQ8Jk5QyyObCUZBmY1TkOdEbpkH6L3giNP-i7hazUSUkKuaxPReDB2YAKdRiF2BBmmHsPQijz_h57UGTsEElqk5FKkZgYjRrYJr835zA-J74BvgG-IcS_glfwCt6FGL7adQM_)
## Explanation
```
( :grep | :min_by + :+@ ) % (~:* & ".*" | ~(:new & Regexp))
(~:* & ".*" | ~(:new & Regexp)) # Construct regexp by joining array with ".*"
( :grep | # Search dictionary with it, then
:min_by + :+@ ) # Get the smallest of the results by length
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), ~~82~~79 bytes
```
d=>x=>d.filter(w=>RegExp(x.join`.*`).test(w)).sort((a,b)=>a.length-b.length)[0]
```
[Try it online!](https://tio.run/##TY47DoMwEET7nCJytRuBlTKN3eUCaRESCxjiCBlkVnxO79hRIlK9N6Mp5kULzY23E@fLLbS2YTs68rsqxBFEJtiTS7va@JgiG@pNMoqbHx0Nfzrsojx1KrRKb0q3srMDGw@r0g/T37cJNvkaravkpULJZmZYEeU8egagrEalSQ7G9fzM669gcS3D5K1j6OD4h/B5K7KziEVCOl0ihjc "JavaScript (V8) – Try It Online")
```
d=>x=>d.filter(w=>RegExp(x.join`.*`).test(w)).sort((a,b)=>a.length-b.length)[0]
d=> // given a dictionary d
x=> // and (via currying) a list of three letter sequences x,
d.filter(w=>RegExp( ).test(w)) // keep only the words from the dictionary which match
x.join`.*` // a regular expression formed by joining each 3 character sequence with ".*" (explained later)
.sort((a,b)=>a.length-b.length) // sort the newly filtered dictionary by length
[0] // and return the first word (should be the shortest)
// Generated regex, using x=["tra", "scr", "ber"] as an example
/tra.*scr.*ber/
tra // the first sequence of letters that needs to occur in the word anywhere
.* // any amount of intermediate characters (including 0)
scr // the second sequence that needs to occur
.* // 0 or more intermediate characters again
ber // the final sequence of characters that needs to occur
```
Might be possible to do this shorter with a reduce, but it escapes me. Maybe `eval` could make the regex shorter, but I don't see it.
LMK if there's a better way to format the TIO page, but I don't know how to import the big dictionary linked in the question. I'll probably make one with a bunch of test cases so you don't have to do your own.
I'm not worried so much though cause this should be theoretically correct assuming there's no weird edge cases :P
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 33 bytes
```
0G`
,
.$*
~)`^
G`
0A`
N$`
$.&
0G`
```
[Try it online!](https://tio.run/##XU67CsIwFN3vV1xKMChtoiBOpeigbgp@gDRNUxqoTUhS7OSvx@Ag4njepxG@j1a5AQurkMrePCzqDpXpKJYl0uP1RLFi0rSKORXi@lxDDoys4LWs75DQ@lDDhdRA2AKSGlMCVCrCqkKmRzsFFrQBKQLyyTvue@EUb7UM/Glc6/983NjA05IexYYPepzmYt5t@e3D4PcIZmSfYfmTjMGJ3EuXN8q9AQ "Retina – Try It Online") Takes a list of sequences on the first line followed by the dictionary but link includes bash wrapper that automatically appends `/usr/share/dict/words` to the input for you (does make the script slow though). Explanation:
```
0G`
```
Get just the list of sequences.
```
,
.$*
```
Replace the commas with `.*` (`*` is the string repetition operator in Retina 1, so it needs to be escaped.)
```
^
G`
```
Prefix `G``.
```
~)`
```
Execute the result as Retina code on the original input.
```
0A`
```
Delete the list of sequences, which obviously matched itself.
```
N$`
$.&
```
Sort in ascending order of length.
```
0G`
```
Keep only the shortest word.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
'?‛.*jr;Þg
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCInP+KAmy4qanI7w55nIiwiIiwiXCJkaWN0aW9uYXJ5XCIsIFwiZGljdG9uYXJ5XCIsIFwiZGljdGlvbmFyeXR3b1wiLCBcInRocmVlZGljdGlvbmFyeVwiLCBcInhcIlxuXCJkaWNcIiwgXCJpb25cIiwgXCJhcnlcIiJd)
Takes in the dictionary and the partial transcription as lists.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~23~~ ~~22~~ 20 bytes
*-3 bytes thanks to @DLosc*
```
{@(aJ`.*`N_FIbSK#_)}
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCJZIiwie0AoYUpgLipgTl9GSWJTSyNfKX0iLCIoeVtcImRpY1wiIFwiaW9uXCIgXCJhcnlcIl0gW1wiZGljdGlvbmFyeVwiIFwidHJlZVwiIFwiZGljdGlvbmFyaWVzXCIgXCJyZWFkXCIgXCJkaWN0XCIgXCJmaWxsZXJcIiBcIndvcmRcIiBcImRpY3Rpb25hcnl5eXl5eXlcIl0pIiwiIiwiIl0=)
```
{@(aJ`.*`N_FIbSK#_)} ; First argument = substrings = a
; Second argument = dictionary = b
{ } ; Create a function that...
@( ) ; takes the first element of...
FIb ; b, filtered by if...
N_ ; each element matches...
aJ`.*` ; the regex formed by joining each substring with ".*"...
SK#_ ; and sorted by the length of the word.
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~88~~ 86 bytes
```
for w in `<$1`;{ echo $w>$w;}
wc -m `printf "*%s*" ${@:2}`|sort -n|head -1|tr -d 0-9\
```
[Try it online!](https://tio.run/##RY5BCsIwFAX3nuJR6qYQYt1ppXgQwaZpagKalJ9IkKZnj3Hl7g08mBmF11k9SC2oJiOTcTYJ@qRAInlJaVRUgb89ca8FKV4@gUdHk0ePH9xn81R5doQIYzFc6nboViipHerY17HbdlGCvTAsZGyYUTV731So1@v5uA3JOwpgNmklJrC2mMEmHNjphpzzX1EWSh1K3Rc "Bash – Try It Online")
First argument is dictionary file.
The followings are the three squence letters.
For each word in dict generate a file containing the word itself.
`printf "*%s*" ${@:2}` generates the pattern `**$2**$3**$4**...` with the rest of the arguments. This pattern is used as a glob tu select files and count word length. `wc -m` otuputs length and filenames so `sort -n|head -1|tr -d 0-9\` so sorts by length, gets first and deletes numbers and space.
Note: If your dictionary file is too large your filesystem has to handle such number of files on same directory (that's why is trimmed down in TIO).
[Answer]
# [Perl 5](https://www.perl.org/) (`-ap`), ~~58~~, 51 bytes
7 bytes saved thanks to Xcali
```
$"=".*";$_=(sort{$a=~y///c-length$b}grep/@F/,@_)[0]
```
[Try it online!](https://tio.run/##DcxBCoMwEEDRfU8RQhZt0U43XdkUV@IdSgkxDiqICTMpRcQevWm2n8cPSPMtbT7gIpq2kPBmAh4tIfSTi/Dx1LOsaqPvTfuo3OwZM9yTklpezrJSRh/ZU9yU1d8VAFw54zLEUXX7QBigbqCozel5faWUl2Lyi7C0HiJZwY5Eh/TzIebMqbThDw "Perl 5 – Try It Online")
[Answer]
# [Thunno](https://github.com/Thunno/Thunno), \$ 22 \log\_{256}(96) \approx \$ 18.11 bytes
```
g".*"z1jAfkD.LZZz:AJAK
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhbb0pX0tJSqDLMc07Jd9HyioqqsHL0cvSGSUDULbkZFK6VkJpdk5uclFlUq6SiAeSgciFRJeT5IoCSjKDUVVUOFUiwX2BAQBygMokBSsRArAA)
#### Explanation
```
g".*"z1jAfkD.LZZz:AJAK # Implicit input
g k # Filter:
j # join
z1 # the second input
".*" # by ".*"
Af # regex test
D.L # Duplicate, length of each
ZZz: # Zip and sort by length
AJAK # Last item of first item
# Implicit output
```
[Answer]
# Python 3, 67 bytes
```
lambda x,d:[e for e in d if re.match(".*?".join(x),e)][0]
import re
```
[Try it online!](https://tio.run/##TYuxjsIwEET7fMVqKxtZDtI1CAnxIUkKE6@VRYltrY2Ar8/5aLgpppj3Jr/rkuLPKcseLuO@uu3mHbyMPw8EIQkQcAQPHEDIbq7Oi0J7uKK9J47qpQ3paThOHW85SW3S/uS6QMoUFfaPIn1ZnFDvea79M4kvaAAFNbgCgVc6d9Dyh@HyGayQ80rbkleuCseIusvCsaqgBmwiGuQUWzt542Q@X/3fqeIaLbO0vpF8nf0X "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 121 bytes
```
MinimalBy[Select[ReadList["/usr/share/dict/words",String],StringMatchQ[#,StringExpression@@Riffle[s,___]]&],StringLength]
```
[Try it online!](https://tio.run/##TU9NSwNBDL37K8IIomVhsEelUAreWtDW2zAscTbbHdidapJFi/jb1xmp1tMj7yMvGVA7GlBjwKl1Uq@jqL9bTJuY4oD96uh21FNQtyVsiuiMHYWtdMhkmxjUvh@4EVPtlGPa@xNuUEP35C5P48PHK5NIPKTlchvbticnVV3X3l/9JtaU9tr56XoGzyQK@S5oxxQ0h2B2cyH0NlIKJLewgE@Tq00FJosFkI/m6/7smf94lLGIErjAC3Hx5C//NnmwFh5zu/6n52d6@gY)
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 82 bytes
```
MinimalBy[Select[d,StringMatchQ[#,StringExpression@@Riffle[s,___]]&],StringLength]
```
[Try it online!](https://tio.run/##dZBBa8MwDIXv/RXCg7GVgFmPK4Uy2K2Frd3NmODZSmNI3E1S2MrYb8/sEtrTTg@h70lP6p202DuJ3o2NCfUmslTAZ7WPq3EbU@xd93Qye@zQiwnVXiimw9aJb1/NzVQ@f38QMsdjWq93sWk6NFzVdW3trZ2QDaaDtHa8m8MbskBeDM2QvGQTzO9njJ8DJo/8ACv4USF6VYHKzSKOTup3eWUWZ0bIlSZ7KvKOVJhsLCOzIzM7dKHcYpQemDS3jlAXQn8dKbCastnlLF9/MeYPXMJY0BpeMiT/IYsrMv4B)
---
Original code is:
```
FindShortestWord[sequences_List, dictionary_List] := Module[
{pattern, matchedWords},
pattern = StringExpression @@ Riffle[sequences, ___];
matchedWords = Select[dictionary, StringMatchQ[#, pattern] &];
MinimalBy[matchedWords, StringLength]
]
(* Load the SCOWL word list *)
scowlWordList = ReadList["/usr/share/dict/words", String];
(* Test the function *)
sequences1 = {"dic", "ion", "ary"};
sequences2 = {"tra", "scr", "ber"};
FindShortestWord[sequences1, scowlWordList]//Print
FindShortestWord[sequences2, scowlWordList]//Print
```
] |
[Question]
[
**This question already has answers here**:
[Mathematical Combination](/questions/1744/mathematical-combination)
(36 answers)
Closed 2 years ago.
Given two inputs, a number n and a dimension d, generate the nth d-dimensional pyramid number.
That was confusing, let me try again.
For d = 1, the numbers start 1,2,3,4,5 and is the number of points in a line n points long.
For d = 2, the numbers start 1,3,6,10,15 and is the number of points in a triangle with side length n, also known as the triangle numbers e.g.
```
0
0 0
0 0 0
0 0 0 0
```
For d=3, the numbers start 1,4,10,20,35 and is the number of points in a pyramid of side n. For d=4, it's a 4-d pyramid, and so on.
Beyond this, visualization gets a bit tricky so you will have to use the fact that the nth d-dimensional pyramid number is equal to the sum of the first n d-1-dimensional pyramid numbers.
For example, the number of dots in a 3-d pyramid of side 5 is the sum of the first 5 triangle numbers: 1+3+6+10+15 = 35.
You can expect reasonable input (within your languages boundaries), although [Standard loopholes apply](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default/1063). No builtins explicitly for this purpose (looking at you, Mathematica)
Numbers are 1-indexed, unless you specify otherwise.
Example recursive code in Javascript:
```
function pyramid(dim,num){ //declare function
if(dim == 0){ //any 0-dimensional is a single point, so return 1
return 1;
} else { //otherwise
function numbersUpTo(x){ //helper function to get the numbers up to x
if(x==0){ //no numbers up to 0
return [];
} else { //otherwise recurse
return [x].concat(numbersUpTo(x-1));
}
}
var upto = numbersUpTo(num).map(function(each){ //for each number up to num
return pyramid(dim-1,each); //replace in array with pyramid(dimension - 1,the number)
});
return upto.reduce((a,b)=>a+b); //get sum of array
}
}
```
This is code-golf, so fewest bytes wins.
[Answer]
# JavaScript (ES6), 24 bytes
Expects `(n)(d)`.
```
n=>g=d=>d?n++/d*g(d-1):1
```
[Try it online!](https://tio.run/##Dco7DsIwDADQvafwGBO3ECh/HA6CGKK6qUDFqVrEgjh76PSW9wyfMDXjY3iXmqTNkbOy71jYy1WtXcqiM1I6PLkc02gEGNwZBC4M9ay1CN8CoEk6pb6t@jR3gpujNW2opi3taE8HOpJb3atXGIwCe4hG0QgiFr/8Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), ~~7~~ 6 bytes [SBCS](https://github.com/abrudz/SBCS)
```
⊢!1-⍨+
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9S1SNFQ91HvCm0A&f=M1VIUzDkMgWSRgA&i=AwA&r=tryAPL&l=apl-dyalog&m=dfn&n=f), [Old version(8 bytes)](https://razetime.github.io/APLgolf/?h=AwA&c=e9S1SF875lHv4kd9Ux/1bgaSAA&f=AwA&i=S@My5TLgSgOShmDSCAA&r=tio&l=apl-dyalog&m=tradfn&n=f)
-1 from rak1507.
A train submission which takes `n` on the left and `d` on the right.
Uses the combination based formula mentioned in the question comments.
1-indexed.
## Explanation
```
⊢!1-⍨+
+ n + d
1-⍨ - 1
! choose
⊢ d
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
+’c
```
[Try it online!](https://tio.run/##y0rNyan8/1/7UcPM5P///5v@NwYA "Jelly – Try It Online")
Accepts `n` as the first argument and `d` as the second argument. Uses the formula $$n+d-1 \choose d$$
## Explanation
```
+’c Main dyadic link
+ Sum
’ Decrement
c Combinations with the right argument
```
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
’çⱮSɗṛ’?
```
[Try it online!](https://tio.run/##y0rNyan8//9Rw8zDyx9tXBd8cvrDnbOBPPv///8b/zcFAA "Jelly – Try It Online")
Accepts `d` as the first argument and `n` as the second argument. Uses the algorithm described in the challenge.
## Explanation
```
’çⱮSɗṛ’? Main dyadic link
? If
’ d-1 ≠ 0
ɗ then (
’ d-1
ç Apply this link
Ɱ with each [1..n] as the right argument
S Sum
ɗ )
ṛ else n
```
For some reason, this does not work with `ß` instead of `ç`. It would be nice if someone explained why.
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
[!<:@+
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/oxVtrBy0/2tyKXClJmfkK2gYamfqmWgqpCkZ6EM4hgaaXP8B "J – Try It Online")
[Answer]
# [Whispers v2](https://github.com/cairdcoinheringaahing/Whispers), ~~52~~ 49 bytes
```
> Input
> Input
>> 1+2
>> ≺3
>> 4C2
>> Output 5
```
[Try it online!](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtO2ykYahuBqEedu4xBtIkzmOtfWgKUVzD9/9@UyxgA "Whispers v2 – Try It Online")
Inputs the numbers from STDIN.
-3 bytes from Michael Chatiskatzi.
If floating point output is not allowed, then [63 bytes.](https://tio.run/##K8/ILC5ILSo2@v/fTsEzr6C0hAtBG3LZAQltIxBlomsMokydwbxHPR1mj3q6QUz/0hKgagXz//9NuYwB "Whispers v2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 41 bytes
```
sub f{($n,$d)=@_;$d?$n/$d*f($n+1,$d-1):1}
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4NEkhrVpDJU9HJUXT1iHeWiXFXiVPXyVFKw0oqG0IFNY11LQyrP2fll@kkFupoJKioGGop2eiWc2loFBQlJlXoqCUYquSYqWgoKBkDRSDqcsDqzM0ACuEK1VQ0lFIg1oHUl2LMCUmD6i/9j8A "Perl 5 – Try It Online") Influenced by Arnaulds javascript answer.
```
$D=$_,print"d=$D: ".join(" ",map f($_,$D), 1..10)."\n" for 1..4;
d=1: 1 2 3 4 5 6 7 8 9 10
d=2: 1 3 6 10 15 21 28 36 45 55
d=3: 1 4 10 20 35 56 84 120 165 220
d=4: 1 5 15 35 70 126 210 330 495 715
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 17 bytes
```
Binomial[##-1,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73ykzLz83MzEnWllZ11BHOVbtf0BRZl6JvkNIYlJOanRadIpOXqxOdYqOea1OdR6QjP0PAA "Wolfram Language (Mathematica) – Try It Online")
The boring answer. Input `[d, n]`.
---
### 29 bytes
```
Nest[Tr@*Array~Curry~2,1&,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCQ6pMhBy7GoKLGyzrm0qKiyzkjHUE1HOVbtf0BRZl6JvkNIYlJOanRadEpsdF6sTnWKjnmtTnUekIz9DwA "Wolfram Language (Mathematica) – Try It Online")
Input `[d][n]`.
Returns the `d`-pyramid function, constructed using the given recursive definition. Call it on `n` for the `n`th `d`-pyramid number.
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
```
0#n=1
d#n=(d-1)#(n+1)*n/d
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/30A5z9aQKwVIaqToGmoqa@RpG2pq5emn/M9NzMxTsFUoKMrMK1FQUTBWNv0PAA "Haskell – Try It Online")
This was my old solution, same idea, but much longer, 37 bytes
```
a%b=product[a+1..b-1]
d#n=d%(n+d)/0%n
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P1E1ybagKD@lNLkkOlHbUE8vSdcwlitFOc82RVUjTztFU99ANe9/bmJmnoKtQkFRZl6JgoqCsbLpfwA "Haskell – Try It Online")
[Answer]
# [Julia](http://julialang.org/), ~~26~~ 22 bytes
```
d>n=d<1||sum(~-d.>1:n)
```
[Try it online!](https://tio.run/##DcExCoAwDADAva/ImAwWM7gUm78IUajUKNWCg/j16t1ac5r4bk3Foo78PGfd8O3UCwejtuwFFJIBh8HB7yjJrmyoEAVQyQty4J7IzabtAw "Julia 1.0 – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 8 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
r+k╒m╠ε*
```
First input \$d\$ as an integer, second input \$n\$ as a float.
Port of [my 05AB1E answer](https://codegolf.stackexchange.com/a/219307/52210).
[Try it online.](https://tio.run/##y00syUjPz0n7/79IO/vR1Em5j6YuOLdV6/9/QwVDPQMuIzBpDCYNFUzBIqZgERBpAiZNwSRQvQFEgwFEhwFYAZgyBVMA)
**Explanation:**
```
r # Push a list in the range [0, first (implicit) input `d`)
+ # Add the second (implicit) input `n` to each: [`n`,`n+1`,...,`n+d-1`]
k # Push the first input `d` again
╒ # Pop and push a list in the range [1,`d`]
m╠ # Divide the values at the same positions from one another:
# [`n/1`,`(n+1)/2`,...,`(n+d-1)/d`]
ε* # Take the product (reduce by multiplying)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~56~~ ~~55~~ 51 bytes
Saved a byte thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!!
Saved 4 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
f=lambda n,d:d<1or sum(f(i+1,d-1)for i in range(n))
```
[Try it online!](https://tio.run/##TY/LjsIwDEX3/Qrvkggj1W0BiSH8CMOiNAmNGELVFglU9ds7DuLlja/vkV/Nva8vIZ8mp//K88GUENCszYYuLXTXs3TSzwjNnJRjx4MP0JbhaGVQarK3xla9NaBBEmaYY4ELJM5LpBQp6iKqLMU8FovosVqlKqlqW51sG3vF7zVbFZVAeCjKhUo8gzSJS81nKU9Q6wQ4IgjfYPkEMTrudZIfUW/LsvU6d@f3Px5mGuiNm9aHXjoxhBFhMCPMtzB0IwzPK3dW624/CjX9Aw "Python 3 – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~7~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
+<Ic
```
\$a(n,d) = {n+d-1\choose d}\$
The inputs are in the order \$n,d\$.
[Try it online](https://tio.run/##yy9OTMpM/f9f28Yz@f9/QwMuEwA) or [verify some more test cases](https://tio.run/##yy9OTMpM/R/i6hcKxC4RSim2h/fr5AEJhUdtkxSU7CP@a9tEJP/X@Q8A).
**Previous 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) answers:**
```
L©<+®/P
```
The inputs are in the order \$d,n\$ and the output is a float.
[Try it online](https://tio.run/##yy9OTMpM/f/f59BKG@1D6/QD/v834TI0AAA) or [verify some more test cases](https://tio.run/##yy9OTMpM/R/i6hcKxC4RSim2h/fr5AEJhUdtkxSU7CP@@xxaaaN9aJ1@wH@d/wA).
*Equal-bytes alternative by porting* [@Razetime*'s APL answer*](https://codegolf.stackexchange.com/a/219304/52210)*:*
```
LIGηO}θ
```
The inputs are in the order \$n,d\$.
[Try it online](https://tio.run/##yy9OTMpM/f/fx9P93Hb/2HM7/v83NOAyAQA) or [verify some more test cases](https://tio.run/##yy9OTMpM/R/i6hcKxC4RSim2h/fr5AEJhUdtkxSU7P/7RLif2@5fe27Hf53/AA).
**Explanation:**
```
+ # Add the two (implicit) inputs together
< # Decrease it by 1
I # Push the second input `d`
c # Get the number of combinations / the binomial coefficient: `n+d-1` choose `d`
# (after which it is output implicitly as result)
L # Push a list in the range [1, first (implicit) input `d`]
© # Store it in variable `®` (without popping)
< # Decrease each by 1 to make the range [0,`d`)
+ # Add the second (implicit) input-integer `n` to each: [`n`,`n+1`,...,`n+d-1`]
® # Push list [1,`d`] from variable `®` again
/ # Divide the items at the same positions in the two lists:
# [`n/1`,`(n+1)/2`,...,`(n+d-1)/d`]
P # Take the product of this list
# (after which it is output implicitly as result)
L # Push a list in the range [1, first (implicit) input `n`]
IG # Loop the second input `d` - 1 amount of times:
η # Get the prefixes of the current list
O # And sum each prefix together
}θ # After the loop: pop and leave just the last item
# (after which it is output implicitly as result)
```
[Answer]
# [Haskell](https://www.haskell.org/), 44 39 bytes
```
d#n=sum$iterate(scanl(+)0)[1..n]!!(d-1)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P0U5z7a4NFclsyS1KLEkVaM4OTEvR0Nb00Az2lBPLy9WUVEjRddQ839uYmaegq1CQVFmXomCioKxssl/AA "Haskell – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), ~~63~~ 58 bytes
```
|n,d|(n..=n+d-1).product::<u32>()/(1..=d).product::<u32>()
```
[Try it online!](https://tio.run/##ZclLDkAwEADQNacYXU2jKohNfe4iSiJhNNWu6NnL3ts@6y8X40pwTBshhztN9sWBgQEeEvpBknKgXBcVl8ae2s9Oqd439Yi8xOpL/Y8uTYzdyO2UIbsDE2CwFdDwb0KMLw "Rust – Try It Online") (with calling code)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~36~~ 35 bytes
*-1 byte thanks to att!*
```
Last@Nest[Accumulate,1~Table~#,#2]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73yexuMTBL7W4JNoxObk0tzQnsSRVx7AuJDEpJ7VOWUfZKFbtf0BRZl5JtEJatKmOcaxC7H8A)
Just to prove that Mathematica can do things without builtins! One nice thing about this function is that it calculates the pyramidal numbers exactly according to the definition, by summing (using `Accumulate`) over pyramidal numbers of one dimension less (hence recursively starting from the 0-dimensional pyramidal numbers, here generated as an array of `1`s of the correct length, using `1&~Array~#`).
[Answer]
# [Python 3](https://docs.python.org/3/), 33 bytes
```
f=lambda n,d:d<1or n/d*f(n+1,d-1)
```
[Try it online!](https://tio.run/##TY7NbsJADITveQrfNluMiPMDEu32RSiHNN6UVVsTJUECRXn21FtRVF88nk/WTHcbT2cplqV1X/X3O9cgyHt@oXMPsuGnNpUVIa/JLv7a@Wb0DA5SwhwLLLFC0r1FypCiLqPKMyziUUVP1S6zSXPyzafv4695u@S7sjEIv4oKY5OgIEtaDWUIAn0tH15DKrtPQCcC@Q@2dxBn0F@tiWwfllfrr@4hHJ8DrBzQA3d9kDFtzSQzwsQzrF9hGmaY7i0P3rnhOBu7/AA "Python 3 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~33~~ 28 bytes
```
function(n,d)choose(n+d-1,d)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jTydFMzkjP784VSNPO0XXEMj9n5ZfpJGikJmnYGhlqqlQUJSZV6JRnFhQkFOpARTRSQOq0fwPAA "R – Try It Online")
5 bytes saved by Dominic van Essen.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
→!¡∫ḣ
```
[Try it online!](https://tio.run/##ARgA5/9odXNr///ihpIhwqHiiKvhuKP///81/zI "Husk – Try It Online")
Same idea as my APL answer. Takes n and k, both 1 indexed, as command line args.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 48 bytes
```
int f(int n,int d){return d<1?1:f(n+1,d-1)*n/d;}
```
[Try it online!](https://tio.run/##VVDbbsIwDH3fV1iVKiWrYQQokygVX7AnHhEPHU6ncnFRE9imqt/eOd09So4dH8s5J4fiVowOdOz3p8I5eCoqbvuKPZQqIGNA0m1j/bVhoJVZm2WpODFII6Pv@YGyrge4XJ9P1R6cL7yEW10RnGWW2vim4pftDgrd3oEsmSc3@3axe28JcmD7@llsDU5xhnNM0UhcoJmgCfk8ZNMJzsIlDTXJHiddNgws6wYGrZSbTASmAkmiB@4Py4Hl1UJAWGi/@EEQuDyoCOaVHos7JJ39a7D5t@KtGnynCY/M7rdp8@68PY/rqx9fxLEvVVSqmDAmLR5jAohdzBHKjwIhONl5bmENUX2MlhBx7UGyn2e7u3C6/gM "Java (JDK) – Try It Online")
[Answer]
# [Groovy](http://groovy-lang.org/), 27 bytes
```
f={n,d->d?f(n+1,d-1)*n/d:1}
```
[Try it online!](https://tio.run/##PY7RasMwDEXf@xUXg8Fe1S5ukw0KXj8k5GmyRxnIJQmlo/TbM7lsBYOOjox0v8ZSLj8Lp4y85HgT4s0HH7OTdVAM/kVe@RDuy0nmfkC6ntPnnBgRfaAd7amljoLWNwoNhcptpV1D@9p01Sm9N8MqlxFO94BxEoTttvUr4Gnlz3YeN/VAlVPUKMT@KVL8z9C7R75uLZswPObnUX9kZ7KzTJa9prQM2MmKIQiBCZO@GBOOMOXbHGCkzFCqF@7LLw "Groovy – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~18~~ 13 bytes
```
≔…¹NθI÷Π⁺NθΠθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU8jKDEvPVXDUEfBM6@gtMSvNDcptUhDU1NHoVDTmiugKDOvRMM5sbhEwzOvxCWzLDMlVSOgKD@lNLlEIyCntFgDRRdIk44CTL5QEwis//83VTD@r1uWAwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Now inspired by @KevinCruijssen's 05AB1E answer.
```
≔…¹Nθ
```
Input `n` and generate an exclusive range from `1` to `n`.
```
I÷Π⁺NθΠθ
```
Input `d` and vectorised add it to the range, then divide the product of that range by the product of the original range.
] |
[Question]
[
## Challenge
Given a number `x` and a precision `e`, find the lowest positive integer `q` such that `x` can be approximated as a fraction `p / q` within precision `e`.
In other words, find the lowest positive integer `q` such that there exists an integer `p` such that `abs(x - p/q) < e`.
## Input
* The pair `(x, e)` where `x` is a floating-point number, and `e` is a positive floating-point number.
* **Alternatively**, a pair `(x, n)` where `n` is a nonnegative integer; then `e` is implicitly defined as `10**(-n)` or `2**(-n)`, meaning `n` is the precision in number of digits/bits.
Restricting `x` to positive floating-point is acceptable.
## Output
The denominator `q`, which is a positive integer.
## Test cases
* Whenever `e > 0.5` ------------------------> `1` because `x` ≈ an integer
* Whenever `x` is an integer ----------------> `1` because `x` ≈ itself
* `(3.141592653589793, 0.2)` ------------> `1` because `x` ≈ 3
* `(3.141592653589793, 0.0015)` --------> `7` because `x` ≈ 22/7
* `(3.141592653589793, 0.0000003)` ---> `113` because `x` ≈ 355/113
* `(0.41, 0.01)` -------------------------------> `12` for 5/12 or `5` for 2/5, see Rules below
## Rules
* This is code-golf, the shortest code wins!
* Although the input is "a pair", how to encode a pair is unspecified
* The type used for `x` must allow a reasonable precision
* Floating-point precision errors can be ignored as long as the algorithm is correct. For instance, the output for `(0.41, 0.01)` should be `12` for 5/12, but the output `5` is acceptable because 0.41-2/5 gives 0.009999999999999953
## Related challenges
* [Find the simplest value between two values](https://codegolf.stackexchange.com/questions/38425/find-the-simplest-value-between-two-values)
* [Closest fraction](https://codegolf.stackexchange.com/questions/26278/closest-fraction)
* [Convert a decimal to a fraction, approximately](https://codegolf.stackexchange.com/questions/221196/convert-a-decimal-to-a-fraction-approximately)
[Answer]
# [R](https://www.r-project.org/), Xx bytes
*Note: this challenge is quite a good introductory-challenge for [R](https://www.r-project.org/), which is the 'language-of-the-month' for September 2020, so I've blanked-out my answer in the hope of encouraging some other golfers to have a shot at it in [R](https://www.r-project.org/), too...*
>
> 50 bytes
>
>
>
>
> `function(x,e,s=1:e^-1)s[(x-round(x*s)/s)^2<e^2][1]`
>
>
>
[Try it online!](https://tio.run/##bc9NDoIwEAXgvaeYxE1rClh@gho5CYEEpWJjaE1bhCPoNb1IJagJCrP83rxJRtmSCVlzURipEntqxNFwKVBHGNEJ3bHcoVinqHOUbESJupXGnsa5v2e5n6U0G/fRlROKYQl0MdaAuNFU53d7ddeDx1Pv512hwWz4if2QxhH0Cs/HHeJoG268wfBPy/m/Cej7PrRSXTS03JxBsKow/MZANPWBKU3ASImtfQE "R – Try It Online")
Function with arguments x & error e. Can handle negative x (even though not required for challenge)
---
*Note 2: dammit! a port of [xnor's approach](https://codegolf.stackexchange.com/questions/210572/diophantine-approximation-find-lowest-possible-denominator-to-approximate-withi/210595#210595) is 6 bytes shorter still:*
>
> 44 bytes
>
>
>
>
> `function(x,e,s=1:e^-1)s[(x+e)%%(1/s)<2*e][1]`
>
>
>
[Try it online!](https://tio.run/##bc/hCoIwEAfw7z3FQQhbTd0U0SKfRAysVo1wCzfTR6jX7EVsGJKh9/F397/jqu7EpSqFLIyq0u5cy6MRSqKWcKJTtuV7l2GdoXbNseMg5mu8C1Y8z1g@TqK7IAzDEthirCHxoqnOz1r1aO/x1G19IyycbQ79MKBJBJbh/XoCozTeJH6P@C/n/q7ZlYCGv6FR1U1DI8wVJL8URjw4yLo88EoTMErhrvsA "R – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~13~~ 9 bytes
```
∞.Δ*`Dòα›
```
[Try it online!](https://tio.run/##yy9OTMpM/f//Ucc8vXNTtBJcDm86t/FRw67//6MN9AwMDE11jPUMTQxNLY3MTI1NLSzNLY1jAQ "05AB1E – Try It Online")
**Commented:**
```
# implicit input [e, x]
∞ # in the list of natural numbers
.Δ # find the first that satisfies: [e, x], q
* # multiply [e*q, x*q]
` # dump on stack e*q, x*q
D # duplicate e*q, x*q, x*q
ò # round to integer e*q, x*q, round(x*q)
α # absolute difference e*q, abs(x*q - round(x*q))
› # is this larger? e*q > abs(x*q - round(x*q))
```
[Answer]
# [Python](https://docs.python.org/3/), 46 bytes
```
f=lambda x,e,q=1:(x+e)%(1/q)<e*2or-~f(x,e,q+1)
```
[Try it online!](https://tio.run/##fZDRSsMwFIbv@xQHRJJs2doky2qH9UXUi26e6GBrtzSDSqnX@pq@SE0C3m09EEg4/8cfvtOn@2hqNY6mPFTH7VsFHUd@LsWGdnNk91SkZ/aIM9nYxZehcTkXbHTYuhZKoAn4oVQtxUroQq610g9FXigO2VIzDsKfO9jirrq0CB38/nxDVcO@dviO9p8OaXEjvXctHsxUj7xBqikoy0T4X36FkzLNp9EwKrQKda1X69RvEpbYoIi8XGS@2hEO8SYUYYlpLDiO3gNElZvYF4waOnMsvk7WW6KG9G6AxRP07QC9ffaZEvB1IGz8Aw "Python 3 – Try It Online")
We want to check that \$x\$ is within \$\pm \epsilon\$ of a multiple of \$1/q\$, that is, it falls within the interval \$(-\epsilon,\epsilon)\$ modulo \$1/q\$. To do this, we take \$x+\epsilon\$, reduce it modulo \$1/q\$, and check if the result is at most \$2 \epsilon\$.
A same-length alternative using only `%1`, which might help with porting:
```
f=lambda x,e,q=1:(x+e)*q%1<e*q*2or-~f(x,e,q+1)
```
[Try it online!](https://tio.run/##fZDRSsMwFIbv@xQHRJp02dYki7XD@iLqRTdPdDDbNcmgUuq1vqYvUpOAd1sPBBLO//GH7/Tp3ttGTpOujvXH7rWGniHrKr4l/QJp1t3yB8y6TLRm@aVJXC44nRxaZ6ECkoAfQuSKb7gqxZ2S6r4sSskgXynKgPtzAzvc12eL0MPvzzfUDRwah29o/umQ5lfSB2fxqOd6xBVSzkF5zsP/igucEOtiHg0jQyuXl3qVWvtNQhMTFKXPZ1Fs9imDeOMypYluDTiG3gNEldvYF4xqkjkaXyfjLRGdDm6E5SMMdoTBPPlMBfgypnT6Aw "Python 3 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
```
Denominator@*Rationalize
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773yU1Lz83My@xJL/IQSsIKJyfl5iTWZX6P6AoM69EwSE92ljP0MTQ1NLIzNTY1MLS3NJYR8FAzyiWC78CAwNDU8JqQMA49v9/AA "Wolfram Language (Mathematica) – Try It Online")
All the credits go to @the default
[Answer]
# [Python 3](https://docs.python.org/3/), ~~74~~ \$\cdots\$ ~~52~~ 50 bytes
Saved ~~a~~ ~~4~~ 6 bytes thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs)!!!
```
f=lambda x,e,q=1:not-x*q%1>e*q<x*q%1or-~f(x,e,q+1)
```
[Try it online!](https://tio.run/##fZDRasMgFIbv8xQHxlBT00aty1KWvsi2i7TTtdAljVrICNn19pp7kUyF3bU5IBzx//jlO3@6Q9uIadLVqf7YvdXQU0W7im2a1mV92t2zrUq7p7i1JvvSOAYWjExOWWehApyAH4zFkq2ZLPmDFPKxLEpBIV9KQoH5cwc7ta8vVkEPvz/fUDdwbJx6V@afDml2I310Vp30XA@/QYo5KM9Z@F9xheN8VcyjYURoZeJar5Qr/5KQxARF6OXCi/UeUYgbE4gkujXgqPIeIKrcxL5gVOPUkXg7G28JazS4EbItDHaEwTz7TAXqdURk@gM "Python 3 – Try It Online")
[Answer]
# JavaScript (ES7), 38 bytes
Expects `(x)(e)`.
A port of [@xnor's method](https://codegolf.stackexchange.com/a/210595/58563), which is significantly shorter than my original approach.
```
(x,q=0)=>g=e=>(x+e)%(1/++q)<e*2?q:g(e)
```
[Try it online!](https://tio.run/##jc1BDsIgEIXhvfcwmRFFGIqKkXqWpk5JTVPEGtPboyyNm77t9yfv3rybqX32j9dujDfOnc8wb5NX6Ovg2dcwC8Y16L0QCS@8oWs6B2DMbRynOLAcYoAOSJFCUFIpjbj6NU3SVAXtHxmpK20dHayxJ3d0pmS0LPte2aVlmUHMHw "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES7), 46 bytes
Expects `(x)(e)`.
```
(x,q=0)=>g=e=>((x*++q+.5|0)/q-x)**2<e*e?q:g(e)
```
[Try it online!](https://tio.run/##jc1BDsIgEIXhvSeZAYsDFBUj9SxNpY1NU8Qaw8K7oyyNm77t9ydvbF/t0j1u92c1h6vPvcuQttERumZw3jUAiXEeuTBvwl2sEjKmzp75SzwN4DF3YV7C5MUUBuhBkSIEEkQScfNrUgldFzR/pIWspbFqb7Q52oPVJVPrsu@VWVuWacT8AQ "JavaScript (Node.js) – Try It Online")
We want to avoid using the lengthy `Math.round()` and `Math.abs()`. So we look for the lowest \$q>0\$ such that:
$$\left(\frac{\left\lfloor xq+\frac{1}{2}\right\rfloor}{q}-x\right)^2<e^2$$
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~63~~ ~~59~~ 58 bytes
Saved a byte using [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s idea in his [Python answer](https://codegolf.stackexchange.com/a/210595/9481)!!!
```
i;f(x,e,q)float x,e,q;{for(q=0;fmod(x+e,1/++q)>2*e;);i=q;}
```
[Try it online!](https://tio.run/##jZLfaoMwFMbv@xQHQUhqtEZrO8nszdhTrGWInnRCq/XPRZj46nPR6jq6XkxiSD5/3/mSg4l9TJK@z4QkiiErqTwVcQPjWrSyqEgZuUKei5QoCxlfWVZJd94SBRVZVIquz/IGznGWE7poF6Cfa4UG6@ZdvR0g0lLrO3zNg9DbBH7wFG5Dn8EwHqj/klxnzTtxn4ZzmutsBoYPkzdMrssDXQhtdztuZ/NwdlQXVA2ms1m7rkOjnOuwYIKTj7haQjVyrbFXr95ehS/6DQwGv/e@oR3XwxUVkCEky1NU2ueKafkMdfaJhSRzPF1NwvJHEWBZI03h2tnbfYdaU4dH4iDuAJwB/ANMl9bAz9UfIbUGxp@C3vRLpb9IYhBTMjAdDynYOzBTMOt9rrugGCCDmukujQkR1IfJ3i26/iuRp/hY9/bp/A0 "C (gcc) – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~17~~ 5 bytes
```
2$YQ&
```
[Try it online!](https://tio.run/##y00syfn/30glMlDt/39jPUMTQ1NLIzNTY1MLS3NLYy4DPQMwMAYA) Or [verify all test cases](https://tio.run/##y00syfmf8N9IJTJQ7X@ES1RFyH9jPUMTQ1NLIzNTY1MLS3NLYy4DPVMDQy4TIyDDAAqMuLApwy5qYGBoikMCBIwB).
### Explanation
```
2$ % The next function will take two inputs
YQ % (Implicit inputs: x, e). Rational approximation with specified tolerance.
% Gives two outputs: numerator and denominator
& % The next function will use its alternative default input/output
% configuration
% (Implicit) Display. With the alternative specification, this displays
% only the top of the stack, that is, the denominator
```
## Manual approach: 17 bytes
```
`GZ}1\@:q@/-|>~}@
```
[Try it online!](https://tio.run/##y00syfn/P8E9qtYwxsGq0EFft8aurtbh//9oAz0DMDDWUTDWMzQxNLU0MjM1NrWwNLc0jgUA) Or [verify all test cases](https://tio.run/##y00syfmf8D/BParWMMbBqtBBX7fGrq7W4X@sS1RFyP9oAz1TA0MdBWM9QxNDU0sjM1NjUwtLc0vjWC6glAEUGOkomBiBRYxwKzU0xW@MMTZpAA).
### Explanation
```
` % Do...while
GZ} % Push input: array [e, x]. Split into e and x
1\ % Modulo 1: gives fractional part of x (*)
@:q % Push [0, 1, ... , n-1], where n is iteration index
@/ % Divide by n, element-wise: gives [0, 1/n, ..., (n-1)/n]
-| % Absolute difference between (*) and each entry of the above
>~ % Is e not greater than each absolute difference? (**)
} % Finally (execute on loop exit)
@ % Push current iteration index. This is the output
% End (implicit). A new iteration is run if all entries of (**) are true;
% that is, if all absolute differences were greater than or equal to e
% Display (implicit)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 27 bytes
```
NθNη≔¹ζW›↔⁻∕⌊⁺·⁵×θζζθη≦⊕ζIζ
```
[Try it online!](https://tio.run/##TY1BDoIwEEX3nKLLaYIExKqEFdFoWGBYeIEKE2lSCrQFEy9fS3ThZjLv58@8puO6Gbh0rlTjbG9z/0ANE82Df@48F8aIp4IkJG9Pr05IJHDVyK0vFA8zyNkiVELNBs5iES3CRQ6Dhlr6JI5YSO6iRwPT@oHSdYZkWpeOUlLx8WcoVaOxR2Wx/bpqLZSFEzcW/GHuXBolu4Rl2z1L2TE7ZGkQR3GcMLdZ5Ac "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input \$ x \$ and \$ \epsilon \$.
```
≔¹ζ
```
Start off with \$ q = 1 \$.
```
W›↔⁻∕⌊⁺·⁵×θζζθη
```
Calculate \$ p = \lfloor 0.5 + q z \rfloor \$ and repeat while \$ | \frac p q - x | > \epsilon \$...
```
≦⊕ζ
```
... increment \$ q \$.
```
Iζ
```
Output \$ q \$.
[Answer]
# [Scala](http://www.scala-lang.org/), ~~84~~ ~~60~~ 52 bytes
*Saved a whopping 24 bytes thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)!*
```
x=>e=>1 to 9<<30 find(q=>(x-(x*q+.5).floor/q).abs<e)
```
[Try it online!](https://tio.run/##jY69CsIwHMR3n@I/JooxaRq10hQEFwfxAcQhbVOohKQfUQris9eqi530puPux3FtpozqXXrRmYeDKi3ozmubt7CtKrhPbspAsYGdu6ZGg0y@3LHypbOnvfVnkH0nEy0TBt5BFMecQlHaHNUyQd0cddN6RgQmhXGuWdSYqLSNNe6rprTeWFQgTljIRBQsBRfraBVxjCgJMJ78QChl4h/qJT4CKQnZu2OjmA0/P7tD/Oif "Scala – Try It Online")
[Answer]
# Wolfram Language 89 bytes
```
f[n_,e_]:=Denominator@Cases[{#,Abs[n-#]}&/@Convergents@n,x_/;x[[2]]<=e][[1,1]]
```
---
```
f[0.41,.01]
(* 5. *)
```
This uses the convergents as candidates for approximations.
```
pi = 3.1415926535897932384626433832795028842
```
The first 8 convergents of pi:
```
Convergents[pi, 8]
(* {3, 22/7, 333/106, 355/113, 103993/33102, 104348/33215, 208341/66317, 312689/99532}*)
f[pi, 0.01]
(* 7 *)
f[pi, 0.001]
(* 106 *)
f[pi, 0.00001]
(* 113 *)
f[pi, 0.0000001]
(* 33102 *)
f[pi, 0.0000000001]
(* 99532 *)
```
[Answer]
# [Java (JDK)](http://jdk.java.net/), 52 bytes
Port of [xnor’s method](https://codegolf.stackexchange.com/a/210595/95792)
```
x->e->{int q=0;for(;(x+e)%(1./++q)>=e*2;);return q;}
```
[Try it online!](https://tio.run/##pY6xTsMwEIb3PIUXJJuSI04aIDLJhJAYmDoiBpM6kUNqJ86lahXl2YMrdYCpCG65k/77Pv2N3Muw2X4uZSuHgbxKbaagGz9aXZIBJfq1t3pLdj6gG3Ta1G/vRLp6YGQKGk/DiLqFajQlamvg@Xw8PllvUTfkNz8vBlWtXFGQylqSL4ewUGExaYOkzyNRWUcFPawUu6IcblernhW5uo4FE07h6AzpxbyIYHMcUO3Ajgidb4qtod4HsuvaI02Ar3maxXdpkj5k91nCzkEEMWN/h6OIp//jT5NcVESw5t8ofhHgkP5oeQLmYF6@AA "Java (JDK) – Try It Online")
# [Java (JDK)](http://jdk.java.net/), ~~83~~ 69 bytes
```
x->e->{int q=0;for(;Math.abs(x-Math.ceil(x*++q-.5)/q)>=e;);return q;}
```
[Try it online!](https://tio.run/##pZAxb4MwEIV3foVHuykuDqEtojBVlTpkylh1cIihpo4N9hERIX47daoM2RK1t9xJ7753T9fwAw@b3fdcKu4cWnOpx6Dtt0qWyAEH3w5G7tDeC3gDVur64xNxWzuCxqDxNO1BKlr1ugRpNH07Dy@vxruIe3TLzrsGUQtbFKgyBuXzEBYiLEapAXV5lFXG4mzN4YvyrcND@DuWQio83C0WXUgT8tCRIhcZyayA3mrUZdOcBZujA7Gnpgfa@uigNPYHKG9bdcQxZSuWpMvHJE6e06c0JmchoktC/g5HEUv@x58qvmoR0RW7oNhVgPk/XaY8AVMwzT8 "Java (JDK) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 58 bytes
```
sub f{grep{$p=$_[0]*$_;abs$p-int$p+.5<$_[1]*$_}1..1/$_[1]}
```
[Try it online!](https://tio.run/##zVRRT8IwEH7nV1xwRqZjrB1lsjniD9A3jQ@EEMAOm@DWrMXMEN71b/pH5rVMSYRXEy7Levf1cndfvraSlytWrxWHO6F0HD9qsYKLTJRKXyQtgz9wg98XJQeNrkpHLKnVeg7ZZllyuXFk6kzHweTSmSazuXJkV@TakVc@u0GcGHxLfJ/0bLSts6LswDj0SZ@wIR2wkF0Po2HoQeBT2Fk6AjLx0DmDOV/MzBQVfH1@QAgnYC37P84gCAhrGERHGVDai06cgbHQakBC5HCgAWM93DkJBoHfJ3ZociQHGbBGA0IBjx3g4BTMeioKEBr22SBqTs7h/D@34OmF5/yNlyiBUDDLAa8YX2Jscv7oI7Tiq@z/GbgbS@L1veNUnsPxq6Sb3uIr8IsvC@2m2W7f3cMizwo3VbJEFlm7Ss@7NFAAHB1inUryhebPGDMMsYr12t6@kWdq7yru36c4Fso2bVJsn6S1rb8B "Perl 5 – Try It Online")
] |
[Question]
[
This is a [restricted-source](/questions/tagged/restricted-source "show questions tagged 'restricted-source'"), [kolmogorov-complexity](/questions/tagged/kolmogorov-complexity "show questions tagged 'kolmogorov-complexity'"), [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge to produce a fixed output with no input.
The output format, however, is flexible - it may be printed to standard out, printed to standard error, returned as a list of characters, returned as a list of bytes, or returned as a list of integers. If you think anything else seems reasonable just ask in the comments!
Here is a simple, big-letter ASCII art **CODEGOLF**:
```
CCCC OOO DDDD EEEEE GGG OOO L FFFFF
C O O D D E G O O L F
C O O D D EEE G GG O O L FFF
C O O D D E G G O O L F
CCCC OOO DDDD EEEEE GGGG OOO LLLLL F
```
Without any newlines (or trailing spaces on any lines) it is 256 characters long:
```
CCCC OOO DDDD EEEEE GGG OOO L FFFFFC O O D D E G O O L FC O O D D EEE G GG O O L FFFC O O D D E G G O O L F CCCC OOO DDDD EEEEE GGGG OOO LLLLL F
```
The (0-based) indices of the non-space characters are:
```
1, 2, 3, 4, 8, 9, 10, 14, 15, 16, 17, 21, 22, 23, 24, 25, 29, 30, 31, 36, 37, 38, 42, 49, 50, 51, 52, 53, 54, 61, 65, 68, 72, 75, 82, 89, 93, 96, 103, 104, 111, 115, 118, 122, 125, 126, 127, 132, 135, 136, 139, 143, 146, 153, 154, 155, 156, 163, 167, 170, 174, 177, 184, 188, 191, 195, 198, 205, 207, 208, 209, 210, 214, 215, 216, 220, 221, 222, 223, 227, 228, 229, 230, 231, 235, 236, 237, 238, 242, 243, 244, 248, 249, 250, 251, 252, 255
```
You **may not use any of these 97 bytes in your code** but must produce a list (or similarly output) these bytes, in this order, with the missing bytes replaced by the 32nd byte in the code page you are using (in many, many code-pages a space character).
You may include the pretty-printing\* newlines (but no trailing spaces on the lines) if it helps.
For example using the [Jelly code-page](https://github.com/DennisMitchell/jellylanguage/wiki/Code-page "Jelly Wiki Page - Git Hub") this output is acceptable:
```
¢£¤¥ ®µ½ ÇÐÑ× ßæçðı øœþ $%& * 12345
6 = A D H K R Y ] ` g
h o s v z }~¶ ⁴ ⁷⁸ ⁻ Ɓ Ƒ ƲȤɓ
ƈ ɲ ʂ ȥ Ẹ Ḳ Ṭ Ỵ Ḃ Ḟ İ Ṡ
ẆẊẎŻ ẹḥị ṇọṛṣ ẉỵẓȧḃ ḟġḣŀ ṗṙṡ ẏż«»‘ ”
```
...but so is:
```
¢£¤¥ ®µ½ ÇÐÑ× ßæçðı øœþ $%& * 123456 = A D H K R Y ] ` gh o s v z }~¶ ⁴ ⁷⁸ ⁻ Ɓ Ƒ ƲȤɓƈ ɲ ʂ ȥ Ẹ Ḳ Ṭ Ỵ Ḃ Ḟ İ Ṡ ẆẊẎŻ ẹḥị ṇọṛṣ ẉỵẓȧḃ ḟġḣŀ ṗṙṡ ẏż«»‘ ”
```
...and so is:
```
[32, 1, 2, 3, 4, 32, 32, 32, 8, 9, 10, 32, 32, 32, 14, 15, 16, 17, 32, 32, 32, 21, 22, 23, 24, 25, 32, 32, 32, 29, 30, 31, 32, 32, 32, 32, 36, 37, 38, 32, 32, 32, 42, 32, 32, 32, 32, 32, 32, 49, 50, 51, 52, 53, 54, 32, 32, 32, 32, 32, 32, 61, 32, 32, 32, 65, 32, 32, 68, 32, 32, 32, 72, 32, 32, 75, 32, 32, 32, 32, 32, 32, 82, 32, 32, 32, 32, 32, 32, 89, 32, 32, 32, 93, 32, 32, 96, 32, 32, 32, 32, 32, 32, 103, 104, 32, 32, 32, 32, 32, 32, 111, 32, 32, 32, 115, 32, 32, 118, 32, 32, 32, 122, 32, 32, 125, 126, 127, 32, 32, 32, 32, 132, 32, 32, 135, 136, 32, 32, 139, 32, 32, 32, 143, 32, 32, 146, 32, 32, 32, 32, 32, 32, 153, 154, 155, 156, 32, 32, 32, 32, 32, 32, 163, 32, 32, 32, 167, 32, 32, 170, 32, 32, 32, 174, 32, 32, 177, 32, 32, 32, 32, 32, 32, 184, 32, 32, 32, 188, 32, 32, 191, 32, 32, 32, 195, 32, 32, 198, 32, 32, 32, 32, 32, 32, 205, 32, 207, 208, 209, 210, 32, 32, 32, 214, 215, 216, 32, 32, 32, 220, 221, 222, 223, 32, 32, 32, 227, 228, 229, 230, 231, 32, 32, 32, 235, 236, 237, 238, 32, 32, 32, 242, 243, 244, 32, 32, 32, 248, 249, 250, 251, 252, 32, 32, 255]
```
(This last one is a valid list output in any language with any code-page, and one may use any reasonable list-formatting too.)
---
[Here is Python 3 code](https://tio.run/##JZC7bsMwDEX3foW22IAGi3rYGvIlRYeidRoDheMIydCvd@9xBsnm5aVInu3vcb2tcd/v5/fgnXkXvUveTd5V78KgoyhknaIzyoJNPpPRlDPlTN4ob1Quyhfli3oiyZeUy8pl5bLirLqsuqK4qLbIN0of9T/pO8lf5an0GyIXE4TAxRxBBYEJAq2D4TM1DBEtojFDiCyQeCAR0jfkYxksGa2gFWpHNh3JjoQTfxONKn0rFVWhDWw7gGE4wgqQgQsUzGeAMkN7oYLVAYshzSiDlwHMIGbMbMxsgDPIGegsHYx5OR0aZbA0YBo0LeePt60t66Nr89a6x3P7nbuva@uW3l1uzS1uWV37XH/mznLpl8tLufe9d/P6fT6d@n3/Bw "Python 3 - Try it online!") which shows the unavailable ASCII bytes.
\* Although the printing itself might not actually be all that pretty!
[Answer]
# [Python 2](https://docs.python.org/2/), ~~321~~ 203 bytes
```
print map(lambda(i,x):(x>'0'and i-8-8-8-8)+8+8+8+8,enumerate(bin(int(reduce(lambda x,y:x+repr('abcdefijkl'.find(y)),'cfjdbljcibkeajjejiljjlcbjddlafklebajjlceljdeadficijflealkeklkljadfbbckjebclkf','')))))
```
[Try it online!](https://tio.run/##LVDLbtswELz7KwhfJCFMIC71NJBe2p77AUEPfAkhRcuO4AD217s7UkWQ4s7Ocmfn@rh9XhZ6fr1/KClICi1FI8UgxSiFqnlzpFreHe@eKaAxj5hInCPOEXM1czXnNPM08zQ/0TCv4VzLuZZzLcct17Vc13HccW3HvJ7xnu8D/wfmj8wZ0a/WOKBAKRzQobhAQYFCa0XgETdUGpgGBg1KY4AGDzQI0Ve12zCgtMA6YB1qe0zaI9sjHHAb0GhE3xEVI4dUY9oaNtRbOMKQGgesgD6CUUTAdqvg1WYWRBKhDH4RDCM4RtBM0EwwjuAcwTpqNo/xcrNhKIOXBDMJblLb/j0cfv759fv9eDw@r2tcbuJsrmU2Z@tNGeW9OpX3H0VdmMWL@Drsq3oZ9iXD8n0Oq7mF0sal5PJyDf7bhf8viLt8nO4va7iuZWGs82GKac7F2xQXXz6qShZuSt7m5KKdg0kppJhTys4m77OZ5hysQRxy8sH4KbqYphxMnsOc55wYstbNKViX56mQRVHhe/I8H@r0qni@fayieEsX1ujEdFmFE3ERGFzESVxWX7qKga9qJx/CPbgtfXj@Aw "Python 2 – Try It Online")
---
**Explanation:**
from the inside out:
`cfjdbljcibkeajjejiljjlcbjddlafklebajjlceljdeadficijflealkeklkljadfbbckjebclk` is the number `25731972618407747697792173390589410779249734035626759409848989703511287412985` encoded with allowed characters. (No `123456`'s allowed)
`reduce(lambda x,y:x+repr('abcdefijkl'.find(y)),'cfjdbl..bclkf','')`
maps the string to its decimal string:
* `reduce(lambda x,y:x+y,'..','')` is the same as `''.join('..')` (No `o`'s allowed)
* `repr('..')` instead of `str('..')` (No `s`'s allowed)
* `'abcdefijkl'.find(y)` maps a char to a digit.
`enumerate(bin(int(...)))` converts the number string to a binary string, and enumerates. This gives the pairs `[(0,0), (1,b), (2,1), (3,1), ...]`
`map(lambda(i,x):(x>'0'and i-8-8-8-8)+8+8+8+8, ... )` converts the enumerated list to the final result.
* `map(lambda(i,x):.. , .. )` instead of `[... for(i,x)in ...]` (No `o]`'s allowed)
* `lambda(i,x): ..` converts each (index,value) pair to either the index or `32`.
* `(x>'0'and i-8-8-8-8)+8+8+8+8` is the same as:
+ `x>'0'and i or 8+8+8+8`, (No `o`'s allowed)
+ `[8+8+8+8,i][x>'0']` or `[8<<9-7,i][x>'0']`, (No `]`'s allowed)
* `8+8+8+8` = `32` (No `23`'s allowed)
This means that the program is essentially the same as:
```
print[[32,i][x>'0']for i,x in enumerate(bin(25731972618407747697792173390589410779249734035626759409848989703511287412985))]
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 318 bytes
```
main(_){--_<88+80+88?printf((int[:>){77707-989908070??>,((int[:>){0xE8E8C79E^0xB0B0080,0xC07E0870^0xE0000C00,0xCC08099C^0xEE0C008E,0xE8888989^0xCC00808,0x9E088990^0x800C0000,0x990C8888^0x080ECC00,0xF9C7a088^0x080000C0,0x9F8C78F8^0x900000??>[_>>(0xC^0x9):>>>(_<<9+9+9>>9+9+9))<<(70^89)>>(70^89)?_:' '),main(_+9-7):0;??>
```
[Try it online!](https://tio.run/##RZDdisMgEIVfZe@qJMLcOZOKgYp5iUIlBJoN7JaS9iLQd697NCwdwZ9vzpwZnMw8TTn/jstNJf0yJjnmhqlh7u/rcntelcJ@7rx@WWvJGmERYrLU9779JGmLHDlYiRfaTnQiaFraAtlIbAkwEiJQpQFZkVBoLIxjWwwQsL9UARQMKCgvHQG5llcDgFDUoNDFsNsOEuxI/7R2K9oBY/FQqBRYBj8n7xXaFKY7j0dyThos7@uhtXMKY7NoJPdLn7rD10G3@2c1Yqzu6Ai3nN/T9WecH9k812Vex/v34w8 "C (gcc) – Try It Online")
This one is a bit of a journey...
### 1. Compressing the list
Somehow we will need to check if a given integer is one of the special code points. Any 'naked' list will be far too long, so we use a check list. This list has a non-zero value at code points that are 'restricted' and a zero value at those that aren't.
Unfortunately this still takes 512 bytes just to have the list (it looks like `0,0,7,7,0,7,0,...`). This can be shortened with a bitmask.
To make use of the bitmask we will break each byte into two pieces. The first 3 bits will pick a mask from an array while the last 5 will pick a bit in the array. We can't shrink the array any further because the 32-bit integers used by default don't support any more than 2^5=32 bits.
Using a reference implementation I wrote:
```
int main() {
int i;
int vals[] = {1, 2, 3, 4, 8, 9, 10, 14, 15, 16, 17, 21, 22, 23, 24, 25, 29, 30, 31, 36, 37, 38, 42, 49, 50, 51, 52, 53, 54, 61, 65, 68, 72, 75, 82, 89, 93, 96, 103, 104, 111, 115, 118, 122, 125, 126, 127, 132, 135, 136, 139, 143, 146, 153, 154, 155, 156, 163, 167, 170, 174, 177, 184, 188, 191, 195, 198, 205, 207, 208, 209, 210, 214, 215, 216, 220, 221, 222, 223, 227, 228, 229, 230, 231, 235, 236, 237, 238, 242, 243, 244, 248, 249, 250, 251, 252, 255, 0};
for (i = 0; i <= 0xFF; ++i) {
int j,f;
f = 0;
for (j = 0; vals[j]; ++j)
if (vals[j] == i)
f = 1;
if (f)
printf("1");
else
printf("0");
if (i%32 == 31)
printf("\n");
}
return 0;
}
```
I was able to generate the appropriate values for this new array using the command `echo "obase=16;ibase=2;$(./a.out | rev)" | bc`. This passes the output of the above program (`./a.out`) to the `rev` program, which reverses each line. It prints this along with a header to bc that sets the output base to 16 and input base to 2. Thus bc converts the binary digits to a hexadecimal bitmask.
The resulting array is can be seen in this 'beta' solution:
```
f(){
int x;
int arr[] = {0xE3E3C71E, 0x207E0470, 0x22040912, 0xE4488181, 0x1E048990, 0x91024488, 0xF1C7A048, 0x9F1C78F8};
for (x=0; x<=0xFF; ++x) {
int mask = arr[x >> 5];
int bit = mask >> (x & 0x1F);
if (bit & 1)
printf("%c", x);
else
printf(" ");
}
}
```
### 2. Dealing with the constraints
There are a lot of constraints that need to be placed on the above code. Here I go through each of them 1-by-1.
1. No assignment
This is felt by other languages as well, without assignment in C it is very hard to get any guaranteed values into variables. The easiest way for us is to write our function as a full program. The first argument of `main` will be passed the value of `argc` which will be 1 if called with no arguments.
2. No looping
The only looping constructs in C are `for`, `while`, and `goto` all of which contain restricted characters. This leaves us with using recursion. The main function will start at 1 and recurse until the argument is >256, meanwhile it will decrement the argument internally to use a 0-indexed value.
3. Hex values
The values in the above array are hexadecimal, even when converted to decimal, these contain some restricted symbols, most notably 123456 (AD can be lower-cased). To work around this each constant is XORed with another such that the restricted characters are removed. 1 becomes 9^B, 2 becomes C^E, 3 becomes B^8, 4 becomes 8^C, 5 becomes 9^C, and 6 becomes 9^F (there are more ways to do it, I chose this way).
4. Printing
The restrictions don't leave many printing functions left to us. `putchar` and `puts` are both restricted, leaving `printf`. Unfortunately we have to send `printf` a format string, ideally "%c". All such strings have that pesky percent sign that we wish to remove. Luckily we assume a little-endian machine (because apparently that's what TIO uses, and that's pretty typical). By constructing the integer whose bytes in memory are 0x25 (%), 0x63 (c), 0x00 (\0), anything (doesn't matter, its after the null terminator) we can just pass its address to `printf` and it will assume it is a string. One such number that works is -989830363 (0xC5006325). This is easy to create under the restrictions as 77707-989908070.
There's still the issue that we can't reference any values (because we can't assign them and because we can't use &), so we have to use an array literal (int[]){...}. We actually use this for the bitmask array above as well.
5. Closing brackets
We can't use ']' or '}' to close either our arrays or functions. Luckily C has digraphs and trigraphs that work. `:>` will become `]`, while `??>` will become `}`. This requires gcc to take the `-trigraphs` switch, as it ignores trigraphs by default (in violation of the standard).
6. Bitwise operations
We can't use `&` to mask bits off of our index, nor can we use `%` to get there the old-fashioned way. Therefore we rely on implementation specific behaviour. In particular we shift our 32-bit integers far enough to the left to lose bits, then back to the right. For example to get the last 5 bits of our number we first shift it left 27 bits (leaving `abcde00000...`) then shift it back to the right by 27 bits (leaving `...00000abcde`).
7. Miscellaneous values
We need a few more literal values throughout the code - these are taken from Arnauld's JS answer, plus 27 (for the reason above) is added by me as `9+9+9`.
### 3. Putting it together
Here is the description of the source with all of these changes together.
```
main(_){ // This is our main entry point
--_<88+80+88 // This subtracts 1 from the argument (_) and checks if it is less than 256
? // If it is less than 256 we 'continue'
printf( // first we call printf with...
(int[:>){ // An integer array that will be interpreted as a string
77707-989908070 // With the value we determined above, to represent "%c\0\xC5"
??>, // This is a trigraph for }, just as the :> above is a digraph for ]
((int[:>){ // We immediately create another integer array
0xE8E8C79E^0xB0B0080, // Each row is the bit-mask for 32 characters
0xC07E0870^0xE0000C00,
0xCC08099C^0xEE0C008E,
0xE8888989^0xCC00808,
0x9E088990^0x800C0000,
0x990C8888^0x080ECC00,
0xF9C7a088^0x080000C0,
0x9F8C78F8^0x900000??>
[_>>(0xC^0x9):> // This is {arr}[_>>5] just in a roundabout way
>>(_<<9+9+9>>9+9+9)) // Similarly this is (...)>>(_&0x1F)
<<(70^89)>>(70^89) // This is <<31>>31 or &1, to check the last bit
?_:' ') // If its 1, we print the character, otherwise we print a space
,main(_+9-7):0; // We recurse, the :0 is the other branch of the if, it terminates execution
??>
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 635 bytes
```
++++++++++++++++++++++++++++++++.>+.+.+.+.<...>++++.+.+.<...>++++.+.+.+.<...>++++.+.+.+.+.<...>++++.+.+.+....++++.+.+.<...>++++.<......>+++++++.+.+.+.+.+.<......>+++++++.<...>++++.<..>+++.<...>++++.<..>+++.<......>+++++++.<......>+++++++.<...>++++.<..>+++.<......>+++++++.+.<......>+++++++.<...>++++.<..>+++.<...>++++.<..>+++.+.+.<....>+++++.<..>+++.+.<..>+++.<...>++++.<..>+++.<......>+++++++.+.+.+.<......>+++++++.<...>++++.<..>+++.<...>++++.<..>+++.<......>+++++++.<...>++++.<..>+++.<...>++++.<..>+++.<......>+++++++.<.>++.+.+.+.<...>++++.+.+.<...>++++.+.+.+.<...>++++.+.+.+.+.<...>++++.+.+.+.<...>++++.+.+.<...>++++.+.+.+.+.<..>>-.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fmwDQs9PWg0AbPT0gBySEycPkY4oAARbdIBaMg6wbUwZFjx1uEXQ9hM1AtZ8ce@H67LTRxIl3K3V9TboeO21qxTR@/RA32Onq/f8PAA "brainfuck – Try It Online")
In response to finally being beaten by Javascript, I have golfed what I can out of this:
1 byte saved by having 32 in cell 0 and incrementing cell 1 (the only reason I initially had it the other way was because of a quick fix when OrjanJohansen pointed out I couldn't use `]`)
1 byte saved by decrementing a third cell (initially at 0) to generate `255` = `-1`
2 bytes saved by printing spaces between characters 31 and 36 without using `<>` but instead simply stopping at 32 to print from cell 0 when incrementing from 31 through 33.
# [brainfuck](https://github.com/TryItOnline/brainfuck), 639 bytes
```
>++++++++++++++++++++++++++++++++.<+.+.+.+.>...<++++.+.+.>...<++++.+.+.+.>...<++++.+.+.+.+.>...<++++.+.+.>....<+++++.+.+.>...<++++.>......<+++++++.+.+.+.+.+.>......<+++++++.>...<++++.>..<+++.>...<++++.>..<+++.>......<+++++++.>......<+++++++.>...<++++.>..<+++.>......<+++++++.+.>......<+++++++.>...<++++.>..<+++.>...<++++.>..<+++.+.+.>....<+++++.>..<+++.+.>..<+++.>...<++++.>..<+++.>......<+++++++.+.+.+.>......<+++++++.>...<++++.>..<+++.>...<++++.>..<+++.>......<+++++++.>...<++++.>..<+++.>...<++++.>..<+++.>......<+++++++.>.<++.+.+.+.>...<++++.+.+.>...<++++.+.+.+.>...<++++.+.+.+.+.>...<++++.+.+.+.>...<++++.+.+.>...<++++.+.+.+.+.>..<+++.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v/fTpsA0LPR1oNAOz09IAckhMnD5GNTD@Giy4JlYHJI@jFlUPTY4BZB10PYDFT7ybEX3Y8IceLdSl1fk67HRps6cU1IP8IN//8DAA "brainfuck – Try It Online")
First we generate the number 32. Then we just go through incrementing one cell and switching the printing between that cell and the one containing 32. Steadily increasing numbers are something Brainfuck does well.
It's nice to beat Javascript with Brainfuck, it doesn't happen often!
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), ~~1918~~ ~~1598~~ ~~1487~~ 1431 bytes
*Saved 56 bytes thanks to @user202729*
```
print(8<<98,7/7,9-7,7>>97,8>>97,8<<98,8<<98,8<<98,8,9,0xa,8<<98,8<<98,8<<98,0xe,0xf,7+9,8+9,8<<98,8<<98,8<<98,7+0xe,7+0xf,8+0xf,9+0xf,78^87,8<<98,8<<98,8<<98,77^80,70^88,70^89,8<<98,8<<98,8<<98,8<<98,9<<98,70^99,77>>97,8<<98,8<<98,8<<98,98-070,8<<98,8<<98,8<<98,8<<98,8<<98,8<<98,9^070,80^98,80^99,87^99,87^98,9^077,8<<98,8<<98,8<<98,8<<98,8<<98,8<<98,70-9,8<<98,8<<98,8<<98,7^70,8<<98,8<<98,9^77,8<<98,8<<98,8<<98,7^79,8<<98,8<<98,70^0xd,((8<<98)+' ').repeat(8^0xe)+(8^90),((8<<98)+' ').repeat(8^0xe)+89,8<<98,8<<98,8<<98,7^90,8<<98,8<<98,7+89,((8<<98)+' ').repeat(8^0xe)+(7|97),7+97,((8<<98)+' ').repeat(8^0xe)+(77|98),8<<98,8<<98,8<<98,80|99,8<<98,8<<98,8^0x7e,8<<98,8<<98,8<<98,0x7a,8<<98,8<<98,0x7d,0x7e,0x7f,8<<98,8<<98,8<<98,8<<98,7+0x7d,8<<98,8<<98,0x87,0x88,8<<98,8<<98,0x8b,8<<98,8<<98,8<<98,0x8f,8<<98,8<<98,7+0x8b,((8<<98)+' ').repeat(8^0xe)+0x99,0x9a,0x9b,0x9c,((8<<98)+' ').repeat(8^0xe)+(7+0x9c),8<<98,8<<98,8<<98,0xa7,8<<98,8<<98,0xaa,8<<98,8<<98,8<<98,0xae,8<<98,8<<98,78+99,((8<<98)+' ').repeat(8^0xe)+0xb8,8<<98,8<<98,8<<98,0xbc,8<<98,8<<98,0xbf,8<<98,8<<98,8<<98,97+98,8<<98,8<<98,99+99,((8<<98)+' ').repeat(8^0xe)+0xcd,8<<98,0xcf,0xd0,7+0xca,7+0xcb,8<<98,8<<98,8<<98,7+0xcf,0xd7,0xd8,8<<98,8<<98,8<<98,0xdc,0xdd,0xde,0xdf,8<<98,8<<98,8<<98,7+0xdc,7+0xdd,7+0xde,7+0xdf,0xe7,8<<98,8<<98,8<<98,0xeb,0xec,0xed,0xee,8<<98,8<<98,8<<98,7+0xeb,7+0xec,7+0xed,8<<98,8<<98,8<<98,0xf8,0xf9,0xfa,0xfb,0xfc,8<<98,8<<98,0xff)
```
[Try it online!](https://tio.run/##jVTbasMwDP2VvXUmzuY3SVD6KQbHF@jGutCWkUH/PZNsNojrNHvIEdjHR4qO7Df35S7@fByv/WU8hnj@@Dy9x@95Hs/H0/UZ93tCDa@gqQcNhwOBxoJ5Z4GatJlcY8dMkb@koSON8t0xoBOOYGKGIGUEtNjKBWDRaDAWMWNLsyAVvrFEfGqldMLegFnVWFBtZrIeZuTM8ItlF/6lA6ZvNsJWdZBtCjKPKj1rpqCfi2Wq2z3t1Ms5jtGxi7wVVceRjHpIwXZNZCq3mPcwE9wIlPgNGzwmomo1ydyoqoWPQGxOF7h6IehMZkjrDnSZuDzJ08ZQJ8ChmRfTnSAzH/2wmUguCTmBQcBvNEiOeNVM76BeaF8@t@wa8BWkjSoHbCoNvl5otZfY92qFtlP68KfqE0MwuaHelTCsOFi44lpo1xy8gAxEkIEIaUWIeTmEEsprFEQ9QvtNE/@iqEdRj3HtXRtKKPoxNMVSBpmNJLORRDvV3U5JzfMP "JavaScript (SpiderMonkey) – Try It Online")
### How?
The fact that `=` is not allowed is a show-killer in JS. We can't do any variable assignment, and we also can't use any arrow function.
The above code is instead computing each number separately, using the allowed digits in either decimal, octal or hexadecimal (\$0\$, \$7\$, \$8\$, \$9\$ and **0xa** to **0xf**) and the following operators: `+`, `-`, `/`, `|`, `^`, `<<` and `>>`.
```
1 = 7/7 | 50 = 80^98 | 136 = 0x88 | 216 = 0xd8
2 = 9-7 | 51 = 80^99 | 139 = 0x8b | 220 = 0xdc
3 = 7>>97 | 52 = 87^99 | 143 = 0x8f | 221 = 0xdd
4 = 8>>97 | 53 = 87^98 | 146 = 7+0x8b | 222 = 0xde
8 = 8 | 54 = 9^077 | 153 = 0x99 | 223 = 0xdf
9 = 9 | 61 = 70-9 | 154 = 0x9a | 227 = 7+0xdc
10 = 0xa | 65 = 7^70 | 155 = 0x9b | 228 = 7+0xdd
14 = 0xe | 68 = 9^77 | 156 = 0x9c | 229 = 7+0xde
15 = 0xf | 72 = 7^79 | 163 = 7+0x9c | 230 = 7+0xdf
16 = 7+9 | 75 = 70^0xd | 167 = 0xa7 | 231 = 0xe7
17 = 8+9 | 82 = 8^90 | 170 = 0xaa | 235 = 0xeb
21 = 7+0xe | 89 = 89 | 174 = 0xae | 236 = 0xec
22 = 7+0xf | 93 = 7^90 | 177 = 78+99 | 237 = 0xed
23 = 8+0xf | 96 = 7+89 | 184 = 0xb8 | 238 = 0xee
24 = 9+0xf | 103 = 7|97 | 188 = 0xbc | 242 = 7+0xeb
25 = 78^87 | 104 = 7+97 | 191 = 0xbf | 243 = 7+0xec
29 = 77^80 | 111 = 77|98 | 195 = 97+98 | 244 = 7+0xed
30 = 70^88 | 115 = 80|99 | 198 = 99+99 | 248 = 0xf8
31 = 70^89 | 118 = 8^0x7e | 205 = 0xcd | 249 = 0xf9
32 = 8<<98 | 122 = 0x7a | 207 = 0xcf | 250 = 0xfa
36 = 9<<98 | 125 = 0x7d | 208 = 0xd0 | 251 = 0xfb
37 = 70^99 | 126 = 0x7e | 209 = 7+0xca | 252 = 0xfc
38 = 77>>97 | 127 = 0x7f | 210 = 7+0xcb | 255 = 0xff
42 = 98-070 | 132 = 7+0x7d | 214 = 7+0xcf |
49 = 9^070 | 135 = 0x87 | 215 = 0xd7 |
```
**Note:** Bitwise shifts are processed modulo \$32\$. This is explicitly stated in [the ECMAScript specification](https://www.ecma-international.org/ecma-262/9.0/index.html#sec-signed-right-shift-operator):
>
> Let *shiftCount* be the result of masking out all but the least significant 5 bits of *rnum*, that is, compute *rnum* & 0x1F.
>
>
>
For instance, `8<<98` really does `8<<2` (which is \$32\$).
[Answer]
## Haskell, ~~623~~ ~~617~~ ~~614~~ ~~594~~ ~~360~~ 342 bytes
Edit: -234 bytes thanks to @Lynn by finding a pattern encoding as a string. -18 bytes thanks to @Ørjan Johansen.
```
map(\i->cycle(8+8+8+8:filter(\_->" XXXX XXX XXXX XXXXX XXX XXX X XXXXXX X X X X X X X X X XX X X X X XXX X XX X X X XXXX X X X X X X X X X X X XXXX XXX XXXX XXXXX XXXX XXX XXXXX X"!!i>' ')(pure i))!!9)(take(0xf8+8)(iterate(9-8+)0))
```
[Try it online!](https://tio.run/##hVDRCsIwDPyVdC9LGIU9bsL2HT4MpJRWy@ooWwX9eWt1VjcRlpJcueNSeicx9craoJsunIXDzvBW3qRVWBWvs9PGejVid@BtBvtYAPCZCb5k0gAgaek@9wJgBQvyv@O9f9Z/HZuv/CE3frPWnsaMMdPmkBO6y6jAEDFWE3rRKyyvOsZFaGJawiuseVVQSRRjNQM04EYzeNDhLrUVxylw6dwD "Haskell – Try It Online")
How it works
```
map(\i-> ) -- map the lambda over the
(take(0xf8+8) -- first 256 elements of
(iterate(9-8+)0)) -- the list [0,1,2,....]
-- the lambda is:
cycle -- make an infinite list by repeating the list
8+8+8+8: -- wih element 32 followed by
pure i -- the singleton list with 'i'
filter -- but keep 'i' only if
\_->" XXXX..."!!i>' ' -- the pattern has an 'X' at index 'i', else
-- remove it to make an empty list
-- i.e. the cycled list is, if the pattern is
-- a space: [32,32,32,32,32,32,32,32,32,32,...]
-- an 'X': [32, i,32, i,32, i,32, i,32, i,...]
-- ^
-- 9th element ---/
!!9 -- pick the 9th element which is the result
-- of the lambda
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) -r, ~~4190~~ 4188 bytes
```
(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((())())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())())())())())())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())())())()<((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))>()()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())())())())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())()<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()())()<(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())>())())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())()<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()())())())())())()<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()())
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X0NDkzKoqUF7oKmJhGzAIhQ6WlPTDuZ82hpLU5OHorOpbqwNLJFQbCbCWKxBTWu7aBIyFJtnN3RcR9OIGcGxTsPMNZqhBqnrkKOHCpFjhxYt1HTnaDFH5bpuNFOO2FpuNGIGZcRQaq7daBdqtAtFfGhQKV/8//9ftwgA "Brain-Flak – Try It Online")
This one is a little bit difficult for Brain-flak since we can't use `]` or `}`. Meaning the only useful characters are `<>()`.
[Here](https://tio.run/##7VbfS4RAEH73rxiWwF2soHqTUyiip3q5gh4OHzZv0OX2VNa9@vNtVoU85Oi6HxWRgivffDvzzac45rJeoNZNo5ZVaSzcSivP71VtPe9F2QdZQQQGX9HUCLMns8JTuJO63rR0jOF1H9pO7GOW2EgbB3YS/fVsWwUOwj1E70dS8Hts207Qp/u/3bq/9f79kIT/D@PuSloo8bxqVedXlzR0GOdiv1MwmmFGqgLCEGY3ZakTOIvh0RpVZH1klrhSk3gSsx7hTg@ENPRqKyjYoZbAKSEQBOBPfIpnWKBR6RQrrVJpEZzy62W5Kiz43HfEvhe6G5HX2KJls5i5JS0LYgAfbeGDLQFcCHJIMOHBW44GPwRGMDdl9ZwrjaDmbRsedMcgQQQai8zmcAJWLnCd3hvRPpKBE66rsPfD9F4w8plsXjosogKW3KWcHan7gWiadw "Haskell – Try It Online")'s a Haskell program that helped me write this
It just counts up skipping where spaces need to be and pushing those individually.
[Answer]
# [JavaScript (SpiderMonkey)](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Releases/45), ~~1001~~ ~~919~~ ~~789~~ 441 bytes
```
print(/u/.exec().map.call('0777700077700077770007777700077700007770007000000777777000000700070070007007000000700000070007007000000770000007000700700070077700007007700700070070000007777000000700070070007007000000700070070007007000000707777000777000777700077777000777700077700077777007',''.repeat.bind(Number)).map(/u/.exec().find.bind(/()/.exec().fill(Number.bind(0,88-070)).fill(/u/.exec().fill,!0),''.indexOf)).map(Map.call.bind(Map.call)))
```
[Try it online!](https://tio.run/##hVFRDoMgDD3LvqCJYv/mJbadAbUmbOoI08WdnuGADRcTSeDBe30tlKt8ykdtlB7zh1YNmf4@3OhlrTZqGHkxFYJmqjmIXmpRy67jDI9uIOJ3jfAjo4aIUYt7PxPAFSTktiPk9/q/Y7fKBrnzmrW2GFnGmDCkSY6iUkPDz1NfkYFPj9KWtU70EQWHhHVN9BYvYlaWubsIBG2VoeuyA8JS0YXSfGlDmVP4Dp8ingDA2jc "JavaScript (SpiderMonkey) – Try It Online")
Finally beats BF!!!
### General idea
Convert each character of the long string string to its index or 32, depends on the value.
### `Array.prototype.map`? How to get array
[Brute force](https://tio.run/#%23ZVNtb9s2EP4s/gom8CqytSU7y/oSTAYCdMCAok2xfRg2111o@WwxkUmFpJw4tvrXsyNl2QtCwJZ099zd89zxbsRa2NzIyg1sJedgVlrdwubpaS0MrYxULsu1srqEpNRL4q1zaUVZ6vssnfR@evV6dPbz@S9vs8uPv3/64@9v0@tloe36sfkxTUkJjm4IWdQqd1IrugR3WZZfja7AOAmW6dkN39I0pYVzlb1IU@tEfqvXYBZYIMn1KhXp@@HZ@dmHc0LxyIWPybKsVnNYSAXz3a41qLosuQFXG0Un0wD2ZEVbz9Kss1Lap3ltDFowMpjmert3tUHVPuJqdgO5S5D21b3a0958EStk7jPwQ1AISBba/CbygnV6mTfzY@pWAGUdp0SiiIerRYujKIIORvwZ3J8DvKpt0WIPmKZ9be4LWQLbyzrSxjin3aYCLBIYt/B9m7rEpCEEZ4DT1ka6Db2roQbKlHZUV06u5CPMOUV1OPqbW@uMwNClDuOt7rLJaRyf9mM25DH@vwv/Jxv/SIdp@PAeEre0mHcouKefRXV4/xOO9r9A3O595GDoAJgxgQfIfbEp3g@VC8fIi3vlCml5spClA8MesvHJQ7ISDkfT3V2OnfCadeBEB2O6koqWoLob7rIDR4LKmddqsR8LVMy9P7FICdaiZNbxPv4IaYdQ3SWYZ@kKnLwvMW4PQbvVxjEm@jOejWd71EB0cNLWyBBYaaxL/WLYAmPAegcu45LgAmDtNmL8dshnBrsTInXWsSFhb/Gtf@qVnfZZHL/RPLFVKR2Lv6mYT4ZTJNwJk17Xy@XkqCDCgvJF87DxTqoagvuk86ffJ5eDf8Tg8d/e9HUv/T@MREHcKLvuba1rkt5WNtfPkqffWY7ZwezCA3bCLOsVKGf581TObJBW5OekR3vNuDVRk4c84ElHbQd8sVFDLy4oGIPXt7eF5hqh0TFbE0iwkzDSQqDqEee7XfjEjvjPrtt2dBxsFB3ugB71Q/3Iz81vaMsGlwrH92t7CGmenv4D) to see which objects are accessible by accessing object properties (because `]` is not allowed, so only properties with name matching an identifier is accessible).
`RegExp.prototype.exec` returns an array-like object when there is a match. When no argument is provided, the argument defaults to `undefined`, so `/u/.exec()` matches and return an array.
### Get 2 arbitrary distinct values on 2 different characters
We want to have `(x,y)=>x=='0'?32:y`, but we can't use `=`.
Instead, we're going to do
```
new Array(a)
.map(x=>x=='0'?()=>32:function()this)
.map((x,y,z)=>x.call(y,z))
```
We can `map` the string over some function, but `=>` is not allowed, so only a few functions can be used. It may have bound `this` and some bound arguments (so it has the form `(x,y,z)=>pre_filled_function.call(pre,filled,args,etc,x,y,z)`)
After considering a list of functions (`repeat exec bind create map indexOf replace fill find reduce filter findIndex call bind apply`), I decide that the following functions will be used (after considering all other combinations)
* `repeat`: number -> different strings.
* `find`: thisArg -> first element in array match.
The general idea would be:
```
[].map.call('07070707...', (x,y,z)=>[elem1,elem2].find(somefunction,x,y,z)
```
where `somefunction` considers the `this` argument (`x`) and the first argument (`elem1` or `elem2`) and return whether it matches.
The last arrow function is rewritten to `[].find.bind([elem1,elem2],somefunction)`.
### Array literal
We can use regex exec to get an array, and `fill` it with different values. For example `/()/.exec()` returns a length-2 array, then we can fill it as we need.
### Which `somefunction` do we need?
We need one that returns a truthy/falsy value depends on `this` (which is 1 of 2 functions we're going to return) and first argument (must be a string or array).
For that, I used `indexOf` -- it returns falsy value iff the first argument is a prefix of the `this` argument.
### Represent the function literals
[Answer]
# TI-Basic (83 series), 578 bytes
```
8XFact8-ΔTbl
seq(X and XX≤8+8 or 8≤X and X≤Xmax or 7+7≤X and X<9+9 or 7+7+7≤X and X<8π or 9π<X and X<πXmax or 9 nCr 7≤X and X+X<77 or X=7²-7 or 7²≤X and X≤7*9-9 or X=70-9 or X=8²+ΔTbl or X=78-Xmax or X=9*8 or X=89-7-7 or X=89-7 or X=89 or X=900-807 or X=88+8 or 809-707<X and X≤97+77-70 or 9X=999 or 8X=990-70 or X=888-770 or X=899-777 or 8*7+77-8≤X and X+X<Ans or 7²X/77=77+7 or 999+77<8X and 7X<970-9-7 or 8²X=8888+8 or X+X=99+99+88 or 7X=9099-8077 or 9+8≤X/9 and X<997-770-70 or X=99+8² or X=87+80 or X=80+90 or X=87+87 or X=87+90 or X=87+97 or X=98+90 or X=999-808 or X=97+98 or X=99+99 or X=99+99+7 or 9²8<πX and X+X+X≤70*9 or 70π-π-π<Xand X+X+X≤9²8 or 70π<X and X<70π+π or 997-770≤X and X+X+X≤99*7 or 77+79+79≤X and X+8+9≤Ans or 77π<X and X<Ans-Xmax or 7*8*9-8≤X+X and X+X≤7*8*9 or X=Ans,X,0,Ans
8XFact+Ansseq(X,X,⁻8XFact,70π+π
```
TI-Basic has [its own very special "code-page"](http://tibasicdev.wikidot.com/one-byte-tokens) with weird design choices like moving the space character over to 0x29 so that 0x20 can be the `randM(` command.
It's tricky to figure out how to get TI-Basic to output the right kind of object. Strings wouldn't work for multiple reasons: there's no way to reference a token without using the token, and also we're not allowed the `"` character. We can't just write a list, because `{` and `}` are forbidden. We are allowed the `[` and `]` characters for matrices, but a 1 by 256 matrix doesn't work, since matrices are allowed at most 99 rows and columns. We can't use `→` to assign to variables, and we can't get at the list variables `ʟ` or `L₁` through `L₆` anyway.
So here, we write down a complicated logical formula with inequalities that says when a character is one of the ones we want to output. Then we use the `seq(` command to generate a list with `1` in those positions and `0` elsewhere. From there, another `seq(` command and some arithmetic finishes the job.
That was the exciting part; the rest is golfing the constants and I probably haven't done that as much as possible. One of the tricks I use is that by default, `Xmax` is 10, `XFact` is 4, and `ΔTbl` is 1.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak) -r, 3894 bytes
```
(((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())<((())((()())()))>)))(((((((()()()()()()()())(()()()()()()()()())(()()()()()()()()()())()()()()())))<((((((((()()()()()()()()()()()()()())((((((((((()()()()()()()()()()()()()()())((()()()()()()()()()()()()()()()())()))))<((((((((((((()()()()()()()()()()()()()()()()()()()()())())())())())()()()()()()())))<((((((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()())())())()))))()()()())())())>)))()()()()()()()()()())>))))))()()())())())())())())<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()()())>)))())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()()())<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()()())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()()())())<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()()())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())())())<((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))>()()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()()())())())())<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()()())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()()())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())<((((((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))))))>()()()()()()())<(()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())>()())())())())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())())())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())())())())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())())())())())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())())())())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())())())<(((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()())))>()()()())())())())())<((()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()()))>()()())
```
[Try it online!](https://tio.run/##7VVBCoNADPyOc/AHkr/ooVCUHvw/RHQpxiXFlp2AxV1zUHFnJpPEHeb@@WofUz@qNqSFsgvdioEEtAYE26MHDocOrgR7mzhO1eLbpHCedaI1vD85lUXzKZkC8/cA8pcC@HsE5vM8OlI/bEsc5nevlOKLaTyCWjl2MlVdlJ3x4Pf0tVp7XXW2PITiSH6EEXXW3xxtHOtQ3vyUq4W5ZGFKccUZcKaZobChyP8oO9wN2lyoajsv "Brain-Flak – Try It Online")
I wrote a program to generate the optimal Brain-Flak program for any output. Assume that:
* `<>` is not used
* My program is correct
, then this solution is optimal.
However, I was a bit lazy and implement a solution that is not very hard to come up with, and it ends up running in 1m13s (takes time \$O(n^5)\$ or so). I may look for more efficient solution later.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~162~~ 157 bytes
*Warning*: Unprintable characters ahead!
```
print map(lambda(i,x):(x>'0'and i-0xe0/7)+0xe0/7,enumerate(bin(reduce(lambda x,y:(x<<0xd-7)-x+y,bytearray('7?QcZ;+BqiQJUS!?B0W
Based on [TFeld's existing answer](https://codegolf.stackexchange.com/a/176331/69850), but with a few changes:
* Use `0xe0/7` instead of `8+8+8+8` to represent 32. ([a program to find shortest representation of a number](https://tio.run/#%23XZDdTsMwDIWvl6ewtIskWijTJP6qZY8AD1AVqbTuFuiSKsmmVsCzF6dDgLiIfOLYn3Pcj/Hg7GaaXB90AbAEY6HB2mMVjN1D77HGBm2NOePXXDG@4opfkVjy7ZbkbjfrZ5IfpErGOhMJVbLWeTAJ5yu7R7FWm5tbmbNFyoeULw44CCOVq2MKIXoKJVUsTAuVHcUA1sVUydd39w/VS91g@zRwSIQh5YPMoXY2GntCakuTMxwi2kaIkL65ClIy1np3BBPRR@c6Gn3snY9kzTWnOjIcek8f5jx7dcaKQf7yv0tEAivakEpClqsULn1ZIJR4w1F3aGlUZYN@//zvfXZOT4Up9aOzyH52MEPIcvRjDqjxXHUiSLbAocY@/nVHO8HUQRg6TYoFlmACJGJ@ueowo8VZofwuzsj4MQiZ997YCGfFQesdcIXT9AU))
* Use a `bytearray` to represent the huge literal.
A `bytearray` is similar to a `str` that it's iterable, however, iterating it gives integers, not characters. We can use it to encode a base-N literal and `reduce(lambda x,y: x*N+y, my_bytearray)` to decode it.
Because Python 2 files don't have an encoding by default, only characters in ASCII (0..127) can be used. Null byte, newlines, backslashes and quotes take 1 more byte.
Also, it's not possible to use all bases.
I wrote a [program](https://tio.run/#%23bVTbbtswDH2Ov4JIMVha3Mx2Lo7TGNgX7AfaIlVsJRGmyJkkt86GfntHybkWfbFlkjqHPCS9P9htrUYfH2td72DdqNLWtTQgdvtaW9C8akoeSd0sS1ZueRCoIp1koyTP0mkyG8dZNs6meZblaZKNRnk8meXjJHbf4zwbjePRZJpOs0k@jvPZeJbP8gxNSZLOsnGS5rNJUImNsKZ4FLCuNRARtRSEAq6aHdfMcrISiiiKxjW0RRHGITBVgVggxnMQVHwNZd0ou2zUXgtl2UrinYPlZV1xQ@cAd8CMQTR8lUIEPc1toxVIrq7i7jGCjNJFwRZFkk59MswlcgnpyDTf6@VnAmOReuN93HBMwopawZuwW9gJT7Wx2wjERtWaAwbvJb//09SWV0GvLRyaucIcVv5AQp9xSIcILFmJhqenMMIHvig8Bb3elUd7j76JVt6mbmyxt8UhfQh6qKmrG3WN2zT1Rbe3RS8u/uwr/xyTOAoa9sNBeyHqe55@SAd4RC4uDb@K7of9q2j8ivpYVZ8O8PgQBHegUB2wW2bxIXAgDVR8z1WF8gKKu5H1ikl4ZVq4lsPLihn@4mfjpZupFwQ5kjGQwuC1NXQueNuKcuswGQqwMtz7SOekHoS/Mtng/BlEsTUQnEc/mI4GiHvS4Od5L8iOtUb85cWvWqHDDYqp5Sv31@ZeaDy5@x3H/JgYGiMnTedfONiTyyEFPaZwN56DnpNeMmP99SscFBTvOpr7s5t@8zhlraxQDYL0VnKJg9lIW3RZfYr/8aOrx2OdY5082ASfiONxuQzZ3vWAnIMG5AwTUXpeLpx6guHRb34oJNutKgbtnLiV6/anpTT6Ym/R7Bcdr4Kbl06EwGW37JRw23bqpe9C5LeOBk4g3xvURjO14WQSpXHsxPc1D32flqXkTBPaCXtsEfX9cZyfKj7xnqo@EqIFS/WMncUZHK/BXyavyOnabfVXxT8mz1goMvjKyTr0/YJ/7vUeud8FflziPd@750X7xfYeujqM4ecfNTmxRYd5@93BDQ4@u6JQHx//AQ) to find the shortest representation of `n`, given those restrictions.
] |
[Question]
[
Take two positive integers `N` and `M` and create the concatenated cumulative sums of `[N]`, with `M` iterations. Output the result of the last iteration.
**Definition of the concatenated cumulative sum:**
1. Start with a number `N` and define a sequence `X = [N]`
2. Append to `X` the cumulative sums of `X`
3. Repeat step 2 `M` times.
The cumulative sum of a vector, `X = [x1, x2, x3, x4]` is: `[x1, x1+x2, x1+x2+x3, x1+x2+x3+x4]`.
**Example with `N = 1` and `M = 4`:**
`P` = the cumulative sum function.
```
M = 0: [1]
M = 1: [1, 1] - X = [1, P(1)] = [[1], [1]]
M = 2: [1, 1, 1, 2] - X = [X, P(X)] = [[1, 1], [1, 2]]
M = 3: [1, 1, 1, 2, 1, 2, 3, 5] - X = [X, P(X)] = [[1, 1, 1, 2], [1, 2, 3, 5]]
M = 4: [1, 1, 1, 2, 1, 2, 3, 5, 1, 2, 3, 5, 6, 8, 11, 16]
```
Note that the first `X = [1]` is not counted as an iteration. You may choose to take `M = 5` for the above example (thus counting `X = [1]` as one iteration).
This is [OEIS A107946](https://oeis.org/A107946)
---
### Test cases:
```
N = 5, M = 1
5, 5
N = 2, M = 3
2, 2, 2, 4, 2, 4, 6, 10
N = 4, M = 6
4, 4, 4, 8, 4, 8, 12, 20, 4, 8, 12, 20, 24, 32, 44, 64, 4, 8, 12, 20, 24, 32, 44, 64, 68, 76, 88, 108, 132, 164, 208, 272, 4, 8, 12, 20, 24, 32, 44, 64, 68, 76, 88, 108, 132, 164, 208, 272, 276, 284, 296, 316, 340, 372, 416, 480, 548, 624, 712, 820, 952, 1116, 1324, 1596
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins. Optional input and output formats.
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
```
n!m=iterate((++)<*>scanl1(+))[n]!!m
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P08x1zazJLUosSRVQ0NbW9NGy644OTEvx1BDW1MzOi9WUTH3f25iZp5tQVFmXomKoaLJfwA "Haskell – Try It Online")
Thanks to H.PWiz for -18 bytes
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
¸IFDηO«
```
[Try it online!](https://tio.run/##MzBNTDJM/f//0A5PN5dz2/0Prf7/34TLDAA "05AB1E – Try It Online")
**Explanation**
```
¸ # wrap input_1 in a list
IF # input_2 times do:
D # duplicate the list
η # get prefixes of the list
O # sum the prefixes
« # concatenate to the current list
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~9~~ ~~8~~ 7 bytes
*Thanks to H.PWiz for saving 1 byte.*
```
!¡S+G+;
```
[Try it online!](https://tio.run/##yygtzv7/X/HQwmBtd23r////m/w3BwA "Husk – Try It Online")
Uses 1-based `M`.
### Explanation
```
; Wrap N in a list to get [N].
¡ Iterate the following function on this list and collect
the results in an infinite list.
S+ Concatenate the current value with...
G+ ...the cumulative sum. We're not using the cumsum built-in ∫
because it prepends a zero.
! Use M as an index into the infinite list.
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
:"tYsh
```
Inputs are `M`, then `N`.
[Try it online!](https://tio.run/##y00syfn/30qpJLI44/9/Yy4jAA) Or [verify all test cases](https://tio.run/##y00syfmf8N9KqSSyOON/rEFyhEvIf0MuUy5jLiMuMy4TAA).
### Explanation
```
:" % Implicitly input M. Do the following M times
t % Implicitly input N the first time. Duplicate
Ys % Cumulative sum
h % Concatenate horizontally
% Implicitly end loop. Implicitly display stack
```
[Answer]
# Mathematica, 34 bytes
```
Nest[#~Join~Accumulate@#&,{#},#2]&
```
[Try it online!](https://tio.run/##y00sychMLv6fbvvfL7W4JFq5zis/M6/OMTm5NLc0J7Ek1UFZTadauVZH2ShW7X9AUWZeiYJDerSJjlnsfwA "Mathics – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~83~~ ~~78~~ ~~75~~ ~~71~~ ~~65~~ ~~63~~ 60 bytes
```
def f(n,m):r=n,;exec"s=0\nfor c in r:s+=c;r+=s,\n"*m;print r
```
[Try it online!](https://tio.run/##JcUxDoAgDADA3Vc0TqIMiE4QfsKGEBkopDDo6zGGW6687c4oe798gLAgT0yRQa79491cjbAYMoGDiECqbsZp2kzlFuc16UIRG1APy84Fm/72kRwdo5P1Dw "Python 2 – Try It Online")
Saved ~~6~~ 8 bytes thanks to Rod
Saved 3 bytes thanks to Erik
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 12 bytes
```
{(⊢,+\)⍣⍺⊢⍵}
```
Takes N on the right side and M on the left.
[TryAPL here!](http://tryapl.org/?a=f%20%u2190%20%7B%28%u22A2%2C+%5C%29%u2363%u237A%u22A2%u2375%7D%20%u22C4%206%20f%204&run)
Explanation:
```
{(⊢,+\)⍣⍺⊢⍵}
{ } an anonymous function
(⊢,+\) a train for a single iteration:
⊢ the right argument
, concatenated with
+\ the cumulative sum
⍣ repeated
⍺ left argument times
⊢⍵ on the right argument
```
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~194~~ ~~181~~ ~~175~~ ~~163~~ ~~134~~ 110 bytes
```
(n,m)->{int a[]=new int[1<<m],c=1,i;for(a[0]=n;m-->0;)for(n=0;2*n<c;c++)for(i=++n;i-->0;a[c]+=a[i]);return a;}
```
[Try it online!](https://tio.run/##dY9Ba8MwDIXv/RU6xkti2rGbk8J2GOwwGPQYctDctKiL5WArHaX0t2deFnYZEwjEp/eE3gnPWPqh49P@Y1qRG3wQOCWoR6FeH0a2Qp71nfm7TGwY33uyYHuMEV6RGK5RUBJ6oufFW72wdMcuFPA7EEvTbsF6tigdp96/YRDCfje6CDVMGRdOldtrUgI2bc3d5@zaVJVrC1tvCjIHHzJs1mlpXFlu10Z9E67X5v6OK2tsns@E6jxnQ7MEG9vmNTbUKhM6GQMDmttkYEmyfH/2tAeX8mQ7CcTHpgUMx6jguoKldpcondN@FD0kiWSPIeAlavE/luyfdBqHob9km@JBKWXmc7fVbfoC "Java (OpenJDK 8) – Try It Online")
[Answer]
# [jq](https://stedolan.github.io/jq/), 51 bytes
```
reduce range(.[1])as$j([.[0]];.+[.[:keys[]+1]|add])
```
[Try it online!](https://tio.run/##yyr8/78oNaU0OVWhKDEvPVVDL9owVjOxWCVLI1ov2iA21lpPG8iwyk6tLI6O1TaMrUlMSYnV/P8/2kjHOBYA "jq – Try It Online")
done with some help from the `#jq` IRC channel at libera.chat.
returns a nice JSON array.
-1 byte from ovs.
-7 bytes from Michael Chatiskatzi.
[Answer]
# [Dyalog APL](https://www.dyalog.com/), 19 bytes
```
{0=⍺:⍵⋄(⍺-1)∇⍵,+\⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24RqA9tHvbusHvVufdTdogFk6hpqPupoB/J1tGOAZO3//4YKaQqmXMZA0ojLDEiaAAA "APL (Dyalog Unicode) – Try It Online")
Dyadic function, with `N` on the right and `M` on the left.
```
{
0=⍺: ⍵ ⍝ if a = 0 return
(⍺-1) ∇ ⍵,+\⍵ ⍝ recurse with the array
⍝ joined with its cumsum (+\⍵)
}
```
[Answer]
# [R](https://www.r-project.org/), 46 bytes
```
function(N,M){for(i in 1:M)N=c(N,cumsum(N))
N}
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NPx1ezOi2/SCNTITNPwdDKV9PPNhkomlyaW1yaq@GnqcnlV/s/TcNQx0zzPwA "R – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 12 bytes
```
L+bsM._byF]E
```
[Try it here.](http://pyth.herokuapp.com/?code=L%2BbsM._byF%5DE&input=6%0A4&debug=0)
[Answer]
# JavaScript (ES6), ~~55~~ 54 bytes
Takes input in currying syntax `(m)(n)`.
```
m=>g=a=>m--?g([...a=+a?[a]:a,...a.map(x=>s+=x,s=0)]):a
```
### Test cases
```
let f =
m=>g=a=>m--?g([...a=+a?[a]:a,...a.map(x=>s+=x,s=0)]):a
console.log(f(1)(5).join(', '))
console.log(f(3)(2).join(', '))
console.log(f(6)(4).join(', '))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
;+\$¡
```
[Try it online!](https://tio.run/##y0rNyan8/99aO0bl0ML///@b/DcDAA "Jelly – Try It Online")
Suggested version by [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) (returns `n` instead of `[n]` for singleton arrays).
[Answer]
## Clojure, 67 bytes
```
#(loop[c[%]i %2](if(= i 0)c(recur(into c(reductions + c))(dec i))))
```
[Answer]
# [Julia 1.5](http://julialang.org/), 31 bytes
```
n>m=m<1 ? n : [n;cumsum(n)]>m-1
```
[Try it online!](https://tio.run/##yyrNyUw0rPivrFCSr5CbWJKcoZAFElIw1DPlckosTtVLLs0tLs3VqNC0hbKiK/T09GI1/@fZ5drm2hgq2CvkKVgpROdZQ@XzNGPtcnUN/xcUZeaV5ORpmNoZanLBOEZ2xgiOiZ2Z5n8A "Julia 1.0 – Try It Online")
] |
[Question]
[
For this challenge, you are to output the result of the sum of some numbers. What are these numbers? Well, you are given input, (`a`, `b`), which are integers (positive, negative, or zero) , `a != b`, and `a < b` , and each integer within `a` and `b` (including them) will have exponents according to the Fibonacci numbers. That's confusing so here's an example:
```
Input: (-2, 2)
Output: -2**1 + (-1**1) + 0**2 + 1**3 + 2**5 =
-2 + -1 + 0 + 1 + 32 = 30
```
Given that the first Fibonacci number is represented by `f(0)`, the formula is:
```
a**f(0) + ... + b**f(b-a+1)
```
**Input, Processing, Output**
To clarify the above, here are some test cases, the processing of the input, and the expected outputs:
```
Input: (1, 2)
Processing: 1**1 + 2**1
Output: 3
Input: (4, 8)
Processing: 4**1 + 5**1 + 6**2 + 7**3 + 8**5
Output: 33156
Input: (-1, 2)
Processing: -1**1 + 0**1 + 1**2 + 2**3
Output: 8
Input: (-4, -1)
Processing: -4**1 + -3**1 + -2**2 + -1**3
Output: -4
```
**Rules**
* No standard loopholes allowed
* Exponents must be in order according to Fibonacci series
* Code must work for above test cases
* Only the output needs to be returned
**Winning Criteria**
Shortest code wins!
[Answer]
## Mathematica, 38 bytes 37 bytes 31 bytes
```
Sum[x^Fibonacci[x-#+1],{x,##}]&
```
This is just rahnema1's answer ported to Mathematica. Below is my original solution:
```
Tr[Range@##^Fibonacci@Range[#2-#+1]]&
```
Explanation:
`##` represents the sequence of all the arguments, `#` represents the first argument, `#2` represents the second argument. When called with two arguments `a` and `b`, `Range[##]` will give the list `{a, a+1, ..., b}` and `Range[#2-#+1]` will give the list of the same length `{1, 2, ..., b-a+1}`. Since `Fibonacci` is `Listable`, `Fibonacci@Range[#2-#+1]` will give list of the first `b-a+1` Fibonacci numbers. Since `Power` is `Listable`, calling it on two lists of equal length will thread it over the lists. Then `Tr` takes the sum.
Edit: Saved 1 byte thanks to Martin Ender.
[Answer]
# [Python](https://docs.python.org/3/), 49 bytes
A recursive lambda which takes `a` and `b` as separate arguments (you can also set the first two numbers of fibonacci, `x` and `y`, to whatever you want - not intentional, but a nice feature):
```
f=lambda a,b,x=1,y=1:a<=b and a**x+f(a+1,b,y,x+y)
```
[**Try it online!**](https://tio.run/nexus/python3#TYzLCoMwFET3fsXgKtGb0kgXRZr@SOniphoQqhbNQhH76zYp9LE7M3OYzZk7t7ZiMFmajKbZ6JJPxoK7CpxlU@6EesZ1pimf5ebr0d94rEcYXBIAQhMKSW9UxY8PhOOn/ldCr3QI1yRx/YD4h6bD97eM2mNoOi9EuuxXqDMWvaZyF/SWvYgmwYksgpRyewE) (includes test suite)
Golfing suggestions welcome.
[Answer]
# [Perl 6](http://perl6.org/), ~~32~~ 30 bytes
```
{sum $^a..$^b Z**(1,&[+]...*)}
```
`$^a` and `$^b` are the two arguments to the function; `$^a..$^b` is the range of numbers from `$^a` to `$^b`, which is zipped with exponentiation by `Z**` with the Fibonacci sequence, `1, &[+] ... *`.
Thanks to Brad Gilbert for shaving off two bytes.
[Answer]
# Maxima , 32 bytes
```
f(a,b):=sum(x^fib(x-a+1),x,a,b);
```
[Answer]
## Pyke, 11 bytes
```
h1:Foh.b^)s
```
[Try it here!](http://pyke.catbus.co.uk/?code=h1%3AFoh.b%5E%29s&input=2%0A-2%0A)
```
h1: - range(low, high+1)
F ) - for i in ^:
oh - (o++)+1
.b - nth_fib(^)
^ - i ** ^
s - sum(^)
```
[Answer]
## JavaScript (ES7), 42 bytes
```
f=(a,b,x=1,y=1)=>a<=b&&a**x+f(a+1,b,y,x+y)
```
Straightforward port of @FlipTack's excellent Python answer.
[Answer]
## Haskell, 35 bytes
```
f=scanl(+)1(0:f);(?)=sum.zipWith(^)
```
Usage:
```
$ ghc fibexps.hs -e '[4..8]?f'
33156
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
ŸDg!ÅFsmO
```
[Try it online!](https://tio.run/nexus/05ab1e#@390h0u64uFWt@Jc////DbmMDAA "05AB1E – TIO Nexus")
```
Ÿ # Push [a, ..., b].
Dg! # Calculate ([a..b].length())! because factorial grows faster than fibbonacci...
ÅF # Get Fibonacci numbers up to FACTORIAL([a..b].length()).
s # Swap the arguments because the fibb numbers will be longer.
m # Vectorized exponentiation, dropping extra numbers of Fibonacci sequence.
O # Sum.
```
Doesn't work on TIO for large discrepancies between `a` and `b` (E.G. `[a..b].length() > 25`).
But it does seem to work for bigger numbers than the average answer here.
Inefficient, because it calculates the fibonacci sequence up to `n!`, which is more than is needed to compute the answer, where `n` is the length of the sequence of `a..b`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 23 bytes
```
&:ll&Gw-XJq:"yy+]JQ$h^s
```
[Try it online!](https://tio.run/nexus/matl#@69mlZOj5l6uG@FVaKVUWakd6xWokhFX/P@/rgmXriEA "MATL – TIO Nexus") Or [verify all test cases](https://tio.run/nexus/matl#U3JIj6o1Uonw/q9mlZPjXa4b4VVopVRZqR3rFaiSEVf8/391tKGCUaxCtImCBZDUhXB0TRR0DWNrAQ).
```
&: % Binary range between the two implicit inputs: [a a+1 ... b]
ll % Push 1, 1. These are the first two Fibonacci numbers
&G % Push a, b again
w- % Swap, subtract: gives b-a
XJ % Copy to cilipboard J
q: % Array [1 2 ... b-a-1]
" % For each (repeat b-a-1 times)
yy % Duplicate the top two numbers in the stack
+ % Add
] % End
J % Push b-a
Q % Add 1: gives b-a+1
$ % Specify that the next function takes b-a+1 inputs
h % Concatenate that many elements (Fibonacci numbers) into a row vector
^ % Power, element-wise: each entry in [a a+1 ... b] is raised to the
% corresponding Fibonacci number
s % Sum of array. Implicitly display
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 6 bytes
```
Σz^İf…
```
[Try it online!](https://tio.run/##yygtzv7//9ziqrgjG9IeNSz7//9/tK6RjlEsAA "Husk – Try It Online")
## Explanation
```
Σz^İf…
… rangify the input
z^ zip using the power function
İf using the fibonacci numbers
Σ sum the result
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 6 bytes
```
ṡ:ẏ∆fe
```
[Try it online](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4bmhOuG6j+KIhmZlIiwiIiwiOFxuNCJd), or see a [seven byte flagless solution](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuaE64bqP4oiGZmXiiJEiLCIiLCI4XG40Il0=). Takes input with b first, then a.
Explanation:
```
ṡ # Range from a to b
: # Duplicate
ẏ # Range from 0 to length
∆f # Nth Fibonacci number
e # To the power of
# Sum with the s flag
```
[Answer]
# R, 51 bytes
An anonymous function.
```
function(a,b)sum((a:b)^numbers::fibonacci(b-a+1,T))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
ạµ1+⁸С0
r*çS
```
[Try it online!](https://tio.run/nexus/jelly#AR0A4v//4bqhwrUxK@KBuMOQwqEwCnIqw6dT////LTL/Mg "Jelly – TIO Nexus")
[Answer]
# [Whispers v3](https://github.com/cairdcoinheringaahing/Whispers), 87 bytes
```
> Input
> Input
> fₙ
>> 1…2
>> #4
>> 3ᶠ5
>> L*R
>> Each 7 4 6
>> ∑8
>> Output 9
```
Unfortunately, Whispers v3 isn't on TryItOnline!, so there isn't an online interpreter to test this, aside from downloading the repository and running it locally.
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn) `-x`, [~~11~~ 8 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
gŸ▀<Çúì═
```
[Try it!](https://zippymagician.github.io/Arn?code=Lj16XlsxIDF7Kw==&input=WzEgMl0KWzQgOF0KW18xIDJdCltfNCBfMV0=&flags=ZXg=)
# Explained
Unpacked: `.=z^[1 1{+`
```
.= Rangify input (inclusive)
z^ Zipped with exponentiation to
[1 1{+ The fibonacci sequence, closing }] implied
Then take the sum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 bytes
```
rJÆḞ*@rS
```
[Try it online!](https://tio.run/##y0rNyan8/7/I63Dbwx3ztByKgv///2/y3wIA "Jelly – Try It Online")
-1 byte [thanks to](https://codegolf.stackexchange.com/questions/105203/fibonacci-exponents/215112?noredirect=1#comment503014_215112) [ZippyMagician](https://codegolf.stackexchange.com/users/90265/zippymagician)
## How it works
```
rJÆḞ*@rS - Main link. Takes a on the left and b on the right
r - Range from a to b
J - Length range of that
ÆḞ - n'th Fibonacci number of each
r - Range from a to b
*@ - Raise each to the power of the Fib numbers
S - Sum
```
[Answer]
## Ruby, 46 bytes
```
->a,b{n=s=0;m=1;a.upto(b){|x|s+=x**n=m+m=n};s}
```
Nothing particularly clever or original to see here. Sorry.
[Answer]
# Java 7, 96 bytes
Golfed:
```
int n(int a, int b){int x=1,y=1,z=0,s=0;while(a<=b){s+=Math.pow(a++,x);z=x+y;x=y;y=z;}return s;}
```
Ungolfed:
```
int n(int a, int b)
{
int x = 1, y = 1, z = 0, s = 0;
while (a <= b)
{
s += Math.pow(a++, x);
z = x + y;
x = y;
y = z;
}
return s;
}
```
[Answer]
# R, 57 bytes
```
x=scan();sum((x[1]:x[2])^numbers::fibonacci(diff(x)+1,T))
```
Pretty straightforward. `gmp::fibnum` is a shorter built-in, but it doesn't support returning the entire sequence up to `n`, which `numbers::fibonacci` does by adding the argument `T`.
First I had a more tricky solution with `gmp::fibnum` which ended up 2 bytes longer than this solution.
```
x=scan();for(i in x[1]:x[2])F=F+i^gmp::fibnum((T<-T+1)-1);F
```
[Answer]
# [dc](https://en.wikipedia.org/wiki/Dc_(computer_program)), 56 bytes
```
?sf?sa0dsbsg1sc[lblcdlfrdsb^lg+sg+sclf1+dsfla!<d]dsdxlgp
```
Finishes for input `[1,30]` in 51 seconds. Takes the two inputs on two separate lines once executed and negative numbers with a leading *underscore* (`_`) instead of a dash (i.e `-4` would be input as `_4`).
[Answer]
# PHP, ~~77~~ 75 bytes
```
for($b=$argv[$$x=1];$b<=$argv[2];${$x=!$x}=${""}+${1})$s+=$b++**$$x;echo$s;
```
takes boundaries from command line arguments. Run with `-nr`.
showcasing PHP´s [variable variables](http://php.net/variables.variable) again (and [what I´ve found out about them](https://codegolf.stackexchange.com/a/105835#105835).
**breakdown**
```
for($b=$argv[$$x=0}=1]; # $"" to 1st Fibonacci and base to 1st argument
$b<=$argv[2]; # loop $b up to argument2 inclusive
${$x=!$x} # 5. toggle $x, 6. store to $1/$""
=${""}+${1} # 4. compute next Fibonacci number
)
$s+=$b++** # 2. add exponential to sum, 3. post-increment base
$$x; # 1. take current Fibonacci from $""/$1 as exponent
echo$s; # print result
```
[FlipTack´s answer](https://codegolf.stackexchange.com/a/105204#105204) ported to PHP has 70 bytes:
```
function f($a,$b,$x=1,$y=1){return$a>$b?0:$a**$x+f($a+1,$b,$y,$x+$y);}
```
[Answer]
# Axiom, 65 bytes
```
f(a,b)==reduce(+,[i^fibonacci(j)for i in a..b for j in 1..b-a+1])
```
test code and results
```
(74) -> f(1,2)
(74) 3
Type: Fraction Integer
(75) -> f(4,8)
(75) 33156
Type: Fraction Integer
(76) -> f(-1,2)
(76) 8
Type: Fraction Integer
(77) -> f(-4,-1)
(77) - 4
Type: Fraction Integer
(78) -> f(3,1)
>> Error detected within library code:
reducing over an empty list needs the 3 argument form
protected-symbol-warn called with (NIL)
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 67 bytes
```
$e=1;$args[0]..$args[1]|%{$s+=("$_*"*$e+1|iex);$e,$f=($e+$f),$e};$s
```
[Try it online!](https://tio.run/nexus/powershell#@6@SamtorZJYlF4cbRCrpwdhGcbWqFarFGvbaiipxGspaamkahvWZKZWaFqrpOqopNlqAAVU0jR1VFJrrVWK////b/Lf4mtevm5yYnJGKgA "PowerShell – TIO Nexus")
Found a slightly better way to do the sequence, but powershell doesn't compare to other languages for this one :)
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-x`](https://codegolf.meta.stackexchange.com/a/14339/), 9 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
òV ËpMgEÄ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LXg&code=8lYsyHBNZ1nE&input=LTIsMg)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ŸvyN>Åfm}O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6I6ySj@7w61pubX@//8bcekaAQA "05AB1E – Try It Online") Takes two lines of input, the first line being `b` and the second line being `a`.
```
v # for y in...
Ÿ # [a, ..., b] (implicit input)
m # push...
y # current item in list
m # to the power of...
Åf # the...
N> # current index in list...
Åf # th Fibonacci number
} # end loop
O # push sum(stack)
# implicit output
```
] |
[Question]
[
# Definition
From the description on OEIS [A006345](https://oeis.org/A006345):
>
> To find `a(n)`, consider either a `1` or a `2`. For each, find the longest repeated suffix, that is, for each of `a(n)=1,2`, find the longest sequence `s` with the property that the sequence `a(1),...,a(n)` ends with `ss`. Use the digit that results in the shorter such suffix. `a(1) = 1`.
>
>
>
# Worked-out Example
`a(1)=1`.
If `a(2)=1`, we will have the sequence `1 1` where the longest doubled substring from the end is `1`. If `a(2)=2` instead, then it would be the empty substring. Therefore `a(2)=2`.
When `n=6`, we choose between `1 2 1 1 2 1` and `1 2 1 1 2 2`. In the first choice, `1 2 1` is doubled consecutively from the end. In the second choice, it is `2` instead. Therefore, `a(6)=2`.
When `n=9`, we choose between `1 2 1 1 2 2 1 2 1` and `1 2 1 1 2 2 1 2 2`. In the first choice, the longest doubled consecutive substring is `2 1`, while in the second choice `1 2 2` is doubled consecutively at the end. Therefore `a(9)=1`.
# Task
Given `n`, return `a(n)`.
# Specs
* `n` will be positive.
* You can use 0-indexed instead of 1-indexed. In that case, please state so in your answer. Also, in that case, `n` can be `0` also.
# Testcases
The testcases are 1-indexed. However, you can use 0-indexed.
```
n a(n)
1 1
2 2
3 1
4 1
5 2
6 2
7 1
8 2
9 1
10 1
11 2
12 1
13 2
14 2
15 1
16 1
17 2
18 1
19 1
20 1
```
# References
* [WolframMathWorld](http://mathworld.wolfram.com/LinusSequence.html)
* Obligatory [OEIS A006345](https://oeis.org/A006345)
[Answer]
## Haskell, ~~146~~ ~~140~~ ~~137~~ ~~133~~ 118 bytes
```
s!l|take l s==take l(drop l s)=l|1<2=s!(l-1)
g[w,x]|w<x=1|1<2=2
a 1=1
a n=g$(\s x->(x:s)!n)(a<$>[n-1,n-2..1])<$>[1,2]
```
[Answer]
## Python, 137 bytes
```
def a(n,s=[0],r=lambda l:max([0]+filter(lambda i:l[-i:]==l[-i*2:-i],range(len(l))))):
for _ in[0]*n:s+=[r(s+[0])>r(s+[1])]
return-~s[n]
```
This solution is using 0-based indexing.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~25~~ ~~24~~ ~~22~~ 20 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
**2 bytes thanks to Dennis.**
```
2;€µḣJf;`€$ṪLµÞḢ
Ç¡Ḣ
```
[Try it online!](http://jelly.tryitonline.net/#code=MjvigqzCteG4o0rFk3MyRSTDkGbhuapMwrXDnuG4ogrDh8Kh4bii&input=MjA)
A port of my [answer in Pyth](https://codegolf.stackexchange.com/a/87356/48934).
```
Ç¡Ḣ Main chain
¡ Repeat for (input) times:
Ç the helper chain
Ḣ Then take the first element
2;€µḣJf;`€$ṪLµÞḢ Helper chain, argument: z
2;€ append z to 1 and 2, creating two possibilities
µ µÞ sort the possibilities by the following:
ḣJ generate all prefixes from shortest to longest
;`€ append the prefixes to themselves
f $ intersect with the original set of prefixes
Ṫ take the last prefix in the intersection
L find its length
Ḣ take the first (minimum)
```
[Answer]
# Mathematica, 84 bytes
```
a@n_:=a@n=First@MinimalBy[{1,2},Array[a,n-1]~Append~#/.{___,b___,b___}:>Length@{b}&]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~30~~ ~~29~~ ~~28~~ ~~27~~ 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
;€¬;\€Z;/f;`€$ṪḢ;
1Ç¡o2Ḣ
```
[Try it online!](http://jelly.tryitonline.net/#code=O-KCrMKsO1zigqxaOy9mO2Digqwk4bmq4biiOwoxw4fCoW8y4bii&input=&args=MTk) or [verify all test cases](http://jelly.tryitonline.net/#code=O-KCrMKsO1zigqxaOy9mO2Digqwk4bmq4biiOwoxw4figbjCoW8y4biiCjIw4bi2xbzDh-KCrCRH&input=).
[Answer]
# [MATL](https://github.com/lmendo/MATL), 34 bytes
```
vXKi:"2:"K@h'(.+)\1$'XXgn]>QhXK]0)
```
[Try it online!](http://matl.tryitonline.net/#code=dlhLaToiMjoiS0BoJyguKylcMSQnWFhnbl0-UWhYS10wKQ&input=MTc) or [verify all test cases](http://matl.tryitonline.net/#code=YCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAlIGRvLi4ud2hpbGUgbG9vcAp2WEtpOiIyOiJLQGgnKC4rKVwxJCdYWGduXT5RaFhLXTApICAgICUgYWN0dWFsIGNvZGUKRCAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAlIGRpc3BsYXkgcmVzdWx0ClQgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgICAgJSBsb29wIGNvbmRpdGlvbjogaW5maW5pdGUgbG9vcA&input=MQoyCjMKNAo1CjYKNwo4CjkKMTAKMTEKMTIKMTMKMTQKMTUKMTYKMTcKMTgKMTkKMjA).
### Explanation
```
v % Concatenate stack vertically: produces empty array
XK % Copy to clipboard K. This clipboard holds the current sequence
i: % Take input n. Generate vector [1 2 ... n]
" % For each k in [1 2 ... n]
2: % Push [1 2]. These are the possible digits for extending the sequence
" % For each j in [1 2]
K % Push contents of clipboard K (current sequence)
@ % Push j (1 or 2)
h % Concatenate horizontally: gives a possible extension of sequence
'(.+)\1$' % String to be used as regex pattern: maximal-length repeated suffix
XX % Regex match
gn % Convert to vector and push its length: gives length of match
] % End. We now have the suffix lengths of the two possible extensions
> % Push 1 if extension with "1" has longer suffix than with "2"; else 0
Q % Add 1: gives 2 if extension with "1" produced a longer suffix, or 1
% otherwise. This is the digit to be appended to the sequence
h % Concatenate horizontally
XK % Update clipboard with extended sequence, for the next iteration
] % End
0) % Get last entry (1-based modular indexing). Implicitly display
```
[Answer]
# Python 2, 94 bytes
```
import re
s='1'
exec"s+=`3-int(re.search(r'(.*)(.)\\1$',s).groups()[1])`;"*input()
print s[-1]
```
Uses 0-based indexing. Test it on [Ideone](http://ideone.com/c26gpy).
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 26 bytes
```
huh.mleq#.<T/lT2._b+RGS2QY
```
[Test suite.](https://pyth.herokuapp.com/?code=huh.mleq%23.%3CT%2FlT2._b%2BRGS2QY&input=1+%0A2+%0A3+%0A4+%0A5+%0A6+%0A7+%0A8+%0A9+%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20&debug=0)
### Explanation
When `n = 6`, we choose between `1 2 1 1 2 1` and `1 2 1 1 2 2`.
We generate these two possibilities, and then look at their suffixes.
For the first one, the suffixes are: `1`, `2 1`, `1 2 1`, `1 1 2 1`, `2 1 1 2 1`, `1 2 1 1 2 1`.
We filter for doubled suffixes by checking if they are the same after rotating them for their length divided by 2 (it turns out that this check is not perfect, because it confirms `1` and `2` also).
We take the last doubled suffix and then take its length.
We then choose the possibility that corresponds to a minimum length generated above.
Then we proceed to the next value of `n`.
For the purpose of this program, it was golfier to generate the reversed array instead.
```
huh.mleq#.<T/lT2._b+RGS2QY
u QY repeat Q (input) times,
start with Y (empty array),
storing the temporary result in G:
+RGS2 prepend 1 and 2 to G,
creating two possibilities
.m b find the one that
makes the following minimal:
._ generate all prefixes
q# filter for prefixes as T
that equals:
.<T/lT2 T left-rotated
by its length halved
e take the last one
l generate its length
h take the first minimal one
h take the first one from the generated
array and implicitly print it out
```
[Answer]
# Pyth, ~~46~~ 29 bytes
Took some inspiration from @Leaky Nun's excellent Pyth answer. Tried to see if there was a shorter way using strings. Still 3 bytes short!
```
huh.melM+kf!x>blTT._bm+dGS2Qk
```
You can try it out [here](https://pyth.herokuapp.com/?code=huh.melM%2Bkf%21x%3EblTT._bm%2BdGS2Qk&input=1&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20&debug=0).
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~51~~ 42 bytes
**9 bytes thanks to Martin Ender.**
```
.+
$*x
+`((.*)(^|2|(?<3>1))\2)x
$1$#3
!`.$
```
[Try it online!](http://retina.tryitonline.net/#code=LisKJCp4CitgKCguKikoXnwyfCg_PDM-MSkpXDIpeAokMSQjMwohYC4k&input=MjA)
A port of [this answer](https://codegolf.stackexchange.com/a/87352/48934).
[Answer]
# Perl, 40 bytes
```
$a.=/(.*)(.)\1$/^$2for($a)x$_;$_=$a%5+1
```
The code is **39 bytes** long and requires the `-p` switch (**+1** byte).
The loop is inspired by the Perl solution on the relevant [OEIS page](https://oeis.org/A006345), although I did come up independently with the regular expression.
Test it on [Ideone](http://ideone.com/Yzck9i).
[Answer]
# JavaScript (ES6), 84
Index base 0
```
n=>eval("s='1';for(r=d=>(s+d).match(/(.*)\\1$/)[0].length;n--;s+=c)c=r(1)>r(2)?2:1")
```
**Less golfed**
```
n=>{
r = d => (s+d).match(/(.*)\1$/)[0].length;
c = '1';
for(s = c; n--; s += c)
c = r(1) > r(2) ? 2 : 1;
return c;
}
```
**Test**
```
F=
n=>eval("s='1';for(r=d=>(s+d).match(/(.*)\\1$/)[0].length;n--;s+=c)c=r(1)>r(2)?2:1")
for(n=0;n<20;n++)console.log(n,F(n))
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 20 bytes
```
!¡λ◄(L←SnmDṫ:⁰)ḣ2);1
```
[Try it online!](https://tio.run/##ASsA1P9odXNr//8hwqHOu@KXhChM4oaQU25tROG5qzrigbAp4bijMik7Mf///zIw "Husk – Try It Online") or [Verify first 20 values](https://tio.run/##AS0A0v9odXNr///ihpHCoc674peEKEzihpBTbm1E4bmrOuKBsCnhuKMyKTsx////MjA "Husk – Try It Online")
Same algorithm as Leaky Nun's answers.
] |
[Question]
[
I don't know who coined these words, and I'm not Irish, but I give you an Irish blessing:
```
May the road rise up to meet you
May the wind be always at your back
May the sun shine warm upon your face
The rains fall soft upon your fields
And until we meet again
May God hold you in the hollow of His hand
```
I was planning on posting this a few weeks from now, but it just dawned on me that yesterday was Saint Patrick's Day.
**Rules:**
* Produce the above text exactly.
*(Feel free to break this rule for the sake of cleverness and amusement.)*
* The program must generate the text on its own accord. `cat` is not a valid solution.
* The solution with the fewest characters "wins".
I saw slight variations in wording among versions of the blessing I obtained from the Internet, so I tried to average them out. Please use the version posted above. Also, I dropped the punctuation to make it a bit easier.
May the luck of the Irish enfold you.
[Answer]
## Python, 143 chars
```
#coding:u8
print u'慍⁹桴⁥潲摡爠獩⁥灵琠敭瑥礠畯䴊祡琠敨眠湩⁤敢愠睬祡⁳瑡礠畯⁲慢正䴊祡琠敨猠湵猠楨敮眠牡灵湯礠畯⁲慦散吊敨爠楡獮映污潳瑦甠潰潹牵映敩摬ੳ湁⁤湵楴敷洠敥⁴条楡੮慍⁹潇⁤潨摬礠畯椠桴⁥潨汬睯漠⁦楈⁳慨摮'.encode("u16")[2:]
```
[run at codepad.org](http://codepad.org/0ISLOJct)
[Answer]
## Haskell, 179 characters
```
e="\n "++['='..'z']++e;i r=[e!!div r 64,e!!r]
main=putStr$i.fromEnum=<<"뒦뾁빭몁뷴릩끷뮸몁뺵끹봁벪몹끾봺뀒릾끹뭪끼뮳멁맪끦뱼릾븁릹끾봺뷁맦먰뀒릾끹뭪끸뺳끸뭮볪끼릷벁뺵봳끾봺뷁뫦먪뀙뭪끷릮본끫릱뱁븴뫹끺뵴볁뾴뺷끫뮪뱩븀놳멁뺳빮뱁뼪끲몪빁리릮변뒦뾁댴멁뭴뱩끾봺끮볁빭몁뭴뱱봼끴뫁덮븁뭦볩뀀"
```
This exploits the ancient common bond between the Irish and the Koreans. You all knew that lace and potato farming came via Korea, and that Kimchi was first made in Dublin... right?
---
* Edit: (197 -> 184) No need to `mod` (why‚Åà :-) ); eliminated separate declaration for the Korean text.
* Edit: (184 -> 179) Used a more compact to represent code book.
[Answer]
## [INTERCALL](https://github.com/theksp25/INTERCALL), 3421 bytes
A simple solution.
Genered automatically, if anyone is wondering...
```
INTERCALL IS A ANTIGOLFING LANGUAGE
SO THIS HEADER IS HERE TO PREVENT GOLFING IN INTERCALL
THE PROGRAM STARTS HERE:
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH CXI
PRINT
PUSH XCVII
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH CV
PRINT
PUSH CXV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CXI
PRINT
PUSH XXXII
PRINT
PUSH CIX
PRINT
PUSH CI
PRINT
PUSH CI
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH XCVIII
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CVIII
PRINT
PUSH CXIX
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH XCVIII
PRINT
PUSH XCVII
PRINT
PUSH XCIX
PRINT
PUSH CVII
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CXVII
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CIV
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH XCVII
PRINT
PUSH CXIV
PRINT
PUSH CIX
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH CXI
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH XCVII
PRINT
PUSH XCIX
PRINT
PUSH CI
PRINT
PUSH X
PRINT
PUSH LXXXIV
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CXIV
PRINT
PUSH XCVII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH XCVII
PRINT
PUSH CVIII
PRINT
PUSH CVIII
PRINT
PUSH XXXII
PRINT
PUSH CXV
PRINT
PUSH CXI
PRINT
PUSH CII
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CXII
PRINT
PUSH CXI
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH CXIV
PRINT
PUSH XXXII
PRINT
PUSH CII
PRINT
PUSH CV
PRINT
PUSH CI
PRINT
PUSH CVIII
PRINT
PUSH C
PRINT
PUSH CXV
PRINT
PUSH X
PRINT
PUSH LXV
PRINT
PUSH CX
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXVII
PRINT
PUSH CX
PRINT
PUSH CXVI
PRINT
PUSH CV
PRINT
PUSH CVIII
PRINT
PUSH XXXII
PRINT
PUSH CXIX
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CIX
PRINT
PUSH CI
PRINT
PUSH CI
PRINT
PUSH CXVI
PRINT
PUSH XXXII
PRINT
PUSH XCVII
PRINT
PUSH CIII
PRINT
PUSH XCVII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH X
PRINT
PUSH LXXVII
PRINT
PUSH XCVII
PRINT
PUSH CXXI
PRINT
PUSH XXXII
PRINT
PUSH LXXI
PRINT
PUSH CXI
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH CXI
PRINT
PUSH CVIII
PRINT
PUSH C
PRINT
PUSH XXXII
PRINT
PUSH CXXI
PRINT
PUSH CXI
PRINT
PUSH CXVII
PRINT
PUSH XXXII
PRINT
PUSH CV
PRINT
PUSH CX
PRINT
PUSH XXXII
PRINT
PUSH CXVI
PRINT
PUSH CIV
PRINT
PUSH CI
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH CXI
PRINT
PUSH CVIII
PRINT
PUSH CVIII
PRINT
PUSH CXI
PRINT
PUSH CXIX
PRINT
PUSH XXXII
PRINT
PUSH CXI
PRINT
PUSH CII
PRINT
PUSH XXXII
PRINT
PUSH LXXII
PRINT
PUSH CV
PRINT
PUSH CXV
PRINT
PUSH XXXII
PRINT
PUSH CIV
PRINT
PUSH XCVII
PRINT
PUSH CX
PRINT
PUSH C
PRINT
END
```
Wow
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~117~~ 115 bytes
```
'€¿“‡âŽÓ€î€†€€èÊ€‚“„€Ë‡´).ª“€¿€€†â£ƒ€¾€„‰Ã€î““€¿€€ïë€ï‡Š€›€ž‚ƒ““€¿€€‡µã»©ÃˆÉ€žŠÑ““€€¥·sާš¼ˆÉ€ž™æ““€ƒ‡æ€¦‰Ã†î“).ªÀ»
```
[Try it online!](https://tio.run/##XY89CsJAEIWPIzbeScHCyiIXWIwIaqV2IiE/GH9RC0UwJsI81sZb7EXizASC2MzyHt@8N9v32p1etywbbnCklzMrZyLENseCDZx4OBPKZLXFRPVSsUCsKeN0bbZoL55GKMtLiCl5z8Ur1AicucCvUmX/F8cZB304zmqdefC0BZdxxj8upTcklNEO/meEsbI2xKxGhV7T3bM5bWxEz5pywxhpjUl4xJrptLqPD5f75EswlJXlFw "05AB1E – Try It Online")
Thanks to Kevin Cruijssen for -2 bytes
```
'€¿ "may"
“‡âŽÓ€î€†€€èÊ€‚“ "god hold you in the hollow of"
„€Ë‡´ "his hand"
) push stack into a list
.ª sentence-case each
“€¿€€†â£ƒ€¾€„‰Ã€î“ "may the road rise up to meet you"
“€¿€€ïë€ï‡Š€›€ž‚ƒ“ "may the wind be always at your back"
“€¿€€‡µã»©ÃˆÉ€žŠÑ“ "may the sun shine warm upon your face"
“€€¥·sާš¼ˆÉ€ž™æ“ "the rains fall soft upon your fields
“€ƒ‡æ€¦‰Ã†î“ "and until we meet again"
) push stack into a list
.ª sentence-case each
À rotate list left
» join by newlines
implicitly print
```
[Answer]
## GolfScript (204 chars)
Contains non-printing characters, so copy-paste may not work:
```
:k'May the road rise up to meet you
wind be always ar back¢ sun shin¬armÈon€face
Tåainsll soft¡ields
Aäuntil we meet ag²áGod holdø inñlow of His hand'{k{{k$}*0:k;}{127.2$<{-:k}*;}if}/](+
```
Base64-encoded:
```
OmsnTWF5IHRoZSByb2FkIHJpc2UgdXAgdG8gbWVldCB5b3UKnwh3aW5kIGJlIGFsd2F5cyBhnAVy
IGJhY2uiCXN1biBzaGlurANhcm3IA29upAZmYWNlClTlBGFpbnONA2xsIHNvZnShDGllbGRzCkHk
A3VudGlsIHdlIG1lZXQgYWeyA+EFR29kIGhvbGT4BCBpbvEFjgNsb3cgb2YgSGlzIGhhbmQne2t7
e2skfSowOms7fXsxMjcuMiQ8ey06a30qO31pZn0vXSgr
```
There really is less redundancy than you might expect in the string. I think gzip's savings are 2/3 from Lempel-Ziv and 1/3 from the Huffman encoding; what I'm using is essentially LZ, but I have more overhead than the gzip format.
Note that this is the first solution to take fewer *bytes* than the output.
[Answer]
## Bash/Sed, 206 chars
I didn't manage to beat Peter Taylor, but like his solution, it's fewer **bytes** than the original. But I didn't use unprintable characters.
`sed` was useful in the similar ["no strangers to codegolf"](https://codegolf.stackexchange.com/a/6087/3544) challenge. But there I used it twice, to compress the list of replacements. Here, the text is too short for this trick.
```
sed 's/Z/May the /;s/W/ uponYr f/;s/Y/ you/'<<X
Zroad rise up to meetY
Zwind be always atYr back
Zsun shine warmWace
The rains fall softWields
And until we meet again
May God holdY in the hollow of His hand
```
[Answer]
# PHP, 431 425 bytes
```
<?php $s="May therodisupm\nwnblckfTAgGH";$p=array('01234563','3cd8h328c73m','jj','3e6643');$b=str_split('s781937ab63cd348v28cfsgah93i631jg12b314328c73i1klfsbch3b5ah63g17et1k6fn56371ahb3m1u3b8m4ta6j9bfoh93ch4aj3g6v1p1ahf0123q89358j9328c3ah3456358u8g38m3rab351h9');foreach($b as $x){$x=b($x);if($x>27){$c=str_split($p[$x-28]);foreach($c as $y){echo $s[b($y)];}}else{echo $s[$x];}}function b($a){return base_convert($a,36,10);}
```
An approach of mapping and base conversion to store the information. However, I failed at keeping the program size very small.
[Answer]
## Haskell - 284
```
s n=words"And God His May The again always at back be face fall fields hand hold hollow in meet of rains rise road shine soft sun the to until up upon warm we wind you your"!!(fromEnum n-48)
main=mapM_(putStrLn.unwords.map s)$words"3IEDLJAQ 3IP967R8 3IHFNMR: 4C;GMR< 0KOA5 31>Q@I?B2="
```
Sadly, this is *much longer* than the output or putting the string verbatim. Even the string literals themselves (without quotes) total to two characters longer than the input. How can that be?
[Answer]
# [Quetzalcoatl](https://bitbucket.org/max1234/quetzalcoatl), 218 bytes
```
"May the road rise up to meet you\nMay the wind be always at your back\nMay the sun shine warm upon your face\nThe rains fall soft upon your fields\nAnd until we meet again\nMay God hold you in the hollow of His hand"
```
Strings are implicitly printed.
# Or pyth, 217 bytes
```
"May the road rise up to meet you\nMay the wind be always at your back\nMay the sun shine warm upon your face\nThe rains fall soft upon your fields\nAnd until we meet again\nMay God hold you in the hollow of His hand
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), 175 chars
```
‚Äò3p‚Äò¬Æm‚Äò00‚Äò¬Æt¬∂¬©m ¬©t 2¬Ω;4‚Ä¢;up to 2m;you\n¬©m ¬©t 2‚¨©;be 0»¶;at 0B;0‚àû;\n¬©m ¬©t sun k∆ù;4»¶;0M;0B;0»Ω;\nThe A‚ë£;2√∑;4l;0M;0B;8R;\nAnd 0üÑÑ;we 2m;0¬°;\n¬©m God 1‚ë£;you in ¬©t d…Ö;of His 0‚ïë;
```
Thank goodness all long words are in Keg's dictionary. Just uses string compression to reduce length.
TIO currently doesn't work as it needs to be updated.
[Try it online!](https://tio.run/##y05N////UcMM4wIgcWhdLpA0MAAzSw5tO7QyV0Hh0MoSBQWjQ3utTR41LLIuLVAoyVcwyrWuzC@NyUNS8GjNSuukVAWDE8usE0sUDJysDR51zLNGVlJcmqeQfWyutQlQiYGvNUjJib1AFSEZqQqOjyYutjY6vN3aJAcqZxEElHLMS1Ew@DC/pcW6PBVkqcGhhTAj3fNTFAxBuoAOUcjMg1iRcrLVOj9NwSOzWMHg0dSJ1v//AwA "Keg – Try It Online")
[Answer]
# [Wren](https://github.com/munificent/wren), 248 bytes
Adopting [this](https://codegolf.stackexchange.com/a/6522/85052) method.
```
System.print("Zroad rise up to meetY\nZwind be always atYr back\nZsun shine warmWace\nThe rains fall softWields\nAnd until we meet again\nMay God holdY in the hollow of His hand".replace("Z","May the ").replace("W"," uponYr f").replace("Y"," you"))
```
[Try it online!](https://tio.run/##TY6xbsMwDER/5aCpBor8Q6dm6dQChgMvTETXRGXKEGUI/nqX7pKOvHd3vFZYj@Nzt8rLZS2i9SXcSqaIIsbYVtSMhbkOo96aaMSdQanRbqA6FNzp8ePINoXNooxGZenpwaN@zYxCooaJUoLlqfbCKdqob160aZWExn/1oG93jvpBO95zxJxTHCCK6iV@pNyQJ1zFMJPGcCm8Jv/ia8NrOFOnMXRPvXfd92f1kdN/MJxgz1vouuP4BQ "Wren – Try It Online")
[Answer]
# [FEU](https://github.com/TryItOnline/feu), 200 bytes
```
a/1road rise up to meet3\n1wind be always at3r back\n1sun shine warm2ace\nThe rains fall soft2ields\nAnd until we meet again\nMay God hold3 in the hollow of His hands
m/1/May the /2/ upon3r f/3/ you/g
```
[Try it online!](https://tio.run/##HY4xDsIwEAR7XrE/sJK8gAoaOso0l/hMLJw75LNl5fXBUK5mNNrA9TzJDVnJI0dj1A@KYmcu0yxDi@KxMCg1OgxUpoyF1ndHVgW2RWE0yvtIK8/y3BiZohgCpQTTUMbIydss1x6qUmJC438e9OrmLA86cFOPTZOfEAWlR/pI2qAB92jYSLxddje4n/zjbnT9qUq/E9zkcGh1r/P8Ag "FEU – Try It Online")
Is everyone sure there isn't a better replacement compression?
] |
[Question]
[
In this challenge, you'll print out the SBCS of [Jelly](https://github.com/DennisMitchell/jellylanguage), a popular golfing language. Its code page looks like this:
| | \_0 | \_1 | \_2 | \_3 | \_4 | \_5 | \_6 | \_7 | \_8 | \_9 | \_A | \_B | \_C | \_D | \_E | \_F |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| **0\_** | `¡` | `¢` | `£` | `¤` | `¥` | `¦` | `©` | `¬` | `®` | `µ` | `½` | `¿` | `€` | `Æ` | `Ç` | `Ð` |
| **1\_** | `Ñ` | `×` | `Ø` | `Œ` | `Þ` | `ß` | `æ` | `ç` | `ð` | `ı` | `ȷ` | `ñ` | `÷` | `ø` | `œ` | `þ` |
| **2\_** | | `!` | `"` | `#` | `$` | `%` | `&` | `'` | `(` | `)` | `*` | `+` | `,` | `-` | `.` | `/` |
| **3\_** | `0` | `1` | `2` | `3` | `4` | `5` | `6` | `7` | `8` | `9` | `:` | `;` | `<` | `=` | `>` | `?` |
| **4\_** | `@` | `A` | `B` | `C` | `D` | `E` | `F` | `G` | `H` | `I` | `J` | `K` | `L` | `M` | `N` | `O` |
| **5\_** | `P` | `Q` | `R` | `S` | `T` | `U` | `V` | `W` | `X` | `Y` | `Z` | `[` | `\` | `]` | `^` | `_` |
| **6\_** | ``` | `a` | `b` | `c` | `d` | `e` | `f` | `g` | `h` | `i` | `j` | `k` | `l` | `m` | `n` | `o` |
| **7\_** | `p` | `q` | `r` | `s` | `t` | `u` | `v` | `w` | `x` | `y` | `z` | `{` | `|` | `}` | `~` | `¶` |
| **8\_** | `°` | `¹` | `²` | `³` | `⁴` | `⁵` | `⁶` | `⁷` | `⁸` | `⁹` | `⁺` | `⁻` | `⁼` | `⁽` | `⁾` | `Ɓ` |
| **9\_** | `Ƈ` | `Ɗ` | `Ƒ` | `Ɠ` | `Ƙ` | `Ɱ` | `Ɲ` | `Ƥ` | `Ƭ` | `Ʋ` | `Ȥ` | `ɓ` | `ƈ` | `ɗ` | `ƒ` | `ɠ` |
| **A\_** | `ɦ` | `ƙ` | `ɱ` | `ɲ` | `ƥ` | `ʠ` | `ɼ` | `ʂ` | `ƭ` | `ʋ` | `ȥ` | `Ạ` | `Ḅ` | `Ḍ` | `Ẹ` | `Ḥ` |
| **B\_** | `Ị` | `Ḳ` | `Ḷ` | `Ṃ` | `Ṇ` | `Ọ` | `Ṛ` | `Ṣ` | `Ṭ` | `Ụ` | `Ṿ` | `Ẉ` | `Ỵ` | `Ẓ` | `Ȧ` | `Ḃ` |
| **C\_** | `Ċ` | `Ḋ` | `Ė` | `Ḟ` | `Ġ` | `Ḣ` | `İ` | `Ŀ` | `Ṁ` | `Ṅ` | `Ȯ` | `Ṗ` | `Ṙ` | `Ṡ` | `Ṫ` | `Ẇ` |
| **D\_** | `Ẋ` | `Ẏ` | `Ż` | `ạ` | `ḅ` | `ḍ` | `ẹ` | `ḥ` | `ị` | `ḳ` | `ḷ` | `ṃ` | `ṇ` | `ọ` | `ṛ` | `ṣ` |
| **E\_** | `ṭ` | `§` | `Ä` | `ẉ` | `ỵ` | `ẓ` | `ȧ` | `ḃ` | `ċ` | `ḋ` | `ė` | `ḟ` | `ġ` | `ḣ` | `ŀ` | `ṁ` |
| **F\_** | `ṅ` | `ȯ` | `ṗ` | `ṙ` | `ṡ` | `ṫ` | `ẇ` | `ẋ` | `ẏ` | `ż` | `«` | `»` | `‘` | `’` | `“` | `”` |
Or, in a code block:
```
¡¢£¤¥¦©¬®µ½¿€ÆÇÐ
ÑרŒÞßæçðıȷñ÷øœþ
!"#$%&'()*+,-./
0123456789:;<=>?
@ABCDEFGHIJKLMNO
PQRSTUVWXYZ[\]^_
`abcdefghijklmno
pqrstuvwxyz{|}~¶
°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾Ɓ
ƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠ
ɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤ
ỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂ
ĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆ
ẊẎŻạḅḍẹḥịḳḷṃṇọṛṣ
ṭ§Äẉỵẓȧḃċḋėḟġḣŀṁ
ṅȯṗṙṡṫẇẋẏż«»‘’“”
```
**Rules:**
1. You can substitute `¶` with `\n` (`0x10`), `§` with `ụ`, or `Ä` with `ṿ` if you wish
2. You may use combining diacritics if these can be normalized to the correct character
3. You may represent characters with their Unicode code points or UTF-8/16/32 representations
4. You may output the characters with any reasonable formatting, as long as they are in order (e.g., a 256 character string, an array of characters, a 2d array representing a table with any dimensions, a string with newlines delimiting each character, etc.)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes (per language) wins.
[Answer]
# Modified [Regenerate](https://github.com/dloscutoff/Esolangs/tree/master/Regenerate) `-a --sep=`, 228 bytes
```
[¡-¦©¬®µ½¿€ÆÇÐÑרŒÞßæçðıȷñ÷øœþ -~
°¹²³⁴-⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥ]|̣[AB-DEHIK-OR-WYZ]|[A-IL-PR-TW-Z]̇|̣[abdehik-or-wyz]|[a-hl-pr-tw-z]̇|[«»‘’“”]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=1TxdjxvXde_8FVezMjz0ktSu8tBgbcZQFDkWmlqBLNRIuAwxS14upxrOTGaGu1qvJNh5iIP0pYkf4qBN66Kxi6JuELsp0qJpCuw2C8vIH2gf8iDkh_Sc-zH3c8hZO2lQPtjLmfN9zj33nHMv9Zfv5yfVIkvfffe9VTXvf_5_Xv7N1pVrq7K4dhCn1_i7z3U68TLPiooUVP5VnpTyz6g4zKOirF_leRGnVadz49Wbt29Pbr584-6rZEiSuKzCZZSH00XRI0WUHtLwc9d7ZPf6H3W73c7tV166_crte18DyHmSRVUYxOk86HY6Mzrn0JN5kS0nVRYm2TEtJgfZKp31yCrP5ZfuXofAJwiCL9OUFlFFSxKlJE6nyaqMjygnQ5AMYTRIlXF8wvAHDP1Gqj8j2RwIzOM0rk5IDPSSMiMlAICiVGAAQ_b_GGQHxXX5uuzF8SJOKLx-YaiLy6XFz0lMkxmJ6-8x2R6SXa56XB5E0_sFndOCplMalhUY91CoWtBqVaTwv8F8lSTLqJouwiIYPH5xf7Yd9IiARbnTrCKvZCntdDrTJCpLci-7T9OSk0E-kwnqOJmEJU3mPbAMvu4qGfHxgD-VzhQwJshhka3ySbpaAtRORyMPwgjqGlWhALwLNQZdhZdTer8JSSGMdsYaSpZvxhgg1I7GKKUPqkktvE3AUo25x0e8Bulw75XTKA3pg7wwHcaNH6Lf4nQWJQl4bXR1a8wc93D_6unD_f3Bw9E39vfH4EbEJ9sk6AZdsR7YcgsNHwnK7M0kSipapFEVZ2ntJYXoe82JHMAKmS4oeng0Zk_K1QGyp2UJwPCYE5hm6RSWl8WBhe6cSAOj5yD2UhI8vBIoU-o8NF90xw7EIILFks5CQwYt3Lyi-VS_BGFhxlpI0Kf-myYlNbnqRvXaxDVrEKwzbEFzWsWO8DyBmCjaonaN-6lM18AcTJDQNJSku2QI0e-sLZZc8DtNfAjXHQT5erQ7FnglbQTSDe2KydF8wVBlS48hnQgdBc_BOgswZwYv4n9Og7Eui2Q4yXLcV7ICOOixqzL33A89JMBBUWSuwj2Ah8QOsgzUAmAmbKKz3Uxn9zJ0Xtwgz25bQqcWIW37qx0BGZEW8XSCPnKWpTCc6RWk3LMo48drdvnRdtf2rM3A85PSdDIgG6VR1myqVjTr6oE74pg97elYz0z-5KMH-p4_EaNBR4GzwkTyWkRFNIXMOWHVgWEn5nyXVqjR8ppBrwQEgLXJbkhIjre8bIQeIxCop3j2TJLjdZpcPd2kih5DVopZG17rBQa-PQ_pRlkx3eN2GnZPHz28sv3ci643HYberMoLQW3r8nuf49UvMZqfffZ59hBkPVJo8KJO_9OCwg6YHk54sT0kL0HJzF-l9BA2yJnxzBHY66FvaJoqKveKFW02tZfQWCPk6OCQ8O0WVywqwMZU2Uwl02xG8wy6gtoevPPJilloCtCFVgiqPHyhC9I184rmjW10x-DPgLhqqyx2NnKzbxqNUjt2zQLqB9BnzWxcb4HiFcNwZOO6cfM0CNOWp2s7E3O9ERx5fNHWFAZb5CbruKAeg7A9jqsFicjiJF_QFPosRCIxNNHQW0JbBfyiRLzt-AUHc0uWbbTfqLVRnT4Uuz4QR1JisXkKTMjkWGAiKTKHSoD9AdlJsfMloI3o-swAbYqPRd6zKa8pEX1J2dcmzWa8njGSt76t-gAaq83lKqniPImnkUsUURqLT1Z39vWSc1OdWSzK1mwdaUeSul5k9JBmi0pjDbdGw7AoupxJWD1-Df_zzKe1SzPX361FvHzWFGH94Pehj6wqlCa19N4aQNWNdvFilZXeZcQKOfZEk5ypWGePGmIQl7P4MK5CbZ4CC_TAn1kbosJHRCO03WQ_riyHUnWVPVRTwrpDI09JZajH47WHofrI7BoZupgNWj6I4pKSP42SFb1VFFkRzgOwMZ1iXRMVsEMsodOaGrF4CEnwVHF9hKNRMcr7E5z7vVpBom4c5_FJ4DAAKfOsHO70yCwu6HS42yPZfF7SCh45-yXhSXoC-fk4KmZD3KZ78iEaUDyJ03xVlUPcduyRGecLfmYTPj6OVCVbcWI6k6GAfGKOCn_p63VK84qE905ybrOeZr9uI50dvVBjOlvjixpevNQGe27BYQD2dzdowi0rlOFfPoM-NbUd08SaP-Cl9s0LJnypIMUD3Uzcn1hNuHUUoyUA6iHhGmPVoGxizL_5JsYIcvqo9bxYxZZCmWb5iQ2f0mMgBCsDyKtlEmr4vTpaepp7PYvB_Ggu6Tl-aIdtOqCn26vrKqDMpBltwHR2051EElNodjAwEcXlhOsdSvX5SwYuD1DuMjJYkAIlDkC4FeO5_LqaTimdldCvsChhcVOReRQn5SDo2LbXmOgy65Ufl0drrKBcfgCoygK4ore179z8euTu4BELR3yBzSAVsHFuIj9bPChItaDE3wqwVG_SGDEGY8wjiOP2GZbEugosuFpMn-yhKodka5NZZdhOu1ssxJh60ossH8ssgC1EBhvMQUJtrXWPmZG6TmFBf5ub5g9jmf5uWzPgWv0UdkC0FkbgNjAiVqSs_wOzuJkAEwE9gvUvmqNQry48SeAWwK7YGSraTSuXsdUvVIZgpdWgbknjMk6BDlZVOgPYAo00XkIbwTahuqJWjvRTwA1EI6Hq3OfYn3zaatGrAcUs1tBfvDCV92ZuTFMCGjOVpDjWUw9Pguql6SJf1ALS2sF-bSRJcrQzxgGR_LZrzecNYn2LmDiTkcj2IY7Ds68xbRV-Hln7LWW1T0a8xJ5rSeyaq7iGiCA7a8Q3HHRJda9dayniM38wEZ9xJOTNDPQWauV4lumOglVwvpasxsCS1z559LZeGpA-MrtLyyw5osQAZqlnGpWV5FNlyIgeapu2QJjUSbjglCZNbBvWPx78mqS89bDfLa5LnA7BsZbJzTqi4s2CahDaxMfGlvNmlD5bsT0B8zw5VTZ5JI8loiQ5CYxxG-cjruVcyrRWcYm7So00I99cRWmFl2zYIFSYvLm4NCJRrJrgcaCH0BeN0IFQQUrZnDHmZbYTNLLmNKN3dH1vbB9rTTOIu5R1NnqFwOmODHp97wG3R76IkwJjMB5tpdttLZ1oGg6pijZGs8esXI9uLBpO3Lsn_rpipmd2uGeuBnZN9mXoZVnZLdkIzzDm15gdDQxnXZtSmunWFWCrUQDYFg-rxaXZ40ADd1RTjK7Ti5mIWj8WFpC3HviWCDtrh3eu5flFMQ2js7VVK81x5DrgL7iq9-586c4epNQjWkAOYCUlDhI1mA29mgdQjUHsYtUHbPe6zhsxvgg1bC8F1l43EvZLuqao5gdaJznl3mBX5cBT-jK9FUNcFKTMlpTcj_mNQFpOo5xCJ_7NFVu8kKfU4U3dSD6vUYmxbj7BzYsKl2sYVlsgajUhkVuoya7Vw9IcwDCykyqbcIZDHiJW22Ttx5yrzdDNVSnPoVx1M1818fZtFp5FYMrHAOQq3t93lvEt0xV2YcXRxf6Qeu6TuIIG-2nQosBqsK5Z-tmInl14lUIwZodp_DokfqnGHjll1B4FRkVi82w87nTXs3f6U1Na0wTpE5D156s8O6mW0-_Dh8YmfUNd16ufYrtl3XVLpXH3xiZfhNXES0VuNdA3juPw46bhy6t2xVDtK_F9qFiVfj1yAOulrLIcq0FW3rDMkuX4tsTCp8ywvy41IseUzFnSgdqlWkQVOc6K-6VmqhVkPxmA5nH-_xMzmmLo6jjXAsDeGoRL_qCg0f0G3xiuuanf1Xxe5GM0MRg4IlW8hCQNq3JV4LXx5ERfghj-DUbENAmrG3P8HsIt0McJnbM-hfEwwN3NXL5x8wY2REIcQX9ZDy7ncVHiFQK6RMfhEz3oLDIRn4OlGj6416x1GMFJHhWVL6nhB1HEZVayLUCgSHZCSlGSCUtGlnrTKqzEZ310IUeUzOaFz9pzsWX2MMIP955i551fyQh0plfoT3mbsn7YdFMQ6yJnctdibOWzD7tLXueBnbGxvciHcr90NtsbKaHLHJo0_RcSBcUMwVsF8UsJA83URP7Ow6h2tBujoubFukJH9DbfW-SOaunEjUusxKM4xYNUa3jA0if2kHRmUWE1zCw-ilmWPDjRjtjwwyv5JoFfsKc15v1X7bTOuuPorCwev3nJ_HOZX7wYLsQzIu8EqTnf4Mdf5KhFbK2py-8M_LN-BeNH5pYRU6VPdntE_jX23ur0yfzZ0wCjpDRvEBY_zZnA2IBCcweKcggqalXOTddXVbRoSRaMCDlKDgX0rg0aHiOoPvPO3uw1bL68J3UdB5_OVPfsnKlpyuzVNE3_2keho9paY6l_zcKz0W4q3oxbwDgTw9rZSLtywTZPDDnaZ6rKQ0aj-3spyOX0IU5l36Vd3eiJ0R7ItIwrvBkiJKD5EFsiLUgqaGMSbB-ANPyfinsgR7Q4yEo6ZGWommWIx5px-QOkHMnbT0EfP6rvYj8hDB3IekbVdEfBvprg489pB3fRBHtag8Wf8wa4nSD48y7YaiZi9MJ_7qURWMOd_QQMez5XAoNqS0nYfS0lCL8_7yG0RqKvIg5eSKWGSOztgP8v1Nm0lAwTUCyDSUypIQ1RtqrwMgZPSDrllllau9Ah4ljcnuhqSQpjhXzB3g-5xHWA9zCPDQPHE7rQLgwjvU12yReGxtoxWammBEdN1sqxndDt6NfvRGcoD1jk72xxvci_BzeKQzBkWjHvFaGc1YMVJ2W2KqZUAy4G0Qyap1W1wrn-hD4QP4zlP8kQuDIxgSKXRdXZMvhICBcG_SLY5FVIAYzARsAFTSAlrTBYcWILUoh6NtgsxryNGHOoEVtKAc6dickr-10xQ90sRtxGjLKaxelGwIjNcodBCSuOTirIxC1FB0loIWTP8P4NcnNiwJY82UQdBGeIm-Bw6goLdlNJBqshgpUF-9F6OK7TMnoQL1dLeS00E7N2vMSQiTp-s4pRCxVhFWyCurxjZEixgwPgUAsPiQhnxxjywQbRRAsGbdGqgmTYFeqa61hTtlwvFIYhzdfDSBdZVUKTfmrbP6DVMYXFyy6TlWy4ITTeJPUGRiB1mvVFjl0PanppjqVLGyVmGZ6dchvjyEjkdSJ5bpD_aKP8Yje9jPCbQ0w4YJEd4_XPIiJLMHt0uNHe8NeGOEkRZIjX9jfzFzVaGB2B0aKDhOLoU1xvvPoYCs-rj6_DbltNBxi9cuvEI5HypBwAoyP7VGSLvIY_q0kz1KDkWwJecS7zBBYO7hLIWWpboyl1xXV3QA5HYHyEDsa-H7DIYe3Qj6zEFYADll_NwQ8m3DKn03geU5zsinPQ5RKHcxg9qiiIylK1K5Iky9Q6STzK1PYg9r7HJs05xmRUkVt3XrJVGMhaMVApxbmlwG_iY3nvdhcmne0hr73DLv5TBfoRiri8ACJ4ri7UGkrjLLMjNvKOErmW9HrL4DmAgqzE31OFyM9qTG0tje-jvb5-_0W-w81bt-u94oTvG9FMTEprG6vKA5HWGBDjMsvZ1SvFpIsRP99k0iGZD5C3_hs4ZktfLRvczFbY7LHxNMirqpGeoV-PPRziSoI4oUVhNpf4nD6Iq3C369oHQ9y2j_4OW2l2fYMzYtfl5nzuNstoiRkTjy96GgkGbh5LAqUdzWFIWP5rHS3MjNi_U_PaSMjAkxiEF17JRJSoBR7itt1fCEKsH1phGsJpaVYs2Zi-6-TNRi_pHrKTDdQMTqoayFK-nryK6pRVGQII2o4YL92n0ZJOJmweMpngoGAyEVMRlfis3kRUU7GKcHO2oPvRmjEYEmoGUIOHOuVhj-aMHeTbNJOPNCJyGiGBxPcu_2eOxL929LMRq8VZzcdLnWEw_u_fjs7-tn_2_tk_nH1w9pOzfzn7j7P_fPqtD86_ff7W-V-cf-_8B-fv_Or75399_jfn75___flP_-vDj39-_uH5z8__9Vdvn_-S9B93zn569m9nH53989M3f9Z_-uYvL968eOviuxffu3j74p2nH_7k4kcXP7744OKjj3_85O2L7zz5wcX3n7z75P2LHz758MlHF-998u6TX3zyrYt_-uTPP35v_PDXfze68cX-l269fPuP-3fu9l_72tfHD0c3-re_0v_q3f691_pfH__6LQSKDmZ0Ed_vZ0X_-OR1gIn6i6SfF_3quP86wozO_vHs35--8c7TN3749I2_evrGj8bcAP8L)
I thought Regenerate would be the perfect tool for this. Unfortunately, it only supports ASCII, so I made a trivial modification to allow it to use Unicode.
This is a regex that uses a bunch of character classes to match the various chars, along with combining diactritics to match all the dotted letters. ~~This somehow beat Vyxal :)~~ not anymore :(
The `-a` flag is to list all matches, listing all the possible characters within those character classes. The `--sep=` flag is so that the matches are separated by nothing.
[Answer]
# Jelly (trivial), 2 bytes
```
ØJ
```
[Try it online!](https://tio.run/##y0rNyan8///wDK///wE "Jelly – Try It Online")
>
> `ØJ`: Yield Jelly's codepage.
>
>
>
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 246 bytes
```
5ʀ⁺<+»*⌊~⁼UIȮǏẇ↳:∵o3tʀ-ð∪ßḭ∩E∑ɽ∨Ẏs„ǎ⁼ṡ{ṪhCcṪėǒ_(»8365τ94ʀ32+₀»=ǒf↲‛ȧ∩¶⁋Ż⌊⁰gḞ~{OGtṪʀ9]•æ§s⁽=%ǔṀ‡Ǐ⟨0⌈Ŀ0w₃pε→sż›7~1Ẋġ:/t≈gʀḞ}ƛƛo"2†⌈ẎḢj\⟑↵$Vꜝ₅İ;ƒ₆βḭ↔#₄ε€@1 SyȧƈḭKǎuẋ→]k≬»»-ṫ»τ20ʀ⁺R+ø⟇C«?kZǎẎQ>l«C803v"»«g}9£~Ŀg»7926τka«× D∇«FC775v"»ƛioꜝ∵~∇¶sẇ»8222τWC
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwiNcqA4oG6PCvCuyrijIp+4oG8VUnIrseP4bqH4oazOuKItW8zdMqALcOw4oiqw5/huK3iiKlF4oiRyb3iiKjhuo5z4oCex47igbzhuaF74bmqaENj4bmqxJfHkl8owrs4MzY1z4Q5NMqAMzIr4oKAwrs9x5Jm4oay4oCbyKfiiKnCtuKBi8W74oyK4oGwZ+G4nn57T0d04bmqyoA5XeKAosOmwqdz4oG9PSXHlOG5gOKAoceP4p+oMOKMiMS/MHfigoNwzrXihpJzxbzigLo3fjHhuorEoTovdOKJiGfKgOG4nn3Gm8abb1wiMuKAoOKMiOG6juG4ompcXOKfkeKGtSRW6pyd4oKFxLA7xpLigobOsuG4reKGlCPigoTOteKCrEAxIFN5yKfGiOG4rUvHjnXhuovihpJda+KJrMK7wrst4bmrwrvPhDIwyoDigbpSK8O44p+HQ8KrP2tax47huo5RPmzCq0M4MDN2XCLCu8KrZ305wqN+xL9nwrs3OTI2z4RrYcKrw5cgROKIh8KrRkM3NzV2XCLCu8abaW/qnJ3iiLV+4oiHwrZz4bqHwrs4MjIyz4RXQyIsIiIsIiJd)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `D`, 201 bytes (UTF-8)
```
`.[-]+`kA`CFGJPQX JKQUV`½vF:N+÷\i-"½vvf`̣̇`f+ƒYf∑`¡©€Æ ŒÞ ıȷñ %¶° ²⁴%ƁⱮƝȤɓƈɗƒɠƙɱƥʠɼƭʋȥΠ«‘`kPs10\*"Ṡ%λC¦C∑;øṙ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJEIiwiIiwiYC5bXHUwMDAxLVx1MDAxZl0rYGtBYENGR0pQUVggSktRVVZgwr12RjpOK8O3XFxpLVwiwr12dmZgzKPMh2BmK8aSWWbiiJFgwqFcdTAwMDFcdTAwMDFcdTAwMDFcdTAwMDFcdTAwMDHCqVx1MDAwM1x1MDAwMlx1MDAwN1xiXHUwMDAy4oKsw4ZcdTAwMDFcdFx1MDAwMVx1MDAwNlx1MDAwMcWSw55cdTAwMDFcdTAwMDdcdTAwMDFcdMSxyLfDsVx1MDAwNlx1MDAwMVx1MDAwNiAlwrbCsFx0wrJcdTAwMDHigbQlxoFcdTAwMDZcdTAwMDNcdTAwMDdcdTAwMDJcdTAwMDXisa7GnVx1MDAwN1xiXHUwMDA2yKTJk8aIyZfGksmgXHUwMDA2xpnJsVx1MDAwMcalyqDJvFx1MDAwNsatyovIpc6gwqtcdTAwMTDigJhcdTAwMDFcdTAwMDNcdTAwMDFga1BzMTBcXFx1MDAwMSpcIuG5oCXOu0PCpkPiiJE7w7jhuZkiLCIiLCIiXQ==)
Warning: This contains a *ton* of unprintables.
One technique this answer uses is to replace bytes preceding multiple `0x01` to `0x1F` with the cumulative sums of those byte sequences. It might be even golfier to allow printable ASCII with this approach but I'm not gonna try now. The code for this no longercontains an epic emoji:
[](https://i.stack.imgur.com/ZZHvm.png)
All the dotted letters are created with combining characters. I take advantage of how the lowercase form of the second dotted alphabet is the uppercase form minus `i`.
That's pretty much it! This is horribly cursed, but it was fun to make.
[Answer]
# [Python](https://www.python.org), 344 bytes
```
x="̣".join("ABDEHIKLMNORSTUVWYZȦ")+"ḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻ"
print("¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑרŒÞßæçðıȷñ÷øœþ"+'%c'*95%(*range(32,127),)+"¶°¹²³⁴⁵⁶⁷⁸⁹⁺⁻⁼⁽⁾ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥ"+x+x.replace("İ","").lower()+"«»‘’“”")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NdDZSgJRGABguu0xDkRjmlAR1UUXRUHRBu11F2EboSJGdjdHosIgUqGMtsllojJRS51xKfjPeJiRnqC78z9JRfUGH9-l6t3zb3jcipLa8a-19342LQb6yUeCOLc8m26JDAwODY-Mjo1PTE5Nz8zOzS8sLZsqsdmJ0IJGSGgh40xoN4YitLiRNd6FLgt938wI_UzoMaErQn8U5QNRDonySb1Cmr2-TbdfInAHcUhAElKgwgOkIQMFqME7BtPsgB2yUxZm5yxWj7AbdstUds-yRs4ssRwrMa0eZW_E3tqy2trW190itflW3OsuqavT0dHZY3N826AIWdAhDy9IX5EWkBaRlpBqSHWkZaQVpFWkNaRvnPJDHuJhHuUxzGX4NU_yNM-bSSvKj6xzHrEUS-UXVs7K81RDsaqNIH9uHJspYg_YA06fy7u9suqSiJElDkJszm3Prssn_RieoIJyDOULlK9Qvia23-C_5__vLw)
xnor saved 4 bytes with `'%c'`. Thanks!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 170 bytes
```
“¡¢£¤¥¦©¬®µ½¿€ÆÇÐÑרŒÞßæçðıȷñ÷øœþ”;ØṖ⁵Ż+⁽ø9Ọ“¶°¹²³”;“ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥẠḄḌẸḤỊḲḶṂṆỌṚṢṬỤṾẈỴẒȦḂĊḊĖḞĠḢİĿṀṄȮṖṘṠṪẆẊẎŻạḅḍẹḥịḳḷṃṇọṛṣṭ§Äẉỵẓȧḃċḋėḟġḣŀṁṅȯṗṙṡṫẇẋẏż”⁾«»⁾‘’⁾“”
```
[Try it online!](https://tio.run/##HZBdUlpBEIUXlBVYWU9eLDeQt3sRwYAmClUCiT/8XKASEQGDdM8oVnXPnbqXXZzZCI4@dVefr8451Yffjo6@7/chuZaBDGUkmYxlIn9lJnNZy6u8hcpMa1rXC73Ujnbzlt7qnU50qgu3LDa61I1S3tZtSG6@ahd8FdJ1br@E9FXpAPbsw/tZFsKykqcPKB586uu@4S9923fDcu5vfOZnflVkZduflh3fKvvlxPfKZbny412/fNlV/MOuWYxh@qAq6AyGQBlsA7QCPYMr4FpMA/8GD8Ez2Ay8hTmF/Q/TKiagiot0w12Bbl20GbqFewMn4Goxj73BsX0f/A@mBtOA@ZlbmAHoBHQOw6AxbBP0BNqAj8F12HPwH/AI/CBTrcL8gF3DtIsp6NhFtuk6oDsXTUZ5DErBJ8UjuAPugQfge5g6TBPmV/4SfxPSrdyLjSMk3ZD0PpfrKOz37w "Jelly – Try It Online")
Builtins are boring, so here is a slightly-less-but-still-kinda-boring answer. Despite multiple attempts to shorten the code by manipulating the code points, it turns out that string literals are the way to go.
That said, we do use some actual encoding in places, and use a couple of tricks to save bytes. The main trick used is "unparseable nilads": when Jelly encounters a nilad that doesn't form one of the [chaining patterns](https://codegolf.stackexchange.com/a/71001/66833), then the current value of the chain is printed, and the nilad becomes the argument to the rest of the chain.
Outputs a newline instead of `¶`
## How it works
```
“¡¢...øœþ”;ØṖ⁵Ż+⁽ø9Ọ“¶°¹²³”;“ƁƇƊ...ẋẏż”⁾«»⁾‘’⁾“” - Main link. No arguments
“¡¢...øœþ” - String literal
ØṖ - Printable ASCII
; - Concatenate
⁵ - Unparseable nilad. Output the characters, and continue with 10 as argument
Ż - Zero range; [0, 1, ..., 10]
⁽ø9 - Compressed integer: 8308
+ - Add to each; [8308, 8309, ..., 8318]
Ọ - Convert from code points
“¶°¹²³” - String literal
; - Prepend; [182, 176, ..., 179, 8308, ..., 8318]
“ƁƇƊ...ẋẏż” - Unparseable nilad: string literal
⁾«» - Unparseable nilad: "«»"
⁾‘’ - Unparseable nilad: "‘’"
⁾“” - Unparseable nilad: "“”"
```
Note that we have to use `⁾«»`, `⁾‘’` and `⁾“”` as all these characters are special characters in strings.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 385 bytes
```
$=>`¡¦-©¬®µ½¿€ÆÇÐÑרŒÞßæçðıȷñ÷øœþ [-]~-
°¹²³⁴⁾-ƁƇƊƑƓƘⱮƝƤƬƲȤɓƈɗƒɠɦƙɱɲƥʠɼʂƭʋȥ<̣ABDEHIKO-RW-YZ><̇AI->Ŀ<̇MP-RT-WZ-><̣abdehiko-rw-yz><̇ah->ŀ<̇mp-rt-wz->«»‘’“”`[R='replace'](/..-/g,g=([a,b])=>a<b?a+g(String.fromCharCode(a.charCodeAt()+1)+b):b)[R](/<(.)(.+?)>/g,(_,x,y)=>y[R](/./g,'$&'+x)).normalize`NFC`
```
[Try it online!](https://tio.run/##LZBPSxtBGIfvfgoP0syweUe81uxKjJZKqS2pIDUEM7tuNrHJblhDNTmUTQSV9tKagxH8i5pSjGJixZZWhRkzZEM@xX6RdFp6e3jeH8/hXabv6YrhZgtFsJ0lc5BWByOqlmLHrAHsG2uyS3bD7thDUG3yjVj/K/8821/nO7ze2eYH/JA3DOmuHlvdW1v6W/6jU@P3wwlIfoAhdsV@sja7Dirfg8o9iIrYFB/FF1ET9aB1KfbFqWiKdvfUr4ktf0ds@0d@Q@z6Lb8tznpH/u9eVVz0PnXPIv2T6OTU9POZF68gPg9vF7RIfzM6A9rjg4SXryE@B/MLIO0J1ZfMTPadA@4qlMp/dzQDWseTkC@AW4TVMmjsnP0KvHrg7QbeXuDtpxJxNeSahRw1zFASjRICo1bYUlGChvUkVjUa0SeoYqE3RTdrWyTtOvlYhrox@TBEifEfo0WElTGs6PipjhNxGYogghFRJrAme2gxvBYuyVrp341IFRp5ElLWMCa24@ZpLls2U7PPYqmB4dgrTs4kOcdCaYTx@OAP "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 198 bytes
```
Y{^zRMg}._MU"̣cfgjpqx ̇jkquv"^sY[UCyyR"i̇"x]i:C1X5\"¡\i©€Æ ŒÞ ıȷñœþ\PA¶° ²⁴\i\iƁⱮƝȤɓƈɗƒɠƙɱƥʠɼƭʋȥ\y«‘\"R`.[-]+`$.C$+*:A*_H\,#_
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLG51bGwsIll7XnpSTWd9Ll9NVVwizKNjZmdqcHF4IMyHamtxdXZcIl5zWVtVQ3l5UlwiacyHXCJ4XWk6QzFYNVxcXCLCoVxcacKpXHUwMDAzXHUwMDAyXHUwMDA3XGJcdTAwMDLigqzDhlx1MDAwMVx0XHUwMDAxXHUwMDA2XHUwMDAxxZLDnlx1MDAwMVx1MDAwN1x1MDAwMVx0xLHIt8OxXHUwMDA2XHUwMDAxxZPDvlxcUEHCtsKwXHTCslx1MDAwMeKBtFxcaVxcacaBXHUwMDA2XHUwMDAzXHUwMDA3XHUwMDAyXHUwMDA14rGuxp1cdTAwMDdcYlx1MDAwNsikyZPGiMmXxpLJoFx1MDAwNsaZybFcdTAwMDHGpcqgybxcdTAwMDbGrcqLyKVcXHnCq1x1MDAxMOKAmFx1MDAwMVx1MDAwM1x1MDAwMVxcXCJSYC5bXHUwMDAxLVx1MDAxZl0rYCQuQyQrKjpBKl9IXFwsI18iLCIiLCIiLCIiXQ==)
-21 thanks to DLosc.
This is a huge mess. Sorta a port of my Vyxal answer, but got a bit out of hand. Beats Vyxal!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 222 bytes
```
≔I⪪”}∨q;'⁶γV_⁶BιP§τÀ%OC?^H·εY⁴⊞›⊙D⁹↷Sχ↓\⸿↶T×⮌RR,s≕⁵aH↓E¬[≕\G�ν⁶⁹GG≦XCq⎇bIV¿↑+σQkiVÀ⌕✳◧´IkE«⁻∕s⁴ⅉN▶δ§⦃εDr\E∧⁵¶L=/UJ⊕M⁰↓|À|⊗ς▶≡c℅⬤_÷⌈9∧vºξPveυΦ"RU(⊘↧β↨|QκRMGXZ↑H℅→S↖kAw+⪫B:↗:≡⊙iν∨⎚‴S;⁻¤η⪫x¶⁵tZÀzBΣr⟦X⎚5y↶M⪫)H⪪↥W” υ⭆υ⎇ι℅Σ…υ⊕κγ
```
[Try it online!](https://tio.run/##nVLBasMwDL3vK0RPDsRg2Y4d09PIaYfBoPuBkIUuLE1Lmg769dmTc9hlh22YWMrzk/Qku3tv5@7cjuv6eL0Ox0k17XVRh8s4LGrHgel7OSxLkWrsNUdHuuYQcJDwiWVrSTOLGzMcKrIBmLMhExIjpiJDOgINYGgh1mwT8Q9Lx@QcIh3yWaqITUJBLYazECRlTz6StgbiDBxO4BqpBwz1s5zNreC47YTBzmoNOrKii6uAhCzC2MPJhSpLHm3J5rz05oVjAJktVnxTk0619BQDRXbIED3KRm99dlHCb6gVF8MQFJGV/FUkLE4GQkyerWS1NeAc7tG9lyn@SaGOAcUwV1j@p0aXfisQ88UNQp7JN@mIdyXtaFcUJd2K/cPLPEx4VQvM8bm9qFtJr/08tfNdDSU1eINtt/SzOtxOqrl3Y9@8nzPraerm/tRPS/@mPopC8h2x79d11Z/jFw "Charcoal – Try It Online") Link is to verbose version of code. Explanation: The most cost-effective approach seems to be to take a compressed list of Unicode ordinal differences, calculate the cumulative sum and convert to Unicode. Additionally, one of the values is `0` which indicates that the ASCII characters to `~` should be interpolated at this point instead, which saves 3 bytes. Oddly, omitting the value completely (i.e. just having an empty string in the list) actually undoes the saving.
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 418 bytes
```
00000000: 04c1 0312 c300 0004 c0b7 d7e3 1a83 ba8d ................
00000010: 6de3 2e7a 475e 925d bcf1 c117 3ffc 2140 m..zG^.]....?.!@
00000020: 8606 033e 7294 e35c e39a 1bee b8e7 95b7 ...>r..\........
00000030: f6c0 079f 1428 d26a ec21 a4cd 9051 7b64 .....(.j.!...Q{d
00000040: 3149 4151 4959 4555 4d5d 4353 4b5b 4757 1IAQIYEUM]CSK[GW
00000050: 4fdf c0d0 c8d8 c4d4 ccdc c2d2 cada c6d6 O...............
00000060: cede c1d1 c9d9 c5d5 cddd c3d3 cbdb c7d7 ................
00000070: cf3f 2030 2838 2434 2c3c 2232 2a3a 2636 .? 0(8$4,<"2*:&6
00000080: 2e3e 2131 2939 2535 2d3d 2333 2b3b 2737 .>!1)9%5-=#3+;'7
00000090: 2fbf a0b0 a8b8 a4b4 acbc a2b2 aaba a6b6 /...............
000000a0: 8e0b d0d0 581d 4a0e 0341 3075 b3fd 9861 ....X.J..A0u...a
000000b0: 9999 7946 3af4 6965 c8a2 2792 f377 7755 ..yF:.ie..'..wwU
000000c0: a5db 94d3 7d7a 10f7 28ee 49dc b3b8 1771 ....}z..(.I....q
000000d0: 495c 1657 89ab c5fd 21ee 4f71 7f59 d7c6 I\.W....!.Oq.Y..
000000e0: f6d6 bed8 37fb 2dbb b56d d9a1 5dda 7d3e ....7.-..m..].}>
000000f0: 2cde 6c52 7cd9 d7a2 5b8c 6dad d815 7b3b ,.lR|...[.m...{;
00000100: 2abb c58f d2b3 abf2 2e1f 4175 4101 e81e *.........AuA...
00000110: 8a40 43e8 5bd0 1e74 067b e008 fa1e 5c07 .@C.[..t.{....\.
00000120: f7c1 4be8 21f8 1754 027d 847a cdc7 20cf ..K.!..T.}.z.. .
00000130: 54ef 5bf3 096a 9b4a d337 5bf3 1bec 8083 T.[..j.J.7[.....
00000140: 7c0d fe04 7f83 bbe0 3954 0475 0bf5 78d5 |.......9T.u..x.
00000150: 503d 5008 7a80 62d0 08fa 0e74 005d c03e P=P.z.b....t.].>
00000160: 3886 7e00 37c0 03f0 2a9d fc0b a06e a04f 8.~.7...*....n.O
00000170: 506f f904 e49b ea7b 67be 401d 5349 06d7 Po.....{[[email protected]](/cdn-cgi/l/email-protection)..
00000180: 2ae4 82c3 7c03 fe02 d7c0 3df0 022a 86ba *...|.....=..*..
00000190: 837a bafe 4817 a916 e75b 9c9a 384d 715a .z..H....[..8MqZ
000001a0: ff01 ..
```
[Try it online!](https://tio.run/##jVVrbxZVGPzOr5h6AxGO534ptrQhipWQFilBbGtyrkQCkhIalFL/ep3zdtsYgon7Yd/N5t3ZeWbmmS0npbzsz09enZ/L5ViHtFVBGqVRjZTgPYsqS0AL3UDlaFBybID46Lh2gaCI4Rv/qnvIsMF1JO0aSh0KVakAM0aFVlYCr4R4f/83cTSfvyvWthYMTYzopScP0xF0sujGVZ5Shiq9o8QekBxpTR6bb4Q4/IiHIcbwlROENKCsjmjaZ/SqFbKtDUk6hVC8XWa5IV6INf4@Om0LhiWGUTbBKv7VJscr5xxs40DWOANbXJlDkofa2X608@z7Jw@P7j1@cHD/6YLhiGFHGxSxSdTYIqpt1LS2iqobdc4to/rmgd1Pa@qJUXvr1K9RxNQSqmsOtbVGm5pBLa2ghhb@05cwMYYZ0JQGOpoIbY2FroZuaKOhs8nQ3pCHuAt5I35hb333mb65/pVfMCIxdKclWhkFnUyCdsZBN9OgjaHpxRToYCaPzTX1dfrS3d743Hxz53pYMNLEGGUgyyKRY4l0o1jkWiqyLho5l4zsC3l8@@lZ8sxHlwVtauqiohtZdsbFKhgZHIoZNDh6daHHL@InIbblCS/zglGIkXggJOth8rDwyVPTmClFSBrDhIAQ6Dcx/vphXfzehbguxLt3TxaMSozsqHyy9IDqM51yBKrLiNpEgylHhAph4XH2fsZsZ14eLxht5iMx3MozRTFl@uhIXquJMfhkGMxdC5V67ByKp/PhNbF7LJ5d6dFXWWeASme8TBj0oJWC4nxDS1nBNWYsNFq34hHEbSG4fEfibHPBGNOXyoz56jRCbfOdlMKVWLnQmUBROe4LDcYt8fLnD8Q5mCDi9M61ZfUnRi5zgji4bsUgl0E5uxrcIfpilVToUZHHzStXt0@2r7xVsz9iZjlY0yPfToNVDxbSh4LODGJkPu6qnBnbukcO4q04nTiHlxizP0Zgj9lCDK3G9MARQ4eGaGkTl482yTqmHg/m2u@LM0F3cIkx@8PZPkhhGMjE6kjFZjTDcK/usYgqomQhYn@yeMGQhYN/5VTN/gjce4zOFg1jdmfpEiZNMqwNyDKoaeQu48OiRtoXzOmflxizP5zkfrk5e8hRwmuKIuPIkCtlJNuoyunt3sYehygT5i3NXbxVsz9MjB6BAjIfsxXNYAvkRG5sdy6j7zxZ6hHF38yHECt//hC7C0ZY8fADI3GWbhPdyLSEtjCnkivoDJtS@tlBe69Xo5w@F1vi8c6VHqv@yN0isnWmMmYqo2e4SauRkdQ6s/pZAKt8XGiysSKzYMz@iIYWljz44sgPSk7Kowc2car8QJhoG4JyxJiO/ihWQRXx4fGvC8bsjzGYxP9zCHF@/g8 "Bubblegum – Try It Online")
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) (trivial), 2 bytes
```
kC
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWi7KdlxQnJRdDuTBhAA)
Thunno 2 and Jelly share the same codepage :)
>
> `kC`: Thunno 2 Codepage
>
>
>
] |
[Question]
[
## Background
You awake on the ground. Above you is a giant stepped pyramid-like structure. Based on your ancient history lessons, you recognize it as a [ziggurat](https://en.wikipedia.org/wiki/File:Chogha_Zanbil,_Ziggurat_(model).jpg). You have been transported by Dr. Sargostein back into ancient Mesopotamia to play a game.
In this King of the ~~Hill~~ Ziggurat challenge, you will write a bot that tries to stay as far up the ziggurat as possible. You may use Java, or any language that can interface with it (i.e. Scala, Groovy, Kotlin). I have implemented a socket protocol as well, if you wish to use other languages. The ziggurat (and the map that you will be playing on) is shaped as follows:
```
11111111111
12222222221
12333333321
12344444321
12345554321
12345654321
12345554321
12344444321
12333333321
12222222221
11111111111
```
Where the number indicates the elevation of that area. Coordinates start at the top left corner and increase down and right.
There will be five rounds, each consisting of 50, 100, 250, 500, and 1000 turns. Each turn will proceed as follows: each bot will tick, moving in one of 8 directions (see [here](https://github.com/Seggan/KingOfTheZiggurat/blob/master/src/main/java/io/github/seggan/kingoftheziggurat/MoveDirection.java)), as well as increasing its "strength" stat depending on the bot's level: 4 if on levels 1 and 2, 2 on levels 3-5, and 0 on 6. Once all moves have been queued, the map will be updated for all bots simultaneously. Then, if any 2 bots are in the same tile, they will decide whether or not to fight. If neither want to fight, nothing happens. If one wants to fight and not the other, the one that does not want to fight steps a level down. If both want to fight, each bot generates a random number between its "strength" value and `floor(strength / 2)`. The bot with a higher number wins and loses 10% of its strength. The loser goes down a level and loses 20% of its strength. If there is a tie, nothing happens. If there are 3 or more bots in the same location, they will fight in an order determined by Java's `HashMap` (I don't know the order, maybe overriding `hashCode` has an effect. If it does, feel free to do that). If the bots are on the bottom level, they will still fight, but they won't move down. After all fights had happened, each bot's score is incremented by the level of the ziggurat it is standing on top of. After the turns are finished, the bot's score is set to `score / numOfTurns`. After all rounds are done, the bot's score is averaged for each round, and the result is the final score of the bot.
## API
The controller can be downloaded [here](https://github.com/Seggan/KingOfTheZiggurat). To run your bot, place the bot in the `io.github.seggan.kingoftheziggurat.bots` package. There are a few example bots in there already. Then edit [this array](https://github.com/Seggan/KingOfTheZiggurat/blob/2d2daa1b0b9aa526affb44cebc9ef0dfcd172475/src/main/java/io/github/seggan/kingoftheziggurat/Main.java#L47) to include your bot. You may remove the 3 examples in there.
Your bot will take the following form:
```
public class YourBot extends io.github.seggan.kingoftheziggurat.Bot {
@Override
protected boolean fight(Bot opponent) {
// return true whether you want to fight the other bot, false otherwise
}
@Override
protected void tick() {
// do your stuff
}
}
```
The `Bot` class has some useful methods. They can be accessed in your bot subclass.
```
public class Bot {
/** Gets the x and y position of the bot */
public Point getPosition() {
}
/** Gets the bot's elevation */
public int getElevation() {
}
/** Gets the strength stat of the bot. You cannot get the strength of any bot other than yours */
public int getStrength() {
}
/** Gets all the players playing */
public Set<Bot> getPlayers() {
}
/** Queues the bot to move in the specified direction */
public void move(MoveDirection direction) {
}
/** Gets the height of the point in the specified direction */
public int getElevationRelative(MoveDirection direction) {
}
/** Gets the score of the bot */
public int getPoints() {
}
/** Moves the bot one level up if possible */
public void moveUp() {
}
}
```
To run your bot, simply execute `./gradlew runShadow` in the project's directory. The controller needs a Java version of at least 16.
## Movement
All directions of movement are absolute. There is a `moveUp()` method available in the `Bot` class that automagically moves you up one level.
* NORTH decreases your Y
* SOUTH increases your Y
* WEST decreases your X
* EAST increases your X
And so on for NORTH\_EAST, SOUTH\_WEST, etc.
## Using Non-Java Languages
I have made a simple wrapper bot class that allows you to use any language you like with the challenge. It uses a socket-based protocol. To add your bot to the controller, simply edit [the array](https://github.com/Seggan/KingOfTheZiggurat/blob/2d2daa1b0b9aa526affb44cebc9ef0dfcd172475/src/main/java/io/github/seggan/kingoftheziggurat/Main.java#L47) to include `new io.github.seggan.kingoftheziggurat.bots.BotWrapper(<arguments>)`. The `<arguments>` is a list of double-quoted strings that run your program on the command line. For example, in Python it would be `new io.github.seggan.kingoftheziggurat.bots.BotWrapper("python", "your_bot.py")`. It is recommended in your program to wait a few milliseconds for the socket server to start up.
### The Socket Protocol
First, connect to localhost. But wait, you say, what port do I connect to? **The port to connect to is the very first argument given to your program**. Then, listen on the socket. **All messages are delimited by `\n`**. The first message received will be either "tick" or "fight". The next message is a JSON object that depends on the first message. If the first message is "tick", do your ticking logic and once done, send the direction you want to go in through the socket. The direction can be `NORTH`, `SOUTH`, `EAST`, `WEST`, `NORTH_EAST`, `NORTH_WEST`, `SOUTH_EAST`, or `SOUTH_WEST`. If you do not want to move, send `NONE`. If the first message is "fight", send either `true` or `false` back to the controller to indicate whether you want to fight or now. If the first message is "tick", the JSON in the second message will look like [this](https://pastebin.com/HDVWVx31). If it is "fight", it will look like [this](https://pastebin.com/YNJcSMSs). These two messages will *always* be sent in a row, and after sending, the controller will *always* wait for a reply.
## Restrictions
* [Standard loopholes apply](https://codegolf.meta.stackexchange.com/q/1061/107299)
* Attempts to mess with the controller or other bots will be disqualified
* Answers using reflection will be disqualified
* Modifying the `BotWrapper` class to give yourself more information than is given will not be tolerated either
* I reserve the right to disqualify any submissions taking excessive time or memory to run
* Discussions about bots should happen [here](https://chat.stackexchange.com/rooms/135680/king-of-the-ziggurat)
All submissions will be tested on my 8 GB RAM laptop using an Intel Core i5-4310 processor.
## Scores
* Round 1: Surprisingly, RealisticPacifist turned out first.
* Round 2: JazzJock is acting strangely. Sometimes it languishes with a score of ~4.2, other times it pulls ahead beating RealisticPacifist by ~0.1 points. The scores shown are the typical case.
* Round 3: Seems chaos does not like crabbiness
* Round 4: Rebuilding bots from the ground up seems to work
```
Round 1 (50 turns):
RealisticPacifist (#1): 249, Averaged: 4.980
Crab (#2): 247, Averaged: 4.940
GreedyBot (#3): 235, Averaged: 4.700
CrabberInTraining (#4): 249, Averaged: 4.980
WeightCrab (#5): 255, Averaged: 5.100
GroundUpBot (#6): 258, Averaged: 5.160
ChaoticWalkerIII (#7): 255, Averaged: 5.100
JazzJock (#8): 186, Averaged: 3.720
Round 2 (100 turns):
RealisticPacifist (#1): 501, Averaged: 5.010
Crab (#2): 495, Averaged: 4.950
GreedyBot (#3): 463, Averaged: 4.630
CrabberInTraining (#4): 513, Averaged: 5.130
WeightCrab (#5): 506, Averaged: 5.060
GroundUpBot (#6): 521, Averaged: 5.210
ChaoticWalkerIII (#7): 495, Averaged: 4.950
JazzJock (#8): 434, Averaged: 4.340
Round 3 (250 turns):
RealisticPacifist (#1): 1227, Averaged: 4.908
Crab (#2): 1261, Averaged: 5.044
GreedyBot (#3): 1202, Averaged: 4.808
CrabberInTraining (#4): 1313, Averaged: 5.252
WeightCrab (#5): 1292, Averaged: 5.168
GroundUpBot (#6): 1299, Averaged: 5.196
ChaoticWalkerIII (#7): 1305, Averaged: 5.220
JazzJock (#8): 982, Averaged: 3.928
Round 4 (500 turns):
RealisticPacifist (#1): 2433, Averaged: 4.866
Crab (#2): 2601, Averaged: 5.202
GreedyBot (#3): 2405, Averaged: 4.810
CrabberInTraining (#4): 2601, Averaged: 5.202
WeightCrab (#5): 2599, Averaged: 5.198
GroundUpBot (#6): 2635, Averaged: 5.270
ChaoticWalkerIII (#7): 2625, Averaged: 5.250
JazzJock (#8): 2002, Averaged: 4.004
Round 5 (1000 turns):
RealisticPacifist (#1): 4819, Averaged: 4.819
Crab (#2): 5177, Averaged: 5.177
GreedyBot (#3): 4804, Averaged: 4.804
CrabberInTraining (#4): 5276, Averaged: 5.276
WeightCrab (#5): 5189, Averaged: 5.189
GroundUpBot (#6): 5257, Averaged: 5.257
ChaoticWalkerIII (#7): 5227, Averaged: 5.227
JazzJock (#8): 4003, Averaged: 4.003
Final Scores:
RealisticPacifist (#1): 4.917
Crab (#2): 5.063
GreedyBot (#3): 4.750
CrabberInTraining (#4): 5.168
WeightCrab (#5): 5.143
GroundUpBot (#6): 5.219
ChaoticWalkerIII (#7): 5.149
JazzJock (#8): 3.999
```
[Answer]
# JazzJock
A rather more complicated bot, this bot is a rather macho jock, who will attempt to push their way to the top unless they are feeling very weak. However, [due to their exposure to jazz music](https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Fimageproxy.ifunny.co%2Fcrop%3Ax-20%2Cresize%3A640x%2Cquality%3A90x75%2Fimages%2Fe6db17aefb5ae967987a07f03a7d3260633203ed74eda9af5195f6d52cc9a28e_1.jpg&f=1&nofb=1), they move in a random and unpredictable way, moving sideways along the pyramid as they climb.
```
import java.awt.Point;
import java.util.concurrent.ThreadLocalRandom;
public class JazzJock extends io.github.seggan.kingoftheziggurat.Bot {
@Override
protected boolean fight(Bot opponent) {return getStrength()>15;}
@Override
protected void tick() {
Point pos = getPosition();
if (getStrength()>10) /* if we have a little bit of strength, try to move up the pyramid */{
if(getElevation() == 6) /* center, don't move */ {move(NONE);}
else if (pos.x==pos.y) /* one diagonal, move up along it */ {move(pos.x<5 ? SOUTH_EAST : NORTH_WEST);}
else if (pos.x+pos.y==10) /* other diagonal, move up along it */ {move(pos.x-pos.y<0 ? NORTH_EAST : SOUTH_WEST);}
else if (getElevation() == 5) /* one step from the top, move directly there */ {
if (pos.x+pos.y < 10) {
if(pos.x-pos.y < 0) /* west side */ {move(EAST);}
else /* north side */ {move(SOUTH);}
}
else {
if(pos.x-pos.y < 0) /* south side */ {move(NORTH);}
else /* east side */ {move(WEST);}
}
}
else if (pos.x+pos.y < 10) {
if(pos.x-pos.y < 0) /* west side */ {moveRand3(EAST, SOUTH_EAST, NORTH_EAST);}
else /* north side */ {moveRand3(SOUTH, SOUTH_EAST, SOUTH_WEST);}
}
else {
if (pos.x - pos.y < 0) /* south side */ {moveRand3(NORTH, NORTH_EAST, NORTH_WEST);}
else /* east side */ {moveRand3(WEST,NORTH_WEST, SOUTH_WEST);}
}
}
else /* too weak, circle on current level */ {
if (pos.x==pos.y) /* one diagonal, move either corner */ {
if(pos.x+pos.y < 10) /* north-west corner */ {moveRand2(EAST,SOUTH);}
else /* south-east corner */ {moveRand2(NORTH,WEST);}
}
else if (pos.x+pos.y==10) /* other diagonal, move either corner */ {
if(pos.x-pos.y>0) /* north-east corner */ {moveRand2(SOUTH, WEST);}
else /* south-west corner */ {moveRand2(NORTH, EAST);}
}
else if (pos.x+pos.y < 10) {
if(pos.x-pos.y < 0) /* west side */ {moveRand2(NORTH, SOUTH);}
else /* north side */ {moveRand2(EAST, WEST);}
}
else {
if (pos.x - pos.y < 0) /* south side */ {moveRand2(EAST, WEST);}
else /* east side */ {moveRand2(NORTH, SOUTH);}
}
}
}
private void moveRand2(MoveDirection A, MoveDirection B) {
switch (ThreadLocalRandom.current().nextInt(2)) {
case 0:move(A);
case 1:move(B);
}
}
private void moveRand3(MoveDirection A, MoveDirection B, MoveDirection C) {
switch (ThreadLocalRandom.current().nextInt(3)) {
case 0:move(A);
case 1:move(B);
case 2:move(C);
}
}
}
```
[Answer]
# Weight Crab
Possesses the ordinary Crab's singleminded drive to reach the top and refusal to back down from a fight, but tries a bit harder not to pick fights by de-ranking its ascentful options by how likely another bot is to land there (though not differentiating between other bots by age, gender or weight), making it hard to eat while going about relieving its competitors of their scores.
```
package io.github.seggan.kingoftheziggurat.bots;
import io.github.seggan.kingoftheziggurat.Bot;
import static io.github.seggan.kingoftheziggurat.MoveDirection.*;
import io.github.seggan.kingoftheziggurat.MoveDirection;
import java.util.Map;
import java.util.HashMap;
import java.util.stream.Collectors;
import java.awt.Point;
import java.lang.Math;
public class WeightCrab extends Bot {
@Override
protected boolean fight(Bot opponent) {
return getElevation() > 1;
}
@Override
protected void tick() {
if (getElevation() == 6) {
move(NONE);
return;
}
Map<MoveDirection, Integer> weights = new HashMap<>();
Map<Point, Integer> botPositionCounts = new HashMap<>();
for (Bot bot : getPlayers()) {
Point position = bot.getPosition();
botPositionCounts.put(position, botPositionCounts.getOrDefault(position, 0) + 1);
}
for (MoveDirection direction : MoveDirection.values()) {
int weight = (getElevationRelative(direction) - getElevation()) * 89;
Point candidate = relativePositionFrom(direction, getPosition());
for (Map.Entry<Point, Integer> entry : botPositionCounts.entrySet()) {
Point position = entry.getKey();
int count = entry.getValue();
if (defaultUpFrom(position).equals(candidate)) {
weight -= 2 * count;
}
if (elevationAt(candidate) > elevationAt(position) && withinReachOf(candidate, position)) {
weight -= count;
}
}
weights.put(direction, weight);
}
MoveDirection chosen = weights.entrySet().stream().collect(
Collectors.maxBy((a, b) ->
a.getValue().compareTo(b.getValue())
)).get().getKey();
move(chosen);
}
private static Point relativePositionFrom(MoveDirection direction, Point from) {
int x = from.x;
int y = from.y;
switch(direction) {
case NORTH:
return new Point(x, y - 1);
case SOUTH:
return new Point(x, y + 1);
case EAST:
return new Point(x + 1, y);
case WEST:
return new Point(x - 1, y);
case NORTH_EAST:
return new Point(x + 1, y - 1);
case NORTH_WEST:
return new Point(x - 1, y - 1);
case SOUTH_EAST:
return new Point(x + 1, y + 1);
case SOUTH_WEST:
return new Point(x - 1, y + 1);
default: // why won't it let me just do an exhaustive enum match ;(
return from;
}
}
private static int elevationAt(Point point) {
int fromCorner = Math.min(point.x, point.y) + 1;
return Math.min(fromCorner, 12 - fromCorner);
}
private static Point defaultUpFrom(Point from) {
for (MoveDirection direction : MoveDirection.values()) {
if (elevationAt(relativePositionFrom(direction, from)) > elevationAt(from)) {
return relativePositionFrom(direction, from);
}
}
return from;
}
private static boolean withinReachOf(Point a, Point b) {
return Math.abs(a.x - b.x) <= 1 && Math.abs(a.y - b.y) <= 1;
}
}
```
[Answer]
# RealisticPacifist
A rather weak bot with more complexity than it is worth. It tries to avoid fights unless it has a fair amount of strength relative to the number of rounds played so far. It then tries to fight when it can. It tries to stay around an elevation of 4 or 5, so as to avoid the strong bots at the center (6). It occasionally moves to the east or to the west. It won rounds #1 and #2 through luck and randomness. Full disclosure: I have not used Java before today.
```
import java.util.Random;
class RealisticPacifist extends io.github.seggan.kingoftheziggurat.impl.Bot {
Random random = new Random();
int ticks = 0;
@Override
protected boolean fight(Bot opponent) {
return (random.nextDouble()<0.4) || (getStrength() > (ticks/7));
}
@Override
protected void tick() {
ticks += 1;
if (random.nextDouble() > 0.025) {
moveUp();
} else {
if (getPosition().x > 7) {
move(WEST);
}
else if (getPosition().y > 7) {
move(NORTH);
}
else if (getPosition().x < 4) {
move(EAST);
}
else if (getPosition().y < 4) {
move(SOUTH);
} else
{
switch (random.nextInt(4)) {
case 0: move(EAST);break;
case 1: move(WEST);break;
case 2: move(NORTH);break;
case 3: move(SOUTH);break;
}
}
}
}
}
```
Note: This is my first time participating in a KOTH challenge. If I have done something incorrectly, I apologize and will attempt to rectify my mistake as soon as I am able.
[Answer]
# ChaoticWalkerIII (The bot formerly known as MazeRunner)
New and improved Chaotic Walker. Now wins over 50% of the games. Bad midgame, but best bot early and late in general. Code based on both other entries at various points (but with my terrible implementation).
```
package io.github.seggan.kingoftheziggurat;
import java.util.Random;
import static io.github.seggan.kingoftheziggurat.MoveDirection.*;
import java.util.concurrent.ThreadLocalRandom;
class ChaoticWalkerIII extends Bot {
Random random = new Random();
int ticks = 0;
@Override
protected boolean fight(Bot opponent) {
if(random.nextDouble()>.9)
{return ticks > 6;}
else{
return true;}
}
private MoveDirection whichWayUp() {
int relEvUp = getElevationRelative(NORTH)-getElevation();
int relEvDown = getElevationRelative(SOUTH)-getElevation();
int relEvLeft = getElevationRelative(WEST)-getElevation();
if(relEvUp>0) {return NORTH;} else if(relEvDown>0) {return SOUTH;} else if(relEvLeft>0) {return WEST;} else {return EAST;}
}
private MoveDirection diagonalMove(MoveDirection m)
{
if(m==NORTH)
{
if(random.nextBoolean())
{return NORTH_EAST;}
return NORTH_WEST;}
else if(m==SOUTH)
{
if(random.nextBoolean())
{return SOUTH_EAST;}
return SOUTH_WEST;}
else if(m==EAST)
{
if(random.nextBoolean())
{return NORTH_EAST;}
return SOUTH_EAST;
}
else
{
if(random.nextBoolean())
{
return NORTH_WEST;
}
return SOUTH_WEST;
}
}
@Override
protected void tick() {
ticks++;
if (ticks<10)
{
move(diagonalMove(whichWayUp()));
}
else if (getElevation() < 6) {
if(random.nextDouble()>.1||(getStrength()>15))
{moveUp();}
else if (random.nextDouble()>.05) {move(diagonalMove(whichWayUp()));}
else if (random.nextDouble()>.8) {move(MoveDirection.values()[ThreadLocalRandom.current().nextInt(MoveDirection.values().length)]);}
else {move(MoveDirection.NONE);}}
else if (random.nextDouble()>.3)
{
move(MoveDirection.values()[ThreadLocalRandom.current().nextInt(MoveDirection.values().length)]);
}
else
{
move(MoveDirection.NONE);
}}}
```
[Answer]
# Crab
```
public class Crab extends io.github.seggan.kingoftheziggurat.Bot {
@Override
protected boolean fight(Bot opponent) {
return true;
}
@Override
protected void tick () {
if (getElevation() == 6) {
move(NONE);
} else {
moveUp();
}
}
}
```
It's because of Crab that we can't have nice things.
[Answer]
## Greedy Bot
```
import java.util.Random;
public class GreedyBot extends io.github.seggan.kingoftheziggurat.Bot {
private Random random = new Random();
private int roundcount = 0;
private int prevheight = 0; //doesn't really matter at first
private int prevheight2 = -1; //doesn't really matter at first
private int height = -1; //doesn't really matter at first
@Override
protected boolean fight(Bot opponent) {
if (roundcount<10) {
return false;
}
if (getElevation()>=5) {
if (random.nextDouble()>=0.7) {
return true;
}
return false;
} else if (getElevation()==4) {
if (random.nextDouble()>=0.95) {
return true;
}
return false;
} else {
return false;
}
}
@Override
protected void tick() {
roundcount++;
if (getElevation()>prevheight) {
moveUp();
} else if (getElevation()==prevheight && prevheight == prevheight2){
moveUp();
} else if (getElevation()==prevheight) {
if (getElevationRelative(move(NORTH)) <getElevation()) {
move(SOUTH);
} else {
move(NORTH);
}
} else {
if (getElevationRelative(move(NORTH)) <getElevation()) {
if (getElevationRelative(move(East)) <getElevation()) {
move(SOUTH_WEST);
} else {
move(SOUTH_EAST);
}
} else {
if (getElevationRelative(move(East)) < getElevation()) {
move(NORTH_WEST);
} else {
move(NORTH_EAST);
}
}
}
prevheight2 = prevheight;
prevheight = height;
height = getElevation();
}
}
```
This is my first time doing something like this, so this bot may be a bit nieve.
It tries to climb to the top, until it gets stopped by something, where it usually yields to build up a higher strength. When it gets to a position more worth defending, it has a higher chance of defending it. Climbing is pretty deterministic, but when it has climbed and failed a few times because something is in the way, it tries to evade it. This also serves to avoid more aggressive bots from reducing it's strength by too much when it's at the top.
It was also made to be disgusting to the eyes of code golfers. :D
[Answer]
# Ssammbot
Waits on level 3 until it builds up enough strength then attacks for the top. I plan to later make it actually take other bots into account instead of just sitting still while waiting. I may also tweak the numbers depending on what round we are in.
Written in tcl using the socket api and requires `tcllib` for the json parser. Can be added with with `new BotWrapper("tclsh", "bot.tcl")`
```
package require json
#reset the bot for a new round
set round 0
proc init {} {
variable ::map {}
variable ::centerX 0
variable ::centerY 0
variable ::waitLevel 3
variable ::fightTarget 30
variable ::retreatTarget 12
variable ::attacking 0
variable ::enemies [dict create]
variable ::turn 0
incr $::round
}
proc parseMap {mapdata} {
foreach row [split $mapdata \n] {
lappend ::map [split $row {}]
}
set ::centerX [expr [llength $::map] /2]
set ::centerY [expr [llength [lindex $::map 0]] /2]
}
proc moveTowardsCerter {cx cy} {
set ns {}
set ew {}
if {$cx < $::centerX} {
set ew "EAST"
} elseif {$cx > $::centerX} {
set ew "WEST"
}
if {$cy < $::centerY} {
set ns "SOUTH"
} elseif {$cy > $::centerY} {
set ns "NORTH"
}
set res [string trim [string cat $ns _ $ew] _]
if {$res eq {}} { return "NONE" }
return $res
}
proc tick {botState} {
if {[dict get $botState strength] == 0} {
init
}
if {$::map eq {}} {
parseMap [dict get $botState map]
}
set targetLevel $::waitLevel
if {[dict get $botState strength] > $::fightTarget} {
set ::attacking 1
}
if {$::attacking && [dict get $botState strength] < $::retreatTarget} {
set ::attacking 0
}
set targetLevel $::waitLevel
if {$::attacking} {
set targetLevel 6
}
set movement "NONE"
if {[dict get $botState elevation] < $targetLevel} {
set movement [moveTowardsCerter [dict get $botState x] [dict get $botState y]]
}
incr $::turn
return $movement
}
proc fight {botState} {
if {[dict get $botState elevation] == 6 && $::attacking} {
return "true"
}
return "false"
}
proc processCommand {serverSock} {
yield
if {[chan eof $serverSock]} {
chan close $serverSock
exit 0
}
set command [gets $serverSock]
yield
if {[chan eof $serverSock]} {
chan close $serverSock
exit 0
}
set serverData [gets $serverSock]
set args [dict create]
if {[catch {set args [::json::json2dict $serverData]}]} {
puts stderr "Faild to parse json"
puts stderr $::errorInfo
}
set response {}
if {$command eq "tick"} {
if {[catch {set response [tick $args]} err]} {
puts stderr $::errorInfo
set response "NONE"
}
} else {
if {[catch {set response [fight $args]} err]} {
puts stderr $::errorInfo
set response "false"
}
}
puts $serverSock $response
flush $serverSock
tailcall processCommand $serverSock
}
proc main {argc argv} {
if {$argc != 1} {
puts "Usage: bot <port>"
exit -1
}
after 300
set serverSock [socket localhost [lindex $argv 0]]
chan configure $serverSock -blocking 0
coroutine processLine processCommand $serverSock
chan event $serverSock readable processLine
}
main $argc $argv
vwait closeBot
```
```
[Answer]
# CrabberInTraining
The bot's name came from the original code, which would only fight Crab and WeightCrab unless absolutely necessary, but I removed that functionality because I didn't know if it was allowed. It's pretty much a less aggressive WeightCrab with different weights, but with a built-in movement plan for the first ten turns of each round based on ChaoticWalker and a small chance of moving randomly while on top of the Ziggurat. Generally beats all the other bots, but not by a huge margin. Will continue to improve it over time.
```
package io.github.seggan.kingoftheziggurat.bots;
import static io.github.seggan.kingoftheziggurat.MoveDirection.*;
import java.awt.Point;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ThreadLocalRandom;
import java.util.stream.Collectors;
import io.github.seggan.kingoftheziggurat.Bot;
import io.github.seggan.kingoftheziggurat.MoveDirection;
public class CrabberInTraining extends Bot {
Random random = new Random();
int ticks = 0;
protected boolean fight(Bot opponent) {
return getElevation() > 4 || getStrength()>18;
}
private MoveDirection diagonalMove(MoveDirection m) {
if (m == NORTH) {
if (random.nextBoolean()) {
return NORTH_EAST;
}
return NORTH_WEST;
} else if (m == SOUTH) {
if (random.nextBoolean()) {
return SOUTH_EAST;
}
return SOUTH_WEST;
} else if (m == EAST) {
if (random.nextBoolean()) {
return NORTH_EAST;
}
return SOUTH_EAST;
} else {
if (random.nextBoolean()) {
return NORTH_WEST;
}
return SOUTH_WEST;
}
}
private static Point relativePositionFrom(MoveDirection direction, Point from) {
int x = from.x;
int y = from.y;
switch(direction) {
case NORTH:
return new Point(x, y - 1);
case SOUTH:
return new Point(x, y + 1);
case EAST:
return new Point(x + 1, y);
case WEST:
return new Point(x - 1, y);
case NORTH_EAST:
return new Point(x + 1, y - 1);
case NORTH_WEST:
return new Point(x - 1, y - 1);
case SOUTH_EAST:
return new Point(x + 1, y + 1);
case SOUTH_WEST:
return new Point(x - 1, y + 1);
default:
return from;
}
}
private MoveDirection whichWayUp() {
int relEvUp = getElevationRelative(NORTH) - getElevation();
int relEvDown = getElevationRelative(SOUTH) - getElevation();
int relEvLeft = getElevationRelative(WEST) - getElevation();
if (relEvUp > 0) {
return NORTH;
} else if (relEvDown > 0) {
return SOUTH;
} else if (relEvLeft > 0) {
return WEST;
} else {
return EAST;
}
}
private static int elevationAt(Point point) {
int fromCorner = Math.min(point.x, point.y) + 1;
return Math.min(fromCorner, 12 - fromCorner);
}
private static boolean withinReachOf(Point a, Point b) {
return Math.abs(a.x - b.x) <= 1 && Math.abs(a.y - b.y) <= 1;
}
private static Point defaultUpFrom(Point from) {
for (MoveDirection direction : MoveDirection.values()) {
if (elevationAt(relativePositionFrom(direction, from)) > elevationAt(from)) {
return relativePositionFrom(direction, from);
}
}
return from;
}
@Override
protected void tick() {
if(ticks<10||(50<ticks&&ticks<60)||(150<ticks&&ticks<160)||(300<ticks&&ticks<310)||(800<ticks&&ticks<810))
{
move(diagonalMove(whichWayUp()));
}
if (getElevation() == 6) {
if(random.nextDouble()<.9) {move(NONE);}{move(MoveDirection.values()[ThreadLocalRandom.current().nextInt(MoveDirection.values().length)]);}
return;
}
Map<MoveDirection, Double> weights = new HashMap<>();
Map<Point, Integer> botPositionCounts = new HashMap<>();
for (Bot bot : getPlayers()) {
Point position = bot.getPosition();
botPositionCounts.put(position, botPositionCounts.getOrDefault(position, 0) + 1);}
for (MoveDirection direction : MoveDirection.values()) {
double weight = (getElevationRelative(direction) - 2*getElevation()) * 200;
Point candidate = relativePositionFrom(direction, getPosition());
for (Map.Entry<Point, Integer> entry : botPositionCounts.entrySet()) {
Point position = entry.getKey();
int count = entry.getValue();
if (defaultUpFrom(position).equals(candidate)) {
weight -= 3 * count;
}
if (elevationAt(candidate) > elevationAt(position) && withinReachOf(candidate, position)) {
weight -= count;
} weights.put(direction, weight);
}
MoveDirection chosen = weights.entrySet().stream().collect(
Collectors.maxBy((a, b) ->
a.getValue().compareTo(b.getValue())
)).get().getKey();
move(chosen);
}}}
```
```
[Answer]
# GroundUpBot
NOTE: This bot uses pretty much everyone's helper function and a version of their algorithm, so credit to them for creating those bots.
Unlike the ChaoticWalker family, which started as a modified RealisticPacifist, or CrabberInTraining, which is WeightCrab with bits of ChaoticWalkerIII attached to it, GroundUpBot was created from scratch. It re-implements the algorithms of all existing bots and assigns a probability to each location on the Ziggurat for each bot to move. It combines that with a weighting system to decide how important it is to gain strength vs. move up and gain score to reach the best decision it can about where to move. Currently, it cannot approximate the strength of other bots, nor does it take it into account, but a variant of the bot did attempt to guess how strong Crab was by finding when it lost a fight (and therefore, moved down).
Code (now commented):
```
package io.github.seggan.kingoftheziggurat.bots;
import static io.github.seggan.kingoftheziggurat.MoveDirection.EAST;
import static io.github.seggan.kingoftheziggurat.MoveDirection.NONE;
import static io.github.seggan.kingoftheziggurat.MoveDirection.NORTH;
import static io.github.seggan.kingoftheziggurat.MoveDirection.NORTH_EAST;
import static io.github.seggan.kingoftheziggurat.MoveDirection.NORTH_WEST;
import static io.github.seggan.kingoftheziggurat.MoveDirection.SOUTH;
import static io.github.seggan.kingoftheziggurat.MoveDirection.SOUTH_EAST;
import static io.github.seggan.kingoftheziggurat.MoveDirection.SOUTH_WEST;
import static io.github.seggan.kingoftheziggurat.MoveDirection.WEST;
import java.awt.Point;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import io.github.seggan.kingoftheziggurat.Bot;
import io.github.seggan.kingoftheziggurat.MoveDirection;
public class GroundUpBot extends Bot {
Random random = new Random();
int ticks = 0;
@Override
protected boolean fight(Bot opponent) {
if (ticks<10||(50<ticks&&ticks<60)||(150<ticks&&ticks<160)||(300<ticks&&ticks<310)||(800<ticks&&ticks<810))
{
return getStrength()>2; //Fight if not helpless on first ten ticks of each round
}
else
{
return getStrength()>5; //Otherwise, fight once strong enough to stand up to some stuff
}
}
private static Point relativePositionFrom(MoveDirection direction, Point from) {//For WeightCrab/CrabberInTraining
int x = from.x;
int y = from.y;
return switch (direction) {
case NORTH -> new Point(x, y - 1);
case SOUTH -> new Point(x, y + 1);
case EAST -> new Point(x + 1, y);
case WEST -> new Point(x - 1, y);
case NORTH_EAST -> new Point(x + 1, y - 1);
case NORTH_WEST -> new Point(x - 1, y - 1);
case SOUTH_EAST -> new Point(x + 1, y + 1);
case SOUTH_WEST -> new Point(x - 1, y + 1);
default -> // why won't it let me just do an exhaustive enum match ;(
from;
};}
private static int elevationAt(Point point) {//For WeightCrab/CrabberInTraining
int fromCorner = Math.min(point.x, point.y) + 1;
return Math.min(fromCorner, 12 - fromCorner);
}
private static Point defaultUpFrom(Point from) {//For WeightCrab/CrabberInTraining
for (MoveDirection direction : MoveDirection.values()) {
if (elevationAt(relativePositionFrom(direction, from)) > elevationAt(from)) {
return relativePositionFrom(direction, from);
}
}
return from;
}
private static boolean withinReachOf(Point a, Point b) {//For WeightCrab/CrabberInTraining
return Math.abs(a.x - b.x) <= 1 && Math.abs(a.y - b.y) <= 1;
}
private MoveDirection whichWayUp(Bot bot) {//For ChaoticWalkerIII/CrabberInTraining. Can now take arbitrary bot instead of just current bot.
int relEvUp = bot.getElevationRelative(NORTH) - bot.getElevation();
int relEvDown = bot.getElevationRelative(SOUTH) - bot.getElevation();
int relEvLeft = bot.getElevationRelative(WEST) - bot.getElevation();
if (relEvUp > 0) {
return NORTH;
} else if (relEvDown > 0) {
return SOUTH;
} else if (relEvLeft > 0) {
return WEST;
} else {
return EAST;
}
}
private static Point whereMoveTake(MoveDirection direction, Bot bot) {//Generally used by GroundUpBot
int x = bot.getPosition().x;
int y = bot.getPosition().y;
return switch (direction) {
case NORTH -> new Point(x, y - 1);
case SOUTH -> new Point(x, y + 1);
case EAST -> new Point(x + 1, y);
case WEST -> new Point(x - 1, y);
case NORTH_EAST -> new Point(x + 1, y - 1);
case NORTH_WEST -> new Point(x - 1, y - 1);
case SOUTH_EAST -> new Point(x + 1, y + 1);
case SOUTH_WEST -> new Point(x - 1, y + 1);
default -> bot.getPosition();
};
}
private MoveDirection moveBotUp(Bot bot) {//Used by most bots as a replacement for MoveUp
for (MoveDirection direction : MoveDirection.values()) {
if (getElevationRelative(direction) > bot.getElevation()) {
return direction;
}
}
return MoveDirection.NONE;
}
protected HashMap<Point,Double> whatMove(Bot bot,HashMap<Point,Double> defaultGrid)//The main function
{/*
This predicts the movement of any bot it is given and saves the probabilities of motion to each point on the HashMap.
*/
if(bot instanceof Crab)
{
Point p = whereMoveTake(moveBotUp(bot),bot);
defaultGrid.put(p,defaultGrid.getOrDefault(p,0.)-1);//Crab is deterministic, it's easy to predict.
return defaultGrid;
}
else if(bot instanceof RealisticPacifist)
{
if (bot.getElevation() > 4) {
defaultGrid.put(bot.getPosition(),defaultGrid.getOrDefault(bot.getPosition(),0.)-.7);
Point p = whereMoveTake(moveBotUp(bot),bot); //70-30 for RealisticPacifist when at high elevation.
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.3);
return defaultGrid;
}
else
{
Point p = whereMoveTake(moveBotUp(bot),bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.95); //95% it moves up in these cases
if (bot.getPosition().x > 7) { //Otherwise, if near an edge, move towards center
Point p2 = whereMoveTake(WEST,bot);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.05);
} else if (bot.getPosition().y > 7) {
Point p2 = whereMoveTake(NORTH,bot);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.05);
} else if (bot.getPosition().x < 4) {
Point p2 = whereMoveTake(EAST,bot);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.05);
} else if (bot.getPosition().y < 4) {
Point p2 = whereMoveTake(SOUTH,bot);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.05);
}
else
{//Otherwise move randomly on a cardinal direction
Point p2 = whereMoveTake(WEST,bot);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.0125);
Point p3 = whereMoveTake(NORTH,bot);
defaultGrid.put(p3, defaultGrid.getOrDefault(p3,0.)-.0125);
Point p4 = whereMoveTake(EAST,bot);
defaultGrid.put(p4, defaultGrid.getOrDefault(p4,0.)-.0125);
Point p5 = whereMoveTake(SOUTH,bot);
defaultGrid.put(p5, defaultGrid.getOrDefault(p5,0.)-.0125);
}
return defaultGrid;}
}
else if (bot instanceof JazzJock)
{
Point pos = bot.getPosition();
if(ticks<4||(50<ticks&&ticks<54)||(150<ticks&&ticks<154)||(300<ticks&&ticks<304)||(800<ticks&&ticks<804))
{//Can't check its strength, so instead assume it spends ticks 0-3 preparing.
if(pos.x==pos.y)//On northwest-southeast diagonal?
{
if(pos.x+pos.y<10)//On the northwest side?
{
Point p = whereMoveTake(EAST,bot);//Move either east or south.
Point p2 = whereMoveTake(SOUTH,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else {
Point p = whereMoveTake(NORTH,bot); //Otherwise, move north or west.
Point p2 = whereMoveTake(WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
}
else if (pos.x+pos.y==10)//On the other diagonal?
{
if(pos.x-pos.y>0)//Check which side of top you are on.
{
Point p = whereMoveTake(SOUTH,bot);//Move south or west.
Point p2 = whereMoveTake(WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else
{
Point p = whereMoveTake(EAST,bot);//Move north or east.
Point p2 = whereMoveTake(NORTH,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
}
else if (pos.x+pos.y<10)//North or west of center?
{
if(pos.x-pos.y<0)//If west, move N/S
{
Point p = whereMoveTake(NORTH,bot);
Point p2 = whereMoveTake(SOUTH,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else//If north, move E/W
{
Point p = whereMoveTake(EAST,bot);
Point p2 = whereMoveTake(WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
}
else//Do the same for the southeastern side.
{
if(pos.x-pos.y<0)
{
Point p = whereMoveTake(EAST,bot);
Point p2 = whereMoveTake(WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else
{
Point p = whereMoveTake(NORTH,bot);
Point p2 = whereMoveTake(SOUTH,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
}
}
else//Strength high enough to move
{
if(bot.getElevation()==6)//Are you on top?
{
defaultGrid.put(pos, defaultGrid.getOrDefault(pos,0.)-1);//If so, JazzJock won't move.
}
else if(pos.x==pos.y)//Are you on that diagonal?
{
if(pos.x<5)//Figure out which side
{
//Move southeast if that's towards the top
defaultGrid.put(whereMoveTake(SOUTH_EAST,bot), defaultGrid.getOrDefault(whereMoveTake(SOUTH_EAST,bot),0.)-1);
}
else
{
//Otherwise, move northwest
defaultGrid.put(whereMoveTake(NORTH_WEST,bot), defaultGrid.getOrDefault(whereMoveTake(NORTH_WEST,bot),0.)-1);
}
}
else if (pos.x+pos.y==10)//Are you on the second diagonal?
{
if(pos.x-pos.y<0)
{
//If so, move northeast or southwest, depending on which is towards the center.
defaultGrid.put(whereMoveTake(NORTH_EAST,bot), defaultGrid.getOrDefault(whereMoveTake(NORTH_EAST,bot),0.)-1);
}
else
{
defaultGrid.put(whereMoveTake(SOUTH_WEST,bot), defaultGrid.getOrDefault(whereMoveTake(SOUTH_WEST,bot),0.)-1);
}
}
else if (bot.getElevation()==5)//Are you on the second highest level?
{
if(pos.x+pos.y<10)//If so, move directly to the top via cardinal directions.
{
if(pos.x-pos.y<0)
{
defaultGrid.put(whereMoveTake(EAST,bot), defaultGrid.getOrDefault(whereMoveTake(EAST,bot),0.)-1);
}
else
{
defaultGrid.put(whereMoveTake(SOUTH,bot), defaultGrid.getOrDefault(whereMoveTake(SOUTH,bot),0.)-1);
}
}
else
{
if(pos.x-pos.y<0)
{
defaultGrid.put(whereMoveTake(NORTH,bot), defaultGrid.getOrDefault(whereMoveTake(NORTH,bot),0.)-1);
}
else
{
defaultGrid.put(whereMoveTake(WEST,bot), defaultGrid.getOrDefault(whereMoveTake(WEST,bot),0.)-1);
}
}
}
else//Otherwise, move somewhat randomly towards the top. Put a 1/3 probability for all 3 options.
{
if(pos.x+pos.y<10)
{
if(pos.x-pos.y<0)//If on the west side
{
//Move east or east-adjacent.
Point p = whereMoveTake(EAST,bot);
Point p2 = whereMoveTake(SOUTH_EAST,bot);
Point p3 = whereMoveTake(NORTH_EAST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-1./3);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-1./3);
defaultGrid.put(p3, defaultGrid.getOrDefault(p3,0.)-1./3);
}
else//If on the east side
{
//Move west or diagonally west.
Point p = whereMoveTake(WEST,bot);
Point p2 = whereMoveTake(SOUTH_WEST,bot);
Point p3 = whereMoveTake(NORTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-1./3);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-1./3);
defaultGrid.put(p3, defaultGrid.getOrDefault(p3,0.)-1./3);
}
}
else
{
if(pos.x-pos.y<0)//In the south?
{
//Move towards the north.
Point p = whereMoveTake(NORTH,bot);
Point p2 = whereMoveTake(NORTH_EAST,bot);
Point p3 = whereMoveTake(NORTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-1./3);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-1./3);
defaultGrid.put(p3, defaultGrid.getOrDefault(p3,0.)-1./3);
}
else//Otherwise
{
//Move south.
Point p = whereMoveTake(SOUTH,bot);
Point p2 = whereMoveTake(SOUTH_EAST,bot);
Point p3 = whereMoveTake(SOUTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-1./3);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-1./3);
defaultGrid.put(p3, defaultGrid.getOrDefault(p3,0.)-1./3);
}
}
}
}
return defaultGrid;}
else if (bot instanceof ChaoticWalkerIII)//Is it a ChaoticWalker?
{
if(ticks<10)//On the first few rounds, ChaoticWalker moves diagonally upwards. Can't guess which way, so assign 50% to each.
{
MoveDirection v = whichWayUp(bot);//Find which way the bot will head
if(v==NORTH)//Then fill in the diagonal moves from that
{
Point p = whereMoveTake(NORTH_EAST,bot);
Point p2 = whereMoveTake(NORTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else if (v==SOUTH)
{
Point p = whereMoveTake(SOUTH_EAST,bot);
Point p2 = whereMoveTake(SOUTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else if (v==EAST)
{
Point p = whereMoveTake(NORTH_EAST,bot);
Point p2 = whereMoveTake(SOUTH_EAST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else
{
Point p = whereMoveTake(NORTH_WEST,bot);
Point p2 = whereMoveTake(SOUTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
}
else if (bot.getElevation()<6)//Otherwise, 90% of the time you head straight up.
{
Point p1 = whereMoveTake(moveBotUp(bot),bot);
defaultGrid.put(p1,defaultGrid.getOrDefault(p1,0.)-.9);
MoveDirection v = whichWayUp(bot);
if(v==NORTH)//It sometimes moves diagonally though, but quite rare.
{
Point p = whereMoveTake(NORTH_EAST,bot);
Point p2 = whereMoveTake(NORTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-0.0475);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-0.0475);
}
else if (v==SOUTH)
{
Point p = whereMoveTake(SOUTH_EAST,bot);
Point p2 = whereMoveTake(SOUTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-0.0475);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-0.0475);
}
else if (v==EAST)
{
Point p = whereMoveTake(NORTH_EAST,bot);
Point p2 = whereMoveTake(SOUTH_EAST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-0.0475);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-0.0475);
}
else
{
Point p = whereMoveTake(NORTH_WEST,bot);
Point p2 = whereMoveTake(SOUTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-0.0475);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-0.0475);
}
//Even less often, it will move at random or stay still.
defaultGrid.put(whereMoveTake(NORTH,bot),defaultGrid.getOrDefault(whereMoveTake(NORTH,bot),0.)-0.000125);
defaultGrid.put(whereMoveTake(SOUTH,bot),defaultGrid.getOrDefault(whereMoveTake(SOUTH,bot),0.)-0.000125);
defaultGrid.put(whereMoveTake(EAST,bot),defaultGrid.getOrDefault(whereMoveTake(EAST,bot),0.)-0.000125);
defaultGrid.put(whereMoveTake(WEST,bot),defaultGrid.getOrDefault(whereMoveTake(WEST,bot),0.)-0.000125);
defaultGrid.put(whereMoveTake(NORTH_EAST,bot),defaultGrid.getOrDefault(whereMoveTake(NORTH_EAST,bot),0.)-0.000125);
defaultGrid.put(whereMoveTake(NORTH_WEST,bot),defaultGrid.getOrDefault(whereMoveTake(NORTH_WEST,bot),0.)-0.000125);
defaultGrid.put(whereMoveTake(SOUTH_EAST,bot),defaultGrid.getOrDefault(whereMoveTake(SOUTH_EAST,bot),0.)-0.000125);
defaultGrid.put(whereMoveTake(SOUTH_WEST,bot),defaultGrid.getOrDefault(whereMoveTake(SOUTH_WEST,bot),0.)-0.000125);
defaultGrid.put(bot.getPosition(),defaultGrid.getOrDefault(bot.getPosition(),0.)-0.004);
}
else
{
//If on top,it will stay 30% of the time, but move the other 70%.
defaultGrid.put(bot.getPosition(),defaultGrid.getOrDefault(bot.getPosition(),0.)-0.3);
defaultGrid.put(whereMoveTake(NORTH,bot),defaultGrid.getOrDefault(whereMoveTake(NORTH,bot),0.)-0.0875);
defaultGrid.put(whereMoveTake(SOUTH,bot),defaultGrid.getOrDefault(whereMoveTake(SOUTH,bot),0.)-0.0875);
defaultGrid.put(whereMoveTake(EAST,bot),defaultGrid.getOrDefault(whereMoveTake(EAST,bot),0.)-0.0875);
defaultGrid.put(whereMoveTake(WEST,bot),defaultGrid.getOrDefault(whereMoveTake(WEST,bot),0.)-0.0875);
defaultGrid.put(whereMoveTake(NORTH_EAST,bot),defaultGrid.getOrDefault(whereMoveTake(NORTH_EAST,bot),0.)-0.0875);
defaultGrid.put(whereMoveTake(NORTH_WEST,bot),defaultGrid.getOrDefault(whereMoveTake(NORTH_WEST,bot),0.)-0.0875);
defaultGrid.put(whereMoveTake(SOUTH_EAST,bot),defaultGrid.getOrDefault(whereMoveTake(SOUTH_EAST,bot),0.)-0.0875);
defaultGrid.put(whereMoveTake(SOUTH_WEST,bot),defaultGrid.getOrDefault(whereMoveTake(SOUTH_WEST,bot),0.)-0.0875);
} return defaultGrid;}
else if (bot instanceof WeightCrab)//Otherwise, is it WeightCrab?
{
if(bot.getElevation()==6)//WeightCrab never moves down when on the top.
{
defaultGrid.put(bot.getPosition(), defaultGrid.getOrDefault(bot.getPosition(),0.)-1);
}
else {
Map<MoveDirection, Integer> weights = new HashMap<>();
Map<Point, Integer> botPositionCounts = new HashMap<>();
for (Bot bot2 : bot.getPlayers()) {//Otherwise, WeightCrab uses a weighting algorithm which assumes bots would rather go up or stay still.
Point position = bot2.getPosition();
botPositionCounts.put(position, botPositionCounts.getOrDefault(position, 0) + 1);//Mark each point with a bot
}
for (MoveDirection direction : MoveDirection.values()) {
int weight = (bot.getElevationRelative(direction) - bot.getElevation()) * 89;//Assume going up is better
Point candidate = relativePositionFrom(direction, bot.getPosition());
for (Map.Entry<Point, Integer> entry : botPositionCounts.entrySet()) {
Point position = entry.getKey();
int count = entry.getValue();
if (defaultUpFrom(position).equals(candidate)) {
weight -= 2 * count;
}//If you would move somewhere straight up from a bot, WeightCrab avoids that move.
if (elevationAt(candidate) > elevationAt(position) && withinReachOf(candidate, position)) {
weight -= count;
}//If you would move next to a bot, WeightCrab prefers to avoid that move.
}weights.put(direction, weight);
}
MoveDirection chosen = weights.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();
defaultGrid.put(whereMoveTake(chosen,bot),defaultGrid.get(whereMoveTake(chosen,bot))-1);//Find the best option.
}
return defaultGrid;}
else if (bot instanceof CrabberInTraining)//Now, what if it's CrabberInTraining?
{
if(ticks<10||(50<ticks&&ticks<60)||(150<ticks&&ticks<160)||(300<ticks&&ticks<310)||(800<ticks&&ticks<810))
{
//On the first 10 ticks of a round, it moves diagonally upwards, so we can reuse the code from ChaoticWalkerIII.
MoveDirection v = whichWayUp(bot);
if(v==NORTH)
{
Point p = whereMoveTake(NORTH_EAST,bot);
Point p2 = whereMoveTake(NORTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else if (v==SOUTH)
{
Point p = whereMoveTake(SOUTH_EAST,bot);
Point p2 = whereMoveTake(SOUTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else if (v==EAST)
{
Point p = whereMoveTake(NORTH_EAST,bot);
Point p2 = whereMoveTake(SOUTH_EAST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
else
{
Point p = whereMoveTake(NORTH_WEST,bot);
Point p2 = whereMoveTake(SOUTH_WEST,bot);
defaultGrid.put(p, defaultGrid.getOrDefault(p,0.)-.5);
defaultGrid.put(p2, defaultGrid.getOrDefault(p2,0.)-.5);
}
}
else if (bot.getElevation()==6)
{
//If it's on top, it will usually stay still, but rarely will move to another point.
defaultGrid.put(whereMoveTake(NORTH,bot),defaultGrid.get(whereMoveTake(NORTH,bot))-0.0125);
defaultGrid.put(whereMoveTake(SOUTH,bot),defaultGrid.get(whereMoveTake(SOUTH,bot))-0.0125);
defaultGrid.put(whereMoveTake(EAST,bot),defaultGrid.get(whereMoveTake(EAST,bot))-0.0125);
defaultGrid.put(whereMoveTake(WEST,bot),defaultGrid.get(whereMoveTake(WEST,bot))-0.0125);
defaultGrid.put(whereMoveTake(NORTH_EAST,bot),defaultGrid.get(whereMoveTake(NORTH_EAST,bot))-0.0125);
defaultGrid.put(whereMoveTake(NORTH_WEST,bot),defaultGrid.get(whereMoveTake(NORTH_WEST,bot))-0.0125);
defaultGrid.put(whereMoveTake(SOUTH_EAST,bot),defaultGrid.get(whereMoveTake(SOUTH_EAST,bot))-0.0125);
defaultGrid.put(whereMoveTake(SOUTH_WEST,bot),defaultGrid.get(whereMoveTake(SOUTH_WEST,bot))-0.0125);
defaultGrid.put(bot.getPosition(),defaultGrid.getOrDefault(bot.getPosition(),0.)-0.9);
}
else//Otherwise, CrabberInTraining will act like WeightCrab, but is generally more aggressive.
{
Map<MoveDirection, Double> weights = new HashMap<>();
Map<Point, Integer> botPositionCounts = new HashMap<>();
for (Bot bot2 : bot.getPlayers()) {
Point position = bot2.getPosition();
botPositionCounts.put(position, botPositionCounts.getOrDefault(position, 0) + 1);
}
for (MoveDirection direction : MoveDirection.values()) {
double weight = (bot.getElevationRelative(direction) - bot.getElevation()) * 20;
Point candidate = relativePositionFrom(direction, bot.getPosition());
for (Map.Entry<Point, Integer> entry : botPositionCounts.entrySet()) {
Point position = entry.getKey();
int count = entry.getValue();
if (defaultUpFrom(position).equals(candidate)) {
weight -= .3 * count;
}
if (elevationAt(candidate) > elevationAt(position) && withinReachOf(candidate, position)) {
weight -= count;
}
}weights.put(direction, weight);
}
MoveDirection chosen = weights.entrySet().stream().max(Map.Entry.comparingByValue()).get().getKey();
defaultGrid.put(whereMoveTake(chosen,bot),defaultGrid.getOrDefault(whereMoveTake(chosen,bot),0.)-1);//Guess where it will move.
}
return defaultGrid;
}
else//If it's an unknown bot, assume it acts like Crab. Most bots do a good chunk of the time.
{
Point p = whereMoveTake(moveBotUp(bot),bot);
defaultGrid.put(p,defaultGrid.getOrDefault(p,0.)-1);
return defaultGrid;
}
}
@Override
protected void tick() {
double scalingFactor = 2; //use to vary how much you care about going up
ticks++;//Advance the turns.
HashMap<Point,Double> weights = new HashMap<Point,Double>();
for(int i=0;i<11;i++)
{
for(int j=0;j<11;j++)//For all the points on the grid:
{
double val;
Point loc = new Point(i,j);
if(getStrength()>8)//If you are strong enough
{
if(Math.min(10-Math.max(j, i), Math.min(j, i))+1==6) {val=12.5*scalingFactor;}//Assign (usually) 25 points to top level
else if (Math.min(10-Math.max(j, i), Math.min(j, i))+1 == 5) {val = 7.5*scalingFactor;}//15 to level 5
else {val =.1*Math.pow(((double)(Math.min(10-Math.max(j, i), Math.min(j, i))+1)),3);}}//6.4 to level 4, 2.7 to level 3, .8 to level 2, and .1 to level 1.
//This means that it will always move up, except between levels 1 and 3, where a high chance of another bot interfering could cause it to stay.
//Theoretically, if it also knows multiple bots will move to the same location, it won't move there, but on level 6, it would take 5 other bots to try, so it's unlikely to occur the one spot it could.
else
{
val = (Math.min(10-Math.max(j, i), Math.min(j, i))+1)*scalingFactor;//Otherwise, assign 12 points to level 6, 10 to level 5...
}
weights.put(loc,val/2.1);//Divide these weights by 2.1, so that a value of 1 (the standard if it knows a bot will move somewhere) is enough to make a cell not worth visiting relative to one a level lower if the strength is less than 9.
}
}
for (Bot b : getPlayers())
{
weights = whatMove(b,weights);//Edit weights for each bot in the game using all that code above.
}
Point bestScoredLocation= getPosition();
int x= getPosition().x;
int y = getPosition().y;
double bestScore = -1000;//Define some values we need to decide where to move.
HashMap<Point,Double> movablePlaces = new HashMap<Point,Double>();//Create a list of places close enough to move to
List<Point> highestScored = new ArrayList<Point>();//Create a list of which of those have the highest score
for(int i = -1;i<2;i++)
{
for(int j=-1;j<2;j++)
{
movablePlaces.put(new Point(x+i,y+j), weights.getOrDefault(new Point(x+i,y+j),0.));
//Fill in the list of places to move to and their weights
}
}
for (Map.Entry<Point, Double> entry : movablePlaces.entrySet()) {//Find highest scored points
if (bestScore==entry.getValue()) {
bestScore = entry.getValue();
highestScored.add(entry.getKey());
} else if (entry.getValue() > bestScore) {
bestScore = entry.getValue();
highestScored.clear();
highestScored.add(entry.getKey());
}
}
bestScoredLocation = highestScored.get(random.nextInt(highestScored.size()));//Choose one at random (to stop other bots from using its own technique against it very well)
if(bestScoredLocation.x==x)//Decide where to move.
{if(bestScoredLocation.y<y){move(NORTH);}
else if(bestScoredLocation.y>y) {move(SOUTH);}
else{move(NONE);}}
else if (bestScoredLocation.x>x)
{
if(bestScoredLocation.y<y) {move(NORTH_EAST);}
else if(bestScoredLocation.y>y) {move(SOUTH_EAST);}
else {move(EAST);}
}
else
{
if(bestScoredLocation.y<y) {move(NORTH_WEST);}
else if(bestScoredLocation.y>y) {move(SOUTH_WEST);}
else {move(WEST);}
}
return;
}
}
```
## Example of decision process:
Assume that GroundUpBot has reasonably high strength and is currently at level 4. In that case, it will rank all points at level 5 as having a score of 7.5, all points at level 4 as having a score of `0.05*4^3=3.2`, and all points at level 3 as having a score of 1.35. However, say that another bot has a 90% chance of moving onto one of the level 5 cells and a 10% chance of moving onto a level 4 cell. That means that it will susbtract 0.9 from that cell at level 5 and .1 from the one at level 4, leaving two cells with a score of 7.5, which it will choose between at random. In this way, it will avoid cells which would lead to an unncesesary fight.
If it's strength is 8 or less, it will instead rank cells far more evenly, and will not move up a level if it is sure another bot will occupy its route of upward movement.
Generally, it scores somewhere from 5.22 to 5.28, winning against the other bots, while CrabberInTraining and ChaoticWalkerIII are usually in second and third place in some order. WeightCrab still does well, but it's usually in fourth. I don't have things set up to test with Ssammbot, so there's no code for it right now, but it behaves similarly enough to a Crab that my backup code for unidentified bots should handle things.
] |
[Question]
[
Your input will consist of an 18×18 image in any reasonable format, containing a horizontally and vertically centered 14px Roboto Mono character. This can be any of 94 printable ASCII characters (not including the space). But: **you only need to be able to recognize some 80 character subset** of your choice.
Output should be the character in the input image, as a character/string, code point, or some other reasonable representation.
To clarify input formats allowed, you can take input as an image in any reasonable representation, a matrix or array of pixels, or any other reasonable representation. You are allowed to assume the image will first be grayscaled or converted to black and white, and you can use that to, e.g., take input as a matrix of bools for white and black.
## Test cases
Since you choose a subset of printable ASCII to use, these may or may not need to be handled.
[](https://i.stack.imgur.com/fyOBq.png)
`N`, `0x4e`, `78`
[](https://i.stack.imgur.com/FxfMu.png)
`+`, `0x2b`, `43`
[](https://i.stack.imgur.com/SkVXY.png)
`z`, `0x7a`, `122`
[](https://i.stack.imgur.com/mjsDJ.png)
`@`, `0x40`, `64`
## Other
You can find a `.zip` containing all 94 images here: [png](https://drive.google.com/file/d/1eRp0xc_jant0BJVxz2B1mxPb9OP6maSU/view?usp=sharing), [pgm](https://drive.google.com/file/d/10XKr0L1sSdvPMjaMfwAt9ejXWJRs7dCt/view?usp=sharing), [pbm](https://drive.google.com/file/d/11oz3lElpPqmPNLMIWK0ZQX_SWZzZnZGs/view?usp=sharing)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer (in bytes) per-language wins.
[Answer]
# Python 3, 211 209 bytes
```
print("".join([")UUeG5W2jPfE-z@`od;,vlpBuF/D^Ym7Lk[]a%t}R'9>+6O_8gc=#!Z{SH~qCNyir3|xK$wn(J&T4?.Vs"[i]*(2**(0x1666a5a453070400d46a8119056156c0881a5746>>2*i&3))for i in range(81)])[sum(open(0,"rb").read())%203])
```
Reads a .rgba file from stdin and outputs the character to stdout. You can get the .rgba file with `convert input.png -depth 8 output.rgba`. The input is then hashed, by taking the sum of the byte values modulo 203. The long string and the large number are a compressed hash lookup-table.
Correctly recognizes every character except `"<MIA*1XbhO:Q\`
[Answer]
# [Python 2](https://docs.python.org/2/), ~~150~~ ~~149~~ ~~147~~ ~~140~~ ~~136~~ 133 bytes
Takes the content of the *pbm* file as an argument.
```
lambda s:'Bf R N z (y !2VH:3 k9eMI7 CO;g[b# 8LGi n%u <"pEhW|_l ,/ FJ?a10 DKo\'j*Z- $>s} ^xdm+)\{A@STv4Uwr`'[hash(s)%619914302%99]
```
[Try it online!](https://tio.run/##tVt5c9tEFP8/n2IJZGzTUKTV6UAgUI5yd7iHuiBZRx1IbI3tgEPpZw9WJEt779u1M57Rrtc6nt6@4/cOV7fr2WKO78rzyd1Vej3NU7Q6G3xcIvQ9@hahf9HwFr2Bf3565qG/xsU3X0ToyXfvvXw@fROh@OvPL9H85Aa9f1x9Ovvlvz@uEDp9F3325Yep66BPvlpMBn@@/ds76K0PVq/R75v8@tFo8uqjix9@/Nv/6Z9lMng@S1ez4Wp0Errjset7Dj4Zj1/clZdXxQqdo8t5dbMejo6yxXJZZOvtinNULpZonl4XpyhbzNfFfL09C91f8PhyXVyvhqOzI4TW6fJlUV@QzZbDy/l6WF/y/Ay/OEVuOBptz1gWq5ur@oxy2N6oXt096dF5d4vz9tSjalnf6PhJc8rVLcqL9XZS5OgkR4ubNVqU9Sybpct0u7xcHZ8M2/udoqtiPryncjQa3b0a@MHjano9OBs88ydzN0ZuPJlPHOKzcbzJptzNmhFLxu2ZBfjM0ploPoPTQTTVkOeg@pDUh4vuMNlkDjFuHHeyickV4lz6sHEcnojA1fLI7d@8al60@RZONm4/i@9nvmANd2v9rL2T27HfUfMKj6Vk1nfhOCHjSCI4cLzt77S7N02MhyE8a2/lJQ07EPGa/b5Kn9iLWQQUJ5zrxAnwAUqvggx/DFa67Tx3BDLN7Z/k@71AZWZKF@rII8WhuzUrRtIVOCHY1W4XxxXgSN0jlv8mMEmOsQxRlpFTc4Hqc0agv15sURn5irXyhZVPFc2izg6Jfg0V1@o46rkgeSPFR23FBQKoE/nAYlNd@aaSzOI835S@XMueqYXRgry7gEsSFag5VFhwCNuKvbkQYYXMc77EYbwg7VvMZgLL24wJv5Oh3p4V7HM8BcjaiVLIcbe9i5mkYTNJE3sk0hubWGGpvQ3tBM@V8aRBGW7CsMaAtpqq7MFc094urYasGIIwjHSTu6phIEbkz1BtDTIAfSxyBSPYDsaqMXNv21LdZiZSjy6Ey4IDhXc70inrEEAgc@tW3GdCJnmkAZm2l7m7kY01DM2D70OEqn1HnACNeyyYcegioR2/TjkDO4hGizpWLHBGpYPpGl8eaVkY0fEeHw@J4txYG5OJ1VAvcqExUOyj2lBuRwxFL/T15tbludZvTB@Ya7fZo3VN6zQ9PWnjdpyS35s4KN49LKXdE2KEwWvSE24zYBCozS3UoH/idvfyeM@ZlnmKfSWSMi5n1kh99XjPUFBCwKkrEV0Xcpxc0wdIYySiYeIc7lNbtNjGotESJUE6FHcRxVotVa5d1FRKcEcI1UhK1x2e2trSliZJu06qsMD0Jgq4ZZY7wNkB8k9CtsaGjqDePW@/mLdi1HCHb5xK6iNh8a4PQmMJqb@s@fQQCU6j1s4216DuoCPELuRlMR7jzimpi00NAS4eSoLMwp@xBWtE6W7DoIyXb0@0cZ558hmzYIsQ6IRyJg4pYS6QYYEqtO7eVp5aOOAvCqJr0ODuZxUQI@ulBF0z1Q2t3Ed6lBWrx0P5Yqz3LARkZ3C7YQIKAObrwMwiT97jqdSRQFCu/CdD@log6kDpuzgkbqIVsHwgw2lQGKpZkYFjaGU@W7xsUOPB4ASMosoLCgxZ5A0CAcHYJDKlH4F0TkRTSdNQFoIoi3UpAw6dpw6Qbo15CgAphmYMOkvjd48P@t0lZWyXdvq1GZ7WqzN4hs0PH6TNAE8gV2jBzH6YqgFybATsV3al4dQq0SEJibivIYV5oODFjywaIISlwd1KO26k@UDTmCEGV1Y8Ln0gzEhRQaEy8QfLneYQBWAsBMWKkKy/5oLZWJSwi82KaKEBcG7BemtuPTbJTUL0Li1UUVLYQUBQriiKLJDp1rBlXdsNkZxymNkumq04E63d2cKg2O6JZ/3WjbmNbRL9mOKcYbUlwjaYvmISqDJcypdmwOnn1DQbLoHTqt4g05azUFtvrIQhKZFTjO1GDbMKky4JVXYP7Q2m/Qwg8zoUaXYeuGMwtav9lIqMXyyryYNlamqPttlyGlNDFNXciJKsdic9E9fOB4Bix85/55saYX7dtmFPvDfWrXu1/vkgYxVTjS/mwYcl6E9NIuzOnXhMpwZnLWwNhGeuheoOJEnnoULlDpLdxlLsap/eHpskJyt4AZr3k2SWBwb0HStrkHehY9qIfzBshtlu3WnXK0l3HJR5QQQJvjN5YVKEnYnIsxJE6EZgcGoA8zFttS8Yay6y8NKmGwiA9kvrPnZRNBcKmjdCZR87bItVJl/crH6hX6OLydLst2ejAByLKkbAIm1aDBxG7tXXpermUpxbGWXuwvKwrbSqeNamnTZw9mVhLKloSP/94hmlo8LYGixiw9TsHv22QWyQoJW1oypiFS5qMbN1YXTg1gR52xBXyerOTGSCWccpPohAUfmu91dG5cCMCF41e7tXUODxFfCCSUbur8WeTSdF1wlZcn6VxSGVIeCNcgjLYhDmv@gISAChgfqfWK//Bw "Python 2 – Try It Online") or [Try the search program!](https://tio.run/##hZfrT5vJFca/@6@Y7oqVLaCZ25lLSVJVW6lFSmmlzbc0Whls4FWMvbJNdnvJv176OzPG4LBVUQBn3plzec7zPO9wdXpzdfXw8O2wvFrcz@bm9WY7u1ytFr@9fTs6WBxWXy@th@XNV2vDzXL68uhiuNS10bez@fWwnJu/nF/8@MfzH96fX3z/3hQ7Gi1WyxvTftxON7fzzYeP5o3518jwVWysWbyNJRUrMZfo3r07MSJZXBRbkvjio0sp6fJplOBdrkGqOC82@FLaevJVqs/WWiFitJxnvWU4jaVEHxx7o7cayft2JpeSQvC5@uQlRpdF2nphLQQJzrsaarYu9BylSLDWiRNPmRTd4vQcEkp1VBtt8TVGTvczXhdzEEeynKnYtj5CscGJ1BBSjDUS2PWSnGUhhGCz9dkT73kb4iWDScrOBVdqaW2EVL1PNGeLS7YGH6oux5REog2Fiip9l9R3u1RStTXScEqkdk895FQckAAGqBAMSFukwNbsCtATypW8KzUmZiBShBbJk1rDEn1kwbNL@HbR2cf44oplYJEINmsgr70Z7ymEinKN2QbRgB254ByT0MzJ6QFb@6S1jMJ8MkBksV7KYwayAVp1NfEv0cLuSAiVdqMHHIkhZamdTPREmBBTSCmAkU@xt1bpvhIeNCAnCLunQTtXPYhE0tgszDToGaVYLjZXWrYuFujQU2hnCYAso6cil3vqEEOGxkVsTjoeJrpPwXE4F3RwNegp37kEsxNcisSOmo6Bd17GAgg@JIKJT6RoCBa4B92jq7VaCUIv@xTBhmSjgJGnDB16O5IRASKssAWiQkWbe2YNDn4MKEUhVldQ8oxUuWXhSEhO0hOZXM3eSnJFogqlIsmWIZeggFZRKRK19yC1Ij90m7KNLsLo2Jcz9enEgSQjGp/2s8YFEmqgJm8D3AnS@S2ALxAHiFgF3JbW1YiTUE8kMxoKrbEKzhbASJeppnY3afFhBJpF6lE7qCXUNgSUzEjYCVsChiG@1Y@oGDKMZA5EciGWnV05UdBQq0dTsHkvBypTEwg6AaqLnXrgDqcybohQM9MIDekokAteVauT9Ppsx1Q1nhroyvqKINOeRioFrA1e4DNW8W9EZcmKq84nSG7BqPsCQCmF4BzAKoF7X3RfrTqupAyzPJb8GL9CdCZDANzKqeG1EyruiHyKVxvBjVyPr8aL5m1VAHWivQHoGfAivFNNF4zqE4UwnEIszB8OFEhf@xlvU8gBv/CALiC7k7nwxohqtx575NWRQ5eHT3rWFyQuKpu6xwhl8QoADubAq4cCeyTC4IS4s6hP4SadWwm7KOqDyAQbeVQHYseOoaFowaD1zLRhjiOnw@pxPoB0bc6UB5uhesjqxW6nv1MMQeNG7EBHgZc3u1DzIy6KxXMQbZX9GIAyawyP31bFu9pGSEw1FIYZJKnxSedXyAmDQmP0QEhM0nbooAETgu/W1oqWw34MIVB9GxPNA3VpFTl0BgxJX2EekvnakEN6ap5i6QGPzj7tnCuoj3pMBbyxjWdWlPUtBX0T2mSeTLONDTVinAnVQx2sFQo2IeibnYGCucojcWnYeSDK0BepqqSwJcgTjyJN887gdkCTuFq3TdFXFO84CAMr4YX0UA6EwJNJ8JJXOdquZWxC1LKQM1NFeHbPI1Zwv6L@xeXC4@39HayEphKvgyMtL/B3776cjUZXq@Vma4bl1lxwEdoM/5yvrsf9ajQxrw4XPtiPk7OR7p1y8vNqmPH85na6nC3m67Gu663s/m7SL1Q/cWvbXo@/@cPlar09MYspiXh6OV@bn6cbczT7@/KbEzMlJJvnvwzbsePzl1HLcDcdluPJqN/M@mVv/MP5n84v3p88S9rPtvLvVrMfpx8uPj6tXM5J@MYw6r6md03ibj590Ce7jdertRlP2Vbsmdmu7@dnZnp8PGnPevL9Lo05sJONg3ltLvj1uPNwt369emX@3GrUwu4XK/PzsL01y/nNdDt8npvZ8HmYzZczsxg@zc3f/rG9XS0Pzvd2Br2dPqLPf47M1BwDmX442@8HsheFXnLw@eX3jJXXnP7uu/ahYXNsHL1c/u8m7uZ3m/l2rJidmOvpYjM/MZeTs4M9mmw2bLbcwhVtewLEvzSUDrb9KoJazfjgin66jzUxr2n94nSY6C6N2av@CvWXRT8WtSbRHsUjc3n2YlcvVH@@Zffv26ffmfXLjfv@jt@Y3zQGrT/@Wrj2gJCNRwfPn42o1Xdtxvugbw8nddju/@t0R3IOvCwIDr6/nfPXzurT/U@m/xUFDxcL/vaBg5w5dubqdrqeXm3n682L848CVv6NN5Ojo6OZfpt/77ULHfq8odLk644PP/Wf6/n2fr1UcnwZPTz85@p6Mb3ZPJz@9Rpz@C8)
Incorrectly recognizes `&.56=PQXY]cqt~` as `kjdAm0|MMsiOyx`. I've searched for formulas of the form `hash(s)%a%b` for `a` up to the limit of signed 32-bit integers. To improve on this you probably need to use a different idea, maybe `hash(s+'...')%a%b` as suggested by dingledooper, or something involving other operations than moduli.
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-p` + [Tesseract](https://github.com/tesseract-ocr/tesseract) (4.1.1), ~~50~~ ~~47~~ ~~35~~ 34 bytes
```
$_=`tesseract --psm 7 #$_ -`[/.$/]
```
Full program taking the name of a PNG file (terminated by EOF) from STDIN and printing the character to STDOUT. Somewhat fortuitously, exactly 80 characters are correctly identified:
```
"#%&'()*+,-.123456789;<=>?@ABDEFGHIJKMNPQRTUWXYZ[\]_abcdeghijkmnopqrstuvwxyz{|}~
```
The 14 characters not correctly recognised are:
```
input: !$/0:CLOSV^`fl
output: t§I8fcb0sv“7F1
```
All the heavy lifting is done by Tesseract, a full-fledged OCR engine. The `--psm 7` option causes the input image to be treated as a single line of text. For this set of images, `--psm 7` gives the same results as the more appropriate but longer `--psm 10`, which enables single-character mode. (Strangely enough, the results differ for single-word mode, `--psm 8`.)
Tesseract returns a two-character string for some images (even with `--psm 10`); in these cases it turns out that the second character is correct slightly more often than the first. In the general case we therefore extract the last character before the linefeed.
] |
[Question]
[
## Challenge
The challenge is simple, using <http://isup.me>, determine whether an inputted website is up or down.
If the site is up, you should return a truthy value and if the site is down, you should return a falsey value.
## Rules
The input will be a web address such as `stackexchange.com` or `google.co.uk`. The input will never have `http://`, `https://` etc. at the start of the string, but may have `www.` or `codegolf.` at start etc.
You should use the site `isup.me/URL` where URL is the input.
When a site is up, it will look like:

<http://isup.me/codegolf.stackexchange.com>
If a site is down, it will look like:

<http://isup.me/does.not.exist>
URL shorteners are disallowed apart from isup.me.
## Example inputs
Probably up (depending on current circumstances):
```
google.de
codegolf.stackexchange.com
worldbuilding.meta.stackexchange.com
tio.run
store.nascar.com
isup.me
```
Will be down:
```
made.up.com
fake.com.us
why.why.why.delilah
store.antarcticrhubarbassociation.an
```
## Winning
Shortest code in bytes wins.
[Answer]
# sh (+ curl + grep), ~~28~~ 26 bytes
```
curl -L isup.me/$1|grep ^I
```
Outputs via exit status (0 for up, 1 for down). Looks for an `I` at the beginning of a line, which matches when the domain is up (even for the special case of [isup.me/isup.me](http://isup.me/isup.me)).
[Answer]
# [Stacked](https://github.com/ConorOBrien-Foxx/stacked), 44 bytes
```
['http://isup.me/'\+[CS'!'eq sum 2=out]curl]
```
Asynchronous function that outputs `0` if the site is not up, and any other number greater than `0` if it is up.
Example a:
```
['http://isup.me/'\+['s u'split#'1-put]curl] @:isup
'Is google up?' put 'google.com' isup
```
Output (probably): `Is google up? 1`
[Answer]
# Kotlin REPL - 131 108 106 93 79 55 53 64 63 bytes
First try at Kotlin golfing.
Expects the website in a variable or value named `a`.
*Now with reduced whitespace.*
*Who said "loo" isn't enough?*
*Fixed and shorter, doesn't rely on <http://isup.me> anymore.*
*No need to open the connection ourselves, just get the stream of data (or not)*
*The task was to use <http://isup.me>, right? Also: `<` is not a valid character in a URL.*
*Now works with `isup.me` as the website*
*Now reads the website as a line, because one can't assume a variable to contain the website.*
```
"m h" !in java.net.URL("http://isup.me/"+readLine()).readText()
```
Reads one line containing just the website.
Checks for the `m h` part of `from here` that is sent when a site is down.
Returns "true" or "false" respectively.
---
# As a Lambda - 172 120 118 99 85 67 66 bytes
```
{a:String->"m h" !in java.net.URL("http://isup.me/$a").readText()}
```
Can be invoked directly:
```
{ ... }("google.com")
```
[Answer]
# Python 2 or 3 with Requests (~~70~~ ~~69~~ 68 bytes)
```
from requests import*;lambda u:"u. "in get("http://isup.me/"+u).text
```
~~1 byte shaved: `"u. "` → `" u"`~~ Nope, not a valid optimisation.
1 byte shaved: `__import__('requests').` → `from requests import*;`
This is now really a REPL-only piece of code, and after running this line the function will be named `_`.
[Answer]
# Python3 141 133 113 192 141 bytes
Requires [Selenium](https://pypi.python.org/pypi/selenium) (including webdriver) for python.
*Thanks to @cairdcoinheringaahing for reducing 42 bytes!*
*Thanks to @V.Courtois for pointing out a simple fix!*
```
from selenium import*
d=webdriver.Firefox();d.get("http://isup.me/"+input());print("up"in d.find_element_by_xpath("//*[@id='content']/p[1]"))
```
Prints `1` if site is up and running, else prints `0`.
Ungolfed version:
```
from selenium import webdriver
from selenium.webdriver.common.keys import Keys
urlToTest = "www.f.com"
driver = webdriver.Firefox()
driver.get("http://downforeveryoneorjustme.com/"+urlToTest)
res = driver.find_element_by_xpath("//*[@id='content']/p[1]")
print(1 if "up" in res.text else 0)
```
[Answer]
# Javascript (ES6), ~~74~~ 66 bytes
```
f=s=>fetch('//isup.me/'+s).then(r=>r.text()).then(t=>/u!/.test(t))
```
Thanks to @Shaggy, who brought to my attention that a resolved promise counts as output.
Problem with this solution that it will throw a CORS error unless I test it on a page that's already at `isup.me`. But currently, that gets redirected to `downforeveryoneorjustme.com`
Older version:
~~```
f=s=>fetch('//isup.me/'+s).then(r=>r.text()).then(t=>alert(t.match(/u!/)))
```~~
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
}" u"s'+"http://isup.me/
```
Return `True` if the site is up, `False` otherwise. The input URL must be quoted. That cannot be tested on the online interpreter because `'` is disabled on it for safety reasons; instead you will need a local copy of [Pyth](https://github.com/isaacg1/pyth).
**Explanation**
```
Q # Implicit input
+"http://isup.me/ # Concatenate "http://isup.me/" with the input
' # Open the URL
s # Concatenate all the lines of the returned HTML page
}" u" # Test whether " u" is in the page or not
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
"isup.me/ÿ".w#214è'‚‰Q
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fKbO4tEAvN1X/8H4lvXJlI0OTwyvUHzXMetSwIfD/fwA "05AB1E – Try It Online")
Unfortunately `"isup.me/ÿ".w§„ uå` doesn't seem to work.
[Answer]
## PowerShell, 32 bytes
```
(iwr isup.me/$args)-notmatch'u!'
```
[Answer]
# PowerShell, 25 Bytes
```
!(irm isup.me/$args).html
```
Uses the fact that `Invoke-RestMethod` returns the page with a `.html` property only on failure. (no idea why exactly this happens...)
inverts the line to convert to bool, outputs `True` for a live site or `False` for a down site.
```
PS C:\Users\sweeneyc\Desktop> .\Test-SiteUp.ps1 "connorlsw.com"
True
PS C:\Users\sweeneyc\Desktop> .\Test-SiteUp.ps1 "connorlsw.notawebsite"
False
PS C:\Users\sweeneyc\Desktop> .\Test-SiteUp.ps1 "google.com"
True
PS C:\Users\sweeneyc\Desktop> .\Test-SiteUp.ps1 "isthisreallyasite.com"
False
```
[Answer]
# [Halovi](https://github.com/BlackCapCoder/halovi), 20 bytes
```
oisup.me/⁰
\p
ye$hd0
```
Outputs `p.` if the site is down, and `e.` if it is up.
Explanation:
```
oisup.me/⁰ ~# Open the concatination of "isup.me/" and arg0
\p ~# Select first p element
ye$hd0 ~# Edit text with neovim and output result:
~# Go one character before the end of the line and ..
~# delete until beginning
```
[Answer]
# [Haskell](https://www.haskell.org/) (Lambdabot), 157 bytes
```
import Data.ByteString.Lazy.Char8
import Network.HTTP.Simple
f s=httpLBS(parseRequest_$"http://isup.me/"++s)>>=print.not.isInfixOf"u!".unpack.getResponseBody
```
Unfortunately you can't import `Network.HTTP.Simple` on `tio.run`, the easiest way to test would be to run this script (you'll need [`stack`](https://github.com/commercialhaskell/stack)):
```
#!/usr/bin/env stack
-- stack --install-ghc --resolver lts-8.19 runghc --package http-conduit
import Data.ByteString.Lazy.Char8
import Network.HTTP.Simple
import Data.List
main :: IO ()
main = mapM_ test [ "google.de", "made.up.com"]
where test url = print ("testing "++url) >> f url
f :: String -> IO ()
f s=httpLBS(parseRequest_$"http://isup.me/"++s)
>>=print.not.isInfixOf"u!".unpack.getResponseBody
```
[Answer]
# Go, 111 bytes
In typical Go fashion, the shortest method is to shell it out.
```
import"os/exec"
func h(a string)bool{return exec.Command("sh","-c","curl -L isup.me/"+a+"|grep ^I").Run()!=nil}
```
Other implementations here: <https://play.golang.org/p/8T5HSDQFmC>
[Answer]
# Clojure, 63 bytes
```
#(clojure.string/includes?(slurp(str"http://isup.me/"%))"'s j")
```
Checks if the HTML returned by `slurp` contains the string `"'s j"` (as in, "It **'s j**ust you"). I might be able to find a smaller string that's unique to the page, but it would at most save me 2 bytes. It would also potentially make it less accurate. "'s j" isn't going to appear in the markup anywhere except in that one scenario. A string like "u." however could potentially appear in the URL, which would break it.
```
(defn is-up? [site]
(clojure.string/includes?
(slurp (str "http://isup.me/" site))
"'s j"))
```
[Answer]
# Nim, 108 bytes
```
import httpclient,strutils
echo newhttpclient().getcontent("//isup.me/"&stdin.readline.string).find("ks ")<0
```
Unfortunate that `strutils` is needed for `contains`.
Learning Nim, tips appreciated!
[Answer]
# PHP, ~~82~~ 78 bytes
```
<?=$i=$argv[1],+!preg_match("/!.*$i/",file_get_contents("http://isup.me/$i"));
```
Example i/o runs:
```
$ php script.php google.com
> google.com1
```
**Example 2**
```
$ php script.php does.not.exist
> does.not.exist0
```
] |
[Question]
[
# Introduction
In the land of [Insert cool name here], people don't buy things with money, because everyone has a severe allergy to paper. They pay eachother with words!
But how is that? Well, they give each letter number values:
```
a=1,b=2,c=3,etc.
```
(With some other special rules that will be described later)
In this challenge, your task will be to calculate the value of sentences.
# Challenge
You will take an input which will be a sentence. You may assume the input has no newlines or trailing spaces. The challenge will be to calculate the value of the sentence, using these rules:
```
a=1,b=2,c=3,etc.
```
* A capital letter is worth 1.5 times it's corresponding lowercase
letter
`H=h*1.5`
So, the word
```
cab
```
Would be worth `c+a+b = 3+1+2 = 6`
But the word `Cab` with a capital c would be worth `(c*1.5)+a+b = 4.5+1+2 = 7.5`
So if your program input was "Cab" your program would output 7.5
* All non alphabetic characters are worth 1.
This is code golf, so shortest answer in bytes wins. Good luck!
[Answer]
# Python 3, ~~71~~ ~~65~~ 61 bytes
```
lambda z:sum((ord(s)*1.5**(s<'_')-96)**s.isalpha()for s in z)
```
By an extraordinary coincidence, `(ord(s)-64)*1.5` is equal to `ord(s)*1.5-96`, so we only have to write `-96` once. The rest is pretty straight forward.
Edit: Shaved off some bytes using exponentiation shenanigans.
[Answer]
# Python 2, 120 102 bytes
Edit:
```
e=raw_input()
print sum([ord(l)-96for l in e if not l.isupper()]+[1.5*ord(l)-96for l in e if l.isupper()])
```
First submission, not so golfy but one has to start somewhere.
```
def s2(p):
c=0
for l in p:
if l.isupper():
c+=(ord(l.lower())-96)*1.5
else:
c+=ord(l)-96
return c
print s(raw_input())
```
[Answer]
# Pyth, ~~23~~ 20 bytes
```
sm|*hxGrdZ|}dG1.5 1z
```
[Live demo and test cases.](https://pyth.herokuapp.com/?code=sm%7C*hxGrdZ%7C%7DdG1.5+1z&input=Cab&test_suite=1&test_suite_input=Cab%0Acab%0Aca.b&debug=1)
## Explanation
```
m z For each input character
hxGrdZ Get the value of it's lowercase form, or 0 for non-alphabetic characters
* |}dG1.5 Multiply it by 1 if it's lowercase, 1.5 if uppercase
| 1 If it's still zero, it's a non-alphabetic character, so use 1 as its value
s Sum of all the values
```
Quite a few creative uses of booleans values as integers here.
## 23-byte version:
```
sm+*hxGJrdZ|}dG1.5!}JGz
```
[Live demo and test cases.](https://pyth.herokuapp.com/?code=sm%2B*hxGJrdZ%7C%7DdG1.5!%7DJGz&input=Cab%0Acab%0Aca.b&test_suite=1&test_suite_input=Cab%0Acab%0Aca.b&debug=1)
[Answer]
# Julia, 63 bytes
```
s->sum(c->isalpha(c)?(64<c<91?1.5:1)*(c-(64<c<91?'@':'`')):1,s)
```
This simply sums an array constructed via a comprehension that loops over the characters in the input string and performs arithmetic on their codepoints.
Ungolfed:
```
function char_score(c::Char)
(64 < c < 91 ? 1.5 : 1) * (c - (64 < c < 91 ? '@' : '`')) : 1
end
function sentence_value(s::String)
sum(char_score, s)
end
```
Thanks to Glen O for fixing the approach.
[Answer]
# [Stuck](http://kade-robertson.github.io/stuck/), ~~85~~ 43 Bytes
~~Yeah yeah, I know, Python is shorter.. :P~~ I'm using the same logic as Tryth now, for the most part.
```
s_"str.isalpha"fgl;l-|0Gc"_91<1.5;^*96-":++
```
Explanation:
```
s_ # Take input & duplicate
"str.isalpha"fg # Filter for only alpha chars, save
l;l-| # Determine number of symbols in start string
0Gc # Get saved string, convert to char array
"_91<1.5;^*96-": # Logic to find score for each letter
++ # Sum the list of nums, add to # of symbols
```
[Answer]
# Python 2, 101 bytes
```
v=0
for x in raw_input():v+=(ord(x.lower())-96)*(1.5 if ord(x)<96 else 1)if x.isalpha()else 1
print v
```
[Answer]
# CJam, 30 bytes
```
q:i91,64fm1.5f*32,5f-+1fe>f=:+
```
How this works (wow, I've never made one of these!):
```
91,64fm1.5f*32,5f-+1fe> Construct an array so that a[i] == score for chr(i)
q:i Read STDIN and convert to ASCII codes
f= Index each from the array
:+ Sum the result
```
[Answer]
# F#, 168 bytes
Not really golfed yet, but a start:
```
fun(w:string)->w|>Seq.map(fun c->if Char.IsLetter c then (if Char.IsUpper(c) then (float)(Math.Abs(64-(int)c))*1.5 else (float)(Math.Abs(96-(int)c))) else 1.0)|>Seq.sum
```
Here a more readable version:
```
let calc (w : string) =
w
|> Seq.map (fun c -> if Char.IsLetter c then (if Char.IsUpper(c) then (float)(Math.Abs(64 - (int)c)) * 1.5 else (float)(Math.Abs (96 - (int)c))) else 1.0)
|> Seq.sum
```
[Answer]
# K, 30
```
+/1^(,/1 1.5*(.Q`a`A)!\:1+!26)
```
.
```
k)+/1^(,/1 1.5*(.Q`a`A)!\:1+!26)"Programming Puzzles & Code Golf"
349f
```
How it works:
`.Q`a`A` generates two lists of lowercase and uppercase letters
```
k).Q`a`A
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
```
`!:1+til 26`maps each letter in each list from 1 to 26
```
k)(.Q`a`A)!\:1+!26
"abcdefghijklmnopqrstuvwxyz"!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
```
Multiply the first list by 1, the last by 1.5
```
k)1 1.5*(.Q`a`A)!\:1+!26
"abcdefghijklmnopqrstuvwxyz"!1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26f
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"!1.5 3 4.5 6 7.5 9 10.5 12 13.5 15 16.5 18 19.5 21 22.5 24 25.5 27 28.5 30 31.5 33 34.5 36 37.5 39
```
Raze into a single dictionary using `,/`
```
k)(,/1 1.5*(.Q`a`A)!\:1+!26)
a| 1
b| 2
c| 3
d| 4
..
```
Map the characters in the input string to the relevant scores
```
k)(,/1 1.5*(.Q`a`A)!\:1+!26)"Programming Puzzles & Code Golf"
24 18 15 7 18 1 13 13 9 14 7 0n 24 21 26 26 12 5 19 0n 0n 0n 4.5 15 4 5 0n 10.5 15 12 6
```
Fill any null values with 1
```
k)1^(,/1 1.5*(.Q`a`A)!\:1+!26)"Programming Puzzles & Code Golf"
24 18 15 7 18 1 13 13 9 14 7 1 24 21 26 26 12 5 19 1 1 1 4.5 15 4 5 1 10.5 15 12 6
```
Sum
```
k)+/1^(,/1 1.5*(.Q`a`A)!\:1+!26)"Programming Puzzles & Code Golf"
349f
```
[Answer]
# JavaScript, 121 bytes
```
l=process.argv[2].split(""),r=0;for(k in l)c=l[k],o=c.toLowerCase(),r+=(o.charCodeAt(0)-96)*(o===c?1:1.5);console.log(r);
```
call js file with node (node index.js "Cab")
[Answer]
# MATLAB, 68 bytes
This takes advantage of the fact that characters are automatically casted to integers, and that boolean values can be summed as integers.
```
sum([t(t>96&t<132)-96,(t(t>64&t<91)-64)*1.5,t<65|(t>90&t<97)|t>122])
```
[Answer]
# Perl 5, 77 bytes
```
@_=split//,$ARGV[0];$i+=(ord)*(/[a-z]/||/[A-Z]/*1.5||96/ord)-96for@_;print$i
```
Tested on `v5.20.2`.
[Answer]
# Javascript (ES6), ~~85~~ ~~82~~ ~~80~~ 67 bytes
I love quick & easy challenges like this. :)
```
t=>[...t].map(c=>u+=(v=parseInt(c,36)-9)>0?v*(c>'Z'||1.5):1,u=0)&&u
```
This works by interpreting each char as a base-36 number, multiplying it by 1 or 1.5 if it's greater than 9 (`a-z` or `A-Z`), and giving 1 instead if not. As always, suggestions welcome!
[Answer]
# Python 3: 86 85 Bytes
```
t=0
for c in input():k=ord(c)-64;t+=k*1.5if 0<k<27else k-32if 32<k<59else 1
print(t)
```
[Answer]
# C# 81 Bytes
```
decimal a(string i){return i.Sum(c=>c>64&&c<91?(c-64)*1.5m:c>96&&c<123?c-96:1m);}
```
Call with (LinqPad):
```
a("Hello World").Dump();
```
[Answer]
# PHP, 102 bytes
```
foreach(str_split($argv[1])as$c){$v=ord($c)-64;$s+=A<=$c&&$c<=Z?1.5*$v:(a<=$c&&$c<=z?$v-32:1);}echo$s;
```
Usage example:
```
$ php -d error_reporting=0 value.php cab
6
$ php -d error_reporting=0 value.php Cab
7.5
$ php -d error_reporting=0 value.php 'Programming Puzzles & Code Golf'
349
```
Nothing special in the algorithm. Each character from the first program's argument (`$argv[1]`) is checked against `A` and `Z` then `a` and `z` and counted accordingly.
[Answer]
# PowerShell, 108 Bytes
Decently competitive, I'm kinda surprised. Not too shabby for not having a compact Ternary operator.
### Code:
```
$a=[char[]]$args[0];$a|%{$b=$_-64;If($b-in(1..26)){$c+=$b*1.5}ElseIf($b-in(33..58)){$c+=$b-32}Else{$c++}};$c
```
### Explained:
```
$a=[char[]]$args[0] # Take command-line input, cast as char array
$a|%{ # For each letter in the array
$b=$_-64 # Set $b as the int value of the letter (implicit casting), minus offset
If($b-in(1..26)){$c+=$b*1.5} # If it's a capital, multiply by 1.5.
# Note that $c implicitly starts at 0 the first time through
ElseIf($b-in(33..58)){$c+=$b-32} # Not a capital
Else{$c++} # Not a letter
}
$c # Print out the sum
```
[Answer]
# C, 85 bytes
```
float f(char*s){return(*s-96)*!!islower(*s)+1.5*(*s-64)*!!isupper(*s)+(*++s?f(s):0);}
```
The `!!` before `islower` and `isupper` are necessary, because the boolean values returned by these functions are not guaranteed to be `0` and `1` , true value was `1024` on my system indeed !
[Answer]
# [Candy](https://github.com/dale6john/candy), ~~26~~ 22 bytes
~~(~"a"<{A#64-2/3\*|A#96-}h)Z~~
Thanks to @Tryth for the factorization trick!
```
(~"a"<{A2/3*|A}#96-h)Z
```
Invokation is with the -I flag, as in `candy -I "Cab" -e $prg`
The code in it's long form is:
```
while # loop while able to consume characters from stack
peekA # A gets stack to
"a"
less # is pop() < "a"
if
pushA # capitalized
digit2
div
digit3
mult
else
pushA # lower case
endif
number
digit9
digit6
sub
popAddZ # add pop() to counter register Z
endwhile
pushZ # push Z onto stack as answer
```
[Answer]
# Prolog (SWI), 101 bytes
**Code:**
```
X*Y:-X>64,X<91,Y is X*1.5-96;X>96,X<123,Y is X-96.
_*1.
p(L):-maplist(*,L,A),sumlist(A,B),write(B).
```
**Explained:**
```
X*Y:-X>64,X<91, % When X is upper case
Y is X*1.5-96 % Y is 1.5 times charvalue starting at 1
;X>96,X<123, % OR when X is lower case
Y is X-96. % Y is charvalue starting at 1
_*1. % ELSE Y is 1
p(L):-maplist(*,L,A), % Get list of charvalues for all chars in string
sumlist(A,B), % Take sum of list
write(B). % Print
```
**Example:**
```
p(`Cab`).
7.5
```
[Answer]
# PHP, 75 bytes
```
while(~$c=$argn[$i++])$r+=ctype_alpha($c)?ord($c)%32*(1+($c<a)/2):1;echo$r;
```
Run as pipe with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/0a80eaf71f74ecfb297011d65076c59ca2482a9a).
[Answer]
# [Ruby](https://www.ruby-lang.org/), 48 bytes
```
->s{s.bytes.sum{_1>64&&_1<91?(_1-64)*1.5:_1-96}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3DXTtiquL9ZIqS1KL9YpLc6vjDe3MTNTU4g1tLA3tNeINdc1MNLUM9UytgExLs9paiL5VBQpu0UrOiUlKsRCBBQsgNAA)
] |
[Question]
[
# Countdown
Your goal for this code-golf challenge is to count down and meanwhile *recycle* numbers. Let me explain.
First your application reads a number, either as program argument or using stdin.
Next you'll simply need to count down like this:
`10 9 8 7 6` (in *descending* order)
But wait, there is more!
# Recycling
There are situations where we can print every number, but don't list every number, we can do recycling! Let me give a quick example:
```
Input: 110
Output: 11091081071061051041031021010099... etc
Recycled: 10 1
```
We've now still listed all the numbers, 110, 109, 108, but we've recycled a **0** and a **1**.
Another example:
```
Input: 9900
Output: 9900989989897989698959894... etc
Recycled: 9 98
```
# Code-golf challenge
* Read a number (argument or stdin)
* Output the countdown in *descending* order while recycling **all** possible numbers (to stdout or file)
* Stop when you reach 1 OR the moment you've recycled 0 to 9 (whatever happens first)
Simple example (until 1 reached):
```
Input: 15
Output: 15141312110987654321
(Notice the 110 instead of 1110)
```
More advanced example (all recycled):
```
Input: 110
Output: 110910810710610510410310210100998979695949392919089887868584838281807978776757473727170696867665646362616059585756554535251504948474645443424140393837363534332313029282726252423221
Recycled: 10 9 8 7 6 5 4 3 2
(We've recycled all 0-9)
```
[Answer]
## T-SQL - 291 277 267 217 199 191 166 158 153 145 142 128 117
After approaching this in a new way, I managed to get down to 145(142 after a couple minor tweaks), not too shabby. That means I might be able to compete for silver or bronze. ^^
```
DECLARE @ INT=100;WITH N AS(SELECT 1A UNION ALL SELECT A+1FROM N WHERE A<@)SELECT LEFT(A,LEN(A)-1+A%11)FROM N ORDER BY-A
```
This doesn't print a list, it selects the results. The question never gave specifics about output, so this should be fine. This still has the same limit of 100 on the input, partly because I'm abusing the fact that every 11th term under 100 loses a character and partly because of the default 100 recursion limit on common table expressions.
```
DECLARE @ INT=100;
WITH N AS
(
SELECT 1A
UNION ALL
SELECT A+1
FROM N
WHERE A<@
)
SELECT LEFT(A,LEN(A)-1+A%11)
FROM N
ORDER BY-A
```
[Answer]
## Python 143 147
```
def t(n):
p=o='';r=0 # p is previous string, o is output string, r is recycled bitmap
while n and r<1023: # 1023 is first 10 bits set, meaning all digits have been recycled
s=`n`;i=-1 # s is the current string representation of n
# i is from end; negative offsets count backwards in strings
while p.endswith(s[:i])-1:i-=1 # find common ending with prev; s[:0] is '',
# which all strings end with
for j in s[:i]:r|=1<<int(j) # mark off recycled bits
o+=s[i:];p=s;n-=1 # concatenate output, prepare for next number
print o # done
```
First level indent is space, second level is tab char.
[Answer]
# Haskell, ~~154~~ ~~149~~ ~~147~~ ~~145~~ ~~128~~ ~~120~~ ~~119~~ 117 bytes
```
import Data.List
(r%x)n|n>0&&r<":"=[(r\\t)%(x++(show n\\t))$n-1|t<-tails x,isPrefixOf t$show n]!!0|0<1=x
h=['0'..]%""
```
adding in the recycling-checking cost **a lot** of characters... sigh
golfed a bit by remembering what digits weren't recycled yet and stopping when the list is empty. then golfed a bit more by moving to explicit recursion and a few more tricks.
example output:
```
*Main> h 110
"110910810710610510410310210100998979695949392919089887868584838281807978776757473727170696867665646362616059585756554535251504948474645443424140393837363534332313029282726252423221"
```
[Answer]
# Python 2: 119 117
Marking this as community wiki because it is just a more golfed version of [Will's answer](https://codegolf.stackexchange.com/a/37897/).
```
n=input()
d=s,={''}
exec"t=`n`;i=len(t)\nwhile(s*i)[-i:]!=t[:i]:i-=1\ns+=t[i:];d|=set(t[:i]);n-=len(d)<11;"*n
print s
```
[Answer]
## Ruby, ~~145~~ ~~139~~ 130 bytes
```
n=gets.to_i
d=*?0..?9
s=''
n.times{|i|j=(t=(n-i).to_s).size;j-=1 while s[-j,j]!=u=t[0,j];d-=u.chars;s=t;$><<t[j..-1];exit if[]==d}
```
Similar approach to Will's, except I'm not using a bit mask, but a set-like array of unused digits instead. Input is via STDIN.
There's an alternative version using `while` instead of `times` but whatever I try, the number of bytes is the same:
```
n=gets.to_i
d=*?0..?9
s=''
(j=(t=n.to_s).size;j-=1 while s[-j,j]!=u=t[0,j];d-=u.chars;s=t;$><<t[j..-1];exit if[]==d;n-=1)while 0<n
```
[Answer]
## CJam, ~~80~~ ~~77~~ ~~65~~ ~~57~~ 54 Characters
~~Probably not at all optimized, but a~~ After a lot of optimizations and debugging here is the direct conversion of my ES6 answer in CJam:
```
Mr{s:C_,{:H<M_,H->=!_CH@-@}g:T>+:MCT<_O@-+:O,A<Ci(*}h;
```
[Try it online here](http://cjam.aditsu.net/). The function takes the number as STDIN and outputs the recycled countdown, stopping in between if recycling is complete.
I will try to golf it further.
**How it works:**
Basic idea is that for each countdown number C, check if the first H digits are equal to the last H digits of the resultant string, where H goes from number of digits in C to 0
```
Mr "Put an empty string and input on stack";
{ ... }h; "Run while top element of stack is true, pop when done";
s:C "Store string value of top stack element in C"
_, "Put the number of characters in C to stack";
{ ... }g "Run while top element of stack is true";
:H< "Store the digit iteration in H and slice C";
M "M is the final output string in making";
_,H- "Take length of M and reduce H from it";
> "Take that many digits of M from end and..."
=!_ "Compare with first H digits of C, negate and copy";
CH@ "Put C and H on stack and bring the above result to top of stack";
- "Reduce H if the matched result was false";
@ "Bring the matched result on top in order continue or break the loop"
:T "Store top stack element in T after the loop";
>+:M "Take everything but first T digits of C and add it to M and update M";
CT<_ "Take first T digits of C and copy them";
O@ "Put saved digits on stack, and rotate top three elements";
- "Remove all occurence of first T digits of C from O";
+:O "Add first T digits of C to O and update O";
,A< "Compare number of saved digits with 10";
Ci( "Decrement integer value of C and put it on stack";
* "If number of saved digits greater than 9, break loop";
```
[Answer]
## JavaScript ES6, ~~149~~ 146 characters
Such verbose, much characters, wow.
```
C=n=>{s=c='';while(n>0&s.length<10){j=1;while(t=(n+'').slice(0,-j++))if(c.endsWith(t)){s+=~s.search(t)?'':t;break}c+=(n--+'').slice(1-j)}return c}
```
Run it in latest Firefox's Web Console.
After running, it creates a method `C` which you can use like
```
C(12)
12110987654321
```
**UPDATE**: Sometimes, plain old `return` is shorter than arrow function closure :)
] |
[Question]
[
Consider a sequence of natural numbers for which N appears as a substring in N^2. [A018834](https://oeis.org/A018834)
Output the `n`th element of this sequence.
### Rules
Program takes only `n` as input and outputs just one number - `N`.
The sequence can be 0-indexed or 1-indexed.
```
Sequence: 1 5 6 10 25 50 60 76 100 250 376 500 600 625 760 ...
Squares: 1 25 36 100 625 2500 3600 5776 10000 62500 141376 250000 360000 390625 577600 ...
```
This is **code-golf** so shortest code wins.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
1-indexed
```
µNNnNå
```
[Try it online!](https://tio.run/##yy9OTMpM/f//0FY/vzy/w0v//zc0BAA "05AB1E – Try It Online")
**Explanation**
```
µ # loop over increasing N until counter equals input
N # push N (for the output)
Nn # push N^2
N # push N
å # push N in N^2
# if true, increase counter
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~33~~ 31 bytes
*-2 bytes thanks to nwellnhof*
```
{(grep {$^a²~~/$a/},1..*)[$_]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1ojvSi1QKFaJS7x0Ka6On2VRP1aHUM9PS3NaJX42Nr/xYmVCmkacYammtb/AQ "Perl 6 – Try It Online")
### Explanation:
```
{ } # Anonymous code block that returns
( )[$_] # The nth index of
grep { },1..* # Filtering from the natural numbers
$^a² # If the square of the number
~~/$a/ # Contains the number
```
[Answer]
# JavaScript (ES6), 43 bytes
```
f=(n,k=0)=>n?f(n-!!(++k*k+'').match(k),k):k
```
[Try it online!](https://tio.run/##DcxLEkRADADQq8RKIihjOTRn6erR8wmJasr1e6ze7v385Y@QvvvZqL2WnKNDrcV15CadI2pTFMgslXBZUrv5M3xQqBZ6So6WUMHBYwCFEfrulpkgmB62Lu1qb7wLovwH "JavaScript (Node.js) – Try It Online")
---
# Non-recursive version, 47 bytes
```
n=>eval("for(k=0;n-=!!(++k*k+'').match(k););k")
```
[Try it online!](https://tio.run/##FcrNDoIwDADgVylcaG0gmHib9V2WufnT2RIgvP7U03f53vGIW1pfyz6a33Mr0kxu@YgV@@IrqszBRuk6ZNaT8jDQ9Il7eqJSoKA9tX8zEDgHMLjCZf7JTJDcNq95qv7AgkbUvg "JavaScript (Node.js) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 8 bytes (works for any input in theory, but only for `n<10` in practice)
```
úrgɲï╧§
```
[Try it online!](https://tio.run/##ARwA4/9tYXRoZ29sZv//w7pyZ8OJwrLDr@KVp8Kn//8y "MathGolf – Try It Online")
## Alternative (works for `n<49` in practice and theory)
```
►rgɲï╧§
```
The only difference is that instead of creating a list with `10^(input)` values, I create a list with `10^6` items. This takes a while to run, so you could swap the first byte to any other 1-byte literal to test it out.
## Explanation
```
ú pop(a), push(10**a)
r range(0, n)
g filter array by...
É start block of length 3
² pop a : push(a*a)
ï index of current loop
╧ pop a, b, a.contains(b)
Block ends here
§ get from array
```
The reason why this solution doesn't handle large input is that I noticed that the sequence grows less than exponentially, but more than any polynomial. That's why I used the `10**n` operator (I wanted to use `2**n` but it failed for input 1). That means that I create an extremely large array even for small inputs, just to filter out the vast majority of it, and then take one of the first elements. It's extremely wasteful, but I couldn't find another way to do it without increasing the byte count.
[Answer]
# Common Lisp, 95 bytes
```
(lambda(n)(do((i 0))((= n 0)i)(if(search(format()"~d"(incf i))(format()"~d"(* i i)))(decf n))))
```
[Try it online!](https://tio.run/##VYzBCsIwEER/ZQgIE0Go3vVfYtLgQpMtac759bgFL95m38y@uMmxT26qO7I2CHLTgju64rEgKWi4hI4ONwJuL4wwLs6GtLdQ3imweiYlBYv35BPVgnhK5rGGFj8/Bb0byVFqzBBb/tGrGQ2aabW6WvLzvOcX)
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 83 bytes
```
import StdEnv,Text
```
#
```
(!!)[i\\i<-[1..]|indexOf(""<+i)(""<+i^2)>=0]
```
[Try it online!](https://tio.run/##S85JTcz7n5ufUpqTqpCbmJn3PzO3IL@oRCG4JMU1r0wnJLWi5H9aaV5ySWZ@noKtgoaiomZ0ZkxMpo1utKGeXmxNZl5KaoV/moaSko12piaEijPStLM1iOUKLkkEmmQLNLdAAW4GSJupQez/f8lpOYnpxf91PX3@u1TmJeZmJkM4ATmJJWn5RbkA)
```
(!!) // index into the list of
[ i // i for every
\\ i <- [1..] // i from 1 upwards
| indexOf (""<+i) (""<+i^2) >= 0 // where i is in the square of i
]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
1ẇ²$#Ṫ
```
1-indexed.
**[Try it online!](https://tio.run/##y0rNyan8/9/w4a72Q5tUlB/uXPUfyDMFAA "Jelly – Try It Online")**
### How?
Finds the first `n` of the sequence as a list and then yields the tail, `N`.
```
1ẇ²$#Ṫ - Link: integer, n (>0)
1 - initialise x to 1
# - collect the first n matches, incrementing x, where:
$ - last two links as a monad:
² - square x
ẇ - is (x) a substring of (x²)?
- (implicitly gets digits for both left & right arguments when integers)
Ṫ - tail
```
---
If `0` were considered a Natural number we could use the 1-indexed full-program [`ẇ²$#Ṫ`](https://tio.run/##y0rNyan8///hrvZDm1SUH@5c9f@/oRkA "Jelly – Try It Online") for 5.
[Answer]
# Japt, ~~12~~ 11 bytes
```
@aJ±X²søY}f
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=QGFKsViyc/hZfWY=&input=OA==)
```
ȲsøY «U´}a
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.6&code=yLJz+Fkgq1W0fWE=&input=OA==)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 45 bytes
```
->n,i=1{/#{i+=1}/=~"#{i*i}"&&n-=1while n>0;i}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ9PWsFpfuTpT29awVt@2TgnI1MqsVVJTy9O1NSzPyMxJVcizM7DOrP2vYaCnZ2SgqZeamJxRXZNZU6CQFp0ZW/sfAA "Ruby – Try It Online")
[Answer]
# Java 8, ~~66~~ ~~65~~ 63 bytes
```
n->{int r=0;for(;!(++r*r+"").contains(r+"")||--n>0;);return r;}
```
-1 byte thanks to *@Shaggy*.
-2 bytes thanks to *@Arnauld*.
1-indexed.
[Try it online.](https://tio.run/##LY/BDoIwDIbvPkXltLlA1MSLE99ALh7Vw5xohlhIV0yM8uy4oZc2/dt@7V@Zp0mry32wtfEedsbhewLgkEu6GltCEctRACtiRKmD0k9C8GzYWSgAIYcB0@07DlA@19eGhJ4KpWhGKklkZhvkwPZiLD@fNMXtXEtNJXeEQLofdES23bkOyD/52bgLPMKe2DM5vB1OYOTvoXghXnP5QoPb5MtVSErJsQmwf3kuH1nTcdaGTa5ROJWsj5wozIIR@XfRD18)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
int r=0; // Result-integer, starting at 0
for(; // Loop as long as:
!(++r*r+"") // (increase result `r` by 1 first with `++r`)
// If the square of the result `r` (as String)
.contains( // does not contain
r+"")|| // the result `r` itself (as String):
--n>0;); // (decrease input `n` by 1 first with `--n`)
// And continue looping if input `n` is not 0 yet
return r;} // Return the result `r`
```
[Answer]
# [Clojure](https://clojure.org/), 81 bytes
```
(fn[n](nth(filter #(clojure.string/includes?(str(* % %))(str %))(range))n))
```
[Try it online!](https://tio.run/##JY1BCoNAEAS/0hCEGQ/JyZMHyTuCh7AZ15VllHF9/zrRUxVNQYe8LodJpc2SlqygSpN@dCQtM00pFzE8KNzZcy@exVfSkI@f7AP5QC0aNMx/v2hfjeL0CsrMtQMzerwtYhY/OwE "Clojure – Try It Online") (Unfortunately, TIO doesn't seem to support Clojure's standard string library)
If Clojure had shorter importing syntax, or had a `includes?` method in the core library, this could actually be somewhat competitive. `clojure.string/includes?` alone is longer than some answers here though :/
```
(defn nth-sq-subs [n]
(-> ; Filter from an infinite range of numbers the ones where the square of
; the number contains the number itself
(filter #(clojure.string/includes? (str (* % %)) (str %))
(range))
; Then grab the "nth" result. Inc(rementing) n so 0 is skipped, since apparently
; that isn't in the sequence
(nth (inc n))))
```
Since the TIO link is broken, here's a test run. The number on the left is the index (`n`), and the result (`N`) is on the right:
```
(mapv #(vector % (nth-sq-subs %)) (range 100))
=>
[[0 1]
[1 5]
[2 6]
[3 10]
[4 25]
[5 50]
[6 60]
[7 76]
[8 100]
[9 250]
[10 376]
[11 500]
[12 600]
[13 625]
[14 760]
[15 1000]
[16 2500]
[17 3760]
[18 3792]
[19 5000]
[20 6000]
[21 6250]
[22 7600]
[23 9376]
[24 10000]
[25 14651]
[26 25000]
[27 37600]
[28 50000]
[29 60000]
[30 62500]
[31 76000]
[32 90625]
[33 93760]
[34 100000]
[35 109376]
[36 250000]
[37 376000]
[38 495475]
[39 500000]
[40 505025]
[41 600000]
[42 625000]
[43 760000]
[44 890625]
[45 906250]
[46 937600]
[47 971582]
[48 1000000]
[49 1093760]
[50 1713526]
[51 2500000]
[52 2890625]
[53 3760000]
[54 4115964]
[55 5000000]
[56 5050250]
[57 5133355]
[58 6000000]
[59 6250000]
[60 6933808]
[61 7109376]
[62 7600000]
[63 8906250]
[64 9062500]
[65 9376000]
[66 10000000]
[67 10050125]
[68 10937600]
[69 12890625]
[70 25000000]
[71 28906250]
[72 37600000]
[73 48588526]
[74 50000000]
[75 50050025]
[76 60000000]
[77 62500000]
[78 66952741]
[79 71093760]
[80 76000000]
[81 87109376]
[82 88027284]
[83 88819024]
[84 89062500]
[85 90625000]
[86 93760000]
[87 100000000]
[88 105124922]
[89 109376000]
[90 128906250]
[91 146509717]
[92 177656344]
[93 200500625]
[94 212890625]
[95 250000000]
[96 250050005]
[97 289062500]
[98 370156212]
[99 376000000]]
```
This should be able to support any value of `n`; providing you're willing to wait for it to finish (finding the 50th to 100th integers in the sequence took like 15 minutes). Clojure supports arbitrarily large integer arithmetic, so once numbers start getting huge, it starts using `BigInt`s.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 25 bytes
```
Nθ≔¹ηWθ«≦⊕η¿№I×ηηIη≦⊖θ»Iη
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05rLsbg4Mz1Pw1BHIQPIK8/IzElVAEooVHNx@iYWQGU985KLUnNT80pSUyDqODPTFDSc80vzSjScE4tLNEIyc1OLNTJAkpo6CmAhIEtTAWGESyqSESCLa7kCijJh@oGKrf//N/@vW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation:
```
Nθ
```
Input `n`.
```
≔¹η
```
Start `N` at 1. (Or, this could start counting at `0` which would make the input 1-indexed.)
```
Wθ«
```
Repeat until we have found `n` numbers in the sequence.
```
≦⊕η
```
Increment `N`.
```
¿№I×ηηIη
```
If `N*N` contains `N`, then...
```
≦⊖θ»
```
... decrement `n`.
```
Iη
```
Print `N`.
My attempts at golfing this further were stymied by Charcoal a) not having an `if..then` except at the end of a block (which costs 2 bytes) b) not having a `Contains` operator (converting the output of `Find` or `Count` into a boolean that I could subtract from `n` again costs 2 bytes).
[Answer]
## **Edit (response to comments): Python 2, 76 bytes**
Wanted to try for a non recursive method. (New to golfing, any tips would be great!)
```
def f(c,n=0):
while 1:
if`n`in`n*n`:
if c<2:return n
c-=1
n+=1
```
Thanks both BMO and Vedant Kandoi!
[Answer]
## Haskell, 60 bytes
```
([n^2|n<-[1..],elem(show n)$words=<<mapM(:" ")(show$n^2)]!!)
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzXyM6L86oJs9GN9pQTy9WJzUnNVejOCO/XCFPU6U8vyil2NbGJjexwFfDSklBSRMspQLUoRmrqKj5PzcxM0/BVgEkr6BRUJSZV6KXpqkQbaCnZ2gS@/9fclpOYnrxf93kggIA "Haskell – Try It Online")
```
n<-[1..] -- loop n through all numbers starting with 1
[n^2| , ] -- collect the n^2 in a list where
elem(show n) -- the string representation of 'n' is in the list
words ... (show$n^2) -- which is constructed as follows:
show$n^2 -- turn n^2 into a string, i.e. a list of characters
(:" ") -- a point free functions that appends a space
-- to a character, e.g. (:" ") '1' -> "1 "
mapM -- replace each char 'c' in the string (n^2) with
-- each char from (:" ") c and make a list of all
-- combinations thereof.
-- e.g. mapM (:" ") "123" -> ["123","12 ","1 3","1 "," 23"," 2 "," 3"," "]
words=<< -- split each element into words and flatten to a single list
-- example above -> ["123","12","1","3","1","23","2","3"]
( !!) -- pick the element at the given index
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~47~~ 43 bytes
-4 bytes thanks to [Dennis](https://codegolf.stackexchange.com/users/12012/dennis) (adding 1 to recursive call instead of returning `n-1`)
```
f=lambda c,n=1:c and-~f(c-(`n`in`n*n`),n+1)
```
[Try it online!](https://tio.run/##DcixDsIgEAbg3ae48c7SAQeHJn0WOaEoif1LCEZc@uq03/jlf31vuPUe54@uz6DkDWY7eVKEcY/sR3ZwCQ5XODEYrPS4FWqUQEXxWtiahMpFf4@E/K0sItOFcjmXmoncpNv7AQ "Python 2 – Try It Online")
## Explantion/Ungolfed
Recursive function taking two arguments \$c,n\$; \$n\$ is counts up \$1,2,3\dots\$ and everytime \$n \texttt{ in } n^2\$ it decrements \$c\$. The recursion ends as soon as \$c = 0\$:
```
# Enumerating elements of A018834 in reverse starting with 1
def f(counter, number=1):
# Stop counting
if counter == 0:
return 0
# Number is in A018834 -> count 1, decrement counter & continue
elif `number` in `number ** 2`:
return f(counter-1, number+1) + 1
# Number is not in A018834 -> count 1, continue
else:
return f(counter, number+1) + 1
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~31~~ 30 bytes
```
1∘{>⍵:⍺-1⋄(⍺+1)∇⍵-∨/(⍕⍺)⍷⍕⍺×⍺}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/3/BRx4xqu0e9W60e9e7SNXzU3aIBZGgbaj7qaAeK6j7qWKEPFJkKFNR81Lsdwjo8HUjU/k971DaBAv1c1Y/6pgKNACrTUUhTAFK1h1YY6Dzq3Wz6HwA "APL (Dyalog Extended) – Try It Online")
0-indexed.
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 33 bytes
```
map{1while++$\**2!~/${\}/}1..$_}{
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saDasDwjMydVW1slRkvLSLFOX6U6pla/1lBPTyW@tvr/f5N/@QUlmfl5xf91fU31DAwN/usWAAA "Perl 5 – Try It Online")
[Answer]
# [Lua](https://www.lua.org), 137 123 79 bytes
*-thanks @Jo King for 44 bytes*
```
n=io.read()i=0j=0while(i-n<0)do j=j+1i=i+(n.find(j*j,j)and 1or 0)end
print(j*j)
```
[Try it online!](https://tio.run/##Fck7CoAwDADQ3VN0bPyUdDeHKaRiQkmlKB4/4ltfe4q7kfQ0auEIQqiE7ymtRtlsR@AelHTJQrJES4cYR511VSjGIfcREKrxdA2x@x9wz/gB "Lua – Try It Online")
[Answer]
# [Tcl](http://tcl.tk/), 82 bytes
```
proc S n {while 1 {if {[regexp [incr i] [expr $i**2]]&&[incr j]==$n} {return $i}}}
```
[Try it online!](https://tio.run/##NYo7DoMwDIav8g@Igal0zykYI0@RW4wgRG5QK1k@e4qEGL9HTWtrRfeECRn2nWVljDB5waLym38FUXJSCCGepOhkGJ5EfX/5hULossOU66H5zO7eqmwMK0f9IE64T3KMj/YH "Tcl – Try It Online")
[Answer]
# [Tidy](https://github.com/ConorOBrien-Foxx/Tidy), 24 bytes
```
{x:str(x)in'~.x^2}from N
```
[Try it online!](https://tio.run/##K8lMqfyfpmBl@7@6wqq4pEijQjMzT71OryLOqDatKD9Xwe9/fmmJRpqGgaaOQpqGEZg0NNDU5CrOyC/XSNNRMDTV/A8A "Tidy – Try It Online")
Returns a lazy list which, when called like a function, returns the `n`th element in the series.
## Explanation
```
{x:str(x)in'~.x^2}from N
{x: }from N select all natural numbers `x` such that
str(x) the string representation of `x`
in is contained in
'~.x^2 "~" + str(x^2)
```
] |
[Question]
[
Find the area of a region of unit cells given its perimeter loop as a sequence of 90-degree turns.
For example, take the three-cell region
```
XX
X
```
whose perimeter loop we draw
```
L<S<L
v ^
S R>L
v ^
L>L
```
Each turn is marked as left (L), straight (S), or right (R). Starting from the R, the turns are `RLLSLSLL`. So, given input `RLLSLSLL`, we should output 3 for the area.
The input sequence is guaranteed to trace out a loop enclosing a single region on its left.
* The path ends back at the start point, facing the initial direction, forming a loop.
* The loop does not cross or touch itself.
* The loop goes counterclockwise around a region.
**I/O**
You can take input as a list or string of characters `LSR`, or as numbers `-1, 0, 1` for left, straight, right. Output is a positive integer. Floats are OK.
**Test cases**
The inputs are given in both formats followed by their respective outputs.
```
RLLSLSLL
LLLL
SLLSLL
LSRRSLLSSLSSLSSL
SSSSSLSSSSSLSSSSSLSSSSSL
[1, -1, -1, 0, -1, 0, -1, -1]
[-1, -1, -1, -1]
[0, -1, -1, 0, -1, -1]
[-1, 0, 1, 1, 0, -1, -1, 0, 0, -1, 0, 0, -1, 0, 0, -1]
[0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0, -1]
3
1
2
7
36
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 112 bytes
```
(([]){[{}]<{({}()){{}<>([{}]<([{}])>)(<>)}<>(({}[({})])[({}{})])<>}{}<>>({}<({}())>)<>([])}{})({()<({}()())>}{})
```
[Try it online!](https://tio.run/##jYu9CoAwDIRfpWNuKOge8iIlQx0EURxcQ589Ni3uEvJz3122px533q96uhMVhRVrykbWCDBrLDTImBAQCwL2QOkNRaxxsLTIS9c8/wXxrgifjDBxGEHcl/RVXtM/8QI "Brain-Flak – Try It Online")
This program uses [Green's theorem](https://en.wikipedia.org/wiki/Green%27s_theorem#Area_calculation) to compute the area
The current location is stored on the right stack, in a format that depends on the direction faced.
```
Direction top second
north -x y
west -y -x
south x -y
east y x
```
In all instances, the second value on the stack will increase by 1, and the line integral for the area decreases by half the value on the top of the stack. To compensate, the end of the program divides the running total by -2.
```
# For each number in input
(([]){[{}]
# Evaluate turn-handling to zero
<
# If turn:
{
# If right turn:
({}()){{}
# Negate both values on other stack (reverse direction)
<>([{}]<([{}])>)
(<>)}
# Swap the two stack elements and negate the new top of stack
# This performs a left turn.
<>(({}[({})])[({}{})])<>
}{}
<>>
# Evaluate as top of stack and...
({}<
# increment the number below it
({}())
>)<>
([])}{})
# Divide total by -2
({()<({}()())>}{})
```
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), ~~30~~ ~~28~~ 19 bytes
-2 thanks to @Adám
```
(+/9∘○×11○+\)0j1*+\
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob2pm/qO2CQb/04Ckhra@5aOOGY@mdx@ebmgIpLRjNA2yDLW0Y/7/LwHKVz/q3fqoc2ERkJn2qHeXlXp@tvqj7hb1tMTMHHWgAFC6qJbLUOHQegg2QCJBuETBmAvGRogZchmg6YCIG3FBRAwVkMUN4Kai0iUK5lwGCjAIkyGOB3SXGQA "APL (Dyalog Classic) – Try It Online")
uses [tricks with complex numbers](https://codegolf.stackexchange.com/questions/17665/tips-for-golfing-in-apl/155707#155707) to compute the coordinates
the area is ½Σ(xi-xi+1)(yi+yi+1) or equivalently Σ(xi-xi+1)yi as the lines are only horizontal or vertical
[Answer]
# JavaScript (ES6), ~~52~~ 50 bytes
*Saved 2 bytes thanks to @Neil*
Expects the second input format.
```
a=>a.map(k=>r+=(2-(a=a+k&3))%2*(y+=~-a%2),r=y=0)|r
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQCPb1q5I21bDSFcj0TZRO1vNWFNT1UhLo1Lbtk43UdVIU6fIttLWQLOm6H9yfl5xfk6qXk5@ukaaRrShjoIuFBugULqGsZqaCqQCfX0FYy40K3SR7CDPVHQrDNGtMMDwBUUWAa0wwuYLoNmGYIRqnwEuFh4nAK0wx@ILZIQwiWQhsMWguDD7DwA "JavaScript (Node.js) – Try It Online")
### How?
*This description applies to [the previous version](https://codegolf.stackexchange.com/revisions/163401/8): **x** and **y** have since been inverted.*
This is based on [the formula already mentioned by @ngn](https://codegolf.stackexchange.com/a/163397/58563): **A = Σ(xi - xi+1)yi**, which can also be written as **Σdxiyi** where **dxi** is either -1, 0 or 1.
We start with **r = y = 0**.
We keep track of the current direction in **a**:
```
| a = 0 | a = 1 | a = 2 | a = 3
----------+-------+-------+-------+-------
direction | East | South | West | North
dx | +1 | 0 | -1 | 0 <-- -(~-a % 2)
dy | 0 | +1 | 0 | -1 <-- (2 - a) % 2
```
It is updated with `a = a + k & 3`, where **k** is the current element of the input array.
Because **a** initially contains the input array, **a + k** is coerced to **NaN** on the first iteration and then to **0** when the bitwise AND is applied. This means that the first direction change is actually ignored and we always start heading to East. It doesn't matter because the area remains the same, no matter the orientation of the final shape.
Then, we update **y** with `y += (2 - a) % 2`.
Finally, we compute **-dx** with `~-a % 2` and subtract **y \* -dx** from **r**, which -- at the end of the process -- is our final result.
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
f=lambda c,d=1,x=0:c>[]and f(c[1:],d*1j**c[0],x+d.real)-x*d.imag
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIVknxdZQp8LWwCrZLjo2MS9FIU0jOdrQKlYnRcswS0srOdogVqdCO0WvKDUxR1O3QitFLzM3Mf1/QVFmXglQbbSBjgIy0jVE5ZMgFKv5HwA "Python 2 – Try It Online")
Computes ∑xΔy using complex numbers.
[Answer]
# [Haskell](https://www.haskell.org/), ~~71~~ ~~70~~ 69 bytes
```
a 0 0
a x d(t:r)|k<-t+d=x*g k+a(x+g(k-1))k r
a _ _ _=0
g a=sin$a*pi/2
```
Explanation:
Green's Theorem gives the formula for the area : A = ½∑(xk+1+xk)(yk+1-yk), which simplifies to A = ½∑Δx=02xkΔy + ½∑Δy=0(xk+1+xk)\*0 = ∑xΔy when turns are 90 degrees along the axes. We have the following pseudocode for a recursive turn-globbing function that keeps track of the x position and direction:
```
A x dir (turn:turns) = ΔA + A (x+Δx) (dir+turn) turns
```
where the new direction, ΔA and Δx can be seen from the following tables. We can see a sinusoidal periodicity of length four in both ΔA and Δx along the diagonal axis, `dir+turn`, which is implemented using `sin` instead of modular arithmetic.
```
↔|L S R ΔA| L S R Δx| L S R
← ↓ ← ↑ -x 0 x 0 -1 0
↑ ← ↑ → 0 x 0 -1 0 1
→ ↑ → ↓ x 0 -x 0 1 0
↓ → ↓ ← 0 -x 0 1 0 -1
```
[Try it online!](https://tio.run/##lZC7DsIwDEX3fIUHhr4CKWNFNla@IESV6YsqbYnaIHXg2wkp4lGEGJCvZevq@A4@4qCKprGmGAxwIABCxBHQR7OPQWPpgEjQGfH02NfRnHZWfNcnxn5tr8y53sDf1pQnk0SI7el8aAopCSEl31sEBowgjJB7Jun9i9pQE@Z8DCpQIXpjWHmKxr6voHdYOhVnpALkQ90tMND1am1brDv3vBb1LgVP93VnlqUP00/tNSsbrAZLM61v "Haskell – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~36~~ 30 bytes
```
Area@Polygon@AnglePath[.5Pi#]&
```
If you have an older version of Mathematica (~v10) you'll need `Most@` in front of `AnglePath` to avoid closing the polygon. (Thanks to @user202729 for the tips).
original:
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737EoNdEhID@nMj0/z8E3v7jEwTEvPSc1AKgqWlkrIFPfKFbtf0BRZl5JdJpDtYEODOoa6hDHqY39DwA "Wolfram Language (Mathematica) – Try It Online")
updated:
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737EoNdEhID@nMj0/z8ExLz0nNQCoIFrPNCBTOVbtf0BRZl5JdJpDtYEODOoa6hDHqY39DwA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~15~~ 11 bytes
*Thanks to @xnor for pointing out a useless step, saving 2 bytes*
*Thanks to @dylnan for saving another byte*
Expects the second input format. Returns a float.
```
+\ı*Ḟ_\×ƊĊS
```
[Try it online!](https://tio.run/##y0rNyan8/1875shGrYc75sXHHJ5@rOtIV/D///@jdQ11FAx0FAzBCMgA8aFiBrhYsQA "Jelly – Try It Online") or [run all test cases](https://tio.run/##y0rNyan8/1875shGrYc75sXHHJ5@rOtIV/D/w@2Pmtb8/x@tEG2oo6ALxQYolK5hrA6XgkK0LpIKmJgBhiZk1UAhQzBCVWaAiwU3ExkhFJAsFKsQCwA)
### Commented
```
+\ı*Ḟ_\×ƊĊS - main link, taking the input list e.g. [1, -1, -1, 0, -1, 0, -1, -1]
+\ - cumulative sum --> [1, 0, -1, -1, -2, -2, -3, -4]
ı* - compute 1j ** d, --> [(0+1j), (1+0j), (0-1j), (0-1j),
which gives a list of (-dy + dx*j) (-1+0j), (-1+0j), (0+1j), (1+0j)]
Ċ - isolate the imaginary part (dx) --> [1, 0, -1, -1, 0, 0, 1, 0] (floats)
Ɗ - invoke the last 3 links as a monad
Ḟ - isolate the real part (-dy) --> [0, 1, 0, 0, -1, -1, 0, 1] (floats)
_\ - negated cumulative sum (gives y) --> [0, -1, -1, -1, 0, 1, 1, 0]
× - compute dx * y --> [0, 0, 1, 1, 0, 0, 1, 0]
S - sum --> 3
```
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
f=lambda l,p=0,s=1:l>[]and(p/s).imag/2+f(l[1:],p+s,s*1j**l[0])
```
[Try it online!](https://tio.run/##lZDPCsMgDIfP61PkWK2u2qNgX0Q8OIqbI7VSe9nTuzL2p2XsMPiFhI8vOSTdlssUu1K8RjeeBgfIkhYsa6mwN9bFoU5tJscwunPbNb5GI5VlqcksU3mlFI2wpPhpBoQQwRjJgD9L7BqXtgJghm@MFxNfS1t7RfKRvSZ@Te@b23yEv5G1qjqkOcQF1geQcgc "Python 2 – Try It Online")
Similar to [Lynn's solution](https://codegolf.stackexchange.com/a/163725/20260), but using some complex arithmetic to extract the right component of the complex number in one go.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 25 bytes
Uses the `-1, 0, 1` input format.
```
s*Vm_sd._sMKm^.j)sd._QeMK
```
[Try it here!](https://pyth.herokuapp.com/?code=s%2aVm_sd._sMKm%5E.j%29sd._QeMK&input=%5B0%2C0%2C0%2C0%2C0%2C-1%2C0%2C0%2C0%2C0%2C0%2C-1%2C0%2C0%2C0%2C0%2C0%2C-1%2C0%2C0%2C0%2C0%2C0%2C-1%5D&test_suite_input=%5B0%2C0%2C0%2C0%2C0%2C-1%2C0%2C0%2C0%2C0%2C0%2C-1%2C0%2C0%2C0%2C0%2C0%2C-1%2C0%2C0%2C0%2C0%2C0%2C-1%5D&debug=0)
[Answer]
# [Pyth](https://pyth.readthedocs.io), 14 bytes
```
_smec^.j)sd2.:
```
[Test suite](https://pyth.herokuapp.com/?code=_smec%5E.j%29sd2.%3A&input=%5B1%2C+-1%2C+-1%2C+0%2C+-1%2C+0%2C+-1%2C+-1%5D%0A%5B-1%2C+-1%2C+-1%2C+-1%5D%0A%5B0%2C+-1%2C+-1%2C+0%2C+-1%2C+-1%5D%0A%5B-1%2C+0%2C+1%2C+1%2C+0%2C+-1%2C+-1%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+-1%5D%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+-1%5D&test_suite=1&test_suite_input=%5B1%2C+-1%2C+-1%2C+0%2C+-1%2C+0%2C+-1%2C+-1%5D%0A%5B-1%2C+-1%2C+-1%2C+-1%5D%0A%5B0%2C+-1%2C+-1%2C+0%2C+-1%2C+-1%5D%0A%5B-1%2C+0%2C+1%2C+1%2C+0%2C+-1%2C+-1%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+-1%5D%0A%5B0%2C+0%2C+0%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+-1%2C+0%2C+0%2C+0%2C+0%2C+0%2C+-1%5D&debug=1)
```
_smec^.j)sd2.:
Q implicit input
.: take all non-empty contiguous sublists
m map this operation onto each one:
ec^.j)sd2
s the sum of the sublist
^.j) raise it to the complex unit 1j to that power
c 2 halve it
e take the imaginary part
_s take the negated sum of the result
```
This expresses the area as the sum of `-1/2 * g(sum(l))` over all contiguous sublists `l` over the input, where `g` does modular indexing into `[0,1,0,-1]`. The code implements `g` as `g(x)=imag(1j**x)`. There may be a shorter method with direct modular indexing, using `sin`, or an arithmetic function on `x%4`.
] |
[Question]
[
Given a positive integer *n*, compute the *nth* [Wilson number](https://en.wikipedia.org/wiki/Wilson_prime#Wilson_numbers) *W(n)* where

and *e* = 1 if *n* has a primitive root modulo *n*, otherwise *e* = -1. In other words, *n* has a primitive root if there does not exist an integer *x* where 1 < *x* < *n-1* and *x*2 = 1 mod *n*.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so create the shortest code for a function or program that computes the *nth* Wilson number for an input integer *n* > 0.
* You may use either 1-based or 0-based indexing. You may also choose to output the first *n* Wilson numbers.
* This is the OEIS sequence [A157249](https://oeis.org/A157249).
## Test Cases
```
n W(n)
1 2
2 1
3 1
4 1
5 5
6 1
7 103
8 13
9 249
10 19
11 329891
12 32
13 36846277
14 1379
15 59793
16 126689
17 1230752346353
18 4727
19 336967037143579
20 436486
21 2252263619
22 56815333
23 48869596859895986087
24 1549256
25 1654529071288638505
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
1 byte thanks to Dennis.
```
gRỊTP‘:
```
[Try it online!](https://tio.run/##y0rNyan8/z896OHurpCARw0zrP4bmR5uf9S05j8A "Jelly – Try It Online")
You don't really have to compute `e` since you need to divide anyway.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 11 bytes
```
S÷ȯ→Π§foε⌋ḣ
```
[Try it online!](https://tio.run/##ASEA3v9odXNr//9Tw7fIr@KGks6gwqdmb8614oyL4bij////MjU "Husk – Try It Online")
### Explanation
```
ḣ Range from 1 to input
§foε⌋ Keep only those whose gcd with the input is 1
Π Product
ȯ→ Plus 1
S÷ Integer division with input
```
[Answer]
# Mathematica, 91 bytes
```
If[(k=#)==1,2,(Times@@Select[Range@k,CoprimeQ[k,#]&]+If[IntegerQ@PrimitiveRoot@#,1,-1])/#]&
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 11 bytes
```
/h*Ff>2iTQS
```
[Try it here!](https://pyth.herokuapp.com/?code=%2Fh%2aFf%3E2iTQS&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7&debug=0)
---
# How?
* `/h*Ff>2iTQS` - Full program.
* `S` - Generate the inclusive range **[1, input]**
* `f` - Filter-keep those:
+ `iTQ` - whose GCD with the input.
+ `>2` - Is less than two (can be replaced by either of the following: `q1`, `!t`)
* `*F` - Apply multiplication repeatedly. In other words, the product of the list.
* `h` - Increment the product by 1.
* `/` - Floor division with the input.
**TL;DR**: Get all the coprimes to the input in the range **[1, input]**, get their product, increment it and divide it by the input.
[Answer]
# [Python 2](https://docs.python.org/2/), 62 bytes
```
n=input();k=r=1
exec'r*=k/n*k%n!=1or k/n;k+=1;'*n*n
print-~r/n
```
[Try it online!](https://tio.run/##HY1BDsIgEEXXcIpxQabFNg0sXJTMYaqiEmTaEJroxqtj2@XPy3t/@ZbXzLY@5gwJAkOe@Okb04G9tKMUgZe1AMF7Stf7NEKSYsmBC6Dq7YqgIHVS@I@/ASJWpkNoWhcpk5E7wKwpDqyj4hOZ7WcbLp7JONSsWR69/pcHrnviDw "Python 2 – Try It Online")
[Answer]
# J, 33 bytes
```
3 :'<.%&y>:*/(#~1&=@(+.&y))1+i.y'
```
This one is more of a request to see an improvement than anything else. I tried a tacit solution first, but it was longer than this.
# explanation
This is fairly straightforward translation of Mr. Xcoder's solution into J.
[Try it online!](https://tio.run/##y/r/P91WT8FYwUrdRk9VrdLOSktfQ7nOUM3WQUNbT61SU9NQO1OvUp0rNTkjXyFdwRDGMIKLGP//DwA "J – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
Lʒ¿}P>I÷
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f59SkQ/trA@w8D2///98MAA "05AB1E – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 82 bytes
```
function(n)(prod((1:n)[g(n,1:n)<2])+1)%/%n
g=function(a,b)ifelse(o<-a%%b,g(b,o),b)
```
Uses integer division rather than figuring out `e` like many answers here, although I did work out that `e=2*any((1:n)^2%%n==1%%n)-1` including the edge case of `n=1` which I thought was pretty neat.
Uses [rturnbull's vectorized GCD function](https://codegolf.stackexchange.com/a/95328/67312).
[Try it online!](https://tio.run/##PYxBCoAgEADv/UPYpY2wY@hLooNWiiCraB16vdWl2zAMU5rTzV28nSExMEIuaQeQM@PigekDNa3YSxSj4M7rPzZkMbgj1gOSGowQljxYSvj6Vk3O8X4/ciKH7QE "R – Try It Online")
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 bytes
```
n->(prod(i=1,n,i^(gcd(i,n)==1))+1)\n
```
[Try it online!](https://tio.run/##DYoxCoAwDAC/EpwSTIcIjvElIojSkiUNwf/XLgd3XNxppcWooDC8HBjZXzQVdrYL2zOFnVSFaBU6fdSe6PMWhm1niDT/ZligHBMVnYjGDw "Pari/GP – Try It Online")
[Answer]
## JavaScript (ES6), ~~72~~ ~~70~~ 68 bytes
```
f=(n,p=1,i=n,a=n,b=i)=>i?f(n,b|a-1?p:p*i,i-=!b,b||n,b?a%b:i):-~p/n|0
```
```
<input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o>
```
Integer division strikes again. Edit: Saved 2 bytes thanks to @Shaggy. Saved a further 2 bytes by making it much more recursive, so it may fail for smaller values than it used to.
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
f n=div(product[x|x<-[1..n],gcd x n<2]+1)n
```
[Try it online!](https://tio.run/##LYyxCoMwFEX3fsUbHAytgkIXiYNDh84dxSGYqKHmRV5exUL/PW3Fu1w43HMnFZ5mnqN1iyeGxzuwcfkNV0senUFOR8MNjUHEAbDWdk0X8vrVc7t9Npm1RZ5jdxl7DRugLLtzITA6ZbEG7U@wR/18kBkcVwddyCInA6RklIYEpn/t06qCO7KIsbx@AQ "Haskell – Try It Online")
Uses the integer division trick as all the other answers.
Uses 1-based indices.
**Explanation**
```
f n= -- function
div n -- integer division of next arg by n
(product -- multiply all entries in the following list
[x| -- return all x with ...
x<-[1..n], -- ... 1 <= x <= n and ...
gcd x n<2] -- ... gcd(x,n)==1
+1) -- fix e=1
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), 11 bytes
```
õ fjU ×Ä zU
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=9SBmalUg18QgelU=&input=OA==)
---
## Explanation
Implicit input of integer `U`.
```
õ
```
Generate an array of integers from 1 to `U`.
```
fjU
```
Filter (`f`) co-primes of `U`.
```
×
```
Reduce by multiplication.
```
Ä
```
Add 1.
```
zU
```
Divide by `U`, floor the result and implicitly output.
[Answer]
# Axiom, 121 bytes
```
f(n)==(e:=p:=1;for i in 1..n repeat(if gcd(i,n)=1 then p:=p*i;e=1 and i>1 and i<n-1 and(i*i)rem n=1=>(e:=-1));(p+e)quo n)
```
add some type, ungolf that and result
```
w(n:PI):PI==
e:INT:=p:=1
for i in 1..n repeat
if gcd(i,n)=1 then p:=p*i
e=1 and i>1 and i<n-1 and (i*i)rem n=1=>(e:=-1)
(p+e)quo n
(5) -> [[i,f(i)] for i in 1..25]
(5)
[[1,2], [2,1], [3,1], [4,1], [5,5], [6,1], [7,103], [8,13], [9,249],
[10,19], [11,329891], [12,32], [13,36846277], [14,1379], [15,59793],
[16,126689], [17,1230752346353], [18,4727], [19,336967037143579],
[20,436486], [21,2252263619], [22,56815333], [23,48869596859895986087],
[24,1549256], [25,1654529071288638505]]
Type: List List Integer
(8) -> f 101
(8)
9240219350885559671455370183788782226803561214295210046395342959922534652795_
041149400144948134308741213237417903685520618929228803649900990099009900990_
09901
Type: PositiveInteger
```
[Answer]
# JavaScript (ES6), ~~83~~ ~~81~~ ~~80~~ ~~78~~ ~~76~~ 68 bytes
My first pass at this was a few bytes longer than Neil's solution, which is why I originally ditched it in favour of the array reduction solution below. I've since golfed it down to tie with Neil.
```
n=>(g=s=>--x?g(s*(h=(y,z)=>z?h(z,y%z):--y?1:x)(n,x)):++s)(1,x=n)/n|0
```
---
### Try it
```
o.innerText=(f=
n=>(g=s=>--x?g(s*(h=(y,z)=>z?h(z,y%z):--y?1:x)(n,x)):++s)(1,x=n)/n|0
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
```
```
<input id=i type=number><pre id=o>
```
---
# Non-recursive, 76 bytes
I wanted to give a non-recursive solution a try to see how it would turn out - not as bad as I expected.
```
n=>-~[...Array(x=n)].reduce(s=>s*(g=(y,z)=>z?g(z,y%z):y<2?x:1)(--x,n),1)/n|0
```
---
## Try it
```
o.innerText=(f=
n=>-~[...Array(x=n)].reduce(s=>s*(g=(y,z)=>z?g(z,y%z):y<2?x:1)(--x,n),1)/n|0
)(i.value=8);oninput=_=>o.innerText=f(+i.value)
```
```
<input id=i type=number><pre id=o>
```
] |
[Question]
[
Consider a binary string `S` of length `n`. Indexing from `1`, we can compute the [Hamming distances](https://en.wikipedia.org/wiki/Hamming_distance) between `S[1..i+1]` and `S[n-i..n]` for all `i` in order from `0` to `n-1`. The Hamming distance between two strings of equal length is the number of positions at which the corresponding symbols are different. For example,
```
S = 01010
```
gives
```
[0, 2, 0, 4, 0].
```
This is because `0` matches `0`, `01` has Hamming distance two to `10`, `010` matches `010`, `0101` has Hamming distance four to `1010` and finally `01010` matches itself.
We are only interested in outputs where the Hamming distance is at most 1, however. So in this task we will report a `Y` if the Hamming distance is at most one and an `N` otherwise. So in our example above we would get
```
[Y, N, Y, N, Y]
```
Define `f(n)` to be the number of distinct arrays of `Y`s and `N`s one gets when iterating over all `2^n` different possible bit strings `S` of length `n`.
## Task
For increasing `n` starting at `1`, your code should output `f(n)`.
## Example answers
For `n = 1..24`, the correct answers are:
```
1, 1, 2, 4, 6, 8, 14, 18, 27, 36, 52, 65, 93, 113, 150, 188, 241, 279, 377, 427, 540, 632, 768, 870
```
## Scoring
Your code should iterate up from `n = 1` giving the answer for each `n` in turn. I will time the entire run, killing it after two minutes.
Your score is the highest `n` you get to in that time.
In the case of a tie, the first answer wins.
## Where will my code be tested?
I will run your code on my (slightly old) Windows 7 laptop under cygwin. As a result, please give any assistance you can to help make this easy.
My laptop has 8GB of RAM and an Intel i7 [[email protected]](/cdn-cgi/l/email-protection) GHz (Broadwell) CPU with 2 cores and 4 threads. The instruction set includes SSE4.2, AVX, AVX2, FMA3 and TSX.
## Leading entries per language
* **n = 40** in **Rust** using CryptoMiniSat, by Anders Kaseorg. (In Lubuntu guest VM under Vbox.)
* **n = 35** in **C++** using the BuDDy library, by Christian Seviers. (In Lubuntu guest VM under Vbox.)
* **n = 34** in **Clingo** by Anders Kaseorg. (In Lubuntu guest VM under Vbox.)
* **n = 31** in **Rust** by Anders Kaseorg.
* **n = 29** in **Clojure** by NikoNyrh.
* **n = 29** in **C** by bartavelle.
* **n = 27** in **Haskell** by bartavelle
* **n = 24** in **Pari/gp** by alephalpha.
* **n = 22** in **Python 2 + pypy** by me.
* **n = 21** in **Mathematica** by alephalpha. (Self reported)
---
# Future bounties
I will now give a bounty of 200 points for any answer that gets up to **n = 80** on my machine in two minutes.
[Answer]
# Rust + [CryptoMiniSat](https://crates.io/crates/cryptominisat), n ≈ 41
### `src/main.rs`
```
extern crate cryptominisat;
extern crate itertools;
use std::iter::once;
use cryptominisat::{Lbool, Lit, Solver};
use itertools::Itertools;
fn make_solver(n: usize) -> (Solver, Vec<Lit>) {
let mut solver = Solver::new();
let s: Vec<Lit> = (1..n).map(|_| solver.new_var()).collect();
let d: Vec<Vec<Lit>> = (1..n - 1)
.map(|k| {
(0..n - k)
.map(|i| (if i == 0 { s[k - 1] } else { solver.new_var() }))
.collect()
})
.collect();
let a: Vec<Lit> = (1..n - 1).map(|_| solver.new_var()).collect();
for k in 1..n - 1 {
for i in 1..n - k {
solver.add_xor_literal_clause(&[s[i - 1], s[k + i - 1], d[k - 1][i]], true);
}
for t in (0..n - k).combinations(2) {
solver.add_clause(&t.iter()
.map(|&i| d[k - 1][i])
.chain(once(!a[k - 1]))
.collect::<Vec<_>>()
[..]);
}
for t in (0..n - k).combinations(n - k - 1) {
solver.add_clause(&t.iter()
.map(|&i| !d[k - 1][i])
.chain(once(a[k - 1]))
.collect::<Vec<_>>()
[..]);
}
}
(solver, a)
}
fn search(n: usize,
solver: &mut Solver,
a: &Vec<Lit>,
assumptions: &mut Vec<Lit>,
k: usize)
-> usize {
match solver.solve_with_assumptions(assumptions) {
Lbool::True => search_sat(n, solver, a, assumptions, k),
Lbool::False => 0,
Lbool::Undef => panic!(),
}
}
fn search_sat(n: usize,
solver: &mut Solver,
a: &Vec<Lit>,
assumptions: &mut Vec<Lit>,
k: usize)
-> usize {
if k >= n - 1 {
1
} else {
let s = solver.is_true(a[k - 1]);
assumptions.push(if s { a[k - 1] } else { !a[k - 1] });
let c = search_sat(n, solver, a, assumptions, k + 1);
assumptions.pop();
assumptions.push(if s { !a[k - 1] } else { a[k - 1] });
let c1 = search(n, solver, a, assumptions, k + 1);
assumptions.pop();
c + c1
}
}
fn f(n: usize) -> usize {
let (mut solver, proj) = make_solver(n);
search(n, &mut solver, &proj, &mut vec![], 1)
}
fn main() {
for n in 1.. {
println!("{}: {}", n, f(n));
}
}
```
### `Cargo.toml`
```
[package]
name = "correlations-cms"
version = "0.1.0"
authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"]
[dependencies]
cryptominisat = "5.0.1"
itertools = "0.6.0"
```
### How it works
This does a recursive search through the tree of all partial assignments to prefixes of the Y/N array, using a SAT solver to check at each step whether the current partial assignment is consistent and prune the search if not. CryptoMiniSat is the right SAT solver for this job due to its special optimizations for XOR clauses.
The three families of constraints are
*S**i* ⊕ *S**k* + *i* ⊕ *D**ki*, for 1 ≤ *k* ≤ *n* − 2, 0 ≤ i ≤ *n* − *k*;
*D**ki*1 ∨ *D**ki*2 ∨ ¬*A**k*, for 1 ≤ *k* ≤ *n* − 2, 0 ≤ *i*1 < *i*2 ≤ *n* − *k*;
¬*D**ki*1 ∨ ⋯ ∨ ¬*D**ki**n* − *k* − 1 ∨ *A**k*, for 1 ≤ *k* ≤ *n* − 2, 0 ≤ *i*1 < ⋯ < *i**n* − *k* − 1 ≤ *n* − *k*;
except that, as an optimization, *S*0 is forced to false, so that *D**k*0 is simply equal to *S**k*.
[Answer]
# Rust, n ≈ ~~30 or~~ 31 or 32
On my laptop (two cores, i5-6200U), this gets through *n* = 1, …, 31 in 53 seconds, using about 2.5 GiB of memory, or through *n* = 1, …, 32 in 105 seconds, using about 5 GiB of memory. Compile with `cargo build --release` and run `target/release/correlations`.
### `src/main.rs`
```
extern crate rayon;
type S = u32;
const S_BITS: u32 = 32;
fn cat(mut a: Vec<S>, mut b: Vec<S>) -> Vec<S> {
if a.capacity() >= b.capacity() {
a.append(&mut b);
a
} else {
b.append(&mut a);
b
}
}
fn search(n: u32, i: u32, ss: Vec<S>) -> u32 {
if ss.is_empty() {
0
} else if 2 * i + 1 > n {
search_end(n, i, ss)
} else if 2 * i + 1 == n {
search2(n, i, ss.into_iter().flat_map(|s| vec![s, s | 1 << i]))
} else {
search2(n,
i,
ss.into_iter()
.flat_map(|s| {
vec![s,
s | 1 << i,
s | 1 << n - i - 1,
s | 1 << i | 1 << n - i - 1]
}))
}
}
fn search2<SS: Iterator<Item = S>>(n: u32, i: u32, ss: SS) -> u32 {
let (shift, mask) = (n - i - 1, !(!(0 as S) << i + 1));
let close = |s: S| {
let x = (s ^ s >> shift) & mask;
x & x.wrapping_sub(1) == 0
};
let (ssy, ssn) = ss.partition(|&s| close(s));
let (cy, cn) = rayon::join(|| search(n, i + 1, ssy), || search(n, i + 1, ssn));
cy + cn
}
fn search_end(n: u32, i: u32, ss: Vec<S>) -> u32 {
if i >= n - 1 { 1 } else { search_end2(n, i, ss) }
}
fn search_end2(n: u32, i: u32, mut ss: Vec<S>) -> u32 {
let (shift, mask) = (n - i - 1, !(!(0 as S) << i + 1));
let close = |s: S| {
let x = (s ^ s >> shift) & mask;
x & x.wrapping_sub(1) == 0
};
match ss.iter().position(|&s| close(s)) {
Some(0) => {
match ss.iter().position(|&s| !close(s)) {
Some(p) => {
let (ssy, ssn) = ss.drain(p..).partition(|&s| close(s));
let (cy, cn) = rayon::join(|| search_end(n, i + 1, cat(ss, ssy)),
|| search_end(n, i + 1, ssn));
cy + cn
}
None => search_end(n, i + 1, ss),
}
}
Some(p) => {
let (ssy, ssn) = ss.drain(p..).partition(|&s| close(s));
let (cy, cn) = rayon::join(|| search_end(n, i + 1, ssy),
|| search_end(n, i + 1, cat(ss, ssn)));
cy + cn
}
None => search_end(n, i + 1, ss),
}
}
fn main() {
for n in 1..S_BITS + 1 {
println!("{}: {}", n, search(n, 1, vec![0, 1]));
}
}
```
### `Cargo.toml`
```
[package]
name = "correlations"
version = "0.1.0"
authors = ["Anders Kaseorg <[[email protected]](/cdn-cgi/l/email-protection)>"]
[dependencies]
rayon = "0.7.0"
```
[Try it online!](https://tio.run/##1VZLb9pAEL77Vww5RLstmEfVCw9L4RApl0aKq16qFC2bJbix15Z3aYOAv1466zfGlCTtpSshzO7MN9/MfjMmXim933e74lmLWAKPmRYQs3UoR5YVhA/pM2wswNXtwjV7EvBDxMrD3XCRHg@H30NPwkp58hFkCBGLme8L31NB4het5rCQYIzGV224w88Uv6YOCSMRz9gQcCd5nA9hSqHjADFGd1Oa@Jv1cyliAVdDuJa3kguSWN1dwXtwhXxoF3bpmtbsppldYrYpjLP4hObhCU0j7qydZel1JMCFCaw@DEYWD6XS4M6mN5/dodnCA7NvYWacaRKsNGAmXwQfu04bzM95/jMhkT5m0b0FMJuziHFPr5GkM4F59XfJkdksipA6uUwg6ag8SamC8JWoOMwPHFjFYV7mhqSVYDFfEpkk0wYv@1bqgLVJtKCslO2pmQiiGsdelQnaDeAdeFjyPjggK3ZpyJkhJzGiCUZPuk4mDb6DwtH2pA5nHsqWUHvhMz0LWES2aovy5K2vCm1gizDjMXj3lDbXqgStCQjTPd46DHp0bNYhk02jzeHK2L7AMuVQJPV6FwkdrG0H@m@IdoRxfwZjV22lQm6DsYvdc4MFZDqMx/gQYB@5jtOoQ9etadAXGohaeguNHcbUE0VnUqYFLdIiPWAK0DFhjUKiWQcYX@6HeP8T2Brw6v2Yw2cDpuAbZu04kEShcJnEKXvoGXee7Z8x9hhOu5lazUmfGq1mPTCq8FRrk4Y0JFE6OBW1p3Fuku0laiOhQlSVHeHowBP7ylwl223Rq@00JQO7xqHVfCJzTL7GLS4PLiBtvlf0vGdmkylxHzb4yVuoAlf2JK3ddnZai2bG0smI/8sNB0zzZTIR0gkUharpcisE3DAQpIdITm0u/Bmq1YR1gBk1YFazrgvxIWaoqsi26RlNNoKd0Wgx3FM1mjejUqle6YvHTr5OoVY0Xl@55o/G0dHOp1AKU7gTEWpsS/@ddbb6/6Tqb6h2MhWsvyxueWVY5BqnenXLWrysmvl4CEwtckEvwhgHDP6B7Nv24GOllFGMr1tftsjFZjeEze6iDYhZTjxETt6ePXy8z6maEPv9L44v4ke179z@Bg "Rust – Try It Online")
I also have a [slightly slower variant](https://tio.run/##rVTBbptAEL3zFeMcrN0UW@Aol7WhUm6VqvZAzo0wWdKV8IJgUVxRfr10lgWyNk6USOFiPDNv5s28Gcq6Ul2n/hQcIgigvtlsnSSXlYLo4e7bfcS0CR3a7nBZH@C@FBwaB/D5ITLXvOSPnNzlxx3RXrePoSE1zu88Tl2ndZxUgpAVLxWRfVoXxPBbMYhcUAyWh1oZ9FBCpCAgDEDCCvzBpp9rhaR0IGM6/7Z3tMCzig@YHiLOYKb@hkisjWWxJp1Dg@Bj2AtO@IvQ3U6/n1X4tHxvRE3s35fzDVh7otvmA8JlXMERNSIV/MJaoaUHhSUsyIJ4EFcQUcPhC9q3EzLJcpxVgBmWcFw/l3FRCPn0UNV7gnAUyDOxh1glv0FZU52IMIbrCUFo@cbsOmSP2XFjGZP8mZAJ4L5gqTW6l/H109Nse8lwXwzVxhTer71J6NHiQ3uWyVre/nL2lr@92ImOKnlqmNN5V5/D7WJtfV66YBFLkSzIcNTjYiR5LRXRC2DEX4X9B6N5TZ0TZTx35hgbNU2a7EtkTrGt6Z9PZ8CRpX9K7xALScaVTPMS9CqDv15vbi1W405Ysojs/G70cHGwnmuGMz@sIcC/EFCUQqpMLshV0zJo2Nf2ygUMHzpS1Dq3rvuXpFn8VHWrn/8B "Rust – Try It Online") using very much less memory.
[Answer]
## C++ using the [BuDDy library](http://buddy.sourceforge.net/manual)
A different approach: have a binary formula (as [binary decision diagram](http://en.wikipedia.org/wiki/Binary_decision_diagram)) that takes the bits of `S` as input and is true iff that gives some fixed values of `Y` or `N` at certain selected positions. If that formula is not constant false, select a free position and recurse, trying both `Y` and `N`. If there is no free position, we have found a possible output value. If the formula is constant false, backtrack.
This works relatively reasonable because there are so few possible values so that we can often backtrack early. I tried a similar idea with a SAT solver, but that was less successful.
```
#include<vector>
#include<iostream>
#include<bdd.h>
// does vars[0..i-1] differ from vars[n-i..n-1] in at least two positions?
bdd cond(int i, int n, const std::vector<bdd>& vars){
bdd x1 { bddfalse };
bdd xs { bddfalse };
for(int k=0; k<i; ++k){
bdd d { vars[k] ^ vars[n-i+k] };
xs |= d & x1;
x1 |= d;
}
return xs;
}
void expand(int i, int n, int &c, const std::vector<bdd>& conds, bdd x){
if (x==bddfalse)
return;
if (i==n-2){
++c;
return;
}
expand(i+1,n,c,conds, x & conds[2*i]);
x &= conds[2*i+1];
expand(i+1,n,c,conds, x);
}
int count(int n){
if (n==1) // handle trivial case
return 1;
bdd_setvarnum(n-1);
std::vector<bdd> vars {};
vars.push_back(bddtrue); // assume first bit is 1
for(int i=0; i<n-1; ++i)
if (i%2==0) // vars in mixed order
vars.push_back(bdd_ithvar(i/2));
else
vars.push_back(bdd_ithvar(n-2-i/2));
std::vector<bdd> conds {};
for(int i=n-1; i>1; --i){ // handle long blocks first
bdd cnd { cond(i,n,vars) };
conds.push_back( cnd );
conds.push_back( !cnd );
}
int c=0;
expand(0,n,c,conds,bddtrue);
return c;
}
int main(void){
bdd_init(20000000,1000000);
bdd_gbc_hook(nullptr); // comment out to see GC messages
for(int n=1; ; ++n){
std::cout << n << " " << count(n) << "\n" ;
}
}
```
To compile with debian 8 (jessie), install `libbdd-dev` and do `g++ -std=c++11 -O3 -o hb hb.cpp -lbdd`. It might be useful to increase the first argument to `bdd_init` even more.
[Answer]
# Clingo, n ≈ ~~30 or 31~~ 34
I was a little surprised to see five lines of Clingo code overtake my brute-force Rust solution and come really close to Christian’s BuDDy solution—it looks like it would beat that too with a higher time limit.
### `corr.lp`
```
{s(2..n)}.
d(K,I) :- K=1..n-2, I=1..n-K, s(I), not s(K+I).
d(K,I) :- K=1..n-2, I=1..n-K, not s(I), s(K+I).
a(K) :- K=1..n-2, {d(K,1..n-K)} 1.
#show a/1.
```
### `corr.sh`
```
#!/bin/bash
for ((n=1;;n++)); do
echo "$n $(clingo corr.lp --project -q -n 0 -c n=$n | sed -n 's/Models *: //p')"
done
```
[](https://i.stack.imgur.com/StvEA.png)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 23
By default, Pari/GP limits its stack size to 8 MB. The first line of the code, `default(parisize, "4g")`, sets this limit to 4 GB. If it still gives a stackoverflow, you can set it to 8 GB.
```
default(parisize, "4g")
f(n) = #vecsort([[2 > hammingweight(bitxor(s >> (n-i) , s % 2^i)) | i <- [2..n-1]] | s <- [0..2^(n-1)]], , 8)
for(n = 1, 100, print(n " -> " f(n)))
```
[Answer]
## Clojure, 29 in ~~75~~ 38 seconds, 30 in 80 and 31 in 165
Runtimes from **Intel i7 6700K**, memory usage is less than 200 MB.
project.clj (uses [com.climate/claypoole](https://github.com/TheClimateCorporation/claypoole) for multithreading):
```
(defproject tests "0.0.1-SNAPSHOT"
:description "FIXME: write description"
:dependencies [[org.clojure/clojure "1.8.0"]
[com.climate/claypoole "1.1.4"]]
:javac-options ["-target" "1.6" "-source" "1.6" "-Xlint:-options"]
:aot [tests.core]
:main tests.core)
```
Source code:
```
(ns tests.core
(:require [com.climate.claypoole :as cp]
[clojure.set])
(:gen-class))
(defn f [N]
(let [n-threads (.. Runtime getRuntime availableProcessors)
mask-offset (- 31 N)
half-N (quot N 2)
mid-idx (bit-shift-left 1 half-N)
end-idx (bit-shift-left 1 (dec N))
lower-half (bit-shift-right 0x7FFFFFFF mask-offset)
step (bit-shift-left 1 12)
bitcount
(fn [n]
(loop [i 0 result 0]
(if (= i N)
result
(recur
(inc i)
(-> n
(bit-xor (bit-shift-right n i))
(bit-and (bit-shift-right 0x7FFFFFFF (+ mask-offset i)))
Integer/bitCount
(< 2)
(if (+ result (bit-shift-left 1 i))
result))))))]
(->>
(cp/upfor n-threads [start (range 0 end-idx step)]
(->> (for [i (range start (min (+ start step) end-idx))
:when (<= (Integer/bitCount (bit-shift-right i mid-idx))
(Integer/bitCount (bit-and i lower-half)))]
(bitcount i))
(into #{})))
(reduce clojure.set/union)
count)))
(defn -main [n]
(let [n-iters 5]
(println "Calculating f(n) from 1 to" n "(inclusive)" n-iters "times")
(doseq [i (range n-iters)]
(->> n read-string inc (range 1) (map f) doall println time)))
(shutdown-agents)
(System/exit 0))
```
A brute-force solution, each thread goes over a subset of the range (2^12 items) and builds a set of integer values which indicate detected patterns. These are then "unioned" together and thus the distinct count is calculated. I hope the code isn't too tricky to follow eventhough it uses [threading macros](https://clojure.org/guides/threading_macros) a lot. My `main` runs the test a few times to get JVM warmed up.
Update: Iterating over only half of the integers, gets the same result due to symmetry. Also skipping numbers with higher bit count on lower half of the number as they produce duplicates as well.
Pre-built uberjar ([v1](https://s3-eu-west-1.amazonaws.com/nikonyrh-public/misc/so-124424.jar)) (3.7 MB):
```
$ wget https://s3-eu-west-1.amazonaws.com/nikonyrh-public/misc/so-124424-v2.jar
$ java -jar so-124424-v2.jar 29
Calculating f(n) from 1 to 29 (inclusive) 5 times
(1 1 2 4 6 8 14 18 27 36 52 65 93 113 150 188 241 279 377 427 540 632 768 870 1082 1210 1455 1656 1974)
"Elapsed time: 41341.863703 msecs"
(1 1 2 4 6 8 14 18 27 36 52 65 93 113 150 188 241 279 377 427 540 632 768 870 1082 1210 1455 1656 1974)
"Elapsed time: 37752.118265 msecs"
(1 1 2 4 6 8 14 18 27 36 52 65 93 113 150 188 241 279 377 427 540 632 768 870 1082 1210 1455 1656 1974)
"Elapsed time: 38568.406528 msecs"
[ctrl+c]
```
Results on different hardwares, expected runtime is `O(n * 2^n)`?
```
i7-6700K desktop: 1 to 29 in 38 seconds
i7-6820HQ laptop: 1 to 29 in 43 seconds
i5-3570K desktop: 1 to 29 in 114 seconds
```
You can easily make this single-threaded and avoid that 3rd party dependency by using the standard for:
```
(for [start (range 0 end-idx step)]
... )
```
Well the built-in [pmap](https://clojuredocs.org/clojure.core/pmap) also exists but claypoole has more features and tunability.
[Answer]
# Mathematica, n=19
press alt+. to abort and the result will be printed
```
k = 0;
For[n = 1, n < 1000, n++,
Z = Table[HammingDistance[#[[;; i]], #[[-i ;;]]], {i, Length@#}] & /@
Tuples[{0, 1}, n];
Table[If[Z[[i, j]] < 2, Z[[i, j]] = 0, Z[[i, j]] = 1], {i,
Length@Z}, {j, n}];
k = Length@Union@Z]
Print["f(", n, ")=", k]
```
[Answer]
# Mathematica, 21
```
f[n_] := Length@
DeleteDuplicates@
Transpose@
Table[2 > Tr@IntegerDigits[#, 2] & /@
BitXor[BitShiftRight[#, n - i], Mod[#, 2^i]], {i, 1,
n - 1}] &@Range[0, 2^(n - 1)];
Do[Print[n -> f@n], {n, Infinity}]
```
For comparison, [Jenny\_mathy's answer](https://codegolf.stackexchange.com/a/124455/9288) gives `n = 19` on my computer.
The slowest part is `Tr@IntegerDigits[#, 2] &`. It is a shame that Mathematica doesn't have a built-in for Hamming weight.
---
If you want to test my code, you can [download a free trial of Mathematica](https://www.wolfram.com/mathematica/trial/).
[Answer]
## A C version, using builtin popcount
Works better with `clang -O3`, but also works if you only have `gcc`.
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
unsigned long pairs(unsigned int n, unsigned long s) {
unsigned long result = 0;
for(int d=1;d<=n;d++) {
unsigned long mx = 1 << d;
unsigned long mask = mx - 1;
unsigned long diff = (s >> (n - d)) ^ (s & mask);
if (__builtin_popcountl(diff) <= 1)
result |= mx;
}
return result;
}
unsigned long f(unsigned long n) {
unsigned long max = 1 << (n - 1);
#define BLEN (max / 2)
unsigned char * buf = malloc(BLEN);
memset(buf, 0, BLEN);
unsigned long long * bufll = (void *) buf;
for(unsigned long i=0;i<=max;i++) {
unsigned int r = pairs(n, i);
buf[r / 8] |= 1 << (r % 8);
}
unsigned long result = 0;
for(unsigned long i=0;i<= max / 2 / sizeof(unsigned long long); i++) {
result += __builtin_popcountll(bufll[i]);
}
free(buf);
return result;
}
int main(int argc, char ** argv) {
unsigned int n = 1;
while(1) {
printf("%d %ld\n", n, f(n));
n++;
}
return 0;
}
```
[Answer]
# Haskell, (unofficial n=20)
This is just the naive approach - so far without any optimizations. I wondered how well it would fare against other languages.
How to use it (assuming you have [haskell platform](https://www.haskell.org/platform/) installed):
* Paste the code in one file `approx_corr.hs` (or any other name, modify following steps accordingly)
* Navigate to the file and execute `ghc approx_corr.hs`
* Run `approx_corr.exe`
* Enter the maximal `n`
* The result of each computation is displayed, as well as the cumulative real time (in ms) up to that point.
Code:
```
import Data.List
import Data.Time
import Data.Time.Clock.POSIX
num2bin :: Int -> Int -> [Int]
num2bin 0 _ = []
num2bin n k| k >= 2^(n-1) = 1 : num2bin (n-1)( k-2^(n-1))
| otherwise = 0: num2bin (n-1) k
genBinNum :: Int -> [[Int]]
genBinNum n = map (num2bin n) [0..2^n-1]
pairs :: [a] -> [([a],[a])]
pairs xs = zip (prefixes xs) (suffixes xs)
where prefixes = tail . init . inits
suffixes = map reverse . prefixes . reverse
hammingDist :: (Num b, Eq a) => ([a],[a]) -> b
hammingDist (a,b) = sum $ zipWith (\u v -> if u /= v then 1 else 0) a b
f :: Int -> Int
f n = length $ nub $ map (map ((<=1).hammingDist) . pairs) $ genBinNum n
--f n = sum [1..n]
--time in milliseconds
getTime = getCurrentTime >>= pure . (1000*) . utcTimeToPOSIXSeconds >>= pure . round
main :: IO()
main = do
maxns <- getLine
let maxn = (read maxns)::Int
t0 <- getTime
loop 1 maxn t0
where loop n maxn t0|n==maxn = return ()
loop n maxn t0
= do
putStrLn $ "fun eval: " ++ (show n) ++ ", " ++ (show $ (f n))
t <- getTime
putStrLn $ "time: " ++ show (t-t0);
loop (n+1) maxn t0
```
[Answer]
# A Haskell solution, using popCount and manually managed parallelism
Compile: `ghc -rtsopts -threaded -O2 -fllvm -Wall foo.hs`
(drop the `-llvm` if it doesn't work)
Run : `./foo +RTS -N`
```
module Main (main) where
import Data.Bits
import Data.Word
import Data.List
import qualified Data.IntSet as S
import System.IO
import Control.Monad
import Control.Concurrent
import Control.Exception.Base (evaluate)
pairs' :: Int -> Word64 -> Int
pairs' n s = fromIntegral $ foldl' (.|.) 0 $ map mk [1..n]
where mk d = let mask = 1 `shiftL` d - 1
pc = popCount $! xor (s `shiftR` (n - d)) (s .&. mask)
in if pc <= 1
then mask + 1
else 0
mkSet :: Int -> Word64 -> Word64 -> S.IntSet
mkSet n a b = S.fromList $ map (pairs' n) [a .. b]
f :: Int -> IO Int
f n
| n < 4 = return $ S.size $ mkSet n 0 mxbound
| otherwise = do
mvs <- replicateM 4 newEmptyMVar
forM_ (zip mvs cpairs) $ \(mv,(mi,ma)) -> forkIO $ do
evaluate (mkSet n mi ma) >>= putMVar mv
set <- foldl' S.union S.empty <$> mapM readMVar mvs
return $! S.size set
where
mxbound = 1 `shiftL` (n - 1)
bounds = [0,1 `shiftL` (n - 3) .. mxbound]
cpairs = zip bounds (drop 1 bounds)
main :: IO()
main = do
hSetBuffering stdout LineBuffering
mapM_ (f >=> print) [1..]
```
[Answer]
# Python 2 + pypy, n = 22
Here is a really simple Python solution as a sort of baseline benchmark.
```
import itertools
def hamming(A, B):
n = len(A)
assert(len(B) == n)
return n-sum([A[i] == B[i] for i in xrange(n)])
def prefsufflist(P):
n = len(P)
return [hamming(P[:i], P[n-i:n]) for i in xrange(1,n+1)]
bound = 1
for n in xrange(1,25):
booleans = set()
for P in itertools.product([0,1], repeat = n):
booleans.add(tuple(int(HD <= bound) for HD in prefsufflist(P)))
print "n = ", n, len(booleans)
```
] |
[Question]
[
The goal is to animate a star exploding in ASCII art, starting from a single star character `*` to a supernovae and finally to the space void.
Rules :
* You have to display only 80 characters per line on 24 lines (this is
the default terminal size on Linux)
* Only these [95 printable characters from ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) are allowed
* Steps:
1. The initial star must be `*` and centred horizontally and vertically
2. The star has to grow to show that it explodes
3. At the end the screen must be empty (the star has disappeared)
* Length of the code or languages are irrelevant
* Votes will decide of the most creative and beautiful results. Have you ever seen an exploding star? Let's see how you imagine this.
I've added an answer using Python as an example, but you're encouraged to create something different or better.
You have one week to participate, the winner will be chosen on 2014-04-01.
Samples of output (with some frames only):
```
# start
*
# during explosion
****#****
***#@##*#@#****
*@**@@@*##**#*#**#*
**@@*#**#@*#@****#***
****@*@***#****@**@@*
*******@***@@***#****#*
*#***#*##@****##@@@**
**#@###****@*********
*****@**@*@*****@**
************@**
****#****
# star is expanding
*
********* **@******
**** **#**@ #**#*# ****
*** ** **##** *@@*@* ** ***
** * @@ *@*#* ***@* *# * **
*** # * *# *@#** ***@* ** @ * *@*
** * * ** *@ ****@ @**** ** #* * * **
** * @* * ** *@ #### *#** ** ** * @* * **
*# * # ** * #* * **** **** @ ** * ** * * #*
** * *# * @ * # @ @*@ *#* * @ # # * @* * **
*# * * * * # * @* * **# *#* * ** * * * * * # **
** # * * @ * * # * # ** @* * * * * * # @ @ * **
*# * * * * * * * * # * * * * * * @ @ * * * * * **
*# * @ * @ * @ * * * ** *@ * * # * * * * * @ @*
*# # @ * * # * *@ * *** @#@ @ ** * @ @ * * # **
*# * ** * * * @ @ **@ *** * @ * * * @* * #*
** * * ** * #@ * #*** **## * #* * #@ * * @*
*# * *@ * @@ *# **** @*** ** ** * #* * #*
*# * * *@ ** @**@* *@#** ** ** * * @*
*#* @ * @@ **##* ****@ ** # * @**
** @ #* @*@#* @*@*# @# * **
*#* @* @#*@*# **#*@# ** ***
**** *##**# #***@* @***
****@**@* *****@***
# star is disappearing
* - - -- -- ------- ------- -- -- - - *
** - - - -- -- ------ ------ -- -- - - - **
* -- - -- -- -- -- ------ ------ -- -- -- -- - -- *
** - - - -- -- -- -- ------ ------ -- -- -- -- - - - **
* - - -- - -- - - -- ----- ----- -- - - -- - -- - - *
** - - - -- - -- - - -- ----- ----- -- - - -- - -- - - - **
* - - - - - - - - -- -- ----- ----- -- -- - - - - - - - - *
* - - - - - - - -- - -- -- ---- ---- -- -- - -- - - - - - - - *
* -- - - - - - - - -- - -- - ---- ---- - -- - -- - - - - - - - -- *
* - - - - - - - -- - - - - - --- --- - - - - - -- - - - - - - - *
* - - - - - - - - - - - - -- - --- --- - -- - - - - - - - - - - - - *
* - - - - - - - - - - - - - - - -- -- - - - - - - - - - - - - - - - *
* - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - *
* - - - - - - - - - - - - - - - -- -- - - - - - - - - - - - - - - - *
* - - - - - - - - - - - - -- - --- --- - -- - - - - - - - - - - - - *
* - - - - - - - -- - - - - - --- --- - - - - - -- - - - - - - - *
* -- - - - - - - - -- - -- - ---- ---- - -- - -- - - - - - - - -- *
* - - - - - - - -- - -- -- ---- ---- -- -- - -- - - - - - - - *
* - - - - - - - - -- -- ----- ----- -- -- - - - - - - - - *
** - - - -- - -- - - -- ----- ----- -- - - -- - -- - - - **
* - - -- - -- - - -- ----- ----- -- - - -- - -- - - *
** - - - -- -- -- -- ------ ------ -- -- -- -- - - - **
* -- - -- -- -- -- ------ ------ -- -- -- -- - -- *
** - - - -- -- ------ ------ -- -- - - - **
# the star is gone
(there is nothing)
```
Animated example of output:

If you want some inspiration, you can look at an [explosion from Captain Blood](http://youtu.be/NwN3x8GzzFc?t=1m4s), a game from 1988.
[Answer]
# C + curses

I haven't made much of an effort to tidy up the source code. Basically it calculates an expanding shock wave, with a solid background added to the first few frames to give a sort of flash effect. *[[EDIT: The explosion looked a bit odd appearing from a single asterisk, so I added a few frames of expansion at the beginning of the animation.]]*
Random particles are superimposed on top of this, with positions determined according to a basic perspective calculation to give it a slightly 3D feel. (Well that was the idea, anyway.)
```
#include <curses.h>
#include <stdlib.h>
#include <math.h>
#define NUM_FRAMES 150
#define NUM_BLOBS 800
#define PERSPECTIVE 50.0
typedef struct {
double x,y,z;
} spaceblob;
double prng() {
static long long s=1;
s = s * 1488248101 + 981577151;
return ((s % 65536) - 32768) / 32768.0;
}
int main() {
char *frames[NUM_FRAMES], *p;
int i,j,x,y,z,v,rows,cols,ith,i0;
int maxx,minx,maxy,miny,delay=1E6;
double bx,by,bz,br,r,th,t;
spaceblob *blobs;
/* Initialize ncurses and get window dimensions */
initscr();
getmaxyx(stdscr,rows,cols);
minx = -cols / 2;
maxx = cols+minx-1;
miny = -rows / 2;
maxy = rows+miny-1;
/* Generate random blob coordinates */
blobs = malloc(NUM_BLOBS * sizeof(spaceblob));
for (i=0; i<NUM_BLOBS; i++) {
bx = prng();
by = prng();
bz = prng();
br = sqrt(bx*bx + by*by + bz*bz);
blobs[i].x = (bx / br) * (1.3 + 0.2 * prng());
blobs[i].y = (0.5 * by / br) * (1.3 + 0.2 * prng());;
blobs[i].z = (bz / br) * (1.3 + 0.2 * prng());;
}
/* Generate animation frames */
for (i=0; i<NUM_FRAMES; i++) {
t = (1. * i) / NUM_FRAMES;
p = frames[i] = malloc(cols * rows + 1);
for (y=miny; y<=maxy; y++) {
for (x=minx; x<=maxx; x++) {
/* Show a single '*' in first frame */
if (i==0) {
*p++ = (x==0 && y==0) ? '*' : ' ';
continue;
}
/* Show expanding star in next 7 frames */
if (i<8) {
r = sqrt(x*x + 4*y*y);
*p++ = (r < i*2) ? '@' : ' ';
continue;
}
/* Otherwise show blast wave */
r = sqrt(x*x + 4*y*y) * (0.5 + (prng()/3.0)*cos(16.*atan2(y*2.+0.01,x+0.01))*.3);
ith = 32 + th * 32. * M_1_PI;
v = i - r - 7;
if (v<0) *p++ = (i<19)?"%@W#H=+~-:."[i-8]:' '; /* initial flash */
else if (v<20) *p++ = " .:!HIOMW#%$&@08O=+-"[v];
else *p++=' ';
}
}
/* Add blobs with perspective effect */
if (i>6) {
i0 = i-6;
for (j=0; j<NUM_BLOBS; j++) {
bx = blobs[j].x * i0;
by = blobs[j].y * i0;
bz = blobs[j].z * i0;
if (bz<5-PERSPECTIVE || bz>PERSPECTIVE) continue;
x = cols / 2 + bx * PERSPECTIVE / (bz+PERSPECTIVE);
y = rows / 2 + by * PERSPECTIVE / (bz+PERSPECTIVE);
if (x>=0 && x<cols && y>=0 && y<rows)
frames[i][x+y*cols] = (bz>40) ? '.' : (bz>-20) ? 'o' : '@';
}
}
/* Terminate the text string for this frame */
*p = '\0';
}
/* Now play back the frames in sequence */
curs_set(0); /* hide text cursor (supposedly) */
for (i=0; i<NUM_FRAMES; i++) {
erase();
mvaddstr(0,0,frames[i]);
refresh();
usleep(delay);
delay=33333; /* Change to 30fps after first frame */
}
curs_set(1); /* unhide cursor */
endwin(); /* Exit ncurses */
return 0;
}
```
[Answer]
## Javascript
Thought it was worth a shot in JS. Suggest saving and running; very very slow if you paste in console.
```
var boomboom = (function() {
//Clear any existing page
document.getElementsByTagName("body")[0].innerHTML="";
var space=document.createElement("div");
var iterator=0;
var stars = 50;
var timer=100;
//Set container
space.setAttribute("id","space");
space.setAttribute("style","width:1000px;height:600px;margin:auto;border:solid 1px #000;position:relative;overflow:hidden;background:#000;color:#fff");
document.getElementsByTagName("body")[0].appendChild(space);
//Set interval and draw...
var interval = setInterval(function(){ drawStars(iterator,stars); }, timer);
drawStars(iterator, stars);
function drawStars(r,c) {
clearInterval(interval);
//a container for this set of stars
var starContainer=document.createElement("div");
//don't draw more if there are too many, it's got to go
if(iterator < 1000) {
for(var i = 0; i < c; i++) {
var x,y;
if(iterator < 100) {
x=500 + r * Math.cos(2 * Math.PI * i / c) * 0.7;
y=300 + r * Math.sin(2 * Math.PI * i / c) * 0.7;
}
//add some randomness for the boom boom
if(iterator > 100) {
x=500 + r * Math.cos(2 * Math.PI * i / c) * 0.7*Math.random();
y=300 + r * Math.sin(2 * Math.PI * i / c) * 0.7*Math.random();
}
//Make a star
var star=document.createElement("div");
star.setAttribute("class","star");
//Exploding stars are red, I hope
var color = iterator < 100 ? "color:#fff" : "color:rgb("+parseInt(255*Math.random())+",0,0)";
star.setAttribute("style","position:absolute; left:"+ x +"px;top:"+ y +"px;"+color);
//Change the star character as boom boom gets bigger
if(iterator <= 200) {
star.innerText="*";
}
else if(iterator >=200 & iterator <= 400) {
star.innerText="O";
}
else {
star.innerText="-";
}
//Add the star to its container
starContainer.appendChild(star);
}
}
//draw the container
space.appendChild(starContainer);
//increment the iterator. It's an iterator because we're using intervals and it's late.
iterator+=5;
//remove stars when we get too many
if(iterator > 200) {
space.removeChild(space.firstChild);
}
if(iterator < 1500) { //do it all again
timer = timer > 10 ? timer-10 : timer;
interval=setInterval(function(){ drawStars(iterator,stars); }, timer);
}
//make sure it's actually empty
else {
space.innerHTML="";
}
}
}());
```
**Edits**
In JSBin: <http://jsbin.com/worofeqi/5/watch?js,output>
Oddly runs much more smoothly when done from local file system than in JSBin. Honestly not sure why; may look at that this evening.
[Answer]
# Python
```
#!/usr/bin/python
import sys, math, time, random
def distance(x, y):
# ((y - y_center) * 2) -> correct ratio for a true circle
return math.ceil(math.sqrt(((x - 40) ** 2) + (((y - 12) * 2) ** 2)))
def star(radiuses):
for r in radiuses:
#~ clear screen: http://stackoverflow.com/a/2084521/2257664
print chr(27) + "[2J"
# width
for y in range(24):
# height
for x in range(80):
d = distance(x, y)
#~ border
if (d == r):
sys.stdout.write('*')
#~ inside the star
elif (d < r):
if (r > 35):
sys.stdout.write(' ')
elif (r > 25) and ((d % 2) != 0):
sys.stdout.write('-')
elif (r > 15) and ((d % 2) == 0):
sys.stdout.write(' ')
else :
sys.stdout.write(random.choice('****#@'))
#~ space outside the star
else:
sys.stdout.write(' ')
print
time.sleep(0.1)
star(range(0, 12) + range(10, 0, -1) + range(0, 50))
```
[Example output](http://ideone.com/oFzFwT) (using less steps and without clearing the screen).
Excerpts of the output are also displayed in the question.
] |
[Question]
[
# Challenge
Generate two \$16 \times 16\$ grids, each initially filled with "@" symbols and spaces. Each cell in the grids should be independently filled with an "@" or a space, with each character having an equal probability (\$50\%\$) of being chosen for each cell. This ensures that both grids start off identically, with all possible configurations of each grid having the same probability of occurrence, corresponding to a uniform distribution across all possible grid states.
After generating these identical grids, modify a single, randomly selected cell in the second grid by either adding or removing an "@" symbol. This modification guarantees that the second grid differs from the first grid in exactly one position. The selection of this cell must be uniformly random from among the \$256\$ cells, ensuring that each cell has an equal chance (\$\frac{1}{256}\$) of being chosen for modification.
**Input**
None
**Output**
Both grids side by side, separated by a vertical bar "|", to visually compare them and spot the single difference. e.g. row \$3\$, col \$10\$.
```
@ @ @ @ @ @ @@|@ @ @ @ @ @ @@
@@@ @@ @ @| @@@ @@ @ @
@ @@@@@@ @ @ | @ @@@@@@@@ @
@ @ @@ @@ @ | @ @ @@ @@ @
@@@ @@ @@ @ @|@@@ @@ @@ @ @
@ @ @ @@ @@| @ @ @ @@ @@
@ @ @@ @ @@ @@@|@ @ @@ @ @@ @@@
@ @ @@ |@ @ @@
@ @@ @@@ @| @ @@ @@@ @
@@ @ @@ @@ | @@ @ @@ @@
@ @@@@ @ @@|@ @@@@ @ @@
@@ @@ @@ @@@ @@|@@ @@ @@ @@@ @@
@@@ @ @@ @ @| @@@ @ @@ @ @
@ @ @ @ @ | @ @ @ @ @
@@@@ @@@@@ @ @@|@@@@ @@@@@ @ @@
@ @@@ @@@@ @@@| @ @@@ @@@@ @@@
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~147~~ ~~141~~ ~~139~~ ~~138~~ 124 bytes
*-8 bytes thanks to [Mukundan314](https://codegolf.stackexchange.com/users/91267). -14 bytes thanks to [Jonathan Allan](https://codegolf.stackexchange.com/users/53748).*
```
from random import*
g=getrandbits
n=g(4)
r=16
while r:r-=1;s=g(16);print(f'{s:16b}|{s^(r==n)<<g(4):16b}'.translate('@ '*25))
```
[Try it online!](https://tio.run/##HYxbCsMgFAX/XYV/aqAF@5CS5EJXUkioMUKicr1QStq129ivgRnOSW@aYzjfEpYyYVw5DuG5w68pIjXMgbNU3egpswBOXhRD0Ia9Zr9Yji0eQHd5D9qoLqEPJCex5Vab8fvZ8kMiQFB9X5d/KY71MC8DWSnuXDSnq1Kl/AA "Python 3.8 (pre-release) – Try It Online")
## Explanation (outdated)
That's a lot of use out of Python's [`random` module](https://docs.python.org/3/library/random.html). First, it iterates over \$[0, 16)\$ shuffled with `for r in sample(a:=range(16),16)`. The random ordering means that `r` will only be zero once, but it can be on any of the 16 iterations. When this is the case, the row that it outputs in that iteration will contain the difference.
It represents cells as bits and therefore, rows as 16-bit integers. Luckily, `getrandbits(16)` can generate a random 16-bit integer like `16846` or `01000001110011102`. (Though `randrange(65536)` or `randint(0,65535)` would've worked just as well.)
Now, for the interesting bit manipulation. To toggle a random cell, it takes the bitwise XOR of the row with a 16-bit integer that has only one randomly chosen bit turned on like `00010000000000002`. This integer can be made by left shifting 1 bitwise by a random integer in \$[0, 16)\$. When `r` is zero, `r<1` is `True`, which can be used as if it were `1` in numerical operations. `choice(a)` returns a random choice from \$[0, 16)\$. Therefore, `s^(r<1)<<choice(a)` computes something like:
```
00000000000000012
<< 12
--------------------
00010000000000002
^ 01000001110011102
--------------------
01010001110011102
```
However, when `r` is not zero, left shifting `False` or `0` bitwise or taking the bitwise XOR of it with something does nothing.
Finally, in order to represent it as a string and turn the bits into `@`s and spaces, it first uses a format string `{s:16b}`. This converts the integer into binary and pads it with enough spaces to increase its length to 16, turning `16846` into `' 100000111001110'`. It then uses `.translate({49:64,48:32})` (a table of the characters' respective ASCII ordinal numbers) to turn it into `' @ @@@ @@@ '`.
[Answer]
# Google Sheets, ~~170~~ 161 bytes
Formula in \$A1\$
```
=INDEX(LET(g,MAP(A25:P40,LAMBDA(_,IF(COINFLIP(),"@"," "))),r,ROW(1:16),{g,IF(r,"|"),IF((r=RANDBETWEEN(1,16))*(TOROW(r)=RANDBETWEEN(1,16)),IF(g="@"," ","@"),g)}))
```
[](https://i.stack.imgur.com/VJdiE.gif)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 25 ~~ 22 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
⁹ḶẊ⁾ @Ẋḷ\⁹¡¥Ɱs⁴Z€j€”|Y
```
**[Try it online!](https://tio.run/##y0rNyan8//9R486HO7Y93NX1qHGfggOQfrhjewxQ8NDCQ0sfbVxX/KhxS9SjpjVZQPyoYW5N5P//AA "Jelly – Try It Online")**
### How?
```
⁹ḶẊ⁾ @Ẋḷ\⁹¡¥Ɱs⁴Z€j€”|Y - Link: no arguments
‚Åπ - 256
·∏∂ - lowered range {256} -> [0..255]
Ẋ - shuffle -> IsEqualIndicators
‚Åæ @ - list of characters -> " @"
Ɱ - map across {i in IsEqualIndicators} with:
¥ - last two links as a dyad - f(" @", i):
Ẋ - shuffle {" @"} -> " @" or "@ "
‚Åπ¬° - repeat {i} times: (i.e. a no-op when i=0)
\ - cumulative reduce {ShuffledCharacters} by:
·∏∑ - left argument
(first takes " @" to " ", or "@ " to "@@"
then further applications have no more effect)
s‚Å¥ - split into chunks of 16
Z€ - transpose each
j€”| - join each with '|'
Y - join with newlines
```
---
[Here](https://tio.run/##XZExDsIwDEV3n@LvIHECJF@DjYWl6gWQPAArZ2BiZWRBlRi4SXuRkMR22rpDk7x@@/@43anvzymNw3v8PKfba7o8ZL/Lm3G4T9cvNttjPnT25fAbUkoMZgaQ1/JmiYDKyjOFRECA67k8WREAQStQS/JeIiDr5QASAbmctXFRrAG5n4arijWgORZa0hUgbqHVWSKwHuxXZIlAe2hVbSwRkKvdWmwMDZDlgVXYf1kAn2mzlghIY9l06m0DIF76VpcA/g "Jelly – Try It Online") is a difference spotter which accepts an output and replaces any space on one of the two sides where there is an `@` on the other with a `+`.
[Answer]
# [J](http://jsoftware.com/), ~~41 38~~ 37 bytes
```
' @|'{~(?@$&2([,.2,.~:)?|.{.&1)@16 16
```
[Try it online!](https://tio.run/##y/pvqWhlGGumaGWprs6lpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RUcatSr6zTsHVTUjDSidfSMdPTqrDTta/Sq9dQMNR0MzRQMzf5rcqUmZ@QrpKmr/wcA "J – Try It Online")
*-1 thanks to Mukundan314*
* `?|.{.&1` Create a 16x16 grid of zeros with a 1 in the upper left, and randomly rotate it to one of the 256 possible positions
* `?@$&2` Create a 16x16 grid of random 0-1s
* `[,.2` Zip that grid with 2, to make the dividing wall
* `,.~:` Then zip *that* with "where is the random grid not equal to the random-single-1 grid"
* `' @|'{~` Translate all that to the appropriate ascii chars
[Answer]
# [JavaScript (V8)](https://v8.dev/), 107 bytes
A full program.
```
for(R=Math.random,v=R(n=16)*512|0;n--;print(s))for(k=33,m=R(s="")*2**k;k--;)s+=" @|"[k-16?m>>k%17&1^!v--:2]
```
[Try it online!](https://tio.run/##FcrRCsIgFADQXymhUNuNdLQiuasf6GWvUSBFtC66oeLT/t3WeT5fm218hn5MkI@lvIfAO7za9NkG61@DqzJ23KNqhNwrPe2MBzBj6H3iUYh/J6zrys0rImNCainJ0JxE3CBbXCZ2I1DN2bUtrdRhrR7LDHDS91J@ "JavaScript (V8) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 106 bytes
```
f(v,n,m,k){for(v=rand(n=16)&511;n--;)for(m=rand(k=33);~k--;)putchar(~k?k-16?32<<(m>>k%17&1^!v--):124:10);}
```
[Try it online!](https://tio.run/##JYzdCoIwGEDve4p1kXwfOPDTMnD@vEkwVjOZW6FmF6KP3tK6OnAOHMVrpbzXMIYutKHBST86GItOuiu4glIMTkTCcS5wK/ZfTJEkKBaz6edrUHfZwWIqwymtkjjPwZalOdA5oMt@5Bwzio8ZRShm37iBWdk4QDbtGOt/v6GxN4gQxWo0rJj9R@lW1r3n7y8 "C (gcc) – Try It Online")
[Answer]
# APL+WIN, ~~54~~ 46 bytes
Index origin = 0
```
'@ |'[(2|z+m⍴(?i)⌽i↑1),2,z←(m←2⍴16)⍴2|i?i←256]
```
[Try it online!Thanks to Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlwPWooz3tv7qDQo16tIZRTZV27qPeLRr2mZqPevZmPmqbaKipY6RTBVSpkQskjICShmaaQNKoJtM@EyRiahb7H2gG1/80Li4A "APL (Dyalog Classic) – Try It Online")
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 36 bytes
```
⊏:"@ |"⍉⊂⊂:+2⊚16⍜⊡¬⌊×16⊟⚂⚂.⁅⊞⋅⋅⚂.⊚16
```
[Try it!](https://uiua.org/pad?src=0_9_0__ZiDihpAg4oqPOiJAIHwi4o2J4oqC4oqCOisy4oqaMTbijZziiqHCrOKMisOXMTbiip_imoLimoIu4oGF4oqe4ouF4ouF4pqCLuKKmjE2CgriiaEmcCBmCg==)
```
⊏:"@ |"⍉⊂⊂:+2⊚16⍜⊡¬⌊×16⊟⚂⚂.⁅⊞⋅⋅⚂.⊚16
‚ÅÖ‚äû‚ãÖ‚ãÖ‚öÇ.‚äö16 # 16x16 binary random matrix
. # duplicate
⍜⊡¬⌊×16⊟⚂⚂ # invert a random cell
⊂:+2⊚16 # append row of 2s
⊂ # prepend original matrix
‚çâ # transpose
‚äè:"@ |" # convert to proper ascii symbols
```
[Answer]
# [Perl 5](https://www.perl.org/), 92 bytes
```
@s=map{(@z=map{('@',$")[rand 2]}0..15),'|',@z,$/}0..15;$s[34*(0|rand 16)+rand 16]^='`';say@s
```
[Try it online!](https://tio.run/##K0gtyjH9/9@h2DY3saBaw6EKQqs7qOuoKGlGFyXmpSgYxdYa6OkZmmrqqNeo6zhU6ajoQwSsVYqjjU20NAxqwOoMzTS1oYzYOFv1BHXr4sRKh@L////lF5Rk5ucV/9f1NdUzMDQAAA "Perl 5 – Try It Online")
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~49~~ 48 bytes
```
16*$(16*$( @)¶
(.){2}
$?1
.+
$&|$&
@T` @`@ ` |@
```
[Try it online!](https://tio.run/##K0otycxLNPz/n8vQTEtFA0woOGge2saloadZbVTLpWJvyKWnzaWiVqOixuUQkqDgkOCgkKBQ4/D/PwA "Retina – Try It Online") Edit: Saved 1 byte thanks to @Leo. Explanation:
```
16*$(16*$( @)¶
```
Insert a 16√ó16 grid of pairs of spaces and `@`s.
```
(.){2}
$?1
```
Pick a random character from each pair.
```
.+
$&|$&
```
Duplicate each row joined with `|`.
```
@T` @`@ ` |@
```
Flip a random space or `@`.
16-byte difference spotter written in [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d):
```
+`@(.{16})@
$1
```
[Try it online!](https://tio.run/##XZExDsIwDEX3fwoPHUBIlbow@ygwMHTpgNgwZw9JbKftl9pYfUqe/dP367Nuz1JuD73M3@X@uypkWqQUUdX6ivgjxgCtOmtU1BhAxpefSceQIIxhrjsYwKsbGjUGSHs2MwbIqSSsxgASB9xcHQy6w6fKtAT6pHE3noUB@prhtKc9A@zC0eUMEK4U1y4EcPgDsjsOwG8s8rdqDDCiRXdj8Ac "Retina 0.8.2 – Try It Online") Removes all of the paired `@`s.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 31 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₁F„@ Ω}JÐ₅ÝΩ©è„@ ‡®ǝ‚16δôø'|ý»
```
[Try it online.](https://tio.run/##yy9OTMpM/f//UVOj26OGeQ4K51bWeh2e8Kip9fDccysPrTy8Aix6uOlRw8JD647PfdQwy9Ds3JbDWw7vUK85vPfQ7v//AQ)
Replaced the incorrect `„@ ₁×.r₁£` with `₁F„@ ΩJ}` (also -1 byte) to fix the issue mentioned by *@Neil*: *"Strictly speaking, step 1 doesn't generate 256 independent characters; the chances for all `@`s is \$1\$ in \$512!\$ instead of \$1\$ in \$2^{256}\$."*
**Explanation:**
Step 1: Generate a random string of 256 `"@"` and `" "`, with a 50% chance each:
```
‚ÇÅF # Loop 256 times:
„@ # Push string "@ "
Ω # Pop and push a random character from it
}J # After the loop: Join all characters on the stack together
```
[Try just step 1 online.](https://tio.run/##yy9OTMpM/f//UVOj26OGeQ4K51bWev3/DwA)
Step 2: Create a copy, and flip the character at a single random position:
```
Ð # Triplicate the string
‚ÇÖ√ù # Push a list in the range [0,255]
Ω # Pop and push a random integer from it
© # Store this random index-integer in variable `®` (without popping)
è # Pop one of the strings, and get the character at this index
„@ # Push string "@ " again
 # Bifurcate it; short for Duplicate & Reverse copy
‡ # Transliterate "@" to " " and vice-versa
®ǝ # Pop another string, and insert this flipped character at index `®`
‚Äö # Pair the two strings together
```
[Try just the first two steps online.](https://tio.run/##yy9OTMpM/f//UVOj26OGeQ4K51bWeh2e8Kip9fDccysPrTy8Aix6uOlRw8JD647PfdQw6/9/AA)
Step 3: Format it correctly and output the result:
```
δ # Map over both strings in the pair:
16 ô # Split it into parts of size 16 each
√∏ # Zip/transpose; swapping rows/columns
'|√Ω '# Join each inner pair together with "|"-delimiter
» # Join the list of strings together by newlines
# (which is output implicitly as result)
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 30 bytes
```
↶≔¹⁶θEθ⭆θ‽ @C⊕θ⁰θJ‽θ±‽θ§ @⁼ KK
```
[Try it online!](https://tio.run/##RY3BDoIwEETvfEXDaZvURC9euEiMB4waov5AAysSoKXtQvTrayEE9zRvd3ameEtbaNl6n9ejpgu@CHgSpc7VlYLdXjATMLe1IrjKHoxgDwpULXCXqtQdxOwQ8zBJdNT9FzJVWOxQEZZguGDbNWNKOw9d/9SwvE73G1aS8L/hqz@lTJX4mQsEO5lBti5A0DliA3On934ztj8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
↶
```
Change the default drawing direction to upwards.
```
≔¹⁶θ
```
Save the value `16` in a variable because it gets used to much.
```
Eθ⭆θ‽ @
```
Output a random `16√ó16` grid of spaces and `@`s.
```
C⊕θ⁰
```
Copy it `17` characters to the right.
```
θ
```
Draw a line of length `16` in the default drawing direction.
```
J‽θ±‽θ
```
Jump to a random position.
```
§ @⁼ KK
```
Toggle the character at that position.
[Answer]
# [R](https://www.r-project.org), 112 bytes
```
s=sample
A=B=s(2,256,T)
B[i]=3-B[i<-s(256,1)]
`?`=\(v)matrix(c("@"," ")[v],16)
write(rbind(?A,"|",?B),"",33,,"")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMFa5eLUEr3i1NQUDRMjzaWlJWm6FjcLim2LE3MLclK5HG2dbIs1jHSMTM10QjS5nKIzY22NdYGUjS5QGChoqBnLlWCfYBujUaaZm1hSlFmhkayh5KCko6SgpBldFqtjaKbJVV6UWZKqUZSUmZeiYe-oo1SjpGPvpKmjpKRjbKwDpKD2LoBSUBoA)
[Answer]
# Google Sheets, 178 bytes
```
=index(let(y,row(1:16),x,torow(y),t,(x=randbetween(1,16))*(y=randbetween(1,16)),g,map(t,lambda(_,if(coinflip()," ","@"))),{g,if(y,"|"),if(t,if(""=tocol(if(t,g,),1),"@"," "),g)}))
```
Put the formula in cell `A1`.

Ungolfed:
```
=arrayformula(let(
y, sequence(16),
x, transpose(y),
truthyTable, (x = randbetween(1, 16)) * (y = randbetween(1, 16)),
firstGrid, map(truthyTable, lambda(_, if(coinflip(), "@", " "))),
currentChar, tocol(if(truthyTable, firstGrid, iferror(√∏)), 1),
flipChar, if(" " = currentChar, "@", " "),
secondGrid, if(truthyTable, flipChar, firstGrid),
hstack(firstGrid, if(y, "|"), secondGrid)
))
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 34 bytes [SBCS](https://github.com/abrudz/SBCS)
Requires Index Origin 0 (`‚éïIO‚Üê0`)
```
' @|'[A,2,A≠(⍴A←?16 16⍴2)⍴1=?⍨256]
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=e9Q31dP/UdsEAwA&c=U1dwqFGPdtQx0nF81LlA41HvFsdHbRPsDc0UDM2AHCNNIGFoa/@od4WRqVksAA&f=AwA&i=SwMA&r=tio&l=apl-dyalog&m=dfn&n=f)
```
' @|'[A,2,A≠(⍴A←?16 16⍴2)⍴1=?⍨256]­⁡​‎‎⁡⁠⁢⁡⁢‏⁠‎⁡⁠⁢⁡⁣‏⁠‎⁡⁠⁢⁡⁤‏⁠‎⁡⁠⁢⁢⁡‏⁠‎⁡⁠⁢⁢⁢‏⁠‎⁡⁠⁢⁢⁣‏⁠‎⁡⁠⁢⁢⁤‏‏​⁡⁠⁡‌⁢​‎‎⁡⁠⁢⁡⁡‏‏​⁡⁠⁡‌⁣​‎‎⁡⁠⁤⁣‏⁠‎⁡⁠⁤⁤‏‏​⁡⁠⁡‌⁤​‎‏​⁢⁠⁢‌⁢⁡​‎‎⁡⁠⁢⁤⁡‏⁠‎⁡⁠⁢⁤⁢‏⁠‎⁡⁠⁢⁤⁣‏⁠‎⁡⁠⁢⁤⁤‏⁠‎⁡⁠⁣⁡⁡‏‏​⁡⁠⁡‌⁢⁢​‎‎⁡⁠⁢⁣⁣‏⁠‎⁡⁠⁢⁣⁤‏‏​⁡⁠⁡‌⁢⁣​‎‎⁡⁠⁢⁣⁢‏‏​⁡⁠⁡‌⁢⁤​‎‎⁡⁠⁤⁢‏⁠‎⁡⁠⁤⁣‏‏​⁡⁠⁡‌⁣⁡​‎‎⁡⁠⁣⁣‏⁠‎⁡⁠⁣⁤‏‏​⁡⁠⁡‌⁣⁢​‎‎⁡⁠⁣⁡‏⁠‎⁡⁠⁣⁢‏‏​⁡⁠⁡‌⁣⁣​‎⁠‎⁡⁠⁢⁣‏⁠‎⁡⁠⁢⁤‏‏​⁡⁠⁡‌⁣⁤​‎‎⁡⁠⁡‏⁠‎⁡⁠⁢‏⁠‎⁡⁠⁣‏⁠‎⁡⁠⁤‏⁠‎⁡⁠⁢⁡‏⁠‎⁡⁠⁢⁢‏⁠‎⁡⁠⁣⁡⁢‏‏​⁡⁠⁡‌­
16 16⍴2 # ‎⁡generate 16, 16 matrix of 2s
? # ‎⁢replace each with random number less than current value
A← # ‎⁣assign to A
‎⁤
?⍨256 # ‎⁢⁡random permutation of [0, 1, ..., 255]
1= # ‎⁢⁢equals 1 (vectorized)
⍴ # ‎⁢⁣reshape to
⍴A # ‎⁢⁤shape of A (16, 16)
A≠ # ‎⁣⁡not equal/xor against A (vectorized)
2, # ‎⁣⁢concatenate column of 2 to start
A, # ‎⁣⁣concatenate A to start
' @|'[ ] # ‎⁣⁤translate to required characters
üíé
```
Created with the help of [Luminespire](https://vyxal.github.io/Luminespire).
[Answer]
# [Racket](https://racket-lang.org/), 369 Bytes
```
(define(f x)(if(empty? x)x(cons(take x 16)(f(drop x 16)))))(let*([s list->string][b build-list][m map][g((λ(x)(list(m(λ(x y)(xor x y))x(b 256((λ(y)(λ(x)(= y x)))(random 256))))x))(b 256(λ(x)(=(random 2)0))))][h(λ(x)(m(λ(x)(if x #\@#\ ))x))][i(list(m s(f(h(car g))))(m s(f(h(cadr g)))))])(display(string-join(m(λ(x y)(string-append x"|"y))(car i)(cadr i))"\n")))
```
[Try it online!](https://tio.run/##TU9LbsUgELvKKNkMlSK1lfp2/dyDsCCB5E1f@AiolEi9We/QK6WQoLZswB5jj4Mcbzrt7SLtDOEEqPREVuMEK0OaUBufttcMVhydjZjkTcMKDxeGE6rg/AnKwUWnO@QRFoqpe4kpkJ0FH2D4oEV1hRXcgJFe8Bnx@wtzRGHRHAA2hqsLUB45boDHp8shy/wpfoYtb5KTgrTKmSIowZmq6ir7nbP7Mhf8Wiem3pTrQdu/tT0c3wWnugnE3OuKowwwH6X@GFUpJhgqin6RG54lu3dH9l@LykrvtVWwNp9NbnR4EjuNiLGmt0022/cf)
This is my first post here so I'm hoping I'm following all the rules. I'm also still learning Racket so I'm sure this isn't optimized and I'm excited to receive any tips, but I wanted to post as far as I've gotten. Below is a rough description of what's going on.
```
#lang racket
;splits a list of 256 into 16 lists of 16
(define(f x)(if(empty? x)x(cons(take x 16)(f(drop x 16)))))
(let*(
;shorten reused functions
[s list->string]
[b build-list]
[m map]
;generate a pair of boolean lists of lists differing by 1 entry
[g((λ(x)(list(m(λ(x y)(xor x y))x(b 256((λ(y)(λ(x)(= y x)))(random 256))))x))(b 256(λ(x)(=(random 2)0))))]
;convert #t and #f into #\@ and #\
[h(λ(x)(m(λ(x)(if x #\@#\ ))x))]
;create list of strings from list of list of chars
[i(list(m s(f(h(car g))))(m s(f(h(cadr g)))))])
;concat strings
(display(string-join(m(λ(x y)(string-append x"|"y))(car i)(cadr i))"\n")))
```
[Answer]
# Windows Batch Scripting (317 bytes)
*-112 bytes, thanks to Neil*
```
@echo off&setlocal EnableDelayedExpansion
set/av=!random!%%256
for /L %%i in (0,1,255)do (set/ar=!random!%%2&if !r!==0 (set c=@)else (set c= )
set b=!b!!c!)
for /L %%i in (0,1,255)do (set c=!b:~%%i,1!&if %%i==!v! if !c!==@ (set c= )else (set c=@)
set m=!m!!c!)
for /L %%i in (0,16,255)do echo !b:~%%i,16!^|!m:~%%i,16!
```
**Notes**
`EnableDelayedExpansion` Delayed Expansion will cause variables within a batch file to be expanded at execution time rather than at parse time.
`random` generates a random number between \$0\$ and \$32767\$.
**Output**
[](https://i.stack.imgur.com/exG72.png)
[Answer]
# [PYTHON](https://www.programiz.com/python-programming/online-compiler/)
```
import numpy as np
np.random.seed(0)
grid1 = np.random.choice(['@', ' '], size=(16, 16))
grid2 = grid1.copy()
i, j = np.random.randint(0, 16, size=2)
grid2[i, j] = '@' if grid2[i, j] == ' ' else ' '
def print_grid(grid):
return '\n'.join(''.join(row) for row in grid)
for row1, row2 in zip(grid1, grid2):
print(''.join(row1), '|', ''.join(row2))
```
This is my code in Python Language.
] |
[Question]
[
So I have the situation where I have one boolean value `a` and, if that one is `true` and `b<c` I want it to end up as `true`, if `a` is false and `b>c` I want it to resolve as `true` as well. If `b=c` I want it to be always false, no matter the value `b` and `c` are both numbers. My best approach so far is `a?b<c:b>c` or maybe `b^c^a^b<c`. Is there any shorter approach? I can’t stop thinking about it, and want confirmation this is the shortest possible way or find the solution...
[Answer]
## Yes, it can be shorter!
`c-b<a^a` beats `a?b<c:b>c` by 2 bytes. My [tests](https://tio.run/##RYtBCsIwEEX3PcVfttRA3Ykm9iCiMBkSqJS2JLEb6dljGozCLD7vvXnSSp7dsASxnmK0s0M9mgDCbHGzNHpzQHAvc2/wrvDzGgri2F3SkAp5tG1O/g2XhkvDpQFNvkuahZb0oC9BItRryWd95Z0tbphCvRul8kuT6Fal22L8AA) show that it works for any integer, including negatives. The downside to this formula is that `a` is repeated twice, which may be unideal depending on your situation.
[Answer]
# I don't think it can be any shorter, at least in the most general case
See [dingledooper's 7-bytes solution](https://codegolf.stackexchange.com/a/249015/78410) that works for integers.
If the target expression were `a?b<c:b>=c` (note the change on the second comparison), the two conditions are exactly the opposite, and we can get away with comparing `b` and `c` only once with `a^b>=c` or `!a^b<c`.
**But,** the target is `a?b<c:b>c`, and since `b<c` and `b>c` cannot be inferred from each other, you either need to
* mention `b` and `c` twice each, to carry out two separate comparisons, or
* somehow use the three states (negative, zero, positive) of `b-c`.
For the first method, you already have the optimal answer. For the second, the best I can get is `(c-b)*(a-.5)>0`, 14 bytes ([TIO](https://tio.run/##XcrBCgIhEIDh@z7F3FbDWbq4h4jtQcTDaBqF7IRal@jZDSJC9vjx/zd6UvH5eq@48jm0FjmDSKGCIQVOgbfAEYyJlEpQoBXMVkFH3XH@seZH9/7Vte9pJbwGAM9r4RSmxBdBJ3f0B7d4uQnCo5M7QThpuey3dUTEUQ7v1j4)).
Also note that [`b^c^a^b<c` doesn't quite work](https://tio.run/##XcqxCsIwFEbhvU/xb20gcWsHEX2QkEByTUQJvdKkLuKzRxGR0PHwnZt7uEzL9V7UzOdQa@QFQwoF2kl4CTLgCK2jSzlIjBKTkWhybHL6ZVnW5v1XY9/TCDw7gHjOnMIu8WVwJ3@gvT@S2IC3ZJ394BZ6pVQvuletbw).
] |
[Question]
[
Here's a programming puzzle for you:
Given a list of pairs of strings and corresponding numbers, for example, `[[A,37],[B,27],[C,21],[D,11],[E,10],[F,9],[G,3],[H,2]]`, output another list which will have just the strings in the following manner:
1. The total count of any string should be exactly equal to its corresponding number in the input data.
2. No string should be repeated adjacently in the sequence, and every string should appear in the output list.
3. The selection of the next string should be done randomly as long as they don't break above two rules. Each solution should have a non-zero probability of being chosen.
4. If no combination is possible, the output should be just `0`.
The input list may be given in any order (sorted or unsorted), and the strings in the list may be of any length.
---
Sample output for the above sample input 1
`[A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,B,A,C,A,C,A,C,A,C,A,C,A,C,A,C,A,C,A,C,A,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,D,C,E,F,E,F,E,F,E,F,E,F,E,F,E,F,E,F,E,F,E,G,H,G,H,G]`
---
Input sample 2:
`[[A,6],[B,1],[C,1]]`
Output for second input:
`0`
since no list possible based on rules.
---
Sample input 3:
`[[AC,3],[BD,2]]`
valid output: `[AC,BD,AC,BD,AC]`
invalid output: `[AC,BD,AC,AC,BD]`
---
If further clarification is needed, please, do not hesitate to tell me in the comments and I will promptly act accordingly.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes for each language wins!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
Œṙ'Œ!⁻ƝẠ$ƇX
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7Z6ofnaT4qHH3sbkPdy1QOdYe8f9wO0h8xv//0dHqjs7qOgrGsToK0epOLkCmUWwsAA "Jelly – Try It Online")
```
Œṙ'Œ!⁻ƝẠ$ƇX Arguments: z
' Flat: Apply link directly to x, ignoring its left and right depth properties
Œṙ Run-length decode
Œ! Permutations of x
Ƈ Filter; keep elements of x for which the link returns a truthy result
$ ≥2-link monadic chain
Ɲ Apply link on overlapping pairs (non-wrapping)
⁻ x != y
Ạ Check if all elements of x have a truthy value (+vacuous truth)
X Pick a random element of x; return 0 if the list is empty.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
Wẋ¥Ɲ€ẎẎŒ!Œɠ’SƊÐḟX
```
[Try it online!](https://tio.run/##y0rNyan8/z/84a7uQ0uPzX3UtObhrj4gOjpJ8eikkwseNcwMPtZ1eMLDHfMj/v//H63kGKKko2Acq6MQreQEZgEA "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~114~~ ~~189~~ ~~185~~ 174 bytes
```
from random import*
a=input()
s=u=[]
while a:x,y=a.pop(a.index(next((w for w in a if w[1]>sum(v[1]for v in a+u)/2),choice(a))));s=s+[x];a+=u;u=[[x,y-1]]*(y>1)
print[s,0][y>1]
```
[Try it online!](https://tio.run/##PY/NbsMgEITP4SlQLuCEprEjtWoiR2r@mlsvPRVxoA6RURtAGMf207tL4pYD86HZnV1cF0prsr6wJ5UTQvqztxfspTmB6IuzPkyQzLVxdaAJqvI65wI1pf5RWC5b1uVy5qyjcqbNSbXUqDZQ2uCz9bjB2mCJ9Rk3PBXrqr7QK0C0rjdrWiePWcKK0upCUZnAWVV5NeWtWMlpXq9gGIcZD6kQE9qt0wQ5r03gFZsLDm/Rw8rDNh@@Vks0Cr6De6RaVdD4qQQBF8oFvH8/7L23PtpfXslv1HNOXglbPAvGyYaw7AZbgDTCjrD0BnuAeYQDYS9R36Ap6hFKhUD3mKchJR1C0sHZDsWb3X/15587tkaNGYYWzMehscDZnUuvorMQov8F "Python 2 – Try It Online")
Ouch! Much harder with rule 3... :). Still trying to avoid the `O(n!)` approach, so it can handle all the test cases sometime before the heat death of the universe...
Algorithm: suppose the total sum of the string counts is `t`. If any string has a count `n` with `2*n>t+1`, then it is not possible to satisfy the constraints. Therefore, if any string (excluding the previously chosen one) has count `n` with `2*n=t+1`, then we must choose that string next. Otherwise, we can choose at random any string which is not the previously chosen string.
[Answer]
# [R](https://www.r-project.org/), ~~148~~ 141 bytes
```
function(x,y,p=combinatXXpermn(rep(seq(y),y)),q=which(sapply(lapply(p,diff),all)))"if"(n<-sum(q|1),"if"(n-1,x[p[[sample(q,1)]]],x[p[[q]]]),0)
```
[Try it online!](https://tio.run/##ZVNNb9swDL37VzA@FBSqBHG2U5EM2HbZodhtWAHDB9eWG2GSrdjOlqDrb89IOnHczBeL75GPH6LaU9H4Z1vn/dNTMK2vYT2Hal8XvW1qwINmAzbw/cfjo4bFYqEgeo2APlsB2m5R771pbYEHBXd34Ez90m/Z2GwgYeQAn2DJh74l1TMjAvyReT1z6s7syEcwKWUUHKCGqyFYEjuHZA5Ms@8Z/22KvmkxdrbrYw0vufc51nAPiRr8gkSHcyrRSh5qoUo2WhNwnmg4y5ZpkjG8FMvzUdSuWgV6DUGDHwKsKMpx3xk25gWyHkWtBpc/W@sMoIcZjUjB6zgA6iFNbSYJebrS7WRAMqQ0pCScZSNqHOUhRxyp4Z5GBynJjlVfGxnNYvuLAQwpTeaeBkG@Gd0bT0i9D/L5ARlOZxSUTZJU3NEabustU4J5/A@19DWfAtfoujSHZLia1GfvahVuxRyVJ37Z1OB6KeSqdUtI1SPb@/MGDF6rSQ0jNNYx5bzAFC7g22Xporcoqpg5XR4NvZmjDpubZ4W8WLzcR6WPSundhtag2GKXh@CO6IZf0KWtKqVz55RSsa1irNfzbu9x9zdRegBoPfmq0y73wRnc6URldOmC7eik9FKdKiww/hzr@EusNC3pB03rp6Jb@ON/sI6/XiJWOrlw34xzjSYSfjatK@lpxTNyK3BFAqJx@gc "R – Try It Online") (I've copied `combinat::permn` and called it `combinatXXpermn` there.)
Brute force O(n!) solution.
Uses `permn` from the `combinat` package to generate all possible orderings. Then checks to see if any follow the rules, and picks one of those at random.
[Answer]
# JavaScript, 112 bytes
First pass at this, more golfing to (hopefully) follow.
```
f=([i,...a],o=[])=>a.sort((x,y)=>(y[1]-x[1])*Math.random()-n*.5,n=--i[1],o.push(i[0]))+a?f(n?[...a,i]:a,o):n?0:o
```
[Try it online](https://tio.run/##RYzbTsMwDIbv9xi5SoYTtUOAqJRVO3C44QmySIu2lmba7KoN0D19SaYibuzP9uf/5L5df@h8GyTSsRrHWnPjQSnlLJA2VuilUz11gfMBrnHiV5NbOcQi5h8uNKpzeKQLFxLn6gFQS@njEUi1X33DvcmsEHeurDmWJuWCt4UDEgWWWUFj0GZmDFsxuH@yYNiaweIGmwh5gi2D/AYvEbIErwyeU3@LT6m/R9VamHIep5h8Ssn/TptJX2//fcJqMsMPpXWipquq5EbFzg6EPZ0rdaZPHtTFtXzQy5oPQqgTedzvcId7Mf4C)
[Answer]
# J, 60 53 bytes
*-7 thanks to FrownyFrog*
```
(?@#{])@(#~*/@(2~:/\])"1)@(]i.@!@#@;A.;) ::0(#~>)/&.>
```
## original
```
(?@#{])@(#~2&([:*/~:/\)"1)@(A.~i.@!@#)@;@:(([#~>@])/&.>) ::0
```
## ungolfed
```
(?@# { ])@(#~ 2&([: */ ~:/\)"1)@(A.~ i.@!@#)@;@:(([ #~ >@])/&.>) ::0
```
Suggestions for improvement welcome.
[Try it online!](https://tio.run/##dY5Na8JAGITv@RXTLLj7Ft1o9LTxY/2gghQPngT1sNWNUWxWsqWXQv56jMVDETow8DADw5yrUPIUAwWOJtpQtVsS09X7WyVGmv3sSAtWxg2xUa9RqaIthZ06GsvyJPWLZqQTrYTYsHKodxQ15JCgVLuiIDADCcHHU570KBF8MuNJXEOfr9d3Cuw@c0jDDkSXNZUhPGs5kcitPcDAn/LjxeKaFcZbfDlcC/ddQ2ZRmPzgPnPrPT72cCkW3GO1nD/2/1zo/37o0n9NTNUN "J – Try It Online")
[Answer]
# JavaScript (ES6), 160 bytes
```
a=>(g=(a,m=[])=>a.map((v,n)=>v==m[0]||g(a.filter(_=>n--),[v,...m]))>[]?0:r=m)(a.reduce((p,[v,n])=>[...p,...Array(n).fill(v)],r=[]).sort(_=>Math.random()-.5))||r
```
[Try it online!](https://tio.run/##dY7BSsQwEEDvfkXpaQbSsCp6cEll1atfEIIMbdrdpUnKNEaE/ntN6lG8vTAvb@ZKiZaOL3NsfOjtNqhqI9XCqICEU9qgakk6mgGS8PmRlHL6YNZ1BJLDZYqW4UO1vmlQ6CSklM4gtto8H55YOcwW2/6zswBzEXwp6qzNxT0x0zd4LKUJEhrBZadcAseSfad4lky@Dw6wkQ@I68pbF/wSJiunMMIAWtenWlSPRuj6JcNtgdcd8iXHm792Gd7v@lumu3@04O1vrdJ1/Aq7ufOZrd0L5d/2Aw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 38 bytes
```
WΦθ§κ¹«≔‽Φ∨Φι›⊗§κ¹ΣEι§μ¹ι¬⁼κυυ§υ⁰⊞υ⊖⊟υ
```
[Try it online!](https://tio.run/##VY09T8MwEIbn5ldYnmzpkJoyINQpNG3pAFQwRhncxGosHLt1bEBC/HbjS5VKHU73@N4PN51wjRU6xu9OaUnYRmkvHTsDKfzOtPKHfQLJOefkN5sVw6COhr0L09p@sr65iRSQrZMCsbThoGXLbkuAfISevYgTWiepv/SjqtK8Ws/W5yD0gKFwEQJfZrO9U8ZfGwOQOR/PYejwVcrGyV4an77d2xPD6DL7i7GqKlpQuH@ooaJPFBYjrBLkCCWFfIR1gjnChsIj7m0K4X5O1rqu492X/gc "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WΦθ§κ¹«
```
Repeat while there is at least one non-zero count.
```
Φι›⊗§κ¹ΣEι§μ¹
```
Find any count that makes up more than half the remainder.
```
∨...ι
```
If there wasn't one, then just take the non-zero counts filtered earlier.
```
Φ...¬⁼κυ
```
Filter out the string that was output last time.
```
≔‽∨...υ
```
Assign a random element from the first non-empty of the above two lists to the last output string. Note that if an impossible combination is entered, the program will crash at this point.
```
§υ⁰
```
Print the string.
```
⊞υ⊖⊟υ
```
Decrement its count.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 85 bytes
The brute force approach (thanks Jonah for the idea).
```
->l{l.flat_map{|a,b|[a]*b}.permutation.select{|p|r=0;p.all?{|a|a!=r&&r=a}}.sample||0}
```
[Try it online!](https://tio.run/##LY/bSsQwEIbv@xQjCxuQGFoFRZYq7q6HB/DKEGTqpriY2jBNFWny7DHp9ur/mP8AQ2PzF9s6XtyZyYjWoHvv0E4eeeMlqvMmCKupGx26Y/8tBm30h5u89VSXGyvQmPsU9nhW03pNNYYgBuys0d6XIUpYwevncYDffjQHcPiloe1J/2gSBcBKSvbA@NWN4pJtGb@cYZegyrBnvJrhMUGZ4Ynx26zPqZT1JUWV4kVxGrpedqplpspetnZLfrtfCun4NvtKzO@SBwutJBVi/Ac "Ruby – Try It Online")
# [Ruby](https://www.ruby-lang.org/), ~~108 100~~ 96 bytes
Previously, the Bogosort approach
```
->l{w=[];l.map{|a,b|w+=[a]*b;b}.max*2>w.size+1?0:(w.shuffle!until(r='';w.all?{|a|a!=r&&r=a});w)}
```
[Try it online!](https://tio.run/##LY/LisIwFIb3fYojgvESi6mgzJQo3n0AV4YsUkywTGaUaCejts@eSWpX/8f5L3BMkT2com440y9LGU91/C2ur1LgrLQDygTvZ2lW@eNfP5nZ@JY/5YDMR59dz@dCKS1bxc89111DEUptLLSe@3opWtR0OoaKqpfaXuUYtOFwzm9gL4U@wV18SVAXI3@liSOANmNogfB4yjFDS4STGlYeSIA1wqSGjYdRgC3CH0F3vhR076Oc4yh6D02aHdLMkOAFa9Xkl@um4I/H2ufvz00JV1DM8Mq5fw "Ruby – Try It Online")
[Answer]
# Rust 633 bytes
What makes this a little different than the others is that it started with the idea to rearrange the strings by simulating a physical system. Each string is first duplicated the appropriate number of times. Then each individual string is treated as a Particle in a space. Two particles with the same string value "repel" each other, while two particles with different values attract each other. For example if we begin with AAAAAAABBBBCC, the As will repeal each other, moving away from each other, allowing the Bs to move inbetween them. Over time this reaches a nice mixture of particles. After each iteration of 'particle movement', the program checks that no same-particles are adjacent, then stops and prints the state of the system, which is simply the list of strings in order, as they appear in the 1 dimensional space.
Now, when it comes to actually implementing that physical system, it started out as using the old fashiond PC demo/game technique, to store each particles position and velocity as numbers, then go through iterations to update position and velocity. At each iteration, we are adding velocity to position (movement), and adding acceleration to velocity (change in rate of movement), and calculating acceleration (finding the force on the particle). To simplify, the system doesn't calculate force on each particle based on all other particles - it only checks the particles immediately adjacent. There was also a 'damping' effect so that particles wouldn't accelerate too much and fly off to infinity (velocity is reduced by x percentage each step, for example).
Through the process of golfing, however, this whole thing was cut down and simplified drastically. Now, instead of two alike particles repelling each other, they simply 'teleport'. Different particles simply 'scoot' a wee bit to prevent stagnation in the system. For example if A is next to A it will teleport. If A is next to B it will only slightly shift. Then it checks if the conditions are met (no like particles adjacent) and prints the strings in order, based on their position in 1-d space. It is almost more like a sorting algorithm than a simulation - then again, one could see sorting algorithms as a form of simulated 'drifting' based on 'mass'. I digress.
Anyways, this is one of my first Rust programs so I gave up after several hours of golfing, although there might be opportunities there still. The parsing bit is difficult for me. It reads the input string from standard input. If desired, that could be replaced with "let mut s = "[[A,3],[B,2]]". But right now I do 'echo [[A,3],[B,2]] | cargo run' on the command line.
The calculation of stopping is a bit of a problem. How to detect if a valid state of the system will never be reached? The first plan was to detect if the 'current' state ever repeated an old state, for example if ACCC changes to CACC but then back to ACCC we know the program will never terminate, since it's only pseudo-random. It should then give up and print 0 if that happened. However this seemed like a huge amount of Rust code, so instead I just decided that if it goes through a high number of iterations, its probably stuck and will never reach a steady state, so it prints 0 and stops. How many? The number of particles squared.
Code:
```
extern crate regex;
struct P {s:String,x:i32,v:i32}
fn main() {
let (mut i,mut j,mut p,mut s)=(0,0,Vec::new(),String::new());
std::io::stdin().read_line(&mut s);
for c in regex::Regex::new(r"([A-Z]+),(\d+)").unwrap().captures_iter(&s) {
for _j in 0..c[2].parse().unwrap() {p.push(P{s:c[1].to_string(),x:i,v:0});i+=1;}
}
let l=p.len(); while i>1 {
j+=1;i=1;p.sort_by_key(|k| k.x);
for m in 0..l {
let n=(m+1)%l;
if p[m].s==p[n].s {p[m].v=p[m].x;if n!=0 {i=2}} else {p[m].v=1}
p[m].x=(p[m].x+p[m].v)%l as i32;
}
if j>l*l{p.truncate(1);p[0].s="0".to_string();i=1}
}
for k in &p{print!("{}",k.s)};println!();
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 249 bytes
```
l=>(a=[],g=(r,s)=>s.length?s.forEach((x,i)=>g([...r,x],s.filter((y,j)=>j-i))):a.push(r),g([],l.reduce(((a,x)=>[...a, ...(x[0]+' ').repeat(x[1]).split(' ')]),[]).filter(x=>x)),p=a.filter(a=>a.every((x,i)=>x!=a[i+1])),p[~~(Math.random()*p.length)]||0)
```
[Try it online!](https://tio.run/##dY/LbsIwEEX3/Qo3G2bKYEGRWLRyqr6W/QLLi1FikiA3ieyAjIT49dShsGs3M6N7z7x2fOBQ@KYfFm1X2nErlBidyoGVNlQp8BRQ5UE621ZD/RLktvOfXNQAkZrkVKCllJ6ioeQ1brAe4Ei7ZO0WDSI@sez3oQaPlFhDTnpb7gsLAEwxYVM/k0gRol6a@UzMMDG95SEJK4My9K4ZYNINkk7CdU9UeUSkXvFNYZWztAfrj7f74r1i3czTmATq8xm@eKil57bsvgEf@utjaE6nJY5F14bOWem6CrYgtM5eMxJrQ0Jnb5fKCMTnuz@5jaELtZry@5T/hZO7vtAfGT3@YuMP "JavaScript (Node.js) – Try It Online")
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 191 bytes
```
S->N->{var l=new java.util.Stack();int i=0,j;for(var s:S)for(j=N[i++];j-->0;)l.add(s);for(;i>0;){i=0;java.util.Collections.shuffle(l);for(var s:S)if(s.join("",l).contains(s+s))i++;}return l;}
```
[Try it online!](https://tio.run/##ZVCxTsMwEN37FVYmmyZWBRsmkaCICbpkrDqYJC52XTvyXYqqKN8enIhCEZN97717d@@MPMnM1IdRH1sfkJhY8w615apzFWrv@I1Y/CMjVlkJQN6kdqRfENJ271ZXBFBifE5e1@QYOVpi0G6/3REZ9sBmKSEv394PFzb9QbTDWL5qwKIgKh/LrNhkRX@SgdjcNZ9XS5QoqwNlIrYQna9SI5QPdFLCfcmmv8k3W71c7oTJsmIlmOWyrimwWSj0BPWxU/x6rr21zbwJcPjolLINteyPsVYUuPExW5KklvHKO4xJgcISGIvjxBAa7IIjVgyjmAOXZ8DmyH2HvI2J0TqquGxbe6ZTpssZ@uRxnaTJ03MysCt6vkl/l94OjE1@w2IYvwA "Java (JDK 10) – Try It Online")
This never returns if there are no solutions.
] |
[Question]
[
quintopia has posted [here](https://codegolf.stackexchange.com/questions/69424/compute-the-multinomial-coefficient) a challenge to compute multinomial coefficients (some of the text here is copied from there). There is a fun algorithm to compute multinomial coefficients mod 2.
Given a list of numbers, *k1*, *k2*, ... ,*km*, output the residue of the multinomial coefficient:
[](https://i.stack.imgur.com/pFoYU.png)
reduced mod 2. The following algorithm does this efficiently: for each *ki*, compute the binary expansion of *ki*, that is, find *aij* such that each *aij* is either 1 or 0 and
[](https://i.stack.imgur.com/SozeW.png)
If there is any j such that *arj = asj = 1* for r ≠ s, then the associated mod 2 multinomial coefficient is 0, otherwise the mod 2 multinomial coefficient is 1.
## Task
Write a program or function which takes *m* numbers, *k1*, *k2*, ... ,*km*, and outputs or returns the corresponding multinomial coefficient. Your program may optionally take *m* as an additional argument if need be.
* These numbers may be input in any format one likes, for instance grouped into lists or encoded in unary, or anything else, as long as the actual computation of the multinomial coefficient is performed by your code, and not the encoding process.
* Output can be any truthy value if the multinomial coefficient is odd and any falsey value if the multinomial coefficient is even.
* Built-ins designed to compute the multinomial coefficient are not allowed.
* Standard loopholes apply.
## Scoring
This is code golf: Shortest solution in bytes wins.
## Examples:
To find the multinomial coefficient of 7, 16, and 1000, we binary expand each of them:
[](https://i.stack.imgur.com/qsehv.png)
Since no column has more than one 1, the multinomial coefficient is odd, and hence we should output something truthy.
To find the multinomial coefficient of 7, 16, and 76, we binary expand each of them:
[](https://i.stack.imgur.com/mqKO9.png)
Since both 76 and 7 have a 4 in their binary expansion, the multinomial coefficient is even and so we output a falsey value.
## Test cases:
```
Input: [2, 0, 1]
Output: Truthy
Input: [5,4,3,2,1]
Output: Falsey
Input: [1,2,4,8,16]
Output: Truthy
Input: [7,16,76]
Output: Falsey
Input: [7,16,1000]
Output: Truthy
Input: [545, 1044, 266, 2240]
Output: Truthy
Input: [1282, 2068, 137, 584]
Output: Falsey
Input: [274728976, 546308480, 67272744, 135004166, 16790592, 33636865]
Output: Truthy
Input: [134285315, 33849872, 553780288, 544928, 4202764, 345243648]
Output: Falsey
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
S=|/
```
[Try it online!](https://tio.run/##RY25bQNBDEVzV7EFEBCPz2MCV6FwsaESQQ0YcOTEzbgLd6JGRpxNBAI8Pj8f77fH42vO6@f3Zf7/Pn/@5tx3pY1pk4M@dieQkdI5SDegIok1ZVfKdyvMfJ7A@5gB2jSik@LURavBylG9tqTNC0vXRGqNbKsjjAvV3yO1Y0HEnBmyUBI52EdjzMKiwk@wQctNfMmFUdkGd8tirVpUDO0KZc1oosEVFqjjeAE "Jelly – Try It Online")
Test whether the sum is equal to the bitwise-or-sum (i.e. `a+b+c == a|b|c`).
[Answer]
# Python ~~3~~ 2, ~~55~~ ~~43~~ 42 bytes
```
lambda l:sum(l)==eval(`l`.replace(*',|'))
```
-12 bytes from [Mr. Xcoder](https://codegolf.stackexchange.com/questions/153454/mod-2-multinomial-coefficients/153458#comment374860_153458)
-1 byte from [Rod](https://codegolf.stackexchange.com/questions/153454/mod-2-multinomial-coefficients/153458?noredirect=1#comment374918_153458)
[Try it online!](https://tio.run/##TZDBasNADETP8VfsLXYRRStptXKgX5Ia4rZuYnAck6aFQv/dleMeyoJ2RjP7Djt9306Xkebj0/M8tOeXtzYMu4/PczlU/Ri6r3YoD8Ph8dpNQ/valQ9b@NlW1fx@uYY@eGNfbPYECLEBVwkEGOjPRVcCBlHvNruA/E9HRFyfSYIQUQQCqfogWYNIRm5RzXPOEJLJPaAsmazOXk6ijCaGEDSTnwUTOSFKXGBRc42pdg6zspqmFc1CljimZW9SW/ZGSpwNyWzBSk1@CyFldSRLImEVa4pmV2ymaz/eymPZ@2/8Ag "Python 2 – Try It Online")
Explanation: Checks if the sum of the numbers is equal to the bitwise-or of the numbers.
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes
```
lambda l:sum(l)==reduce(int.__or__,l)
```
[Try it online!](https://tio.run/##DYlLCsMgFACv8pYKUvw8n1rwJG2RtElowSSS6qKntzKrmSm/@j523dd473nanvME@fptG8s8xnOZ22thn71eUjrOlETmvZzDYR21tMo47zft0GkfHAmwSEZ69FIAOT1AFKCMlRIVja/IBWmDFmAMGfJkH38 "Python 2 – Try It Online")
Another port of pizzapants184's algorithm...
[Answer]
# [Clean](https://clean.cs.ru.nl), 38 bytes
```
import StdEnv
?l=sum l==foldr(bitor)0l
```
[Try it online!](https://tio.run/##Dcq9CsIwFEDh3afIqFChvblpb4fQRQfBraM4xP4RuEmkTQVf3pjpnOEbeDI@uTDuPAlnrE/WvcMaRR/Hq/8cOtbb7gRrPQce1@PLxrCeSk59NFlp0T0qiUBKVqoQUhK21EAhlJINlUCUF7GFXIQSmhqzQgUoa6Rn@g0zm2VL59s9Xb7eODtsfw "Clean – Try It Online")
Yet another port.
[Answer]
# Japt, 6 bytes
Another port of pizzapants184's & Leaky Nun's solutions.
```
x ¶Ur|
```
[Test it](https://ethproductions.github.io/japt/?v=1.4.5&code=eCC2VXJ8&input=WzcsMTYsNzZd)
[Answer]
# JavaScript (ES6), ~~37~~ ~~35~~ 34 bytes
*Saved 2 bytes thanks to @Mr.Xcoder*
*Saved 1 byte thanks to @ETHproductions*
Comparing the sum with the bitwise OR (like [pizzapants184](https://codegolf.stackexchange.com/a/153458/58563) and [Leaky Nun](https://codegolf.stackexchange.com/a/153459/58563) did) is ~~1~~ ~~3~~ 4 bytes shorter than my initial approach:
```
a=>(q=c=>eval(a.join(c)))`|`==q`+`
```
### Test cases
```
let f =
a=>(q=c=>eval(a.join(c)))`|`==q`+`
console.log(f([2, 0, 1])) // Truthy
console.log(f([5,4,3,2,1])) // Falsey
console.log(f([1,2,4,8,16])) // Truthy
console.log(f([7,16,76])) // Falsey
console.log(f([7,16,1000])) // Truthy
console.log(f([545, 1044, 266, 2240])) // Truthy
console.log(f([1282, 2068, 137, 584])) // Falsey
console.log(f([274728976, 546308480, 67272744, 135004166, 16790592, 33636865])) // Truthy
console.log(f([134285315, 33849872, 553780288, 544928, 4202764, 345243648])) // Falsey
```
---
# Alt. version, 38 bytes
```
a=>!a.some((x,i)=>a.some(y=>i--&&x&y))
```
### Test cases
```
let f =
a=>!a.some((x,i)=>a.some(y=>i--&&x&y))
console.log(f([2, 0, 1])) // Truthy
console.log(f([5,4,3,2,1])) // Falsey
console.log(f([1,2,4,8,16])) // Truthy
console.log(f([7,16,76])) // Falsey
console.log(f([7,16,1000])) // Truthy
console.log(f([545, 1044, 266, 2240])) // Truthy
console.log(f([1282, 2068, 137, 584])) // Falsey
console.log(f([274728976, 546308480, 67272744, 135004166, 16790592, 33636865])) // Truthy
console.log(f([134285315, 33849872, 553780288, 544928, 4202764, 345243648])) // Falsey
```
[Answer]
# [Haskell](https://www.haskell.org/), 38 bytes
`(==).sum<*>foldl1 xor` is an anonymous function returning a `Bool`. Use as `((==).sum<*>foldl1 xor) [2,0,1]`.
```
import Data.Bits
(==).sum<*>foldl1 xor
```
[Try it online!](https://tio.run/##XZDRSsMwFIbv9xRh7KJ1x5GcnCSnw@5iiCDold7N4gp2bpiuo83Qt69ZRQZNLkK@P/n@kH3ZfVXe9/2hPjVtEPdlKBfrQ@gmuzzJ83TRneu7m9Wu8R9eiZ@m7evycMyTbV2ent@3oepCl87EW@KhTSdC3K7E6RxeQvt0FLO4j6PbN9/Ci/lcTEUyvawDaQeSLsUVJTvh08ngXC43yebxGKrPqi1g3TQ@Lf6S/GKNIYIEVcBre65SGJqSjQECDXjhD6XvroGKkIBB2dENFxE4Oz4/YCWlHBeQiZgI0FpApHGukBFQ2tikHRimsRgdOeTMWTBktWRiCdZhnFGqtJGSVFQr6zJpMgStrbZszbhHE7LRysQDTBk7BGO0Y4nM0UwZMhBKdDZ@CBkkbYn/31JM@l8 "Haskell – Try It Online")
* Pretty much the same trick by pizzapants184 and Leaky Nun that everyone uses, except that with Haskell operator names it saves one byte to use (bitwise) `xor` instead of `(.|.)` (bitwise or).
* `(==).sum<*>foldl1 xor` is a point-free version of `\l->sum l==foldl1 xor l`.
[Answer]
# Java 8, 53 bytes
```
a->{int i=0,j=0;for(int x:a){i+=x;j|=x;}return i==j;}
```
Port of [*@LeakyNun*'s Jelly answer](https://codegolf.stackexchange.com/a/153459/52210).
**Explanation:**
[Try it here.](https://tio.run/##lZHLbsIwEEX3fIWXQR2QPR4/0ij9g7JhWXVhQqiSgoOSQKlovp0Ojw8g8kOyfc@dO3IdjmHW7MtYr78vxTZ0nXgPVTxPhKhiX7abUJRicT0KsWqabRmiKBJ@@vgM04yvB148uz70VSEWIopcXMLs7cwaUeUS6lxmm6a9MuL0Gqbn6iU/ZfUfb0Nb9oc2siyvs@GS3a32h9WWrR6Ox6Zaix1HSpZ9W8Wva917nOVv15e7eXPo53t@6bcxifMiieWPuOU7I0hQw/QW8wm5AQINOAZRLCfwoOzzjGM1uLGAklKOaIUME0SA1gIijUAVegSUlpvSDoyn51F05NCnzoIhq6UnL8E65MFJlDZSkuI8yrpUmhRBa6utt2ZEOE3ojVaGWU@pdwjGaOcles9FKUUPhBKd5a8kg6Qt@Yf9MBku/w)
```
a->{ // Method with integer-array parameter and boolean return-type
int i=0,j=0; // Two integers, both starting at 0
for(int x:a){ // Loop over the array
i+=x; // Add them to the first integer
j|=x;} // And bitwise-OR it with the second integer
return i==j;} // Return if both integers are the same after the loop
```
[Answer]
# [Pyth](https://pyth.readthedocs.io), 6 bytes
```
qsQ.|F
```
[Test Suite.](https://pyth.herokuapp.com/?code=qsQ.%7CF&test_suite=1&test_suite_input=%5B2%2C+0%2C+1%5D%0A%5B5%2C4%2C3%2C2%2C1%5D%0A%5B1%2C2%2C4%2C8%2C16%5D%0A%5B7%2C16%2C76%5D%0A%5B7%2C16%2C1000%5D%0A%5B545%2C+1044%2C+266%2C+2240%5D%0A%5B1282%2C+2068%2C+137%2C+584%5D%0A%5B274728976%2C+546308480%2C+67272744%2C+135004166%2C+16790592%2C+33636865%5D%0A%5B134285315%2C+33849872%2C+553780288%2C+544928%2C+4202764%2C+345243648%5D&debug=0)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
§=ΣFv
```
[Try it online!](https://tio.run/##PY69TUVRDIMXcpE4v6egZYmr2yMhqqdHD6tQsAcDMASLHHIpUAo7VvwpT/fb8375eX/bX58P3x@Pr3vv4yAEeuIIOAz88zrqaGjOUiOof6cicp17jHUHM0H6lSmboOQUrRDtk7G82KsS4WnS3oIszkxXLURch6BZS2IRZmnZGRfOnB2mMWH76iIirFrYPTRfbDiFlfO5B93S@zx/AQ "Husk – Try It Online")
[Answer]
# [Perl 6](https://perl6.org), 15 bytes
```
{.sum==[+|] $_}
```
[Test it](https://tio.run/##jZHBasJAEIbveYo5lKK4yu7s7OyEYPHUJ/AmUkRTEKIGYwpifXY72yyl9FQCSWb/f//5dratzw0/@q6GD55tq@JwheftaVfD/HGbdf1hPl9NPtfw9HZ/qLRYnnuVYFQArNCANeDWJhXOoCEjxvFQR/0zzlo7lIGCWi2RAWTWF1JWMFJEKaMuBmJvhURTOaI@ye58sJZc2uQ4ljaU2td79iwcNGJcFQl68bppuh@0oCxeidwvmJjJHIomoGVJ4VHbCmXFE0rwLqQGQqVENYbgo1gUSXxUon4JLUZWNk8ByTNJ5khjXNbdpSraZnPM05pktqp4P53z2vQFFvtj21/gpo333XRX121zhTT50aCMDSSrycZZqxdVFfchZDjs/1K@vX9jHl8 "Perl 6 – Try It Online")
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
.sum # the sum of 「$_」 (implicit method call)
==
[+|] # reduce using &infix:«+|» (numeric binary or)
$_ # the input
}
```
[Answer]
# [Red](http://www.red-lang.org), 78 bytes
```
f: func[x][b: :to-binary t: 0 s: b 0 foreach n x[t: t + n s: s or b n]s = b t]
```
## How it works:
Ungolfed:
```
Red []
f: func [x][ - a function taking a block as an argument
b: :to-binary - an alias for the to-binary function
t: 0 - set the sum of the numbers to 0
s: b 0 - set the "or" total to binary 0
foreach n x[ - for each number in the block
t: t + n - add it to the sum
s: s or b n - bitwise or of its binary representation with the total
]
s = b t - are the sum (binary) and the "or" total equal?
]
```
[Try it online!](https://tio.run/##ZY9BasQwDEX3PcXfl4IsS7ISmEt0G7yYzCR0NklJXJiePtWqpBQv5P@@9cDbdD/epzuGesw95q/lNjzrMPbo2/o2Ppbr9o3Wg7D3GGPM6zZdbx9Y8ByCN7zGNbod6xYPlrrjErPV43N7LA0zBo61VF9@s0KQwX9YiixwJDvBEhHlH0lEdNaJBhIBm4FZzl1iZzBZiHOBupw6LlLYu2JQsUwuTrDCccKVshJJCmOy0pF2jJwtm5ue9VnYNSeN0qXzwlDNxYndwyodO4SJi8WPRVmyidfjBw "Red – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 15 bytes
```
Tr@#==BitOr@@#&
```
[Try it online!](https://tio.run/##VY@/asNADMb3PIWIIdOV6vTv5MHF9AXaoVvIYEpDPKSD8Wb87K6uMYVyg@77PumHdB/m29d9mMfPYbtCB9vH1Ddd9zrOb1PfN6ftfRq/53OT4AhPL3BMcD03lwuc4Lk/wLJQAkyQ13QAWDSBJOAE9GflXxGuh2UPr9RvgvJfZkTcMaJVSkyRRUIke5LJg0ZolcYxqC6PhIoU8rZEu4oxunjsZYXiVVBmRZRccdlKi9oGiNnY3HSHs5ArZ62BS@slWlS5OJJ75UpLUYWQitVDRUnYxNd1@wE "Wolfram Language (Mathematica) – Try It Online")
[Answer]
## Batch, 73 bytes
```
@set/as=o=0
@for %%i in (%*)do @set/as+=%%i,o^|=%%i
@if %s%==%o% echo 1
```
Outputs `1` for truthy, nothing for falsy. Another obvious port of pizzapants184/Leaky Nun's algorithm.
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
+/=+./&.#:
```
Yet another port of pizzapants184's & Leaky Nun's solutions.
## How it works?
`+/.&.#:` - convert the numbers to binary, apply bitwise or to the powers of two and convert back from binary to decimal
`+/` - reduce the input by addition
`=` - are the above equal?
[Try it online!](https://tio.run/##VY/NSgNRDIX38xQHCxapTvOf3IGuBFeufAWxFDe@/2rMphdKCOScJB/J7/60Hq@4bDjiFYSt823F@9fnx346X07r@Xk9bPvLsiw/37c/XCE9wXfhMGhb0@AWhgLH3cmukY@SiWgizFubQSIgYrPBUgKhaJgmvGxekJZSI6N3Q6msCJHS0RRWJzJuFkcO8iFQDY0Kn2A1KVf27pSNSoG7ZpFUNdKGFExIMvo5czENq2X/Bw "J – Try It Online")
## Straightforward alternative
# [J](http://jsoftware.com/), 12 bytes
```
2>[:>./+/@#:
```
## How it works?
`+/@#:` - convert each number to binary and find the sum of each power of 2
`>./` - find the maximum
`2>` - is it less than 2? -> truthy
[Try it online!](https://tio.run/##VY@9SgRRDIX7eYqDFouos/lP7oCLIFhZ2VqKi9js@1ezafaChEDOSfKR/O136@GMlw0HPIGwdT6vePv8eN/l9LWd1uPj8fV@2x@WZfn5/r3gDOkZvgmHQduaBrcwFDhuTnaN/C@ZiCbCvLUZJAIiNhssJRCKhmnCy@YFaSk1Mno3lMqKECkdTWF1IuNmceQgHwLV0KjwCVaTcmXvTtmoFLhrFklVI21IwYQko58zF9OwWvYr "J – Try It Online")
[Answer]
# [Triangularity](https://github.com/Mr-Xcoder/Triangularity), 31 bytes
```
...)...
..IEu..
.)IE...
"|"JE=.
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/X09PTxOIufT0PF1LQbSmpyuIr1Sj5OVqq/f/f7S5jqGZjqGBgUEsAA "Triangularity – Try It Online")
# Alternate solution, 31 bytes
```
...)...
..IED..
.us"|".
JE=....
```
[Try it online!](https://tio.run/##KynKTMxLL81JLMosqfz/X09PTxOIufT0PF1dQHRpsVKNkh6Xl6stUFjv//9ocx1DMx1DAwODWAA "Triangularity – Try It Online")
] |
[Question]
[
## Briefing
Given a Fully Qualified Java Class/ Package name, you must shorten it as such:
Each part of the dot separated package will be shortened to its first letter, apart from the last section and the class (if it exists).
package names will be all lower case, and the class (if it exists) will start with a capital letter and be UpperCamelCase. packages come in the form of:
```
foo.bar.foo
```
and
```
foo.bar.foo.Class
```
## Examples
```
(No Class)
Input com.stackoverflow.main
Output c.s.main
(Class)
Input com.google.parser.Gson
Output c.g.parser.Gson
(Class)
Input com.google.longer.package.TestClass
Output c.g.l.package.TestClass
```
## Rules
* Shortest code in bytes wins
* Standard loopholes apply
[Answer]
## [Retina](https://github.com/m-ender/retina), 17 bytes
```
\B\w+(\.[a-z])
$1
```
[Try it online!](https://tio.run/nexus/retina#@x/jFFOurRGjF52oWxWryaVi@P9/cn6uXnFJYnJ2fllqUVpOfrlebmJmHhdIOD0/Pz0nVa8gsag4tUjPvTgfRTgnPy8dKFwA1JqYnqoXklpc4pyTWFwMAA "Retina – TIO Nexus")
### Explanation
```
\B # Start from a position that isn't a word boundary. This ensures that
# the first letter of the package name is skipped.
\w+ # Match one or more word characters. This is the remainder of the
# package name which we want to remove.
( # Capture the next part in group 1, because we want to keep it...
\.[a-z] # Match a period and a lower-case letter. This ensures that we
# don't match the package that precedes the class, or the package or
# class at the end of the input.
)
```
This is replaced with `$1`, which is the period and lower case letter which shouldn't be removed.
[Answer]
# JavaScript (ES6), ~~68~~ 53 bytes
```
s=>s.split`.`.map((x,y,z)=>z[y+1]>"["?x[0]:x).join`.`
```
* 15 bytes saved thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld).
See my other solution [here](https://codegolf.stackexchange.com/a/119140/58974).
---
## Try it
```
f=
s=>s.split`.`.map((x,y,z)=>z[y+1]>"["?x[0]:x).join`.`
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("com.stackoverflow.main"))
console.log(f("c.g.parser.Gson"))
console.log(f("com.google.longer.package.TestClass"))
```
```
<input id=i><pre id=o>
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~88~~ 81 bytes
```
f=lambda s,d=".":s.count(d)>(s.split(d)[-1]<"[")and s[0]+d+f(s[s.find(d)+1:])or s
```
[Try it online!](https://tio.run/nexus/python2#jY6xbsMwDETn9isIThbsEM1qNFk69Ae6CR5YSzKEyqIhqskQ5NtdpWOnLocD3uHu9nBKvH46Bh3cCQlHpVm@c@2cOXdKuqX48PZwnF7RouHsQO3L1Ls@dGqVQsyuBfrjOBkpoHt4KMQMFmdZSSvPX3LxJSS50sox4wC/ZBFZkqeNi/pC7yp/SZK8NLK1Al48fXitb4lVcRqfn7YScwW83eFwhtsdqe2uXDsdoB0zBvZ/Vf0A "Python 2 – TIO Nexus")
[Answer]
# Java 8, ~~66~~ 41 bytes
```
s->s.replaceAll("\\B\\w+(\\.[a-z])","$1")
```
Port from [*@MartinEnder*'s amazing Retina answer](https://codegolf.stackexchange.com/a/119133/52210).
[Try it online.](https://tio.run/##jZAxT8MwEIX3/IqTxRATcgKJqRVIwMBEF9iaDofrBreOHdnXVlD1twcHEtShA4vl873n992taUflernpTNP6wLBONW7ZWLycZspSjPBCxh0yAONYhxUpDbO@BHjlYFwNKh8uUU7T@zFLR2Rio2AGDu66WN5HDLq1yftgbS6q6rGq9kVeVTin8mshxZW4uBGym/bedvtuk3f4YufNEpqEMKTMF0DyN3/lwxjNOvITRQ0TcHoPo/QglG@w9r62Gq13tQ7YktpQrfGtt/QDpvATVUshJtVz9G5oJBC18bs0u/V77FHEUf4ApBV8RtYN@i1jmyLZunxEKcREFAJEP7kmzm@vy7GFVruaP3IpC4fqzyGH/R27f1Bn55mz88Tf)
[Answer]
# Mathematica, 75 bytes
```
#[[;;-3]]~StringTake~1~Join~#[[-2;;]]~StringRiffle~"."&[#~StringSplit~"."]&
```
Anonymous function. Takes a string as input and returns a string as output.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~30 27~~ 25 bytes
```
¡Y>Zl -('[>ZgJ)-2?X:Xg}'.
```
[Try it online!](https://tio.run/nexus/japt#@39oYaRdVI6CroZ6tF1UupemrpF9hFVEeq263v//Smn5@XpJiUV6yYlFSgA "Japt – TIO Nexus")
[Answer]
# [Python 2](https://docs.python.org/2/), ~~76~~ 73 bytes
```
q=input().split('.')
i=~(q[-1]<'_')
q[:i]=zip(*q[:i])[0]
print'.'.join(q)
```
[Try it online!](https://tio.run/nexus/python2#HcqxCsIwEIDhvS9yF8HDrmImX8EtBAklhNOYuzTp0sFXj8Xt/@Af1XLRraOhppk7AoGZ2H6xuvPsb/A8WN2Vvd1Z8fRP4y5@0pVLP256CResZgxY5ENJJOVIWUqKK2lY3iFFesTW7zm0Bj8 "Python 2 – TIO Nexus") or [Try all test cases](https://tio.run/nexus/python2#XY2/DsIgGMR3noINapTo2tjJwRdwq8SQCuRTyse/auLgq1fa0eSGu/xyd/NdG2o4NC2hsQORg4PCmWANodB9eex3B3lktyXHvgXZfSDwzWqbfi8JTbpMydeGeCB4HhsyG0wUKPiqMBW@bIcEvlDYsqtn2@Vv7tmAo8hFDU986WQcvsWooOIVWETrtAgqZZ3EOeMfcOhtBaHWldXionM5OZUzkz8 "Python 2 – TIO Nexus")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 9 bytes
```
Í쓃…®õÀ!
```
[Try it online!](https://tio.run/nexus/v#@3@49/CaQ5MPNR9qPbTu8NbDDYr//yfn5@oVlyQmZ@eXpRal5eSX6@UmZuZxgYTT8/PTc1L1ChKLilOL9NyL81GEc/Lz0oHCBUCtiempeiGpxSXOOYnFxQA "V – TIO Nexus")
Hexdump:
```
00000000: cdec 9383 85ae f5c0 21 ........!
```
This is a wonderful example of V's signature *regex compression*.
Explanation:
```
Í " Remove every match on every line:
ì " A lower case letter
“ … " *ONLY MATCH THIS PART:*
ƒ " As few characters as possible
® " Followed by a dot
õÀ! " Not followed by an uppercase letter
```
[Answer]
# [Haskell](https://www.haskell.org/), 58 bytes
```
f s|[(a:t,p:x:r)]<-lex s=a:concat[t|x<'a']++p:f(x:r)|1<3=s
```
[Try it online!](https://tio.run/nexus/haskell#XcyxDoIwEIDhV7mwAEGbGLcGJgcXnXQjDJembYyl1/ROZeDdERydvz//4oDnvkItu6Qnneuh3Qc7AXeoDUWD0ss8tSWWQ9Mk7aqtmQ/tseNlxEeEDkZMV6jSS26SLxEUuBr6wtCoWNA86W2zC/RRW17s4CeeyAerEma2WZ2Z/iVQ9KukdYDeqrtlOQVkLoblCw "Haskell – TIO Nexus") Usage: `f "some.string"`.
`lex` parses a string as Haskell tokens, so `lex "some.string"` returns `[("some",".string")]`. `f` recurses over the tokens in the string and always appends the first char `a` of the current token, but the rest `t` of the token only if the remaining string after the colon `p` starts with an uppercase char, that is `x<'a'`. If the pattern match failed, we have reached the last token and simply return `s`.
[Answer]
# JavaScript (ES6), 36 bytes
Another port of [Martin's Retina answer](https://codegolf.stackexchange.com/a/119133/58974). See my other solution [here](https://codegolf.stackexchange.com/a/119127/58974).
```
s=>s.replace(/\B\w+(\.[a-z])/g,"$1")
```
```
f=
s=>s.replace(/\B\w+(\.[a-z])/g,"$1")
i.addEventListener("input",_=>o.innerText=f(i.value))
console.log(f("com.stackoverflow.main"))
console.log(f("c.g.parser.Gson"))
console.log(f("com.google.longer.package.TestClass"))
```
```
<input id=i><pre id=o>
```
[Answer]
# [sed](https://www.gnu.org/software/sed/), 57 22 bytes
I expected sed solution to be a little shorter than this...
**Edit:**
The shorter solution uses regex from [Martin Ender's answer](https://codegolf.stackexchange.com/a/119133/67590).
21 bytes sourcecode + 1 byte for `-r` flag (or `-E` flag for BSD sed).
```
s|\B\w+(\.[a-z])|\1|g
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~108~~ ~~97~~ 89 bytes
```
i=input().split(".")
for x in range(len(i)+~(i[-1][0]<"[")):i[x]=i[x][0]
print".".join(i)
```
[Try it online!](https://tio.run/nexus/python2#FYwxDsMgEAR7vwJdBYpyctoorvKFdIgCWRhdQu4QYMlVvk5ws8VoZjstxHlv2mDNiZoGBDNtUtShiFXxHINOgTWZy0@Tvd6cnd0DLBhzJ3u45ZyBplyI26jxLXTqvcMqX4wiMQVMMo4KZr9@fAz4CrU9k68V/g "Python 2 – TIO Nexus")
-8 with many thanks to @ovs for the tip
[Answer]
# [Go](https://go.dev), 101 bytes
```
import."regexp"
func f(B string)string{return MustCompile(`\B\w+(\.[a-z])`).ReplaceAllString(B,`$1`)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY-9SgQxFIVr8xQhWCQ4G7ATYQXHwkoQtdtZnBBuwmAmCUnGFYd5EptBsLb2UXwbMz82W12459zznfvxqd3444V8ERpwKxqLmta7kDhRbSJfXVKbi1_43wXQ8OYJUp2VWNESxxQaq9ky-gCpCxbfdTHduNY3BmhdldXhjFZ8Jzbve1Yz_gDeCAnXxjzOV7Qs6tPzmg0r7HsOn6pQhnskRYSIL7d4t18pRLqWx5Q7u1cIyrgDn9ykwLOindMGuBchQuC30R0rxlmdlfVp_gS5rRExkgEpF_BzISdcENmFF3qPTu4zOhlLZc7aXuVERSVjaEBr7XFc5h8)
Port of [Martin's Retina answer](https://codegolf.stackexchange.com/questions/119126/shorten-the-java-package/119133#119133).
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~22~~ 19 bytes
```
aR`\B\w+(\.[a-z])`B
```
-3 thanks to [DLosc](https://codegolf.stackexchange.com/users/16766/dlosc)!
Yet another port of [Martin's Regex](https://codegolf.stackexchange.com/a/119133/58974).
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhUmBcXEJcXHcrKFxcLlthLXpdKWBCIiwiIiwiIiwiXCJjb20uZ29vZ2xlLnBhcnNlci5Hc29uXCIiXQ==)
---
## First Attempt(Non-Competing)
# [Pip](https://github.com/dloscutoff/pip), 45 bytes
```
d:"."c:dNae:XU Na?c-1ca:a^dFi,e{a@i:a@i@0}aJd
```
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJkOlwiLlwiYzpkTmFlOlhVIE5hP2MtMWNhOmFeZEZpLGV7YUBpOmFAaUAwfWFKZCIsIiIsIiIsIlwiY29tLmdvb2dsZS5wYXJzZXIuR3NvblwiIl0=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~20~~ 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ΔA3ãvy'.«ÀDõ1ǝ:
```
[Try it online](https://tio.run/##AToAxf9vc2FiaWX//86URMOhbMOqM8OjdnknLsKrw4BEw7Uxx506//9jb20uZ29vZ2xlLnBhcnNlci5Hc29u) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3l/3NTXA4vzDm8yvjw4rJKdb1Dqw83uBzeanh8rtX/2lqd/8n5uXrp@fnpOal6Ofl56alFegWJydmJ6al6IanFJc45icXFXEhqChKLioFq3Ivz88DCxSVA1fllqUVpOfnlermJmXlcaYl5JYnFJZnJemn5@XpppXnJekmJRVxpekl6yWDjQCywwQA). (Extremely slow, so the `A` has been replaced with `Dálê` (duplicate; keep letters; convert to lowercase; sorted-uniquify) in the TIO-links.)
**Original 20 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
'.©¡Rć¬.uisć}s€н`r®ý
```
[Try it online](https://tio.run/##AUsAtP9vc2FiaWX//ycuwqnCoVLEh8KsLnVpc8SHfXPigqzQvWBywq7Dvf//Y29tLmdvb2dsZS5sb25nZXIucGFja2FnZS5UZXN0Q2xhc3M) or [verify all test cases](https://tio.run/##yy9OTMpM/V9TVmmvpPCobZKCkn3lf3W9QysPLQw60n5ojV5pZvGR9triR01rLuxNKDq07vDe/zr/k/Nz9dLz89NzUvVy8vPSU4v0ChKTsxPTU/VCUotLnHMSi4u5kNQUJBYVA9W4F@fngYWLS4Cq88tSi9Jy8sv1chMz87jSEvNKEotLMpP10vLz9dJK85L1khKLuNL0kvSSwcaBWGCDAQ).
**Explanation:**
I basically keep replacing every `ab.c` to `a.c`, where `abc` are any combination of lowercase letter including duplicates:
```
Δ # Loop until the result no longer changes,
# using the (implicit) input-string in the first iteration
A # Push the lowercase alphabet
3ã # Create all possible triplets of lowercase letters with the
# cartesian power of 3
v # Loop over each triplet `y`:
y'.« '# Append a "." to the triplet
À # Rotate it once towards the right: "abc." to "ab.c"
D # Duplicate it
õ1ǝ # Replace the character at index 1 with "": "ab.c" to "a.c"
: # Replace all "ab.c" in the string to "a.c"
# (after which the resulting string is output implicitly)
```
```
'. '# Push "."
© # Store it in variable `®` (without popping)
¡ # Pop and split the (implicit) input by this "."
R # Reverse this list
ć # Extract head; pop and push remainder-list and first item separated
# to the stack
¬ # Get the first character (without popping the string)
.ui # Pop, and if it's uppercase:
s # Swap so the remainder-list is at the top of the stack
ć # Extract its head again
} # Close the if-statement
s # Swap so the remainder-list is at the top of the stack
€ # Map over each string in this list:
н # Pop and only leave its first character
` # Pop and dump these characters to the stack
r # Reverse the stack
®ý # Join the stack by the "."-delimiter from variable `®`
# (after which the result is output implicitly)
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.