text
stringlengths 180
608k
|
---|
[Question]
[
This code challenge will have you compute the number of ways to reach \$n\$ starting from \$2\$ using maps of the form \$x \mapsto x + x^j\$ (with \$j\$ a non-negative integer), and doing so in the minimum number of steps.
(Note, this is related to [OEIS sequence A307092](https://oeis.org/A307092).)
## Example
So for example, \$f(13) = 2\$ because three maps are required, and there are two distinct sequences of three maps that will send \$2\$ to \$13\$:
$$\begin{array}{c} x \mapsto x + x^0 \\ x \mapsto x + x^2 \\ x \mapsto x + x^0\end{array} \qquad \textrm{or} \qquad \begin{array}{c}x \mapsto x + x^2 \\ x \mapsto x + x^1 \\ x \mapsto x + x^0\end{array}$$
Resulting in \$2 \to 3 \to 12 \to 13\$ or \$2 \to 6 \to 12 \to 13\$.
## Example values
```
f(2) = 1 (via [])
f(3) = 1 (via [0])
f(4) = 1 (via [1])
f(5) = 1 (via [1,0])
f(12) = 2 (via [0,2] or [2,1])
f(13) = 2 (via [0,2,0] or [2,1,0], shown above)
f(19) = 1 (via [4,0])
f(20) = 2 (via [1,2] or [3,1])
f(226) = 3 (via [2,0,2,1,0,1], [3,2,0,0,0,1], or [2,3,0,0,0,0])
f(372) = 4 (via [3,0,1,0,1,1,0,1,1], [1,1,0,2,0,0,0,1,1], [0,2,0,2,0,0,0,0,1], or [2,1,0,2,0,0,0,0,1])
```
# Challenge
The challenge is to produce a program which takes an integer \$n \ge 2\$ as an input, and outputs the number of distinct paths from \$2\$ to \$n\$ via a minimal number of maps of the form \$x \mapsto x + x^j\$.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins.
[Answer]
# JavaScript (ES6), ~~111 ... 84~~ 80 bytes
[Returns true](https://codegolf.meta.stackexchange.com/a/9067/58563) rather than \$1\$ for \$n=2\$.
```
f=(n,j)=>(g=(i,x,e=1)=>i?e>n?g(i-1,x):g(i-1,x+e)+g(i,x,e*x):x==n)(j,2)||f(n,-~j)
```
[Try it online!](https://tio.run/##LYzNCsIwEITvPsUePGTttpj4h0rak08hQkNNY0NJpBUptPXVY0APA/PNDGPVW/VV1zxfqfN3HUItmSOLMmdGsoYG0pJHagqdu8KwJuU04OlvEo2J@a1WMR2kdMgsCZymOt6kH4vhfBUEG4ItwY6AR@CR@JFArKPEPrYHcVtkte8uqnowBzKHyrvetzprvWGlYsvRzQgSlmP8xblEDF8 "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is the main recursive function taking:
n, // n = input
j // j = maximum number of steps
) => ( //
g = ( // g is another recursive function taking:
i, // i = number of remaining steps
x, // x = current sum
e = 1 // e = current exponentiated part
) => //
i ? // if there's still at least one step to go:
e > n ? // if e is greater than n:
// add the result of a recursive call with:
g(i - 1, x) // i - 1, x unchanged and e = 1
: // else:
// add the sum of recursive calls with:
g(i - 1, x + e) + // i - 1, x + e and e = 1
g(i, x, e * x) // i unchanged, x unchanged and e = e * x
: // else:
x == n // stop recursion; return 1 if x = n
)(j, 2) // initial call to g with i = j and x = 2
|| f(n, -~j) // if it fails, try again with j + 1
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~78~~ 75 bytes
This implementation uses a breath-first-search in the "tree" of iteratively all necessary mappings `x -> x + x^j`.
```
j#x=x+x^j
f n=[sum[1|x<-l,x==n]|l<-iterate((#)<$>[0..n]<*>)[2],n`elem`l]!!0
```
[Try it online!](https://tio.run/##JYxBCoMwFAX3PcUvuojtV0xsKwXjNboIKbqIGI1BNIVQvHuqlIHHLB7Tt@uojAlhiDz3V/8eTh1YLtbPJOjmq9Sg59zKzVSpdmppnSIkSqq4FnmWWVld6kQwibZRRk2NkedzHqZWW@AwL9o6iMG1o4Jyl6@eX9r1hPMESAdHhGGBN7wjZUgLpE9kOTL2wKJkMgFB8Q/bOXY/y/AD "Haskell – Try It Online")
### Explanation
```
-- computes the mapping x -> x + x^j
j#x=x+x^j
--iteratively apply this function for all exponents [0,1,...,n] (for all previous values, starting with the only value [2])
iterate((#)<$>[0..n]<*>)[2]
-- find each iteration where our target number occurs
[ |l<-...........................,n`elem`l]
-- find how many times it occurs
sum [1|x<-l,x==n]
-- pick the first entry
f n=.............................................................!!0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
2¸[˜DIå#εIÝmy+]I¢
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f6NCO6NNzXDwPL1U@t9X48NzcSu1Yz0OLgBJGZgA "05AB1E – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
f=lambda n,l=[2]:l.count(n)or f(n,[x+x**j for x in l for j in range(n)])
```
[Try it online!](https://tio.run/##HYzLDsIgFAXX@hUsSz1p5OIjNumXkC7wgbbBS0Nqgl@P4G7O5GSW7/oKTDm7wdv39W4Fww@Gxt53t/DhtWEZonANw6RdattZuLKTmFj4P84Vo@Xno1xHmavj6gxB44AjFEFpqAtoD6IT9Lnkt5slTiVfylLmHw "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
2+*¥þ³Ḷ¤F$n³Ạ$¿ċ
```
[Try it online!](https://tio.run/##y0rNyan8/99IW@vQ0sP7Dm1@uGPboSVuKnlA1q4FKof2H@n@//@/oTEA "Jelly – Try It Online")
A full program taking as its argument \$n\$ and returning the number of ways to reach \$n\$ using the minimal path length. Inefficient for larger \$n\$.
[Answer]
# Perl 5 (`-lp`), 79 bytes
```
$e=$_;@,=(2);@,=map{$x=$_;map$x+$x**$_,0..log($e)/log$x}@,until$_=grep$_==$e,@,
```
[TIO](https://tio.run/##FchBCsIwEEDR/ZxjFm0dazOxikggNwkuQinEZqgVAuLVHdPV@3yJaxpVMToMd0@u4Xbn@ZAPlv3VwnLA0nUYaOj7lKcGY3uqYvl6ei/bnDC4aY1ScRjJkyqDhTOMYBiMBXMDHoD5AvbKvyzbnJeXHpP8AQ)
[Answer]
## CJam (27 bytes)
```
qi2a{{_W$,f#f+~2}%_W$&!}ge=
```
[Online demo](http://cjam.aditsu.net/#code=qi2a%7B%7B_W%24%2Cf%23f%2B~2%7D%25_W%24%26!%7Dge%3D&input=13)
Warning: this gets very memory-intensive very fast.
### Dissection:
```
qi e# Read input and parse to int n (accessed from the bottom of the stack as W$)
2a e# Start with [2]
{ e# Loop
{ e# Map each integer x in the current list
_W$,f#f+~ e# to x+x^i for 0 <= i < n
2 e# and add a bonus 2 for the special case
}% e# Gather these in the new list
_W$&! e# Until the list contains an n
}g
e= e# Count occurrences
```
The bonus `2`s (to handle the special case of input `2`, because `while` loops are more expensive than `do-while` loops) mean that the size of the list grows very fast, and the use of exponents up to `n-1` means that the values of the larger numbers in the list grow very fast.
[Answer]
# [Haskell](https://www.haskell.org/), 65 bytes
```
([2]%)
l%n|elem n l=sum[1|x<-l,x==n]|1>0=[x+x^k|x<-l,k<-[0..n]]%n
```
[Try it online!](https://tio.run/##JYrLCoMwFAX3/Yq7UFB6FRP7BONvdJGmECTWkBhCtRCK397UIgOH4TCDnIyyNvbsHjNORZrvbOoWZdUIDiyb3iMnS2gKi4ExJxbSVoyHfXiY7TVNwauydEKkLo5SO2DgX9rNkMAsjYLLKh/tb3oeMsZyyHpokpZTrPGARyQUSY3kirRCSk9Yn6nIgRPcoCv/XWMRv11v5XOKRef9Dw "Haskell – Try It Online")
Golfing [flawr's breadth-first-search](https://codegolf.stackexchange.com/a/190899/20260). I also tried going backwards from `n`, but it was longer:
**73 bytes**
```
q.pure
q l|elem 2l=sum[1|2<-l]|1>0=q[x|n<-l,x<-[0..n],i<-[0..n],x+x^i==n]
```
[Try it online!](https://tio.run/##PYrLCoMwEEX3/YpZdKF0FDP2QcH4G12kKYjEGowhviAUv72ppVAOXM6B21ZTp4wJDb@HIXXLqHYDmFUZ1QMZPi29YCsViZErKzM@CL/ardAXicjS1ErUf/MH/9CcWxn6Slvg4EZtZ9jDXHUKWLbZS7ubntuI8xiiBop9KQhzPOIJGSHLkV2RMiQ6Y34hGYNg@IM2vrudZXjXjameU0hq5z4 "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~78~~ 77 bytes
```
function(n,x=2){while(!{a=sum(x==n)})x=rep(D<-x[x<n],n+1)+outer(D,0:n,'^')
a}
```
[Try it online!](https://tio.run/##RczRCoIwFMbxe59i4YXn4AI9s6Jwd75FFEhsJNgxTGkgPvtqF7W7Hx9/vtFb7e3Mt6kbGFg6Tbi8711vYLO0@jU/wGnNuKLTo3lCU2/d2dV8kZyXmA/zZEZoZHFimV0zTNrVWyAUQqSiTCyoyCpyF1mGOBUUqCKP@Auo@K9Ee/xShd8DBVb@Aw "R – Try It Online")
Using a simplified Breadth-first Search
Unrolled code with explanation :
```
function(n){ # function taking the target value n
x=2 # initialize vector of x's with 2
while(!(a<-sum(x==n))) { # count how many x's are equal to n and store in a
# loop while a == 0
x=rep(D<-x[x<n],n+1)+outer(D,0:n,'^') # recreate the vector of x's
# with the next values: x + x^0:n
}
a # return a
}
```
---
Shorter version with huge memory allocation (failing for bigger cases) :
# [R](https://www.r-project.org/), ~~70~~ 69 bytes
```
function(n,x=2){while(!{a=sum(x==n)})x=rep(x,n+1)+outer(x,0:n,'^')
a}
```
[Try it online!](https://tio.run/##RczBCsIwEATQe78i0kOzNIdmUxWF/RWhSIIF3ZbYYKD022Nz0NzeDMP45Ci5wPdlnFiyioSwfh7j08rDOtA7vGQkYtggkrezjIpbDe0UFuv30F1ZNbcGqmFLTiIIIWqhKydNYV94LNR5XAvMNIUX@A2w@7eIJ9hp8u8ZM/v0BQ "R – Try It Online")
-1 byte thanks to @RobinRyder
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 24 bytes
```
VQIJ/mu+G^GHd2^U.lQ2NQJB
```
[Try it online!](https://tio.run/##K6gsyfj/PyzQ00s/t1TbPc7dI8UoLlQvJ9DIL9DL6f9/IyMzAA "Pyth – Try It Online")
This should produce the correct output, but is very slow (the 372 test case times out on TIO). I could make it shorter by replacing `.lQ2` with `Q`, but this would make the runtime horrendous.
Note: Produces no output for unreachable numbers \$(n \leq 1)\$
### Explanation
```
VQ # for N in range(Q (=input)):
J # J =
m # map(lambda d:
u # reduce(lambda G,H:
+G^GH # G + G^H,
d2 # d (list), 2 (starting value) ),
^U.lQ2N # cartesian_product(range(log(Q, 2)), N)
/ Q # .count(Q)
IJ JB # if J: print(J); break
```
] |
[Question]
[
Given a word consisting of lowercase letters only, do the following:
1. For each letter, get the prime factorization of its position in the alphabet.
2. For each prime factor, *p*, draw a diamond of side length *p* and stick the letter in the middle of the diamond.
3. The biggest diamond is in the middle, subsequent smaller diamonds (from biggest to smallest) alternate between going to the bottom or top.
**Note:** For the letter **a** use a side-length of 1.
Example: **cat**
* **c**: 3 = 3
* **a**: 1 = 1
* **t**: 20 = 5\*2\*2
The diagram:
```
.
. .
. t .
. .
.
.
. .
. . .
. . . .
. . . . .
. c . .a. . t .
. . . . .
. . . .
. . .
. .
.
.
. .
. t .
. .
.
```
Example: **dog**
* **d**: 4 = 2\*2
* **o**: 15 = 5\*3
* **g**: 7 = 7
Diagram:
```
.
. .
. . .
. . . .
. . . .
. . . . .
. . . . . .
. d . . o . . g .
. . . . . .
. . . . .
. . . . .
. . . . . .
. d . . . .
. . . . .
. . . .
. .
. o .
. .
. .
.
```
**-20% bonus** if your program outputs to a text file called "[your-word].txt". Then input a real word (or phrase, made lowercase with no spaces) that is at least **20 letters** long and no one else has chosen yet, and paste the output between a `<pre>` and a `</pre>` in your answer.
[Answer]
# [Funciton](http://esolangs.org/wiki/Funciton), non-competitive, 29199 bytes
I enjoyed this challenge because it highlighted the sore lack of some very useful library functions. I will include all of those functions here (and in the byte count) because I wrote them after this challenge was posted.
**[Full source in a single file](https://gist.githubusercontent.com/Timwi/a39461d7398da6a4d881fbf5bdda56ce/raw/e7a2ad4dbbc7e1fec6d0d0100ad33948b846d6d1/CodeGolf%252068162%2520(Visualizing%2520Words)%2520(full).fnc)**
# Explanation
As always, get a better rendering by executing `javascript:(function(){$('pre,code').css({lineHeight:5/4});})()` in your browser console.
## ① `ɹ` `⇄` Reverse
As you may or may not know, Funciton comes with a library full of functions for *lists*, which are values encoded in a single humongous integer, as well as a separate library for *lazy-evaluated sequences*, which use lambda expressions (anonymous functions) in order to be lazy. Of course there’s also a library for string handling functions.
For this challenge, I needed a function to reverse a string, and a function to reverse a lazy-evaluated sequence. Surprisingly, I only had one for lists — exactly the one I didn’t need. So here are the reverse functions for lazy sequences (`ɹ`) and for strings (`⇄`):
```
╓───╖ ╔════╗ ┌────╖ ╓───╖
║ ɹ ║ ║ 21 ╟─┤ >> ╟──┐ ║ ⇄ ║
╙─┬─╜ ╚════╝ ╘═╤══╝ │ ╙─┬─╜ ┌──┐
┌─────┴─────┐ ┌─┴─╖ ├───────┴────────┤ │
┌─┴─╖ ┌───╖ │ │ ⇄ ║ │ ╔════╗ ┌───╖ │ │
┌─┤ ╟─┤ ɹ ╟─┐ │ ╘═╤═╝ │ ║ −1 ╟─┤ ≠ ╟─┴┐ │
│ └─┬─╜ ╘═══╝ │ │ ┌─┴─╖ ┌─┴─╖ ╚════╝ ╘═╤═╝ │ │
│ │ ┌───╖ │ │ │ ‼ ╟─┤ ? ╟──────────┤ │ │
│ └───┤ ʬ ╟─┘ │ ╘═╤═╝ ╘═╤═╝ ╔═══╗ ┌─┴─╖ │ │
│ ╘═╤═╝ │ ┌─┴─╖ ╔═══╗ ║ 0 ╟─┤ ≠ ╟──┘ │
│ ╔═══╗ ┌─┴─╖ │ ┌─┤ ʃ ╟─╢ 1 ║ ╚═╤═╝ ╘═══╝ │
└─╢ 0 ╟─┤ ? ╟───┘ │ ╘═╤═╝ ╚═══╝ │ │
╚═══╝ ╘═╤═╝ │ └────────────┘ │
│ └─────────────────────────────┘
```
The lazy-sequences one uses `ʬ`, which is “append an element to the end of a lazy sequence”. The string one uses `ʃ` (substring) and `‼` (string concatenate).
## ② `Ṗ` Primes
Although I could have done prime factorization by just trying to divide *n* by all factors in order, I decided I wanted a library function that generates prime numbers. The following function takes an integer *n* and implements the [Sieve of Eratosthenes](https://en.wikipedia.org/wiki/Sieve_of_Eratosthenes) to generate all prime numbers up to *n*. It does this as a lazy sequence, so it’ll generate only as many primes as you actually evaluate.
```
╓───╖
║ Ṗ ║
╔═══╗ ╙─┬─╜
║ 0 ║ ┌─┴─╖
╚═╤═╝ │ ♭ ║
╔═══╗ ┌──┴─╖ ╘═╤═╝
║ 2 ╟─┤ Ṗp ╟───┘
╚═══╝ ╘══╤═╝
┌──────────────┐ │
│ ├─────────────────────────────────────────┐
│ ┌─┴─╖ │
│ ┌─┤ · ╟────────────────────────────┐ ╓┬───╖ │
│ │ ╘═╤═╝ ├───╫┘Ṗp ╟─┤
│ │ │ ╔═══╗ ┌────╖ ┌─┴─╖ ╙─┬──╜ │
│ │ │ ║ 1 ╟─┤ >> ╟─────┤ · ╟───┴─┐ │
│ │ │ ┌───╖ ╚═══╝ ╘══╤═╝ ╘═╤═╝ │ │
│ │ ┌─┴──┤ ♯ ╟─────┐ ┌──┴─╖ ┌───╖ │ │ │
│ │ │ ╘═══╝ ┌─┐ │ ┌──┤ Ṗp ╟─┤ ♭ ╟─┴─┐ │ │
│ │ │ ├─┘ └─┤ ╘══╤═╝ ╘═══╝ ┌─┘ │ │
│ │ │ ╔═╧═╕ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ │ │
│ │ └────────╢ ├─┤ · ╟─┤ ? ╟─────┤ · ╟─┐ │ │
│ │ ┌───╖ ╚═╤═╛ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ │ │
│ ┌─┴─┤ ♭ ╟─┐ ┌──┴─╖ │ ┌─┴─╖ │ │ │ │
│ │ ╘═══╝ └─┤ Ṗp ╟───┘ ┌─┤ ? ╟───────┘ │ │ │
│ ┌───╖ │ ╔════╗ ╘══╤═╝ │ ╘═╤═╝ │ │ │
┌─┴─┤ ÷ ╟──┘ ║ −1 ║ ┌──┴─╖ ╔═╧═╗ │ ┌┴┐ │ │
│ ╘═╤═╝ ╚══╤═╝ ┌─┤ >> ╟─┐ ║ 0 ║ └┬┘ │ │
│ ┌─┴─╖ ┌────╖ │ │ ╘════╝ │ ╚═══╝ │ │ │
│ │ × ╟─┤ << ╟─┘ ┌─┴─┐ ╔═╧═╗ │ │ │
│ ╘═╤═╝ ╘══╤═╝ ┌┴┐ ┌┴┐ ║ 1 ╟───────────────────┴─┐ │ │
└─────┘ ┌┴┐ └┬┘ └┬┘ ╚═══╝ ├─┘ │
└┬┘ │ └──────────────────────────────┘ │
┌─┴─╖ ┌─┴──╖ │
│ ÷ ╟─┤ << ╟─┐ │
╘═╤═╝ ╘════╝ ├──────────────────────────────────┘
┌┴┐ │
└┬┘ │
╔════╗ ┌─┴──╖ │
║ −1 ╟─┤ << ╟───────┘
╚════╝ ╘════╝
```
The helper function, `Ṗp`, takes:
* A running counter which just keeps decrementing until it reaches 0.
* The sieve, which has a bit set for each number that is already known to be not-prime. Initially, the least significant bit represents the number 2, but we shift this right with each iteration.
* A number *n* which indicates what number is represented by the sieve’s lowest bit; this is incremented with every iteration.
At each iteration, if the sieve’s lowest bit is 0, we’ve found a prime *n*. We then use the formula I already described in [Fill the rows, columns, and diagonals of an NxN grid](https://codegolf.stackexchange.com/a/67206) to set every *n*-th bit in the sieve before moving to the next iteration.
## ③ `Ḟ` Prime factorization
```
╓───╖
║ Ḟ ║
╙─┬─╜
┌───────┴──────┐
│ ┌───╖ ┌────╖ │
└─┤ Ṗ ╟─┤ Ḟp ╟─┘
╘═══╝ ╘═╤══╝
│
┌────────────────────────────────────────────┐
│ ╓┬───╖ │
┌───────┴─┐ ┌───────────────────────┐ ┌─╫┘Ḟp ╟─┘
│ ╔═══╗ ┌─┴─╖ ┌─┴─╖ ┌───┐ ┌────╖ ┌─┴─╖ │ ╙────╜
│ ║ 0 ╟─┤ ╟─┤ · ╟─┘┌┐ └─┤ Ḟp ╟──┐ ┌─┤ · ╟─┴──┐
│ ╚═══╝ └─┬─╜ ╘═╤═╝ └┤ ╘═╤══╝ ├─┘ ╘═╤═╝ │
│ ┌─┴─┐ ┌─┴─╖ ╔═╧═╕ ┌─┴─╖ ┌─┴─╖ ┌─┴──╖ ┌─┴─╖
│ │ └─┤ · ╟─╢ ├─┤ ? ╟─┤ · ╟─┤ ÷% ╟─┤ · ╟─┐
│ │ ╘═╤═╝ ╚═╤═╛ ╘═╤═╝ ╘═╤═╝ ╘═╤══╝ ╘═╤═╝ │
│ │ ┌──┴─╖ │ ┌─┴─╖ ┌─┴─╖ └──────┘ │
│ │ │ Ḟp ╟───┘ ┌─┤ ? ╟─┤ ≤ ║ │
│ ┌─┴─╖ ╘══╤═╝ │ ╘═╤═╝ ╘═╤═╝ │
└─────┤ · ╟─────┘ ╔═╧═╗ │ ╔═╧═╗ │
╘═╤═╝ ║ 0 ║ ║ 2 ║ │
│ ╚═══╝ ╚═══╝ │
└──────────────────────────────────────────┘
```
This is fairly straight-forward. Just iterate through the primes up to *n* and see which ones divide *n*. If one does divide *n*, remember to carry on with the *same* prime so that we return it multiple times if it divides *n* multiple times. This returns the empty sequence for any number less than 2.
## ④ `◇` `◆` Generate a diamond
This function generates a single diamond given a character and a radius. It only uses the character to place it in the center of the diamond.
```
┌───╖
┌─────────────────────┤ ♯ ╟───────────┬─────────┐
│ ┌───╖ ╔═══╗ ┌───┐ ╘═══╝ │ │
└─┤ ♫ ╟─╢ 0 ║ │ ┌─┴─╖ │ │
╘═╤═╝ ╚═══╝ │ │ ʭ ╟───┐ │ │
┌─┴─╖ ┌─────┘ ╘═╤═╝ │ │ │
│ ɱ ╟───┤ ┌───╖ ┌─┴─╖ ╔═══╗ ╓───╖ │ │
╘═╤═╝ └─┤ ɹ ╟─┤ ʓ ╟─╢ 1 ║ ┌─╢ ◇ ╟─┤ │
│ ╔═══╗ ╘═══╝ ╘═══╝ ╚═══╝ │ ╙───╜ │ │
│ ║ 0 ║ │ ┌─┴─╖ │
│ ╚═╤═╝ │ │ ♭ ║ │
╔═╧═╕ │ ╔════╗ │ ╘═╤═╝ │
┌───╢ ├─┘ ┌─╢ 21 ║ ┌─┴─╖ ┌─┴─╖ ┌─┴─┐
│ ╚═╤═╛ │ ╚════╝ ┌────────┤ · ╟───┤ · ╟─┐ ┌─┴─╖ │
│ ┌─┴─╖ ┌─┴──╖ ┌───┘ ╘═╤═╝ ╘═╤═╝ ├─┤ = ║ │
│ ┌─┤ ‼ ╟─┤ >> ║ │ │ ┌─┴─╖ │ ╘═╤═╝ │
│ │ ╘═══╝ ╘═╤══╝ │ │ ┌─┤ ? ╟─┘ │ │
│ │ ┌───╖ │ ┌──┘ │ │ ╘═╤═╝ │ │
│ └─┬─┤ ⇄ ╟─┘ │ ┌─────┐ │ │ ┌─┴─╖ │ │
│ │ ╘═══╝ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ └─┤ · ╟──┬──┘ │
│ └───────┤ · ╟─┤ ? ╟─┤ · ╟─┤ ‼ ║ ╘═╤═╝ │ │
│ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ┌─┴─╖ │ │
│ └─────┘ └─┬───┘ ┌───┤ … ║ │ │
│ ┌─────┐ │ │ ╘═╤═╝ │ │
│ ╔══╧═╗ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ╔═╧══╗ │ │
│ ║ 32 ║ │ … ╟─┤ ‼ ╟─┤ ‼ ║ ║ 32 ║ │ │
│ ╚════╝ ╘═╤═╝ ╘═══╝ ╘═╤═╝ ╚════╝ │ │
│ ┌─┴─╖ ╔═╧══╗ │ │
│ ┌───┤ − ╟───┬─┐ ║ 46 ║ │ │
│ ┌─┴─╖ ╘═══╝ │ │ ╚════╝ │ │
└─────────────┤ · ╟─────────┘ └──────────────┘ │
╘═╤═╝ │
└───────────────────────────────────┘
```
This makes heavy use of lazy sequences. Here’s how it works:
* Generate the sequence of integers from 0 to *r* (inclusive).
* For each such integer *α*, generate a string consisting of (*r* − *α*) spaces (`…`), followed by a dot, followed by *α* spaces — unless *α* = *r*, in which case generate one fewer space and append the letter. We now have the top-left quarter of the diamond.
* To each of these strings, append another copy of the same string, but with the characters reversed (`⇄`) and then the first character removed (`>> 21`). We now have the top half of the diamond.
* Take this sequence and append to it the same sequence, but reversed (`ɹ`) and with the first element removed (`ʓ`). We now have the whole diamond.
Now we have the strings that make up the diamond, but we need a little more information. We need to know where the vertical middle of the diamond is. Initially this is of course *r*, but once we’ve appended other diamonds to the top and bottom of this, we will need to keep track of the position of the “middle” diamond so that we can vertically align the other stacks of diamonds correctly. The same goes for the horizontal extent of the diamond (need that when appending diamonds to the top and bottom). I also decided to keep track of the letter; I need that because otherwise the function `⬗` (which we get to in the next section) would have to have four parameters, but Funciton allows only three.
```
┌─────────────────┐
│ ╓───╖ │
├──╢ ◆ ╟──┐ │
│ ╙───╜ │ │
│ ┌─────┴───┐ │
┌─┴─╖ │ ┌───╖ ┌─┴─╖ │
┌─┤ · ╟─┴─┤ › ╟─┤ › ║ │
│ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │
│ ┌─┴─╖ │ ┌─┴─╖ │
│ │ ◇ ╟─────────┤ › ╟─┘
│ ╘═╤═╝ ╘═══╝
└───┘
```
We use the list API (`›` adds elements to the front of a list) to create a structure containing [*x*, *y*, *c*, *q*], where *x* is the x-coordinate of the horizontal center of the diamond, *y* is the y-coordinate of the baseline, *c* is the letter and *q* is the lazy sequence of strings. This structure will be used to contain all of the intermediate stages from now on.
## ⑤ `⬗` Append diamonds vertically
This function takes an existing diamond stack, a radius, and a boolean indicating whether to add the new diamond to the top (true) or bottom (false).
```
┌─────────────────────────────────────────────────┐
┌─┴─╖ ┌───────────────────────────┐ ┌───╖ ┌─┴─╖
┌───┤ · ╟─────────┘ ╔═══╗ ┌───────────────┐ ├─┤ ‹ ╟─┤ ‹ ║
│ ╘═╤═╝ ║ 1 ║ │ ╓───╖ │ │ ╘═╤═╝ ╘═╤═╝
│ │ ╚═╤═╝ └─╢ ⬗ ╟─┐ │ ┌─┴─╖ │ ┌─┴─╖
│ │ ┌───╖ ┌───╖ ┌─┴──╖ ╙─┬─╜ │ └─┤ · ╟─┘ ┌─┤ ‹ ╟─┐
│ ┌─┴─┤ + ╟─┤ ♯ ╟─┤ << ║ │ │ ╘═╤═╝ │ ╘═══╝ │
│ │ ╘═╤═╝ ╘═══╝ ╘═╤══╝ │ ┌─┴─╖ │ │ │
│ │ ┌─┴─╖ └───────┴─┤ · ╟───┐ ┌─┴─╖ │ │
│ └───┤ ? ╟─┐ ╘═╤═╝ ┌─┴───┤ · ╟─┐ │ │
│ ╘═╤═╝ ├───────────────────┘ │ ╘═╤═╝ │ │ │
│ ┌───╖ ┌─┴─╖ │ ┌─────┐ │ ┌───╖ │ │ │ │
└─┤ › ╟─┤ › ║ │ ┌───╖ ┌─┴─╖ │ └─┤ − ╟─┘ │ │ │
╘═╤═╝ ╘═╤═╝ │ ┌─┤ ‼ ╟─┤ ‼ ║ │ ╘═╤═╝ │ │ │
│ ┌─┴─╖ │ │ ╘═╤═╝ ╘═╤═╝ ┌─┴─╖ ┌─┴─╖ │ │ │
┌───┤ · ╟─┘ │ ┌─┴─╖ ├───┤ · ╟─┤ … ║ │ │ │
┌───┐ │ ╘═╤═╝ └─┤ · ╟───┘ ╘═╤═╝ ╘═╤═╝ │ │ │
│ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ╘═╤═╝ │ ╔══╧═╗ │ │ │
│ │ ʭ ╟─┤ ? ╟─┤ › ╟─┐ ╔═══╗ ╔═╧═╕ │ ║ 32 ║ │ │ │
│ ╘═╤═╝ ╘═╤═╝ ╘═══╝ │ ║ 0 ╟─╢ ├─────────┘ ╚════╝ │ │ │
│ ┌─┘ ┌─┴─╖ │ ╚═══╝ ╚═╤═╛ │ │ │
│ └─┬───┤ ʭ ╟─┐ ┌─┴─╖ ┌─┴─╖ │ │ │
│ ┌─┴─╖ ╘═══╝ ├───┤ · ╟─────┤ ɱ ║ │ │ │
└─┤ · ╟───────┘ ╘═╤═╝ ╘═╤═╝ │ │ │
╘═╤═╝ │ ┌─┴─╖ │ │ │
│ └─────┬─┤ ◇ ╟───────────────────────┘ │ │
│ │ ╘═══╝ ┌─┴─╖ │
│ └─────────────────────────────┤ · ╟─────┘
│ ╘═╤═╝
└─────────────────────────────────────────────────────┘
```
This is fairly straight-forward too; use `‹` to unpack the structure; use `◇` to generate the new diamond; use `ɱ` (map) to add spaces to the beginning and end of each string in the new diamond so that it all has the same width; append (`ʭ`) the new strings onto the old (if bottom) or the old onto the new (if top); and finally use `›` to construct the structure containing all the new values. In particular, if we are appending to the bottom, *y* doesn’t change, but if we are appending to the top, *y* must increase by `♯(r << 1)` (*r* is the radius of the new diamond).
## ⑥ `❖` Concatenate stacks horizontally
This is the biggest function of them all. I won’t deny that it was fairly fiddly to get this right. It takes two stacks and concatenates them horizontally while respecting the correct vertical alignment.
```
┌──────────────────────────────────┬───────────────────────┐
│ ┌──────────────────┐ ┌─┴─╖ ┌─┴─╖
│ │ ┌───────────┐ └───────┤ · ╟───┬───────────────┤ · ╟─────────────┐
│ │ ┌─┴─╖ │ ╘═╤═╝ │ ╘═╤═╝ │
│ │ │ ‹ ╟───┐ │ ┌─┴─╖ ┌─┴─╖ │ │
│ │ ╘═╤═╝ ┌─┴─╖ └─────────┤ · ╟─┤ · ╟─────────┐ │ │
│ │ ├─┐ │ ‹ ╟───┐ ╘═╤═╝ ╘═╤═╝ │ │ │
│ │ └─┘ ╘═╤═╝ ┌─┴─╖ ╓───╖ ┌─┴─╖ │ │ │ │
│ │ │ │ ‹ ╟─╢ ❖ ╟─┤ ‹ ║ │ │ │ │
│ │ │ ╘═╤═╝ ╙───╜ ╘═╤═╝ ┌─┴─╖ ┌─┐ │ │ │
│ │ │ │ └───┤ ‹ ║ └─┤ │ │ │
│ │ │ │ ╘═╤═╝ ┌─┴─╖ │ │ │
│ │ │ │ └───┤ ‹ ║ │ │ │
│ │ │ └─────────────────┐ ╘═╤═╝ │ │ │
│ │ │ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ │
│ │ │ ┌──────────────┤ · ╟─┤ · ╟─┤ · ╟─┤ · ╟──────┐ │
│ │ └──────┤ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ │
│ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ │ │ │ │ │
│ ┌─┤ · ╟─────────────┤ · ╟────────────┤ · ╟───┘ │ │ │ │
│ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ │ │ │
│ │ │ │ ┌────╖ │ ┌─┴─╖ │ │ │
╔═══╗ ┌────╖ │ │ │ │ ┌─┤ << ╟─┴─────────┤ · ╟─┐ │ │ │
║ 1 ╟─┤ << ╟────────┘ │ │ │ │ ╘═╤══╝ ╘═╤═╝ │ │ │ │
╚═══╝ ╘═╤══╝ ╔════╗ │ │ ┌─┴─╖ │ ┌─┴─╖ │ │ │ ┌──┴──┐ │
┌─┴─╖ ║ 32 ╟─┐ │ │ ┌─────────────┤ · ╟───┐ │ │ ♯ ║ │ │ │ ┌─┴─╖ ┌─┴─╖ │
│ ♯ ║ ╚════╝ │ │ └─┤ ┌───╖ ╘═╤═╝ │ │ ╘═╤═╝ ┌───╖ ╔════╗ │ │ │ ┌─┤ ? ╟─┤ < ║ │
╘═╤═╝ ┌───╖ │ │ └─┤ − ╟─────────┴─┐ │ │ └───┤ … ╟─╢ 32 ║ │ │ │ │ ╘═╤═╝ ╘═╤═╝ │
└─────┤ … ╟─┘ │ ╘═╤═╝ ┌─┴─╖ │ └───┐ ╘═╤═╝ ╚════╝ │ │ │ │ ┌─┴─╖ ├───┘
╘═╤═╝ │ ┌───╖ ┌─┴─╖ ┌───────┤ · ╟─┴─┐ ╔═╧═╗ ┌─┴─╖ ┌──────┘ │ │ └─┤ · ╟───┘
│ ┌─┴─┤ ʭ ╟─┤ ȶ ║ │ ┌───╖ ╘═╤═╝ │ ║ 1 ║ │ ⁞ ║ │ ┌────────┘ │ ╘═╤═╝
┌─┴─╖ │ ╘═╤═╝ ╘═╤═╝ └─┤ > ╟───┴─┐ │ ╚═══╝ ╘═╤═╝ │ │ ┌──────┘ └────┐
│ ⁞ ║ │ ┌─┴─╖ ┌─┴─╖ ╘═╤═╝ │ ┌─┴─╖ ┌───╖ │ │ │ ┌─┴─╖ ┌───╖ ┌───╖ ┌─┴─╖
╘═╤═╝ └───┤ ? ╟─┤ · ╟─────┴─┐ │ │ − ╟─┤ ȶ ╟─┴─┐ │ │ │ + ╟─┤ ♯ ╟─┤ › ╟─┤ › ║
┌─┴─╖ ╘═╤═╝ ╘═╤═╝ │ │ ╘═╤═╝ ╘═╤═╝ │ │ │ ╘═╤═╝ ╘═══╝ ╘═╤═╝ ╘═╤═╝
┌────────────────────┤ · ╟───────┴───┐ └─┐ ┌─┴─╖ └───┘ ┌─┴─╖ │ │ └───┘ │ │
│ ╘═╤═╝ ┌─┴─╖ │ ┌─┤ · ╟───────────┤ · ╟───┘ │ │
│ ┌────────────────┐ │ ┌───────┤ · ╟─┘ │ ╘═╤═╝ ╘═╤═╝ │ │
│ │ ╔════╗ ┌───╖ ┌─┴─╖ └───┤ ┌───╖ ╘═╤═╝ │ │ │ ┌─┴───┐ │
│ │ ║ 32 ╟─┤ ‼ ╟─┤ · ╟───┐ └─┤ ʭ ╟───┘ │ │ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ │
│ │ ╚════╝ ╘═╤═╝ ╘═╤═╝ │ ╘═╤═╝ ┌─────┘ │ │ ʭ ╟─┤ · ╟─┤ ? ╟─┐ │
│ │ ┌─┴─╖ ╔═╧═╕ ╔═╧═╕ ┌─┴─╖ ┌─┴─╖ │ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ │ │
│ │ │ ‼ ╟─╢ ├─╢ ├─┤ ʑ ╟───┤ ʭ ║ ┌─┴─╖ └─────┘ │ │ │
│ │ ╘═╤═╝ ╚═╤═╛ ╚═╤═╛ ╘═╤═╝ ╘═╤═╝ ┌───┤ · ╟─────────────────────────┘ │ │
│ └──────────┘ │ ╔═╧═╗ │ ├───┘ ╘═╤═╝ │ │
│ └───╢ 0 ║ ┌─┴─╖ ┌─┴─╖ └───────────────────────────────┘ ┌─┴─╖ ╔═══╗
│ ╚═══╝ │ ȶ ╟───┤ · ╟─────────────────────────────────────────────────────┤ › ╟─╢ 0 ║
│ ╘═╤═╝ ╘═╤═╝ ╘═══╝ ╚═══╝
│ ┌─┴─╖ ┌─┴─╖
│ ┌─────┤ ? ╟─┐ │ ɕ ║
│ ┌─┴─╖ ╘═╤═╝ │ ╘═╤═╝
│ ┌───╖ ┌─┤ < ╟───┬─┘ │ │
└────────────┤ ɕ ╟─┤ ╘═══╝ ┌─┴─╖ │ │
╘═══╝ └───────┤ · ╟───┘ │
╘═╤═╝ │
└─────────┘
```
Here’s how it works.
* First, for each stack, generate an infinite sequence (`⁞`) of strings, each of which contains spaces (`…`) according to that stack’s width.
* The *y* values of the stacks tell us which one needs to “move down” and by how much. Prepend the appropriate space sequence, truncated (`ȶ`) to the right length (*y1* − *y2* or *y2* − *y1* as appropriate).
* Now determine the length of each of the string sequences (`ɕ`), which tells us their height. Find out which one is taller.
* Append the infinite space sequences to both stacks.
* Use zip (`ʑ`) to put them together. For each pair of strings, concatenate them (`‼`) along with an extra space in between.
* *Then* use `ȶ` to truncate the result of that to the tallest height. By doing this late, we don’t have to care which one of them needs the padding.
Finally, generate the structure again. At this point, we no longer need the character in the diamonds, so we set that to 0. The *x* value is just summed and incremented (so that the width of the stack can still be calculated as `♯(x << 1)`). The *y* value is set to the higher one of the two.
## ⑦ `↯` Iterate over characters in a string
This is another useful function which I will add to the library. Given a string, it gives you a lazy sequence containing each character code.
```
╓───╖
║ ↯ ║
╙─┬─╜
┌──────────────┴────────────────┐
│ ┌─┐ ╔═══╗ ┌───╖ │
│ └─┤ ┌────╢ 0 ╟─┤ ≠ ╟─┴─┐
┌──────┴─┐ ┌┐ ╔═╧═╕ ┌─┴─╖ ╚═══╝ ╘═╤═╝ │
│ ├─┤├─╢ ├─┤ ? ╟──────────┤ │
│ │ └┘ ╚═╤═╛ ╘═╤═╝ ╔════╗ ┌─┴─╖ │
│ ╔══════╧══╗ ┌─┴─╖ │ ║ −1 ╟─┤ ≠ ╟───┘
│ ║ 2097151 ║ │ ↯ ║ ╚════╝ ╘═══╝
│ ╚═════════╝ ╘═╤═╝
│ ┌─┴──╖ ╔════╗
└─────────────┤ >> ╟─╢ 21 ║
╘════╝ ╚════╝
```
`and`ing a string with 2097151 returns the first character. `>>`ing it by 21 removes it. We check for both 0 and −1 for a reason [explained in the esolangs page](http://esolangs.org/wiki/Funciton#String_handling); this is not relevant to this challenge, but I want the library function to be correct.
## ⑧ `⬖` Convert character to diamond stack
This function takes a single character and returns the structure for the vertical stack representing that one character.
```
╔════╗
║ 96 ║ ╓───╖
╚══╤═╝ ║ ⬖ ║
┌───╖ ┌───╖ ┌─┴─╖ ╙─┬─╜
┌───┤ ɗ ╟─┤ Ḟ ╟─┤ − ║ │
│ ╘═╤═╝ ╘═══╝ ╘═╤═╝ │
│ ┌─┴─╖ ├──────┘ ┌──┐
│ │ ɹ ║ │ ┌───┤ │
│ ╘═╤═╝ ┌─────┘ │ │ │
╔═╧═╗ ┌─┴─╖ ┌─┴─╖ │ ┌┴┐ │
║ 1 ╟─┤ ╟─┤ · ╟─────┐ ╔═╧═╕└┬┘ │
╚═══╝ └─┬─╜ ╘═╤═╝ ┌─┴─╢ ├─┘ ┌┴┐
┌───────────┐ │ └─┐ │ ╚═╤═╛ └┬┘
┌─┴─╖ │ │ ┌───╖ │ └─┐ ╔═╧═╕ ┌──┴─╖ ╔═══╗
┌─────┤ · ╟───┐ │ └─┤ ◆ ╟─┘ ┌─┴─╢ ├─┤ << ╟─╢ 1 ║
┌──┴─┐ ╘═╤═╝ │ │ ╘═╤═╝ │ ╚═╤═╛ ╘════╝ ╚═╤═╝
│ ┌──┴─╖ ┌─┴─╖ ╔═╧═╕ ╔═╧═╕ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖ ┌─┴─╖
│ │ >> ╟─┤ ⬗ ╟─╢ ├─╢ ├─┤ ʩ ╟───┤ · ╟─┤ ʑ ╟────────┤ ⸗ ║
│ ╘══╤═╝ ╘═╤═╝ ╚═╤═╛ ╚═╤═╛ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝ ╘═╤═╝
│ ╔═╧═╗ ┌┴┐ │ ╔═╧═╗ │ └─────┘ ╔═╧═╗
│ ║ 1 ╟─┐└┬┘ └───╢ 0 ║ ║ 0 ║
│ ╚═══╝ ├─┘ ╚═══╝ ╚═══╝
└────────┘
```
This function is interesting because we needed the diamonds to be appended *alternatingly* to the bottom and top. Here’s how I did it:
* First, subtract 96 (so `'a'` becomes 1), get prime factors (`Ḟ` above), use `ɗ` to add the element 1 if the sequence is empty, and then reverse (`ɹ`) the order.
* Take the first element off and call `◆` to jumpstart the stack.
* Now, use `⸗` to generate a lazy sequence that just alternates the numbers 0 and 1 indefinitely.
* Use `ʑ` (zip) on that and the remaining prime factors. For each prime factor, shift it left by 1 and `or` the 0/1 onto it. We now have a sequence that encodes the prime numbers *and* the top/bottom information.
* Finally, use `ʩ` (fold left/aggregate). The initial value is the stack we generated from the first element above. For each value *ν*, call `⬗` (append a new diamond) with the previous stack, the prime (`ν >> 1`) and whether top or bottom (`ν & 1`).
## ⑨ Main program
Here we do the main work.
```
┌─────┐
│ ┌─┴─╖
│ │ ⬖ ║
╔═══╗ ╔═╧═╕ ╘═╤═╝
║ 0 ╟─╢ ├───┘
╚═╤═╝ ╚═╤═╛ ┌───╖ ┌───╖ ╔═══╗
└─┐ └───┤ ɱ ╟─┤ ↯ ╟─╢ ║
┌─────────┐ └─────┐ ╘═╤═╝ ╘═══╝ ╚═══╝
│ ┌─┴─╖ │ ┌─┴─╖
│ ┌───┤ · ╟───┐ └─┤ ╟─┐
│ │ ╘═╤═╝ │ └─┬─╜ │
│ ┌─┴─╖ ╔═╧═╕ ╔═╧═╕ ┌─┴─╖ │
│ │ ❖ ╟─╢ ├─╢ ├─┤ ʩ ╟─┘
│ ╘═╤═╝ ╚═╤═╛ ╚═╤═╛ ╘═╤═╝
└───┘ ╔═╧═╗ │ ┌─┴─╖ ┌─┐
║ 0 ╟───┘ ┌─┤ ‹ ╟─┴─┘
╚═══╝ │ ╘═══╝
┌─┴─╖ ┌─┐
┌─┤ ‹ ╟─┴─┘
│ ╘═══╝
╔════╗ ┌───╖ ┌─┴─╖ ┌─┐
║ 10 ╟─┤ ʝ ╟─┤ ‹ ╟─┴─┘
╚════╝ ╘═╤═╝ ╘═══╝
│
```
First, map (`ɱ`) over the characters in the input string (`↯`) and turn each into a diamond stack using `⬖`. Take the first element off that, and fold (`ʩ`) over the rest to concatenate them all (`❖`). Finally, unpack the structure using `‹` to get to the sequence of strings and join them all (`ʝ`) using 10 (the newline) as the separator.
## Example output
**Input:**
```
crusaders
```
**[Output](https://gist.githubusercontent.com/Timwi/dfd296818c67a8b3e6a1bbaafeaa072e/raw/ccca5d2880ab9f0f88e1ad87179dca8b80796ac1/CodeGolf%252068162%2520(Visualizing%2520Words)%2520example%2520output%2520-%2520crusaders.txt)** (took 9 seconds to compute; cannot post here because size limit).
[Answer]
# Matlab, ~~466~~ 393 - 20% = 314.4 bytes
Golfed: (Could save some more bytes, also because of @AndreasDeak's help!)
```
function q(W);function z=g(l,c);[x,y]=ndgrid(abs(-l:l));z=0*y;z(~x&~y)=c;z(x+y==l)=46;end;w=W-96;n=numel(w);R=n*26;C=1;A=zeros(2*R);for k=1:n;f=sort(factor(w(k)));C=C+max(f)+1;d=-1;r=R;for F=fliplr(f);v=-F:F;while norm(A(r+v,v+C));r=r+d;end;A(r+v,v+C)=g(F,W(k));d=-d;end;C=C+max(f);end;A=A(find(sum(A,2)),find(sum(A)));f=fopen([W,'.txt'],'w');for k=1:size(A,1);fprintf(f,[A(k,:),'\n']);end;end
```
It should work in Octave (opensource) too, but only with a lot of warnings. Use this version if you want to try it in octave (output to console, instead of file):
```
function q(W);function z=g(l,c);[x,y]=ndgrid(abs(-l:l));z=0*y;z(~x&~y)=c;z(x+y==l)=46;end;w=W-96;n=numel(w);R=n*26;C=1;A=zeros(2*R);for k=1:n;f=sort(factor(w(k)));C=C+max(f)+1;d=-1;r=R;for F=fliplr(f);v=-F:F;while norm(A(r+v,v+C));r=r+d;end;A(r+v,v+C)=g(F,W(k));d=-d;end;C=C+max(f);end;A=A(find(sum(A,2)),find(sum(A)));disp([A,'']);end
```
Ungolfed and explained:
```
function q(W)
function z=g(l,c) %get a square matrix for one prime factor
[x,y]=ndgrid(abs(-l:l));
z=0*y;
z(~x&~y)=c; %character in the middle
z(x+y==l)=46; %dots
end;
w=W-96; %convert word to the corresponding indices
n=numel(w);
R=n*26; %keeps track of the main row
C=1; %keeps track of the current column
A=zeros(2*R); %make a 'canvas' matrix that is way to big
for k=1:n;
f=sort(factor(w(k))); %get all the factors of current character
C=C+max(f)+1; %update current column
d=-1; %search direction
r=R;
for F=fliplr(f);
v=-F:F;
while norm(A(r+v,v+C)); %go up or down until there is enough space to write the prime factor
r=r+d;
end;
A(r+v,v+C)=g(F,W(k)); %insert all the prime factors
d=-d;
end;
C=C+max(f);
end;
A=A(find(sum(A,2)),find(sum(A))); %truncate all the unneccessary padding
f=fopen([W,'.txt'],'w'); %write to file
for k=1:size(A,1);
fprintf(f,[A(k,:),'\n']);
end;
end
```
The requested word: (And here as a file: (zoom out a lot): [supercalifragilisticexpialidocious.txt](http://pastebin.com/raw/967RG7Se))
```
. . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . . .
. . . . . . . .
. . . . . . . . . t . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . r . . l . . r . . . . l . . . . . x . . . . l . . . . .
. . . . . p . . . . . . . . . . . . . . . . . . . p . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. s .. u .. p .. e .. r .. c ..a.. l .. i .. f .. r ..a.. g .. i .. l .. i .. s .. t .. i .. c .. e .. x .. p .. i ..a.. l .. i .. d .. o .. c .. i .. o .. u .. s .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
. . . . . p . . . . . . . . . . . . . . . . . . . . . . . . . . . . . p . . . . . . . . d . . . . . . . . .
. . . . . . . . . l . . . . f . . . . . . . . l . . . . . . . . . x . . . . . . l . . . . . . . . . . . . .
. . . . . r . . . . i . . . . r . . . i . . . . i . . . . . . i . . . . . i . . . . i . . . . . i . . . . . .
. . . . . . . . . . . . . . . . . . . . t . . . . . . . . . . . . . . . . . . .
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . o . . . . o . . . . .
. . . . . p . . . . . . . . . . . . . p . . . . . . . . . . . .
. . . u . . . . . . x . . . . . . . . u . . .
. . . . . . . . . . . . . . . .
. . . . . . . . . . .
. . . . . . . .
. . . . . .
. . . . . .
. . . . . .
. . . . . .
. . .
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 84 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
εUAyk>ÐV≠iÒDg;Y18Q-._}εXs<ú'.ìηy>j.º».∊}».c.B€SøJ•ΓXÇôнҤŨ Â<’|Ë•24вYèú»}».B€SøJćÛ»
```
[**Try it online.**](https://tio.run/##yy9OTMpM/f//3NZQx8psu8MTwh51Lsg8PMkl3TrS0CJQVy@@9tzWiGKbw7vU9Q6vObe90i5L79CuQ7v1HnV01QKpZD2nR01rgg/v8HrUsOjc5IjD7Ye3XNh7eNKhJYdbD61QONxk86hhZs3hbqCskcmFTZGHVxwG6gbphOk70n549qHd//8nJ5ak5KcDAA)
No 20% bonus, although I might try that later on. 05AB1E isn't able to write files to disk itself, but it can evaluate Python code, so I might be able to write a file to disk using Python code. It definitely won't save enough bytes to be worth the 20% bonus, though.
**Explanation:**
```
ε # Map over each letter of the (implicit) input-string
U # Pop and store the letter in variable `X`
k # Get the 0-based index
y # of the letter
A # in the lowercase alphabet
> # And increase it by 1 to make it a 1-based index
Ð # Triplicate it
V # Pop and store one in variable `Y`
≠i } # If it's NOT equal to 1 (so not 'a'):
Ò # Get all prime factors including duplicates
Dg # Get the amount of prime factors (without popping by duplicating first)
; # Halve that amount
Y18Q # Check if `Y` is 18 (1 if truthy; 0 if falsey)
- # Subtract that from halve the amount of prime factors
._ # And rotate the list of prime factors that many times towards the left
# (which only uses the integer portion and ignores the decimal values)
# (the `Dg;Y18Q-._` is to put the prime factors in the correct order,
# according to the third rule of the challenge description)
ε # Then map over each prime factor `y`:
X # Push the letter `X`
s # Swap so the prime factor is at the top again
< # Decrease it by 1
ú # Pad the letter with that many leading spaces
'.ì '# And prepend a "."
η # Then take the prefixes of this string
y> # Push the prime factor, and increase it by 1
j # Make all prefixes of equal length by padding with spaces,
# up to a length of the prime factor + 1
# (we now have the top-left portion of a diamond)
.º # Mirror each line horizontally with overlap
» # Join them by newlines
.∊ # And also mirror everything vertically with overlap
# (we now have the entire diamond)
} # After the inner map:
» # join all diamonds of the current letter with newline delimiter
.c # Centralize all lines (which pads leading spaces)
.B # Split each line on newlines as box (also adds trailing spaces)
€S # Convert each line to a list of characters
ø # Zip/transpose; swapping rows/columns
J # Join all transposed inner character-lists to a string again
•ΓXÇôнҤŨ Â<’|Ë• # Push compressed integer 384055587443514148837383584634491347
24в # Convert it to base-24 as list:
# [11,23,22,21,22,19,21,17,17,21,19,13,16,11,17,19,17,7,16,5,14,17,13,1,16,19]
Yè # Index value `Y` into this list
ú # Pad each line with that many leading spaces
» # And join them with a newline delimiter again
} # After the outer map:
» # join all diamond-towers together with newline delimiter
.B # Split each line on newlines as box (also adds trailing spaces)
€S # Convert each line to a list of characters
ø # Zip/transpose; swapping rows/columns
J # Join all transposed inner character-lists to a string again
ć # Extract head; pop and push remainder-list of lines and the first line
# (this first line is always a line consisting of only spaces,
# since the padding list was incremented by 1 for each letter)
Û # Trim all leading lines consisting of only spaces
» # And join all remaining lines with newline delimiter
# (after which it is output implicitly as result)
```
[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 `•ΓXÇôнҤŨ Â<’|Ë•` is `384055587443514148837383584634491347` and `•ΓXÇôнҤŨ Â<’|Ë•24в` is `[11,23,22,21,22,19,21,17,17,21,19,13,16,11,17,19,17,7,16,5,14,17,13,1,16,19]`.
] |
[Question]
[
You must use one language to write programs that perform the following nine tasks, **in any order you want**.
* Convert an inputted number from base 10 to base 36.
+ Sample input: `1000`
+ Sample output: `RS` (output must be upper case)
* Convert each character in a string to its base 10 decimal ASCII codes and print the codes concatenated together.
+ Sample input: `Scrambled 3GG5`
+ Sample output: `839911497109981081011002051717153`
* Determine if an inputted number is divisible by 1738.
+ Return a truthy value if it is and a falsy value if it isn't.
* Determine if a string has the letter `q` in it.
+ Return a truthy value if it does and a falsy value if it doesn't.
* Encode an inputted string of letters with a Caesar cipher of +1.
+ Case must be preserved. Non-letter characters will be printed without modification.
+ Sample input: `Good morning, World!`
+ Sample output: `Hppe npsojoh, Xpsme!`
* Find and print the sum of the prime factors of a number.
+ Sample input: `1320`
+ Sample output: `21`
* Print `PPCG`.
* Print the first `n` positive integers that are divisible by `floor(sqrt(n))`.
+ `n` is an inputted integer.
* Replace every `o` and `O` in an inputted string with `ಠ`.
+ Sample input: `Onomatopoeia`
+ Sample output: `ಠnಠmatಠpಠeia`
---
You will have noticed that this challenge is `Code Billiards`, not `Code Golf`. The objective of this challenge, like in billiards, is to set up your code so it can be modified only slightly for the next challenge. This is why your programs do not have to solve the above tasks in order.
Your score is determined as follows
* Your score goes up by `1` each byte in your programs.
* Your score goes up by `floor(n^(1.5))` if two consecutive programs have a Levenshtein distance of `n`. For example if your first program is `potato` and your second program is `taters`, your score goes up by 12 for 12 bytes and by `11`=`floor(5^(1.5))` for a Levenshtein distance of 5.
---
The objective of this challenge is to have as low a score as possible after all nine programs have been written. Standard CG rules apply.
---
To see the leaderboard, click "Show code snippet", scroll to the bottom and click "► Run code snippet". Snippet made by Optimizer.
```
/* Configuration */
var QUESTION_ID = 63675; // Obtain this from the url
// It will be like http://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 43444; // This should be the user ID of the challenge author.
/* App */
var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;
function answersUrl(index) {
return "http://api.stackexchange.com/2.2/questions/" + QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}
function commentUrl(index, answers) {
return "http://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}
function getAnswers() {
jQuery.ajax({
url: answersUrl(answer_page++),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
answers.push.apply(answers, data.items);
answers_hash = [];
answer_ids = [];
data.items.forEach(function(a) {
a.comments = [];
var id = +a.share_link.match(/\d+/);
answer_ids.push(id);
answers_hash[id] = a;
});
if (!data.has_more) more_answers = false;
comment_page = 1;
getComments();
}
});
}
function getComments() {
jQuery.ajax({
url: commentUrl(comment_page++, answer_ids),
method: "get",
dataType: "jsonp",
crossDomain: true,
success: function (data) {
data.items.forEach(function(c) {
if (c.owner.user_id === OVERRIDE_USER)
answers_hash[c.post_id].comments.push(c);
});
if (data.has_more) getComments();
else if (more_answers) getAnswers();
else process();
}
});
}
getAnswers();
var SCORE_REG = /<h\d>\s*([^\n,<]*(?:<(?:[^\n>]*>[^\n<]*<\/[^\n>]*>)[^\n,<]*)*),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;
var OVERRIDE_REG = /^Override\s*header:\s*/i;
function getAuthorName(a) {
return a.owner.display_name;
}
function process() {
var valid = [];
answers.forEach(function(a) {
var body = a.body;
a.comments.forEach(function(c) {
if(OVERRIDE_REG.test(c.body))
body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
});
var match = body.match(SCORE_REG);
if (match)
valid.push({
user: getAuthorName(a),
size: +match[2],
language: match[1],
link: a.share_link,
});
else console.log(body);
});
valid.sort(function (a, b) {
var aB = a.size,
bB = b.size;
return aB - bB
});
var languages = {};
var place = 1;
var lastSize = null;
var lastPlace = 1;
valid.forEach(function (a) {
if (a.size != lastSize)
lastPlace = place;
lastSize = a.size;
++place;
var answer = jQuery("#answer-template").html();
answer = answer.replace("{{PLACE}}", lastPlace + ".")
.replace("{{NAME}}", a.user)
.replace("{{LANGUAGE}}", a.language)
.replace("{{SIZE}}", a.size)
.replace("{{LINK}}", a.link);
answer = jQuery(answer);
jQuery("#answers").append(answer);
var lang = a.language;
lang = jQuery('<a>'+lang+'</a>').text();
languages[lang] = languages[lang] || {lang: a.language, lang_raw: lang, user: a.user, size: a.size, link: a.link};
});
var langs = [];
for (var lang in languages)
if (languages.hasOwnProperty(lang))
langs.push(languages[lang]);
langs.sort(function (a, b) {
if (a.lang_raw.toLowerCase() > b.lang_raw.toLowerCase()) return 1;
if (a.lang_raw.toLowerCase() < b.lang_raw.toLowerCase()) return -1;
return 0;
});
for (var i = 0; i < langs.length; ++i)
{
var language = jQuery("#language-template").html();
var lang = langs[i];
language = language.replace("{{LANGUAGE}}", lang.lang)
.replace("{{NAME}}", lang.user)
.replace("{{SIZE}}", lang.size)
.replace("{{LINK}}", lang.link);
language = jQuery(language);
jQuery("#languages").append(language);
}
}
```
```
body { text-align: left !important}
#answer-list {
padding: 10px;
width: 290px;
float: left;
}
#language-list {
padding: 10px;
width: 290px;
float: left;
}
table thead {
font-weight: bold;
}
table td {
padding: 5px;
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b">
<div id="language-list">
<h2>Shortest Solution by Language</h2>
<table class="language-list">
<thead>
<tr><td>Language</td><td>User</td><td>Score</td></tr>
</thead>
<tbody id="languages">
</tbody>
</table>
</div>
<div id="answer-list">
<h2>Leaderboard</h2>
<table class="answer-list">
<thead>
<tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
</thead>
<tbody id="answers">
</tbody>
</table>
</div>
<table style="display: none">
<tbody id="answer-template">
<tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
<table style="display: none">
<tbody id="language-template">
<tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr>
</tbody>
</table>
```
[Answer]
# [Japt](https://codegolf.stackexchange.com/a/62685/42545), ~~886~~ ~~866~~ ~~766~~ ~~725~~ ~~688~~ 669
Tasks 5 and 6 are killers. Perhaps there are shorter ways to get them done. I think the Levenshtein distances could still be reduced as well.
* Task 3 (divisiblity): `!(U%#ۊ`
7 bytes (arabic char messes up alignment)
* Task 4 ('q' check): `U!=Uk'q` 7 bytes, dist 11
* Task 1 (base conversion): `Us36 u` 6 bytes, dist 14
* Task 2 (ASCII codes): `UmX=>Xc` 7 bytes, dist 14
* Task 7 (see for yourself): `"PPCG"` 6 bytes, dist 18
* Task 9 (ಠ replacement): `Ur"[Oo]",'ಠ` 13 bytes, dist 27
* Task 8 (floor(sqrt(n))): `X=Uq f;XoU*X+1,X` 16 bytes, dist 52
* Task 6 (prime factor sum): `2oU fX=>2oX eY=>X%Y &&!(U%X)r(X,Y =>X+Y` 39 bytes, dist 172
* Task 5 (Caesar cipher): `UmX=>128o mY=>Yd)a k'A i#Z,'A k'a i#z,'a gXc` 44 bytes, dist 216
Here's a snippet that will tell you (one of) the most efficient ways to arrange your programs:
```
function L(s,t) {
if(s == t) return 0;
if(s.length === 0) return t.length;
if(t.length === 0) return s.length;
var v0 = Array(t.length+1),
v1 = Array(t.length+1);
for(var i=0; i<v0.length; i++) v0[i]=i;
for(i=0; i<s.length; i++) {
v1[0]=i+1;
for(var j=0; j<t.length; j++)
v1[j+1] = Math.min(v1[j]+1, v0[j+1]+1, v0[j]+(s[i]==t[j]?0:1));
for(j=0; j<v0.length; j++) v0[j]=v1[j];
}
return v1[t.length];
}
function run(x) {
R.innerHTML='';
var b={}, k=0, min=1/0, item='';
for(var i in x) {
for(var j in x.slice(+i+1)) {
k=b[i+(+i+(+j)+1)]=b[(+i+(+j)+1)+i]=L(x[+i],x[+i+(+j)+1]);
if(k<min) min=k, item=i+(+i+(+j)+1);
}
}
var order=item, q=10;
while(order.length < x.length && q--) {
min=1/0, item='';
for(i in b) {
if(b[i]<min) {
if(i[0]==order.slice(-1) && order.indexOf(i[1])==-1)
min = b[i], item = i[1];
}
}
order+=item;
}
var score=0,y=0;
function getByteCount(s){return(new Blob([s],{encoding:"UTF-8",type:"text/plain;charset=UTF-8"})).size}
console.log("Task",(+order[0]+1)+":",y=getByteCount(x[order[0]])),score+=y
for(i in order.slice(1))
console.log(" ",y=Math.pow(b[order[i]+order[+i+1]],1.5)|0),score+=y,
console.log("Task",(+order[+i+1]+1)+":",y=getByteCount(x[order[+i+1]])),score+=y;
console.log("Total:",score)
}
console.log = function(){R.innerHTML+=Array.prototype.slice.call(arguments).join(' ');R.innerHTML+='<br>'};
```
```
<p>Input programs here, one per line:</p>
<textarea id=O rows="9" style="width:90%"></textarea><br>
<button onclick="run(O.value.split('\n'))">Run</button>
<p id=R></p>
```
With the [latest version of Japt](https://tio.run/nexus/japt) (non-competing in this challenge), most tasks get shorter:
* Task 1: `s36 u` 5 bytes
* Task 2: `mc` 2 bytes
* Task 3: `v#ۊ`
4 bytes
* Task 4: `oq` 2 bytes
* Task 5: `;B±B+C²UrF,@Bg1+BbX` 19 bytes
* Task 6: `k â x` 5 bytes
* Task 7: `"PPCG` 5 bytes
* Task 8: `B=U¬f)oU*B+1B` 13 bytes
* Task 9: `ro'ಠ'i` 6 bytes
The optimal order is now 2,4,3,1,6,7,9,8,5, coming in at a whopping score of **217**, less than one-third of the original!
Suggestions welcome!
[Answer]
# Pyth, score 489
Base conversion: 15
```
s@L+s`MTrG1jQ36
```
Caesar Cipher: 13 + 11^1.5
```
u.rGHrBG1z 36
```
Divisible by 1738: 7 + 11^1.5
```
!%Q1738
```
First N positive integers: 8 + 8^1.5
```
*Rs@Q2SQ
```
Sum of prime factors: 4 + 6^1.5
```
s{PQ
```
Appearance of q in string: 4 + 4^1.5
```
}\qz
```
Join all ASCII codes: 5 + 4^1.5
```
jkCMz
```
Print "PPCG": 5 + 5^1.5
```
"PPCG
```
Replace with `ಠ`: 9 + 7^1.5
```
Xz"oO"\ಠ
```
[Answer]
# Ruby, 1488
Probably a lot of room for improvement here. Spent most of the time calculating the score...
*Sum of prime factors*: 64
```
require'prime';p gets.to_i.prime_division.reduce(0){|s,a|s+a[0]}
```
*Base 36*: 30 + 471.5 = 352
```
puts gets.to_i.to_s(36).upcase
```
*Divisible by 1738*: 22 + 151.5 = 80
```
puts gets.to_i%1738==0
```
*Print PPCG*: 9 + 181.5 = 85
```
puts:PPCG
```
*Does string contain `q`?*: 10 + 81.5 = 32
```
p gets[?q]
```
*Replace `o`*: 23 + 161.5 = 87
```
puts gets.gsub(/o/i,?ಠ)
```
*Ceasar cipher*: 32 + 211.5 = 128
```
puts gets.tr 'A-Za-z','B-ZAb-za'
```
*ASCII codes*: 37 + 261.5 = 169
```
puts gets.chomp.chars.map(&:ord).join
```
*Integers divisible by square root*: 72 + 561.5 = 491
```
puts *(1..1/0.0).lazy.select{|i|i%Math.sqrt(i).floor==0}.take(gets.to_i)
```
[Answer]
# Java, score 8331
Them levenshtein distances are killing my score here.
(These programs take input as command line arguments)
Program 1 (119):
```
class L{public static void main(String[]a){System.out.print(Integer.toString(Integer.parseInt(a[0]),36).toUpperCase());}}
```
Program 2 (120+561.5=539):
```
class L{public static void main(String[]a){/*System.out.print*/for(char b:a[0].toCharArray())System.out.print((int)b);}}
```
Program 3 (101+491.5=444):
```
class L{public static void main(String[]a){System.out.print/*for*/(Integer.parseInt(a[0])%1738==0);}}
```
Program 4 (108+201.5=197):
```
class L{public static void main(String[]a){System.out.print(/*forInteger.parseInt(*/a[0].indexOf('q')>=0);}}
```
Program 5 (186+1071.5=1293):
```
class L{public static void main(String[]a){for(char b:a[0].toCharArray())System.out.print(Character.isLetter(b)?Character.isUpperCase(b)?b>'Y'?'A':(char)(b+1):b>'y'?'a':(char)(b+1):b);}}
```
Program 6 (327+2281.5=3747):
```
class L{public static void main(String[]a){int i,k=0,j=i=Integer.parseInt(a[0]);for(;i>0;i--)if(p(i)&&j%i==0)k+=i;System.out.print(k);}static boolean p(int n){if(n<2)return 0>0;if(n==2||n==3)return 1>0;if(n%2==0||n%3==0)return 0>0;int i,k=(int)Math.sqrt(n)+1;for(i=6;i<=k;i+=6)if(n%(i-1)==0||n%(i+1)==0)return 0>0;return 1>0;}}
```
Program 7 (336+101.5=368)
```
class L{public static void main(String[]a){/*int i,k=0,j=i=Integer.parseInt(a[0]);for(;i>0;i--)if(p(i)&&j%i==0)k+=i;*/System.out.print("PPCG");}static boolean p(int n){if(n<2)return 0>0;if(n==2||n==3)return 1>0;if(n%2==0||n%3==0)return 0>0;int i,k=(int)Math.sqrt(n)+1;for(i=6;i<=k;i+=6)if(n%(i-1)==0||n%(i+1)==0)return 0>0;return 1>0;}}
```
Program 8 (351+341.5=549):
```
class L{public static void main(String[]a){int i,k=1,j=(int)Math.sqrt(i=Integer.parseInt(a[0]));for(;k<i;k++)/*if(p(i)&&j%i==0)k+=i;*/System.out.println(j*k);}static boolean p(int n){if(n<2)return 0>0;if(n==2||n==3)return 1>0;if(n%2==0||n%3==0)return 0>0;int i,k=(int)Math.sqrt(n)+1;for(i=6;i<=k;i+=6)if(n%(i-1)==0||n%(i+1)==0)return 0>0;return 1>0;}}
```
Program 9 (305+841.5=1075):
```
class L{public static void main(String[]a){int i,k=1,j=0;System.out.print(a[0].replaceAll("o|O",""+(char)3232));}static boolean p(int n){if(n<2)return 0>0;if(n==2||n==3)return 1>0;if(n%2==0||n%3==0)return 0>0;int i,k=(int)Math.sqrt(n)+1;for(i=6;i<=k;i+=6)if(n%(i-1)==0||n%(i+1)==0)return 0>0;return 1>0;}}
```
[Answer]
## Pyth, score 817
number 1: 24
```
Jjk+UTrG1VjKvz36=+k@JN;k
```
number 2: (9 + 161.5 = 73)
```
Vz=+kCN;k
```
number 3: (5 + 81.5 = 27)
```
/QC"ۊ
```
number 4: (5 + 141.5 = 57)
```
hxz\q
```
number 5: (39 + 371.5 = 264)
```
J+GrG1VzIhxJNKChCNIhxJKpK)EpC-CK26))EpN
```
number 6: (4 + 391.5 = 247)
```
s{PQ
```
number 7: (5 + 41.5 = 13)
```
"PPCG
```
number 8: (12 + 121.5 = 53)
```
VK/@Q2 1*KhN
```
number 9 (13 + 131.5 = 59)
```
j\ಠcj\ಠcz\o\O
```
Not the best, I just started learning pyth today and thought I'd give it a try, number 5 really killed my score, I think I can get a few of them shorter but That will just hurt me more on the distances. Any tips from more experienced pyth users are appreciated.
[Answer]
# Python 3 (currently invalid), 621 bytes
```
from numpy import base_repr
import math
print(base_repr(int(input()),36))
print("".join([str(ord(c)) for c in input()]))
if int(input())%1738 == 0:print(True)
else:print(False)
if "q" in input().lower():print(True)
else:print(False)
t=bytes.maketrans(b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",b"bcdefghijklmnopqrstuvwxyzaBCDEFGHIJKLMNOPQRSTUVWXYZA")
print(input().encode("utf-8").translate(t).decode("utf-8"))
print("PPCG")
n=int(input())
for i in range(1,n):
if i%math.floor(i**0.5)==0:print(i,end=" ")
print("")
y=input()
z=""
for i in y:
if i.lower()=="o":z+="0"
else:z+=i
print(z)
```
Not really that good code but somewhat works :D.
The sum of prime factors is not working. I always get a different result from your example so I removed it.
Also Python does not support the char `ಠ` so instead it replaces the `o`s with `0`s
IO INFO:
1st input: int in base 10 | Output: that number in base 36
2nd input: a string | Output: Ascii numbers of the string
3rd input: integer | Output: True or False depending if number is dividible by 1738
4th input: string | Output: T or F depending if the string has "q" in it
5th input: string | Output: Caser Cipher +1 of the string
6th: just prints "PPCG" literally
7th input: int n | Output: first n ints divisible by floor(sqrt(n))
8th input: string | Output: Replaced all `o`s with 0 (not with ಠ because python does not support that character, don't get too mad :) )
] |
[Question]
[
*This is a [cops-and-robbers](/questions/tagged/cops-and-robbers "show questions tagged 'cops-and-robbers'") challenge. Answer here if you are a cop (crossword maker), answer the [companion question](https://codegolf.stackexchange.com/q/40305/26997) if you are a robber (crossword solver). You may take on both roles.*
# Cops (Puzzlers)
Your task is to write a 10×10 [crossword puzzle](http://en.wikipedia.org/wiki/Crossword) where, instead of words or phrases, snippets of code are the solutions to clues. Each clue will be a nonempty sequence of characters such that running the snippet of code it refers to will print the sequence to stdout.
Your post must include three things:
1. Your **blank** 10×10 crossword grid, using `#` for *darks* (clue separators) and `_` for *lights* (cells to be filled in).
* Every horizontal or vertical sequence of 2 or more lights (bounded by darks or the grid edge) is an entry you must write a clue for. For convenience you should number these in the usual way (left-to-right, top-to-bottom) by replacing the `_` at the start of each entry with a unique character identifier (e.g. 1, 2,..., A, B,...).
* Your grid may have any number of darks.
* Your grid may have any number of clues.
* Horizontal entries are always read left-to-right and vertical ones top-to-bottom.
2. A list of clues that contains every entry in your crossword, down and across.
* Clues must contain at least 1 and no more than 10 characters.
* If your clues contain spaces make sure they are obvious when you format your post.
3. *Header* and *footer* code snippets, each 20 characters or less.
* These run respectively before and after a solution snippet, and may help in renaming long built-ins and such.
The procedure for ensuring a clue matches its corresponding code snippet is:
1. Concatenate the header, the snippet, and the footer: `[header][snippet][footer]`.
2. Run this as a normal program (independent of past runs) and look at what was printed to stdout.
3. If this matches the clue the snippet is a valid solution.
For simplicity you may only use [printable ASCII](http://en.wikipedia.org/wiki/ASCII#ASCII_printable_characters) (hex codes 20 to 7E) throughout. The header and footer alone may also contain tabs and newlines.
### Additional Notes
* For any snippet, running `[header][snippet][footer]` should not take more than a minute on a [decent modern computer](https://teksyndicate.com/forum/general-discussion/average-steam-users-computer-specs/150190).
* You must specify your programming language (and version).
* You may not use any common hashing algorithms.
* You may not use external libraries.
* Everything in your code must be deterministic, time invariant, and not need a network connection.
* `#` and `_` may occur in snippets (or anywhere else).
* You may reveal some of the characters in the crossword as [COTO has done](https://codegolf.stackexchange.com/a/40309/26997). They still count as lights. Robbers are not required to use these, they are just nice hints.
### Example
A simple example using Python 3. Header: `p=print;t=5;`. No footer.
Unsolved grid:
```
##########
1___2___##
_###_#####
_###_#####
_###_#####
####_#####
####_#####
###3______
####_#####
####_#####
```
Clues:
```
ACROSS
1: 8
3: A!
DOWN
1: 7
2: 10
```
Valid solution:
```
##########
print(8)##
(###+#####
7###=#####
)###5#####
####;#####
####p#####
###p('A!')
####t#####
####)#####
```
# Robbers (Solvers)
Your task is to solve the crosswords posted by the cops. You must use the same exact programming language as the crossword was given in, but otherwise any solution that matches all the clues is valid.
You may not solve your own crosswords, and you may only attempt to answer each of the other crosswords once.
Remember to post your solutions in the [companion question](https://codegolf.stackexchange.com/q/40305/26997).
# Scoring
If a crossword is solved within 72 hours it is no longer in the running. Once a crossword has lasted unsolved for 72 hours it is considered immune and the creator may post the solution (by editing their post and marking it immune).
The winning cop is the user who submitted the immune crossword with the fewest darks (`#`). In case of ties the highest voted submission wins. The solution must be posted for the answer to be accepted.
The winning robber is the user who solves the most crosswords. The tie-breaker is their sum of up-votes in the [companion question](https://codegolf.stackexchange.com/q/40305/26997).
[Answer]
# JavaScript, 0 darks – immune
```
__________
|123456789A|
|B |
|C |
|D |
|E |
|F |
|G |
|H |
|I |
|J |
----------
```
Here is the solution for all of you:
```
__________
|~709-51+90|
|-0x33-31&8|
|8-42^07*70|
|306%4+0x34|
|0xb1204%51|
|-1+2+x>h--|
|'4'*32>>07|
|Math.E>2.7|
|8/2-1-7*22|
|'6'-025036|
----------
```
```
Header: var h=8,x=5;console.log(
Footer: );
```
## Clues
```
Across
1. -671
B. 8
C. -460
D. 54
E. 33
F. false
G. 1
H. true
I. -151
J. -10776
Down
1. NaN
2. 15
3. "1131t2"
4. 64
5. -48
6. 49
7. 6
8. true
9. 8
A. 315
```
Let me know if you think there are any results that I miscalculated.
[Answer]
# CJam, 41 darks - [solved by Martin Büttner](https://codegolf.stackexchange.com/a/40329/16402)
No header, footer or reserved squares. Let me know of any potential bugs.
The solution I originally had in mind had no whitespace - it is not the one that Martin Büttner found.
## Board
```
#5###6#7__
#4_3____##
1##_#_#_#A
2____##_#_
_##_##9___
_##_#E#_#_
_#C#8_____
##_#_####_
##B_______
D__#_####_
```
## Clues
**Across**
```
2: [[4 3]]
4: 24717
7: 32
8: E
9: "" (there is ONE trailing space after the quotes)
B: "m
D: 124
```
**Down**
```
1: [2 2 2 3]
3: 3010936384
5: 2017
6: "18"
7: ' "\"\""
8: !{}
A: -3u3
C: -1
E: Stack: ""
```
Good luck!
[Answer]
# C - 26 darks, 5 reserved - solved by [feersum](https://codegolf.stackexchange.com/questions/40305/code-crosswords-solutions/40337#40337)
```
Clue # Reserved
+----------+ +----------+
|1_2__3_#4_| |" # |
|_#_##_#5_#| | # ## # #|
|6___7_8___| | 8 |
|_#_#9____#| | # # #|
|_#AB_#C___| | # # |
|D_#E_____#| | # #|
|_#F#_#_#_#| | # # # # #|
|_#GH__#I__| | # # |
|_##J_#K#_#| | ## # # #|
|L___#M____| |2 * # _ |
+----------+ +----------+
```
### Header
```
z[4]={9};main(_){_=
```
### Footer
```
;printf("%d",_);}
```
### Clues
```
ACROSS:
1. 48
4. -8
5. -2
6. 0
9. 73
A. 9
C. 0
D. 5
E. 0
G. -2
I. 0
J. 0
L. 18
M. 6247483
DOWN:
1. 45
2. 7680
3. 22
4. -97
5. 0
7. -1073741824
8. 8
B. 0
F. 42
H. 0
K. -2
```
[Answer]
# MATLAB - 28 Darks
## Solved by [feersum](https://codegolf.stackexchange.com/a/40370/31019)
### Boards
```
CLUE # RESERVED
__________ __________
|12 3 4 5 | | [ |
|# # # # ##| |#s# # # ##|
|6 # #7 8| | # # |
|# # # # # | |# # # # # |
|9 A | |6 7 y |
|#B # # # | |# # # # |
|C | | g |
|# # ### # | |# # ### # |
|# # ##D # | |# # ## # |
|E | |d |
¯¯¯¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯¯¯¯
```
**Header**
```
g=4;o=magic(3);disp(
```
**Footer**
```
);
```
### Clues
**Across**
* 1 `2`
* 6 `-1i`
* 7 `eye(3)`
* 9 `0`
* B `sqrt(-1)`
* C `1/25000`
* D `0`
* E `[0;0;0]`
**Down**
* 2 `log(1i)`
* 3 `100`
* 4 `10^16`
* 5 `[2,2;2,2]`
* 8 `512`
* A `inv(1i)`
* D `zeros(3)`
Note that I've changed things up slightly in the clues for this puzzle. Since MATLAB outputs are invariably verbose (for example, even printing the imaginary unit `1i` exceeds 10 characters [`0 + 1.0000i`]) and change depending on the default output format, the clues are all simple expressions whose *displayed output is equivalent to that of the corresponding solutions*.
In other words, you can consider an actual clue to be `disp( CLUE )`, where `CLUE` is the 10-character-or-less clue in the above lists.
Hopefully Calvin doesn't mind. I don't believe this violates the spirit of the clue length rule, which is likely to prevent crossword builders from inserting extremely-hard-to-generate solutions (i.e. words).
### Key
```
KEY
__________
|max([1 2])|
|#s#1#0#*##|
|1i^3#*#o\o|
|#n#+#1#n#(|
|6 -7+eye&1|
|#(i)#1#s# |
|.1 ^ 5*(g)|
|#)#2### #^|
|#*#/##~2# |
|diag(-o)>3|
¯¯¯¯¯¯¯¯¯¯
```
[Answer]
# Python
## Solved by [feersum](https://codegolf.stackexchange.com/a/40421/4020)
Here's one to start us off. I used Python 2.7.8 to obtain the clues. Good luck :)
I've revealed the last snippet since hashing is now disallowed. Also, the grid has 36 darks (I missed the scoring part when I made it).
I've revealed a few more characters to make it easier, but different solutions are fine too.
Crossword grid:
```
1_234##5## * . ## ##
_#6_______ # e /
_#7__##_## # * ##6##
8________# 3 % #
##_#_##_## ##5# ## ##
#9________ #a * b
##_#_##_## ## # ## ##
A________# b 7 1 #
##_####_## ## #### ##
#hash('9') #hash('9')
```
Clues:
```
ACROSS
1: 440380.9
6: 12328.7671
7: 72
8: 4519217.0
9: 79920L
A: 1.55826556
B: 7296021944
DOWN
1: 1211477643
2: 17353.0
3: 5.4
4: 1719.0
5: 7514613.78
```
Header:
```
a=49481
b=97381
x=
```
Footer:
```
print`x`[:10]
```
[Answer]
# Javascript ES4 - 37 Darks, 10 Reserved
## Solved by [bazzarg](https://codegolf.stackexchange.com/a/40333/31019)
### Boards
```
CLUE # RESERVED
__________ __________
|1 2 ###3#| | ### #|
| ## #45 | | ## #I 4|
| ## ## # #| |:##-## # #|
|6 #| | #|
| ## ## # #| | ## ##.# #|
|7 | | ]|
| ## ## ###| | ## ## ###|
|8 #9 | | + # - |
| ## ## ###| |'## ## ###|
| ##A | | ## 4 |
¯¯¯¯¯¯¯¯¯¯ ¯¯¯¯¯¯¯¯¯¯
```
**Header**
```
a=3;I=9;t=
```
**Footer**
```
;console.log(t);
```
### Clues
**Across**
* 1 `51`
* 4 `true`
* 6 `8.14159265` ...
* 7 `"90"`
* 8 `0`
* 9 `-10`
* A `"HI"`
**Down**
* 1 `5`
* 2 `"2pac"`
* 3 `3072`
* 5 `false`
Note that I've included a second representation of the board marked "reserved" to indicate ten lights with characters already filled in. These are to assist the solver and to restrict/disambiguate the possible solutions. I'm not sure whether Calvin wants to count these as darks or lights.
I've used the two separate representations since some of the filled-in characters are numbers and might be confused for clue numbers, and to declutter the board generally.
There are no whitespace characters in any of the solutions, although you're welcome to fill lights with whitespace characters if they work.
**Original Solution**
>
> `__________
> |{},51###6#|
> |a##+#I/a<4|
> |:##-##[#<#|
> |5+Math.PI#|
> |}##+##.#+#|
> |[I+"0"][0]|
> |'##p##/###|
> |a+-a#a=~-I|
> |'##c##=###|
> |]##"\x48I"|
> ¯¯¯¯¯¯¯¯¯¯`
>
>
>
As it turns out, bazzarg's solution for 9 across has the `-` in the wrong place, but the clue was supposed to be `10` instead of `-10` (the clue and answer were originally different and I made the switch hastily). Hence we'll just say that two wrongs do make a right in this case. ;)
[Answer]
## Python 2, 0 darks - Immune
Python 2 is only because of the `print` in the footer. It should work the same way in Python 3 if you change the `print` statement.
I had fun making this, and overall I'm satisfied and a bit excited about the final result.
Let me know if you think my footer is too cruel (if I knew you could refrain from using a program to brute force it, I'd remove the cruelty.) Fun fact: the variables in the header spell 'bread'.
```
__________
|123456789A|
|B |
|C |
|D |
|E |
|F |
|G |
|H |
|I |
|J |
----------
```
**Header:**
```
b=7;r=3;e=6;a=.1;d=
```
**Footer:**
```
;print 2*str(d)[::3]
```
---
## Clues:
**Across**
```
1. 74
B. 282.e2
C. 77
D. 8
E. 94
F. 247351.862e1
G. 99
H. -5312-5312
I. -32
J. 300000
```
**Down**
```
1. 61000
2. 251
3. 09333.8333
4. 7878
5. -70
6. -0045.164
7. 88
8. 61225
9. -350
A. 69971
```
---
**Solution**
>
> `__________
> |r+111-37-r|
> |'2.48e+22'|
> |6+765-0*56|
> |30/7%140*2|
> |0xe6b/0x27|
> |18**+9.1-9|
> |047--01551|
> |04/-7.0131|
> |0-1512%989|
> |'30000700'|
> ----------`
>
>
>
] |
[Question]
[
# Rolling a 1x1x2 block
This challenge is inspired by the game Bloxorz. Like that game, there is a 1x1x2 block, which may be moved on a square grid in any of the four cardinal directions. It moves by rotating 90 degrees about one of its edges which is touching the ground. Initially, the block is standing upright on a single square in a square grid. After some sequence of moves, determine whether it is:
* Standing upright on the starting square,
* Laying half-on, half-off the starting square, or
* Not on the starting square at all.
## Input
Input is given as a string consisting of the characters `F`, `B`, `L`, and `R`, which represent moving forward, backward, left, and right.
## Output
Output can be 1, 0.5, or 0, representing the fraction of the block resting on the starting square. Your program may use some other set of three distinct outputs, as long as they consistently represent the three possibilities.
## Test cases
```
"FFFBBB" -> 1
"" -> 1
"FRRRBLL" -> 1
"FRBL" -> 0.5
"FRBBL" -> 0
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 111 bytes
*-3 thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan), and -2 from there*
Expects an array of ASCII codes. Returns \$0,1,2\$ instead of \$0,1/2,1\$.
```
a=>a.map(d=>o=(p[d<76|0]+="011343011334"[o+=d%7%4*3]-2,2-o%9&7)%3,p=[o=0,0])|o?3>>p[o-1]+1&!p[2-o]:(p=='0,0')*2
```
[Try it online!](https://tio.run/##RZDLboMwEEX3fIWLRGICOAbToD6GqlRlxYqt5YVlQtIqzVgQdZV/pyYP9S5Go3PPZuZb/@rRDF/2lByx2049TBpKzX60pR2UCNTK7rXYnLmKwOdpKnIxT5H7EiPogiLIV0IlWZwlGDwtijAQsQWJwGOuwjO@ibK0EpNUReniwUqnqWdqAZZOWIarbHqRHiF@XddVVfkxIes1SWcy79fcSd22bdU0rvgnVXP1HOHs8cYcvDNPeazH4VObPR0JlMTgccTDlh1wR3sqGWOjupxrLi0zez18uFe8n2g4Z/oD "JavaScript (Node.js) – Try It Online")
### How?
We keep track of the orientation \$o\in[0,1,2]\$ of the rolling block and the position \$p=(x,y)\$ of its top-left cube as described in this diagram:
[](https://i.stack.imgur.com/ViD88.png)
Given the ASCII code \$d\$ of a direction character, we can turn it into a value in \$[0,1,2,3]\$ by reducing it modulo \$7\$ and then modulo \$4\$. To determine whether it's a vertical or horizontal move, we can simply test \$d<76\$.
| Character | d = ASCII code | d mod 7 | (d mod 7) mod 4 | d < 76 |
| --- | --- | --- | --- | --- |
| "B" | 66 | 3 | 3 | true |
| "F" | 70 | 0 | 0 | true |
| "L" | 76 | 6 | 2 | false |
| "R" | 82 | 5 | 1 | false |
We use a lookup string of digits in \$[0\dots4]\$ to get either \$dx+2\$ or \$dy+2\$:
```
p[d < 76 | 0] += "011343011334"[o += d % 7 % 4 * 3] - 2
```
The new orientation is given by the following magic formula (found by Steffan):
```
o = (2 - o % 9 & 7) % 3
```
Once all iterations have been processed, the test to be applied depends on the final value of \$o\$.
```
o ?
3 >> p[o - 1] + 1 & !p[2 - o]
:
(p == '0,0') * 2
```
* \$o=0\$ : return \$2\$ if \$x=0\$ and \$y=0\$, or \$0\$ otherwise
* \$o=1\$ : return \$1\$ if \$y=0\$ and \$x\in[-1,0]\$, or \$0\$ otherwise
* \$o=2\$ : return \$1\$ if \$x=0\$ and \$y\in[-1,0]\$, or \$0\$ otherwise
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~78~~ 43 bytes
```
≔UV1jθ≔E²θηFESXθ⌕FRBιUMη⁺κ×ι⊕№⁺⁻ηι…ηλκI⊘№ηθ
```
[Try it online!](https://tio.run/##PY7BqsIwEEX3fsXQ1RTi4r3tW2mwKCiU6g@EGk00ndQk7cOvjxMRZzGLcw@X2xsVeq9czqsY7ZWwfSbjaTMrN6mksfq5VbWAR/23@AgHNeJvIQIM04sP8GY7Gqd0TMHSFTlr/b8O@BDQWDpj1XTrSoCt@YBt6YdBMTcsuiniXcDJDjqiFbCjPuhBU9JnlH6ihG/lYIm/KSUC5LN3Who/FuBqJvdSzXtaHpBQqphwq9z87TBlcjFybrquW@/3eTm7Fw "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔UV1jθ
```
Get `i` (square root of `-1`) into a variable.
```
≔E²θη
```
Start off with both cubes of the block on the starting square, which I've chosen to be `i` as it's golfier that way.
```
FESXθ⌕FRBι
```
Convert the movements into powers of `i` (`F = 1, R = i, B = -1, L = -i`) and loop over them.
```
UMη⁺κ×ι⊕№⁺⁻ηι…ηλκ
```
Calculate which cube (if any) needs to move two squares (if both cubes were on the same square then I move the second cube two squares otherwise if one cube would have moved onto the square the other cube vacated then that cube moves two squares so that both cubes end up on the same square) and move the cubes appropriately.
```
I⊘№ηθ
```
Output half of the number of cubes that have returned to the starting square.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 39 bytes
Maybe there is a clever string replacement or complex number algorithm that'll crush this score?
```
NÑN
=ḞḢH‘ɓ+0¦
ṚÇṚ
Ṛ1ĿṚ
⁹Ŀ
O:5%6çƒØ0AṀ«1
```
A full program which accepts the string and prints \$0\$ (standing at the origin), \$\frac{1}{2}\$ (covering the origin, but laying down), or \$1\$ (neither).
**[Try it online!](https://tio.run/##y0rNyan8/9/v8EQ/LtuHO@Y93LHI41HDjJOTtQ0OLeN6uHPW4XYgAWIYHtkPYj1q3HlkP5e/lamq2eHlxyYdnmHg@HBnw6HVhs7///9XCnJz83ELAkInHycQCnLycVMCAA "Jelly – Try It Online")**
### How?
Starts at \$[0,0]\$ and executes the string as instructions tracking coordinates of the centre of the block (i.e. executing `F` would lead to \$[0,1.5]\$) then inspects the resulting position.
Note, right and left are actually mirrored to make the code slightly shorter, so executing `R` would lead to \$[-1.5, 0]\$.
```
NÑN - Link 1 (B): [x, y]
N - negate
Ñ - call the next Link (Link 2) as a monad
N - negate
=ḞḢH‘ɓ+0¦ - Link 2 (F): [x, y]
Ḟ - floor -> [floor(x), floor(y)]
= - ([x, y]) equals? (that) (vectorises)
Ḣ - head -> x eqauls floor(x)?
H - halve
‘ - increment -> 1 if rolling or 1.5 if toppling or erecting
ɓ - start a new chain with swapped arguments
0¦ - apply to index 0 (the y of [x, y])
+ - add
ṚÇṚ - Link 3 (L): [x, y]
Ṛ - reverse
Ç - call the last Link (Link 2) as a monad
Ṛ - reverse
Ṛ1ĿṚ - Link 4 (R): [x, y]
Ṛ - reverse
Ŀ - monadic call to Link:
1 - 1
Ṛ - reverse
⁹Ŀ - Link 5 (call correct function): location [x, y]; instruction N
Ŀ - monadic call to Link:
⁹ - chain's right argument = N
- ...i.e. call Link N with argument [x, y]
O:5%6çƒØ0AṀ«1 - Main Link: list of characters, S
O - ordinals (S) e.g. "BFLR" ->[66,70,76,82]
:5 - integer divide by five ->[13,14,15,16]
%6 - mod six ->[ 1, 2, 3, 4]
į0 - starting with [x,y]=[0,0] reduce that using:
ç - call the last Link (Link 5) as a dyad
A - absolute values (that)
Ṁ - maximum
«1 - minimum of that and one
```
[Answer]
# [Python 3.8+](https://docs.python.org/3.8/), 173 bytes
```
f=lambda s,c=[0,0]:f(s[1:],[v*n for v in(lambda x,y:[x,y+1.5-x%1])(*[w*n for w in c[::r]])[::r]])if s and[n:=2*(s[0]in"BL")-1,r:=2*(s[0]in"RL")-1]else min(1,max(map(abs,c)))
```
A recursive function that accepts a string ,`s`, and returns \$0\$ (standing at the origin), \$\frac{1}{2}\$ (covering the origin, but laying down), or \$1\$ (neither).
**[Try it online!](https://tio.run/##bVJNb6MwEL3zK2ZZdbFToNAPaYXEHjjklFOOS1DlJqbxigyR7XxUVX97dgxOy0o7B8DvPc@8eWL/Zrc9Pvzc68ulLTuxe9kIMPG6rLM4a4qWmTovmrg@zhDaXsMRFDIvO8dvRU2P2zx9Ss43ecPZrD554YmEsK6LQjcN9y/VggGBmxqL8n5GrbNGYVgtQp7ksZ5iywFrZGck7GhiHu/Eme3EnokXcsc5v1hprIESWABU4Xw@r6oqjOn7e/IL8hEdzmNN0PlyuawWC0f@g1YLr3dolj594ldiwAMeuAXdfLfj4KMYpHut0LI2Ct8d@BECyd9b5g78I@JBMAqiFSZJssIV/pa6N8CEhV6rV4XcpQNb0R0lwSMGP0Bs/oi1RMvTNF2ha7SRLc22z7Z/VmisPqyt6tEw5KMTLV00UTQcTlvVScCRcYWQlH7rq/i2pEUrir3Gm8dmory7K@HR97QHjU4dDAGg214LfJUsz1z52VNDZOL/Nq8uD50lTcum9EjSz@L5b2T2y/xXyNM7PuzxBmV9@Qs "Python 3.8 (pre-release) – Try It Online")**
[Answer]
# [J](http://jsoftware.com/), 54 bytes
```
1#.0=&><@0 0(2$]-.~]+(*1,1+=/))&.>/@,~0j1<@^'RFLB'i.|.
```
[Try it online!](https://tio.run/##Vc7BCoJAEAbg@zzFZNG6qetuUKCoyAZ7kg57Nw9hZYc8KOEhfHUzy6yBYf5vTv@182a@SLcz3yMEDEZOGPpI0EaOfr8Ow51OVCfmjIfLKIg5cnO9SB3Wppa5ErawQpfSJYvc2G75VQTxgWiVSFKwB@so5MdLiSckSikpJfl6SkprLZPk9yH/9SL0fTjsyzqvwLyjhXlTVHVxO9NXxxEAGWb4mT7CcCYCNIANGO82BjoRCjDG@2kyUb4zZ5tBI4F2Tw "J – Try It Online")
Output:
* 2 = fully on origin
* 1 = half on origin
* 0 = not on origin
## idea
We imagine the moving block as two separate squares which move around together, sometimes sliding on top of one another (flat to upright), sometimes spreading out (upright to flat), sometimes moving in parallel (flat rolling). For example, Consider `FFRR`:
```
0 0 <- start, both blocks on origin
0j1 0j2 <- F, blocks slide apart
0j3 0j3 <- F, blocks slide together
1j3 2j3 <- R, blocks slide apart again
1j2 2j2 <- B, blocks move in parallel
```
At a high level, it works like this:
1. `0j1<@^'RFLB'i.|.` Map `RFLB` to the complex numbers `1 0j1 _1 0j_1`, reverse them, and append `0 0` (the starting point of our two sliding blocks), setting ourselves up for a single reduction.
2. `2$]-.~]+(*1,1+=/)` The reduction logic. Multiply the current "step direction" by either `1 1` or `1 2`. Multiply by `1 1` if our sliding blocks are currently separate, and by `1 2` (to separate them) if they are currently overlapping.
3. `]+` Add that adjusted "step direction" elementwise to the current position to create two new positions...
4. `]-.` And set minus the current positions from the new ones.
5. `2$` Ensure the new position is extended to two elements -- in the case that we go to standing long ways, the previous step will only return a single result -- the new position -- and so we have to duplicate that.
[Answer]
# Python3, 356 bytes:
```
m={'F':[0,1],'B':[0,-1],'L':[1,-1],'R':[1,1]}
def M(x,c,o):p,v=m[x[0]];J=c[[0,-1][v!=1]][0];K=c[[0,-1][v!=1]][1];return[[([(J+2*v,K),(J+v,K)],1),([(J+v,K)],0),([(x+v,y)for x,y in c],o)][o],[([(J,K+2*v),(J,K+v)],2),([(x,y+v)for x,y in c],o),([(J,K+v)],0)][o]][p]
f=lambda x,c=[(0,0)],o=0:1*((0,0)in c)/len(c)if''==x else f(x[1:],*M(x,sorted(c,reverse=1),o))
```
[Try it online!](https://tio.run/##ZZBBT4MwGIbv@xV1Hmjnp9IZE8PSSw8ctnnh@uU7TChxyUZJhwRi/O3Ygs64nXjep7wvoXXfvNvq6aV2w3BUn1EaJRiDJIj0SPcBtx7lhNmIkr5mhSnZK@8gByuSGlp1xA5jotVa5Tg1sb1Rksjb1eZKSlo503y4CpEjX98tFy1sBHgKTwLpGc8pHlPnUy9K61gHPdtXLCf/dUJLMI7AJsyEEU@try2nGvQ@Xdbgp9GO82GEsKZZqQ6741ux8@/mCnkczsCqOJELPqbQF48HU/Fc7MsoUqpj5nAyrOQdyoRgEa7lZF1jCp6DM61xJ6P8/1ghhtrtq4aXfJ6mqdZ6LgS7lbOzvcxplmV6u73WenLxw/M/@6v/pE6n8vAN)
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 145 bytes
A little late to the party, but here is my two cents (or 145, rather).
Outputs:
* 2 = Standing upright on origin
* 1 = Half-on, half-off the origin
* 0 = Not on the origin
```
int f(char*s){int d=0,p=0;for(s--;*++s;){int n=*s>71?*s>79?3:-3:*s>69?2:-2;p+=d&&d!=n?n:n*2;if(d==-n||d==n)d=0;else if(!d)d=-n;}return!p+!(p+d);}
```
[Try it online!](https://tio.run/##fY@xboMwEIbn8hQmlSIb121KpFbBOEgMTJl4A2qbxFI4LNtMCc9OjTplSJe7@/5POt1Ja9lZymUxEFCP5aVzmSe3lZTYvVmx4/3osGeMZ5R6/qdAZP74/Vmt9VDtC7Yv4vh1qPKC5dxSobZblQqooIAs56bHSggG93tsQOJirq9eo5inKiIDPjsdJgeppSm2VBE@L69msKML5Y8J/sMHJSl9vxyTyRs4I@gG7W0nNYqGJ@tRQ2cAE3RLXuQ4BVSW8Z9N0zR1XW/IihrUlT/YZ3nTtm19Oj3X9X/uUc7LLw "C++ (gcc) – Try It Online")
## Explanation
We store the direction the block is facing in variable `d` and the position of one side of the block in variable `p`. We then use numbers 2 and 3 to represent the directions (with ±2 being forward/backward and ±3 being right/left), since 2 and 3 are linearly independent so we can represent any position that way with a single variable.
We then check if `p` equals 0 and if `p+d` equals 0, and add those values. If both `p == 0` and `p+d == 0`, then we are standing upright on the origin. If one of `p == 0` and `p+d == 0` is true, then we are sideways on the origin (since p is always tracking the same end of the block). If neither is true, then we are not on the origin.
### Ungolfed
```
int f(char*s) {
int d = 0; // Direction of the block (-2 = back, +2 = front, -3 = left, +3 = right)
int p = 0; // Position of the block
// Loop through the string with pointer arithmetic. When we reach \0, we break out.
for (s--;*++s;) {
// The current movement of the block.
int n = *s > 71 ? (*s > 79 ? 3 : -3) : (*s > 69 ? 2 : -2);
p += (d && d != n) ? n : n*2; // If (d == 0 || d == n) (if d is upright or d and n are in the same direction), add 2n. Otherwise, add n. (we flipped the conditional to save a byte)
if (d == -n || d == n) d = 0; // If (d == -n || d == n) (in other words, if d is aligned with n), set d to be 0 (upright).
else if (d == 0) d = -n; // If no direction (block is upright), set d to be -n.
// Otherwise, don't touch d since we are rolling "sideways", so the direction does not have to change.
}
return !p+!(p+d); // If p+d == 0, then the block is either straight or sideways on the origin. If additionally, p == 0, then the block is straight and on the origin.
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 78 bytes
```
a=>a.map(d=>p[k=d<76|0]+=~-(d/2&2)*(p[1-k]&1^3),p=[0,0])|'21'[p[0]**2+p[1]**2]
```
[Try it online!](https://tio.run/##Tcy7DoIwFAbgnadoGKDcC0YdtAxNZGJibWrSAPUC0gbUifjqSING/@WcfOfPufInH8r@ou5BJ6t6EnjiOOXhjStY4VTRBlf77WZEzMOvAFZRYiWOCxWNg4ZZ8XHl@ApT5CPmjHYS21RRxFw38eaGnmzaUQMAM8syQojpAxBFINai9yVfyYqiIHk@H35C8qU3CwrXH/ugNi25@fcJGcwIhewPvDzDAeAUlLIbZFuHrTxBAclDiLqHgzNnegM "JavaScript (Node.js) – Try It Online")
Only even positions are tile. Position [1,0] mean half on [0,0] and half on [2,0]. Position [1,1] unused
| Character | d = ASCII code | d in binary | d / 2 & 2 | d < 76 |
| --- | --- | --- | --- | --- |
| "B" | 66 | 1000010 | 0 | true |
| "F" | 70 | 1000110 | 2 | true |
| "L" | 76 | 1001100 | 2 | false |
| "R" | 82 | 1010010 | 0 | false |
```
a=> // Take Buffer input instead to save a byte
a.map(d=> // For each instruction
p[k=d=='B'|d=='F'] // Dimension
+=((d/2&2)-1) // Direction
*(p[1-k]%2?2:3) // If lay on another direction, move 1
, // Else move 1.5
p=[0,0]
)|( // Result
p[0]**2+p[1]**2==0?2:p[0]**2+p[1]**2==1?1:0
)
```
] |
[Question]
[
Programming Puzzles and Code Golf has graduated from beta. Soon we will get a custom site design, and with that the reputation boundaries for privileges will go up. A lot of users will lose privileges on the site. So your task is to write a program that tells us how much extra reputation we'll need to keep our privileges.
## Task
Your task is to write the shortest code to find the amount of extra reputation a user will need to keep their current privileges after the site design, given the number of reputation points.
## Input / Output
You can accept input and give output in any way you like, so long as it follows these rules:
**Input** - An integer from 1 to 250000+ *inclusive*. Your program or function *should* be able to accept numbers bigger than this, but it *must* accept numbers in this range.
**Output** - An integer representing the number of reputation points the user will need to get to keep their current privileges after the graduation.
No [standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default), please.
## Example algorithm
1. Set variable `i` to the input
2. Set variable `r` to variable `i`.
3. While `r` is not in list `beta`:
1. Subtract `1` from `r`.
4. Set `n` to the position of `r` in `beta`.
5. Set `r` to item `n` of `graduated`.
6. Set variable `o` to the result of `r` `-` `i`.
7. If `o` `<` `0`:
1. Set variable `o` to `0`.
8. Output variable `o`.
## Tables
### Table of privileges that will change
```
| privilege name | beta rep | graduation rep |
-+-----------------------------+----------+----------------+-
| create tags | 150 | 1500 |
| access review queues | 350 | 500 |
| cast close and reopen votes | 500 | 3000 |
| established user | 750 | 1000 |
| edit questions and answers | 1000 | 2000 |
| create tag synonyms | 1250 | 2500 |
| approve tag wiki edits | 1500 | 5000 |
| access to moderator tools | 2000 | 10000 |
| protect questions | 3500 | 15000 |
| trusted user | 4000 | 20000 |
| access to site analytics | 5000 | 25000 |
-+-----------------------------+----------+----------------+-
| privilege name | beta rep | graduation rep |
```
### Table of privileges that won't change
```
| privilege name | reputation |
-+------------------------------+------------+-
| create posts | 1 |
| participate in meta | 1 |
| create wiki posts | 10 |
| remove new user restrictions | 10 |
| vote up | 15 |
| flag posts | 15 |
| talk in chat | 20 |
| comment everywhere | 50 |
| set bounties | 75 |
| create chatrooms | 100 |
| edit community wiki | 100 |
| vote down | 125 |
-+------------------------------+------------+-
| privilege name | reputation |
```
## Testcases
```
wizzwizz4 | 750 | 2250
cat | 2004 | 7996
Dennis ♦ | 72950 | 0
Dr Green Eggs and Ham DJ | 4683 | 15317
New User | 1 | 0
```
Not all reputation counts are correct at time of writing
If you want your past or present reputation count here, just comment below and I'll maybe add it.
[Answer]
# Python, 101 bytes
```
lambda n:max(0,eval("+(n>=%d)*%d"*7%(5e3,5e3,4e3,5e3,35e2,5e3,2e3,5e3,15e2,2e3,5e2,15e2,150,15e2))-n)
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~40~~ 37 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
19112203.3b11×ȷḞ>Ḥ¬×9999322D‘¤S×.ȷ_»0
```
[Try it online!](http://jelly.tryitonline.net/#code=MTkxMTIyMDMuM2IxMcOXyLfhuJ4-4bikwqzDlzk5OTkzMjJE4oCYwqRTw5cuyLdfwrsw&input=&args=NzUw) or [verify all test cases](http://jelly.tryitonline.net/#code=MTkxMTIyMDMuM2IxMcOXyLfhuJ4-4bikwqzDlzk5OTkzMjJE4oCYwqRTw5cuyLdfwrswCsOH4oKs&input=&args=NzUwLCAyMDA0LCA3Mjk1MCwgNDY4MywgMQ).
### How it works
```
19112203.3b11×ȷḞ>Ḥ¬×9999322D‘¤S×.ȷ_»0 Main link. Argument: n
19112203.3b11 Convert the float to base 11. Yields
[10, 8, 7, 4, 3, 1, 0.30000000074505806].
×ȷ Multiply each by 1000.
Ḟ Floor. Yields
[10000, 8000, 7000, 4000, 3000, 1000, 300].
Ḥ Unhalve; yield 2n.
> Compare each integer in the list with 2n.
¬ Negate the resulting Booleans.
¤ Chain the three links to the left:
9999322D Convert the integer to base 10.
‘ Increment each digit. Yields
[10, 10, 10, 10, 4, 3, 3].
× Multiply the Booleans with the corr. digits.
S Compute the sum of the products.
×.ȷ Multiply the sum by 500.
_ Subtract n.
»0 Return the maximum of the difference and 0.
```
[Answer]
# CJam, 38 bytes
```
0000000: 72 69 5f 35 30 2f 22 64 50 46 28 1e 0a 03 22 66 ri_50/"dPF(..."f
0000010: 3c 3a 2b 22 fa c8 96 64 32 1e 0f 00 22 3d 69 65 <:+"...d2..."=ie
0000020: 32 5c 2d 55 65 3e 2\-Ue>
```
[Try it online!](http://cjam.tryitonline.net/#code=cmlfNTAvImRQRigeCgMiZjw6KyLDusOIwpZkMh4PACI9aWUyXC1VZT4&input=NzUw) or [verify all test cases](http://cjam.tryitonline.net/#code=cX5dewpSaV81MC8iZFBGKB4KAyJmPDorIsO6w4jClmQyHg8AIj1pZTJcLVVlPgpOfWZS&input=NzUwCjIwMDQKNzI5NTAKNDY4Mwox).1
### How it works
```
ri Read an integer n from STDIN.
_50/ Push a copy and divide it by 50.
"…" Push the string with code points [100 80 70 40 30 10 3].
f< Compare each code point with n / 50.
:+ Add the resulting Booleans.
"…" Push the string with code points
[250 200 150 100 50 30 15 0].
= Select the one at the index of the sum.
i Convert from character to integer.
e2 Multiply by 100.
\- Subtract n from the product.
Ue> Take the maximum of the difference and 0.
```
1 Note that the code contains a null byte, which causes problems in some browsers.
[Answer]
## JavaScript (ES6), ~~137~~ ~~135~~ ~~102~~ 81 bytes
```
n=>(n-=[5,0,.3,.6,1,2,3,4][[.3,1,3,4,7,8,10].findIndex(m=>m*500>n)+1]*5e3)<0?-n:0
```
If the user has 5000 or more reputation then `findIndex` fails, returning -1, so the result is incremented to that I can index into the array of new reputations needed. Edit: Saved 21 bytes by scaling the input and output array.
```
[.3,1,3,4,7,8,10] Old reputations of note, divided by 500
.findIndex(m=>m*500>n) Skip ones that have been achieved
+1 Normalise the return value
[5,0,.3,.6,1,2,3,4][] Index into new reputation needed
*5e3 Scaling factor
n-= Compare to the current reputation
()<0?-n:0 Negate to return the requirement
```
[Answer]
## Python, 88 bytes
```
lambda n:max(sum(500*b*(n>=a*500)for a,b in zip([.3,1,3,4,7,8,10],[3,3,4]+[10]*4))-n,0)
```
For each new beta privilege exceeded, adds the rep amount needed to get to the next graduated privilege. Then, the additional rep needed is the new rep minus the current rep, but no less than 0.
Both rep boundary lists are shortened by rep in multiples of `500`.
[Answer]
# Python ~~156~~ 152 bytes
```
s=str.split;n=input()
for k,v in map(s,s('5e3 5r4e3 5r3500 30./7r2e3 5r1500 10./3r500 6r1 1','r')):
w=u(k);r=eval(v)*w
if w<=n:print max(0,r-n);break
```
The data string (`5e3 5r4e3 5r3500 30./7r2e3 5r1500 10./3r500 6r1 1`) is a list with the format `(old_rep1) (new_rep1/old_rep1)r(old_repr) (new_rep2/old_rep2)` only including privleges which set the new max rep (users with >750 rep still need at least 3k rep post-graduation, even though they will be an established user at 1k. The list is sorted from highest rep first to lowest rep last.
[Answer]
# Pyth - ~~71~~ ~~70~~ ~~69~~ ~~77~~ ~~75~~ 77 bytes
```
eS,Z-@CM"\x00ǴϨלߐৄஸᎈ✐㪘丠憨"xKCM"\x00ŞˮϨӢǴלߐඬྠᎈ"e<#QK
```
[Test Suite](http://pyth.herokuapp.com/?code=eS%2CZ-%40CM%22%5Cx00%C7%B4%CF%A8%D7%9C%DF%90%E0%A7%84%E0%AE%B8%E1%8E%88%E2%9C%90%E3%AA%98%E4%B8%A0%E6%86%A8%22xKCM%22%5Cx00%C5%9E%CB%AE%C2%96%CF%A8%D3%A2%C7%B4%D7%9C%DF%90%E0%B6%AC%E0%BE%A0%E1%8E%88%22e%3C%23QK&test_suite=1&test_suite_input=750%0A2004%0A72950%0A4683%0A1&debug=0).
[Answer]
## LiveCode 8, 318 bytes
```
function g c
local b,g,r
put c into r
put "0.15,0.35,0.5,0.75,1,1.25,1.5,2,3.5,4,5" into b
split b by ","
put "0.3,0.1,0.6,0.2,0.4,0.5,1,2,3,4,5" into g
split g by ","
repeat with i=1 to 11
if c>b[i]*1000 and not c>g[i]*5000 then put max(r,g[i]*5000) into r
end repeat
return r-c
end g
```
As `wizzwizz4` suggested, here is an explanation:
```
function g c
```
Create a function named `g` taking a single parameter `c`. `c` is the user's current reputation. Equivalent to `def g(c)` in Python.
```
local b,g,r
```
Create three local variables: `b`,`g`, and `r`. `b` will be the reputation cutoffs for privileges in beta, `g` will contain the new reputation cutoffs after graduation, and `r` will represent the total reputation the user will have to have after graduation to retain their privileges.
```
put c into r
```
This copies the value of `c`(the user's current reputation) into `r`. Equivalent to `r=c` in Python)
```
put "0.15,0.35,0.5,0.75,1,1.25,1.5,2,3.5,4,5" into b
```
Similar to above, this sets b to a string containing a comma-deliminated list of the reputation cutoffs in beta, divided by 1000. Equivalent to `b="0.15,0.35,0.5,0.75,1,1.25,1.5,2,3.5,4,5"` in Python.
```
split b by ","
```
This splits the local variable `b` into an array, using `,` as the delimiter. This array now contains the reputation cutoffs in beta, divided by 1000. Equivalent to `b.split(",")` in Python.
```
put "0.3,0.1,0.6,0.2,0.4,0.5,1,2,3,4,5" into g
split g by ","
```
Same as above, except that `g` now contains a list of the reputation cutoffs after graduation, divided by 5000
```
repeat with i=1 to 11
```
Similar to a `for` loop in other languages, this repeates 11 times, with `i` assigned the next value in the sequence 1 to 11 each time. Arrays in LiveCode start at index 1. In Python, this would be `for i in range(11)`.
```
if c>b[i]*1000 and not c>g[i]*5000 then put max(r,g[i]*5000) into r
```
This is the main logic of the function. It checks to see if the user has enough reputation for the privilege in position `i` of the beta list, if so, and if they don't have enough reputation for the privilege after graduation, it sets the variable `r`(representing the total reputation that the user will have to have to retain their privileges after graduation) to the reputation cutoff after graduation for that privilege (only if the new reputation is higher than the previous one). The equivalent Python code would be `if c>b[i]*1000 and not c>g[i]*5000:
r=max(g[i]*5000,r)`
end repeat
Ends the repeat loop. Similar to C or Java's `}`. LiveCode uses the syntax `end 'insert contruct name` to end a `repeat` loop, an `if`, a `switch` etc...
```
return r-c
```
Fairly self-explanatory.
```
end g
```
Ends the function `g`.
] |
[Question]
[
The [one-dimensional version of this problem](https://codegolf.stackexchange.com/questions/2563/fill-in-the-lakes) was pretty easy, so here's a harder 2D version.
You are given a 2D array of land heights on standard input, and you have to figure out where the lakes will form when it rains. The height map is just a rectangular array of the numbers 0-9, inclusive.
```
8888888888
5664303498
6485322898
5675373666
7875555787
```
You must output the same array, replacing all locations that would be underwater with `*`.
```
8888888888
566*****98
6*85***898
5675*7*666
7875555787
```
Water can escape diagonally, so there would be no lake in this configuration:
```
888
838
388
```
shortest code wins. Your code must handle sizes up to 80 wide and 24 high.
Three more examples:
```
77777 77777
75657 7*6*7
75757 => 7*7*7
77677 77677
77477 77477
599999 599999
933339 9****9
936639 => 9*66*9
935539 9*55*9
932109 9****9
999999 999999
88888888 88888888
84482288 8**8**88
84452233 => 8**5**33
84482288 8**8**88
88888888 88888888
```
[Answer]
## Haskell, 258 characters
```
a§b|a<b='*'|1<3=a
z=[-1..1]
l m=zipWith(§)m$(iterate(b.q)$b(\_ _->'9'))!!(w*h)where
w=length m`div`h
h=length$lines m
q d i=max$minimum[d!!(i+x+w*y)|x<-z,y<-z]
b f=zipWith(\n->n`divMod`w¶f n)[0..]m
(j,i)¶g|0<i&&i<w-2&&0<j&&j<h-1=g|1<3=id
main=interact l
```
Example run:
```
$> runhaskell 2638-Lakes2D.hs <<TEST
> 8888888888
> 5664303498
> 6485322898
> 5675373666
> 7875555787
> TEST
8888888888
566*****98
6*85***898
5675*7*666
7875555787
```
Passes all unit tests. No arbitrary limits on size.
---
* Edit (281 → 258): don't test for stability, just iterate to the upper bound; stop passing constant argument `m`
[Answer]
## Python, ~~483~~ 491 characters
```
a=dict()
def s(n,x,y,R):
R.add((x,y))
r=range(-1,2)
m=set([(x+i,y+j)for i in r for j in r if(i,j)!=(0,0)and(x+i,y+j)not in R])
z=m-set(a.keys())
if len(z)>0:return 1
else:return sum(s(n,k[0],k[1],R)for k in[d for d in m-z if a[(d[0],d[1])]<=n])
i=[list(x)for x in input().strip().split('\n')]
h=len(i)
w=len(i[0])
e=range(0,w)
j=range(0,h)
for c in[(x,y)for x in e for y in j]:a[c]=int(i[c[1]][c[0]])
for y in j:print(''.join([('*',str(a[(x,y)]))[s(a[(x,y)],x,y,set())>0] for x in e]))
```
I'm pretty sure there's a better (and shorter) way of doing this
[Answer]
## Python, 478 471 characters
(Not including comments. 452 450 characters not including the imports.)
```
import sys,itertools
i=[list(x)for x in sys.stdin.read().strip().split('\n')]
h=len(i)
w=len(i[0])
n=h*w
b=n+1
e=range(h)
d=range(w)
# j is, at first, the adjancency matrix of the graph.
# The last vertex in j is the "drain" vertex.
j=[[[b,1][(t-r)**2+(v-c)**2<=1 and i[r][c]>=i[t][v]] for t in e for v in d]+[[b,1][max([r==0,r>h-2,c==0,c>w-2])]]for r in e for c in d]+[[0]*b]
r=range(b)
for k,l,m in itertools.product(r,repeat=3):
# This is the Floyd-Warshall algorithm
if j[l][k]+j[k][m]<j[l][m]:
j[l][m]=j[l][k]+j[k][m]
# j is now the distance matrix for the graph.
for k in r:
if j[k][-1]>n:
# This means that vertex k is not connected to the "drain" vertex, and is therefore flooded.
i[k/w][k-w*(k/w)]='*'
for r in e:print(''.join(i[r]))
```
The idea here is that I construct a directed graph where each grid cell has its own vertex (plus one additional "drain" vertex). There is an edge in the graph from each higher valued cell to its neighboring lower valued cells, plus there is an edge from all exterior cells to the "drain" vertex. I then use [Floyd-Warshall](http://en.wikipedia.org/wiki/Floyd-Warshall_algorithm) to calculate which vertices are connected to the "drain" vertex; any vertices that are *not* connected will be flooded and are drawn with an asterisk.
I don't have much experience with condensing Python code, so there's probably a more succinct way I could have implemented this method.
[Answer]
## Common Lisp, 833
```
(defun drains (terr dm a b)
(cond
((= (aref dm a b) 1) t)
((= (aref dm a b) -1) nil)
((or (= a 0) (= b 0)
(= a (1- (array-dimension terr 0)))
(= b (1- (array-dimension terr 1)))) t)
(t (loop for x from -1 to 1
do (loop for y from 0 to 1
do (if (and (or (> x 0) (> y 0))
(drains terr dm (+ a x) (+ b y))
(<= (aref terr (+ a x) (+ b y))
(aref terr a b)))
(progn
(setf (aref dm a b) 1)
(return-from drains t)))))
(setf (aref dm a b) -1)
nil)))
(defun doit (terr)
(let ((dm (make-array (array-dimensions terr))))
(loop for x from 0 to (- (array-dimension terr 0) 1)
do (loop for y from 0 to (- (array-dimension terr 1) 1)
do (format t "~a"
(if (drains terr dm x y)
(aref terr x y)
"*"))
finally (format t "~%")))))
```
No attempt has been made to golf this, I just found the problem interesting. Input is the 2D array of the map. The solution checks each square to see if it "drains" -- a square drains if it is on the outer edge or if it is adjacent to an equal or lower height square that drains. To keep from recursing endlessly, the code keeps a "drain map" (dm) where it stores the drainage status of squares that have already been determined.
[Answer]
## Python, 246 chars
```
import os
a=list(os.read(0,2e3))
w=a.index('\n')+1
a+=' '*w
def f(p,t):
if e<a[p]or p in t:return
t[p]=1
return'*'>a[p]or any(f(p+d,t)for d in(~w,-w,-w+1,-1,1,w-1,w,w+1))
z=0
for e in a:
if(' '<e)*~-f(z,{}):a[z]='*'
z+=1
print''.join(a[:~w])
```
The solution works by doing a DFS from each position to determine whether or not to fill.
If trailing whitespace on each line is allowed, it may be shortened by using w=80 and padding the input lines with whitespace to 80 chars.
] |
[Question]
[
## Input
An array that can contain arrays or positive, consecutive, ascending integers. The arrays can have any number of arrays inside of them, and so on and so forth. No arrays will be empty.
## Output
This array simplificated
## How to simplificate an array
We will use the array, `[1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]]` as our example.
First, we check how deep the values are nested. Here are the depths and the numbers at those depths:
```
0 1
1 2 3 9
2 4 7
3 5 6
5 8
```
We construct the output array by taking the numbers in the original array, grouping them by how deep they are nested, and then nesting the groups at depths of the original depths of their elements. Arrange the numbers in ascending order and ascending depth.
So, our output is `[1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]]`
## Examples
```
[1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]] -> [1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]]
[[[1]], [2, [3]], 4, [5, [6, [7, [8], [9, [[10]]]]]]] -> [4, [2, 5], [[1, 3, 6]], [[[7]]], [[[[8, 9]]]], [[[[[[10]]]]]]]
[1] -> [1]
[1, [2], [[3]], [[[4]]], [[[[5]]]]] -> [1, [2], [[3]], [[[4]]], [[[[5]]]]]
[1, [[[[2], 3]]], [[4]]] -> [1, [[4]], [[[3]]], [[[[2]]]]]
```
[Answer]
## Perl, 52 bytes
Just a recursive subroutine. (unusual for a Perl answer, I know..)
```
sub f{say"@{[grep!ref,@_]}";@_&&f(map/A/?@$_:(),@_)}
```
Call it like that :
```
$ perl -E 'sub f{say"@{[grep!ref,@_]}";@_&&f(map/A/?@$_:(),@_)}f(1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9])'
1
2 3 9
4 7
5 6
8
```
Each line of the output corresponds to a depth level of the array (hence the empty line in the example above).
It can be turned into a full program for just a few more bytes : add `-n` flag and an `eval` (inside `@{ }` to transform the input into an array and not an arrayref) to transform the input into a Perl array :
```
perl -nE 'sub f{say"@{[grep!ref,@_]}";@_&&f(map/A/?@$_:(),@_)}f(@{+eval})' <<< "[1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]]"
```
---
My previous approach was slightly longer (65 bytes), but still interesting, so I'll let it here :
```
perl -nE '/\d/?push@{$;[$d-1]},$_:/]/?$d--:$d++for/\[|]|\d+/g;say"@$_"for@' <<< "[1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]]"
```
[Answer]
## JavaScript (ES6), ~~139~~ 109 bytes
```
f=(a,v=b=>a.filter(a=>b^!a[0]))=>a[0]?v().concat((a=f([].concat(...v(1))),b=v())[0]?[b]:[],v(1).map(a=>[a])):[]
```
Explanation using the example input: `v` is a helper method which returns the arrays (with parameter `1`) or values (with no parameter). We start with `a = [1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]]`, which is nonempty. We filter out the arrays, giving `[1]`. We then recursively call ourselves on the arrays concatenated together, which is `[2, 3, [4], [[5, 6], 7, [[[8]]]], 9]`, the result being `[2, 3, 9, [4, 7], [[5, 6]], [[[[8]]]]]`. We again filter out the arrays, which gives us the second term of our output, `[2, 3, 9]`, however we have to be careful not to insert an empty array here. It them remains to wrap the arrays `[4, 7], [[5, 6]], [[[[8]]]]` inside arrays and append them to the output, resulting in `[1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]]`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
fFṄḟ@;/ß
```
Output is one level per line, with empty lines for levels without elements. [Try it online!](http://jelly.tryitonline.net/#code=ZkbhuYThuJ9AOy_Dnw&input=&args=WzEsIFsyLCAzXSwgW1s0XV0sIFtbWzUsIDZdLCA3LCBbW1s4XV1dXSwgOV1d)
### How it works
```
fFṄḟ@;/ß Main link. Argument: A (array)
F Flat; yield all integers (at any level) in A.
f Filter; intersect A with the integers, yielding those at level 0.
Ṅ Print the filtered array and a linefeed. Yields the filtered array.
;/ Reduce by concatenation.
This decreases the levels of all integers at positive levels by 1.
ḟ@ Swapped filter-false; remove the integers at level 0 in A from the array
with decreased levels.
ß Recursively call the main link on the result.
The program stops once A is empty, since ;/ will result in an error.
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~27~~ ~~26~~ ~~25~~ 21 bytes
```
D˜gFvyydi„ÿ ?}}¶?.gG«
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RMucZ0Z2eXlkaeKAnsO_ID99fcK2PylEZ1VgWEfCqw&input=W1tbMV1dLCBbMiwgWzNdXSwgNCwgWzUsIFs2LCBbNywgWzhdLCBbOSwgW1sxMF1dXV1dXV0) (slightly modified as `.g` isn't on TIO yet)
**Explanation**
```
D˜gF # flattened input length times do
vy # for each y current level of list
ydi„ÿ ?} # if y is a digit, print with space
} # end v-loop
¶? # print newline
.g # calculate length of stack (this should be .g but I can't test)
G« # length stack times, concatenate items on stack
```
The main strategy is to loop over each possible level of the nested array and print any digits on one row, while keeping the non-digits (lists) in a list one level less nested.
[Answer]
# JavaScript (ES6) 121 ~~144 152~~
**Edit** Revised a lot, 1 byte saved thx Patrick Roberts, and 21 more just reviewing the code
Recursive function working on arrays in input and output. I don't like the request of having elements at depth 1 as single elements in output array (while greater levels are grouped as one element): `[l1,l1, [l2...], [[l3...]] ]`. While this would be more direct: `[ [l1...], [[l2...]], [[[l3...]]] ]`
```
f=(l,d=0,r=[])=>l.map(v=>v[0]?f(v,d+1,r):r[d]=[...r[d]||[],v])
r.reduce((r,v,d)=>d?[...r,(n=d=>d-->1?[n(d)]:v)(d)]:v,[])
```
Newline added for readability.
Some notes: the line 2 is evaluated again and again at each recursive call, but only the last iteration at the end of recursion is useful.
The special handling when `d==0` in line 2 takes care of the anomaly for level 1 elements.
The `n` recursive function handles the array nesting in output
**Test**
```
f=(l,d=0,r=[])=>l.map(v=>v[0]?f(v,d+1,r):r[d]=[...r[d]||[],v])
&&r.reduce((r,v,d)=>d?[...r,(n=d=>d-->1?[n(d)]:v)(d)]:v,[])
console.log=x=>O.textContent+=x+'\n'
test=[
[
[1, [2,3], 4], /* -> */ [1, 4, [2,3]]
]
,[
[1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]],
// ->
[1, [2, 3, 9], [[4, 7]], [[[5, 6]]], [[[[[8]]]]]]
]
,[
[[[1]], [2, [3]], 4, [5, [6, [7, [8], [9, [[10]]]]]]],
// ->
[4, [2, 5], [[1, 3, 6]], [[[7]]], [[[[8, 9]]]], [[[[[[10]]]]]]]
]
,[
[1], /* -> */ [1]
]
,[
[1, [2], [[3]], [[[4]]], [[[[5]]]]],
// ->
[1, [2], [[3]], [[[4]]], [[[[5]]]]]
]
,[
[1, [[[[2], 3]]], [[4]]],
[1, [[4]], [[[3]]], [[[[2]]]]]
]]
test.forEach(t=>{
var i=t[0], k=t[1], r=f(i),
si=JSON.stringify(i),
sr=JSON.stringify(r),
sk=JSON.stringify(k)
console.log((sr==sk?'OK ':'KO ')+si + " => " + sr)
})
```
```
<pre id=O></pre>
```
[Answer]
# JavaScript (ES6) 168 bytes
```
f=a=>(s=[],b=-1,k=0,a.replace(/\d+|\[|\]/g,a=>a=='['?b++:a==']'?b--:(s[b]=s[b]||[]).push(a)),'['+s.map((a,b)=>k=a&&(k?',':'')+'['.repeat(b)+a+']'.repeat(b)).join``+']')
```
# [Demo](https://jsfiddle.net/po12s07h/2/)
[Answer]
# PHP, 145 Bytes
```
<?function c($r){$n=[];foreach($r as$k=>$v)if(is_array($v)){$n=array_merge($n,$v);unset($r[$k]);}if($n)$r[]=c($n);return$r;}print_r(c($_GET[a]));
```
Breakdown
```
function c($r){
#usort($r,function($x,$y){return is_array($x)<=>is_array($y)?:$x<=>$y;});
#no need to sort and a simple sort($r); do it sort array after scalar
$n=[];
foreach($r as$k=>$v)if(is_array($v)){$n=array_merge($n,$v);unset($r[$k]);} # put arrays on the same depth together
if($n)$r[]=c($n); # recursive if an array exists
return$r; #return changes
}
print_r(c($_GET[a])); #Output and Input
```
[Answer]
## JavaScript (ES6), ~~127~~ ~~137~~ 134 bytes
Takes an array as input and returns a string.
```
f=(a,l=[],d=0,o='')=>`[${a.map(x=>x[0]?f(x,l,d+1,o+'['):l[d]=(l[d]?l[d]+',':o)+x),l.map((s,d)=>x+s+']'.repeat(d,x=','),x='').join``}]`
```
### Test cases
```
f=(a,l=[],d=0,o='')=>`[${a.map(x=>x[0]?f(x,l,d+1,o+'['):l[d]=(l[d]?l[d]+',':o)+x),l.map((s,d)=>x+s+']'.repeat(d,x=','),x='').join``}]`
console.log(f([1, [2, 3], [[4]], [[[5, 6], 7, [[[8]]]], 9]]));
console.log(f([[[1]], [2, [3]], 4, [5, [6, [7, [8], [9, [[10]]]]]]]));
console.log(f([1]));
console.log(f([1, [2], [[3]], [[[4]]], [[[[5]]]]]));
console.log(f([1, [[[[2], 3]]], [[4]]]));
```
[Answer]
# Pyth, ~~19~~ 16 bytes
```
W=Qsf!&sITp+TdQk
```
[Try it online.](http://pyth.herokuapp.com/?code=W%3DQsf!%26sITp%2BTdQk&input=%5B1%2C+%5B2%2C+3%5D%2C+%5B%5B4%5D%5D%2C+%5B%5B%5B5%2C+6%5D%2C+7%2C+%5B%5B%5B8%5D%5D%5D%5D%2C+9%5D%5D&test_suite_input=%5B1%2C+%5B2%2C+3%5D%2C+%5B%5B4%5D%5D%2C+%5B%5B%5B5%2C+6%5D%2C+7%2C+%5B%5B%5B8%5D%5D%5D%5D%2C+9%5D%5D%0A%5B%5B%5B1%5D%5D%2C+%5B2%2C+%5B3%5D%5D%2C+4%2C+%5B5%2C+%5B6%2C+%5B7%2C+%5B8%5D%2C+%5B9%2C+%5B%5B10%5D%5D%5D%5D%5D%5D%5D%0A%5B1%5D%0A%5B1%2C+%5B2%5D%2C+%5B%5B3%5D%5D%2C+%5B%5B%5B4%5D%5D%5D%2C+%5B%5B%5B%5B5%5D%5D%5D%5D%5D%0A%5B1%2C+%5B%5B%5B%5B2%5D%2C+3%5D%5D%5D%2C+%5B%5B4%5D%5D%5D&debug=0) [Test suite.](http://pyth.herokuapp.com/?code=W%3DQsf!%26sITp%2BTdQk&input=%5B1%2C+%5B2%2C+3%5D%2C+%5B%5B4%5D%5D%2C+%5B%5B%5B5%2C+6%5D%2C+7%2C+%5B%5B%5B8%5D%5D%5D%5D%2C+9%5D%5D&test_suite=1&test_suite_input=%5B1%2C+%5B2%2C+3%5D%2C+%5B%5B4%5D%5D%2C+%5B%5B%5B5%2C+6%5D%2C+7%2C+%5B%5B%5B8%5D%5D%5D%5D%2C+9%5D%5D%0A%5B%5B%5B1%5D%5D%2C+%5B2%2C+%5B3%5D%5D%2C+4%2C+%5B5%2C+%5B6%2C+%5B7%2C+%5B8%5D%2C+%5B9%2C+%5B%5B10%5D%5D%5D%5D%5D%5D%5D%0A%5B1%5D%0A%5B1%2C+%5B2%5D%2C+%5B%5B3%5D%5D%2C+%5B%5B%5B4%5D%5D%5D%2C+%5B%5B%5B%5B5%5D%5D%5D%5D%5D%0A%5B1%2C+%5B%5B%5B%5B2%5D%2C+3%5D%5D%5D%2C+%5B%5B4%5D%5D%5D&debug=0)
Note the leading space. Outputs levels on rows like the Perl answer.
### Explanation
* Implicit input in `Q`.
* `f`ilter items `T` of `Q` on:
+ Check if `s`um is `I`dentity on `T`.
+ If it was (it was a number), `p`rint `T` plus a space `+`…`d`.
+ If it wasn't (it was an array), keep it.
* `s`um the items. This removes a layer of arrays from each item. If none are left, yields `0`.
* Assign `=` the result to `Q`.
* `W`hile the result is nonempty, print the empty string `k` and a newline.
[Answer]
## Haskell, ~~124~~ 123 bytes
```
data L=I Int|R[L]
d#R l=((d+1)#)=<<l
d#i=[(d::Int,i)]
[]!_=[]
l!1=l
l!d=[R$l!(d-1)]
h l=R$do d<-[1..];[i|(e,i)<-0#l,d==e]!d
```
As Haskell doesn't support mixed lists (integers and list of integers) by default, I define a custom list type `L`. Usage example:
```
*Main> h (R[I 1, R[I 2, I 3], R[ R[I 4]], R[ R[ R[I 5, I 6], I 7, R[R[R[I 8]]]], I 9]])
R [I 1,R [I 2,I 3,I 9],R [R [I 4,I 7]],R [R [R [I 5,I 6]]],R [R [R [R [R [I 8]]]]]]
```
Note: it takes some time to run, because it loops through all positive Ints (32 or 64bit) to look for a nest level that deep. Also: the custom list type cannot be printed by default, so if you want to see the result as in the example above, you need to add `deriving Show` to the `data` declaration (-> `data L=I Int|R[L] deriving Show`). Because it's not needed for returning a L-list from a function, I don't count the bytes.
How it works:
```
data L=I Int|R[L] -- custom list type L, which is either an Int
-- (-> I Int) or a list of some L (-> R [L])
d#R l=((d+1)#)=<<l -- # makes a list of (depth, I-number) pairs from
d#i=[(d::Int,i)] -- a given L-list, e.g.
-- 0 # (R[I 1,R[I 2,I 3],I 4]) -> [(1,I 4),(2,I 2),(2,I 3),(1,I 4)]
-- the type annotation ::Int makes sure that all
-- depths are bounded. Without it, Haskell
-- would use arbitrary large numbers of type
-- ::Integer and the program won't finish
[]!_=[] -- ! wraps a list of Is with (d-1) additional
l!1=l -- R constructors
l!d=[R$l!(d-1)]
h l= -- main function, takes a L-list
do d<-[1..] -- for each nest level d make
[i|(e,i)<-0#l,d==e] -- a list of all I where the depth is d
!!d -- and wrap it again with d-1 Rs
R$ -- wrap with a final R
```
Edit @BlackCap saved a byte by switching from `>>=` to `do` notation. Thanks!
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 22 bytes
```
{⍬≢⍵:∇⊃,/⍵~⎕←⍵/⍨0=≡¨⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR75pHnYse9W61etTR/qirWUcfyK571Df1UdsEIAvIW2Fg@6hz4aEVQF7t/zSwcB9QIUhj75ZD640ftU0EKg8OcgaSIR6ewf/TFIAsr2B/PwX1aEMdhWgjHQXjWCAdbRILpqJNdRTMgCxzMMciNhYkbBkbq84FsVZdV1dXnQvZlOhoQ7BWoEnRxiCWCZABNCXaDIhBxliAZC1B5hkaxEIAbtMM8cmBbAG70hjqWJNYKCPalJC5EGUg7cZQTSDN6gA "APL (Dyalog Unicode) – Try It Online")
Similar to Dennis' answer, a test case per line.
[Answer]
# [Red](http://www.red-lang.org), 174 bytes
```
func[a][i: charset"0123456789"d: 0 m: copy #()parse mold a[any["["(d: d + 1)|"]"(d: d - 1)|" "|
copy t any i(either m/:d[append m/:d to 1 t][m/:d: to[]t])]]sort/skip to[]m 2]
```
[Try it online!](https://tio.run/##VY3NboQwDITvPMWIXkBVtfwtCzxGr5YPKQkCbYEopIeV9t2pCStVnUPsGX@xndH7p9HE0dBhH36WnhTT1KEflduMj7O8KKtrfWvaWHfIMMtotQ@8Jak9CMzrt4YitTwopjgRSOMdefqM@eU@gkP8jMJPD2ExJWbyo3GYL50mZa1ZdOjhV@TwTIfpxBF7Tpm31fnLdp9siGYUvA@rM6ofoUARRJSDCpQMooqPl66oGbeja1iElvkkifKDKECl1ApCUg0StJG4FSDP@BReu/nvxrG7PC9UfFa6/oNDJFx5jgMVMVm3fhkMUIz9Fw "Red – Try It Online")
A naive approach using the string representation of the array, keeping track of the depth by counting the `[`and `]`. The integers are stored into a map which keys are the depths.
[Answer]
# [R](https://www.r-project.org/), 96 bytes
```
f=function(x,`+`=list,`-`=unlist,i=sapply(x,is.list))c(+sort(-x[!i]),if(length(x[i]))+f(x[i]-F))
```
[Try it online!](https://tio.run/##dZDNboQgEMfvPEV7Wibipny43T1w7UtsmmiMtCTWNQubuE9vKWBUrBzmC2Z@f@Y@Gv3Tt1rpurKNHJVUj662@tbhgZRZKVttLCnzUj46H2ppqr5vn@5am@NfCaDGmbndLc6H66v@BKIVbpvuy37j4epyyJQP8g@AsRkqx2uoH4wp8Y4RDiHyRsAy86YgJyDvafUM7pALAHLq8QHF4S8UHQAtP4YnLKDpEZPJMDpRWXDc5YJEunen4KKMc3x@WaiibxBOIojtCWKzIB5XkvbyvV4@94r1Opfr49tlCtjWwj//0y72@GLmFyt@YpwcviaKLaXYoxSAxl8 "R – Try It Online")
Outputs a nested list.
**Ungolfed code**
```
simplificate=
f=function(x){ # recursive function f with argument x;
islist=sapply(x,is.list) # first determine which elements of x are lists
c( # now make a list of two groups of elements:
list(sort(unlist(x[!islist]))), # the first is the non-list elements of x,
if(length(x[islist])){ # then (but only if there were some)
list( # the second is a list of
f( # the results of a recursive call to f
unlist(x[islist], # with the list elements of x as an argument,
recursive=FALSE))) # after unlisting by one level.
}
)
}
```
---
Or, **88 bytes**
```
f=function(x,`-`=unlist,i=sapply(x,is.list))if(length(x)){print(sort(-x[!i]));f(x[i]-F)}
```
[Try it online!](https://tio.run/##dZDBasMwDIbvfortVAucMcdO11J83UuUQkNJNkGahtgFl7Fnz9zYIYmz6CBZwtL3S22n8dpUWOIlN4XqSlXe64vBW00tOydnda8r1Iah0nnTVA9XRf32LAFgSaui/jLf1AL8NC3Whupba2hij694AjiU1B7xlHzCb1fY3HEKrp69lLM@pEyAf/VOwjTrXca2wD7i6g6csT0AcarphoThL5xsgEwXogMWyPApVdEwPlBTH4TLJQv0Pmx9CDJ24ft@ooq/g7dIULomKB0FiXCSuFes9YqxV87POT2fWB5TwrLm9/xPu1zjy5GfzfiRc3LEnCiXlGyNkgHp/gA "R – Try It Online")
Outputs elements from each level on a different line.
This meets the flexible output allowed in the comments, but feels a bit sneaky when [R](https://www.r-project.org/) is happily able to output a nested list as originally asked for in the challenge...
[Answer]
# [Python 3](https://docs.python.org/3/), 104 bytes
```
v=lambda l,m={},i=1:m if l==[]else v(l[1:],v(l[0],m,i+1)if str(l[0])>'A'else{**m,i:m.get(i,[])+l[:1]},i)
```
[Try it online!](https://tio.run/##ZY7RCsIwDEXf/Yq@uWoQa6fOQQW/I@RBcWqh1aFjIOK3z6QOUSyU3CT33La@N6fL2XZd68I27vZbFSC6xxO8M2VU/qCCc0hVuFWqzQKakkDqlCCCHxvNjltzTRO9Hm6G4nyMRrws4@RYNZkHJD0OWBriVN3VV39usjZDAwpnoCxxxZxSwTmoBatlagoiGa@ItB58OESTzMyiFZWzYA4XfAUsZLuSBDOl9/nmzW8nSelt238hp17g/J99LwSwvS1Plu4F "Python 3 – Try It Online")
] |
[Question]
[
**Input:** You will be passed a string containing a single english word. All letters will be lowercase, and there will be no non-alphabetic characters in the string.
**Output:** You will return an integer from 1 to 7 representing how many syllables you think are in the word.
**Scoring:** Your program will be run against all of the words found on [this repository](https://github.com/nathanmerrill/wordsbysyllables). If you get `N` words correct, and your program is `M` bytes large, then your score is `N-(M*10)`. Largest score wins.
To generate my syllable count, I used [this](https://en.wiktionary.org/wiki/Wiktionary:Frequency_lists/PG/2006/04/1-10000) as my word list and [this](http://www.gutenberg.org/ebooks/3204) to count the syllables.
[Answer]
# Ruby, 8618 correct (91.1%), 53 bytes, 8618 - 10 \* 53 = 8088 score
```
->s{s.scan(/[aiouy]+e*|e(?!d$|ly).|[td]ed|le$/).size}
```
This is an anonymous Ruby function which uses regexes to count syllables.
The function adds a syllable for every instance of:
* A run of non-`e` vowels, followed by zero of more `e`s
* An `e` which is *not* part of a trailing `ed` or `ely`, with the exception of trailing `ted` or `ded`s
* A trailing `le`
## Analysis
The basic idea is to count runs of vowels, but this by itself isn't very accurate (`[aeiouy]+` gets 74% correct). The main reason for this is because of the [silent `e`](https://en.wikipedia.org/wiki/Silent_e), which modifies the previous vowel sound while not being pronounced itself. For example, the word `slate` has two vowels but only one syllable.
To deal with this, we take `e` out of the first part of the regex and treat it separately. Detecting silent `e`s is hard, but I found two cases where they occur often:
* As part of a trailing `ed` (unless it's a `ted` or `ded` like `settled` or `saddled`),
* As part of a trailing `evy` (e.g. `lovely`)
These cases are specifically excluded in what would otherwise be `e.`.
The reason for the `.` in `e(?!d$|ly).` is to consume the next char if there is a double vowel (e.g. `ea` or `ee`), and so that `e` at the end of the word are not counted. However a trailing `le` *is* usually pronounced, so that is added back in.
Finally, vowel runs are counted as one syllable. While this may not always be the case (e.g. `curious`), it's often difficult to work out whether there are multiple syllables. Take the `ia` of `celestial` and `spatial`, as an example.
## Test program
I don't really know Ruby so I'm not sure how well it can be golfed. I did manage to scrape together a test program by consulting a lot of SO though:
```
cases = 0
correct = 0
s = "->s{s.scan(/[aiouy]+e*|e(?!d$|ly).|[td]ed|le$/).size}"
f = eval s
for i in 1 ... 8
filepath = i.to_s + "-syllable-words.txt"
file = File.open(filepath)
while (line = file.gets)
word = line.strip
cases += 1
if f.call(word) == i
correct += 1
end
end
end
p "Correct: #{correct}/#{cases}, Length: #{s.length}, Score: #{correct - s.length*10}"
```
[Answer]
# Python3, 7935 - 10 \* 71 = 7225
My quick-and-dirty answer: count runs of consecutive vowels, but remove any final e's first.
```
lambda w:len(''.join(" x"[c in"aeiouy"]for c in w.rstrip('e')).split())
```
After stripping off the e's, this replaces vowels with `x` and all other characters with a space. The result is joined back into a string and then split on whitespace. Conveniently, whitespace at the beginning and end is ignored (e.g. `" x xx ".split()` gives `["x","xx"]`). The length of the resulting list is therefore the number of vowel groups.
The original, 83-byte answer below was more accurate because it only removed a single e at the end. The newer one thus has problems for words like `bee`; but the shortened code outweighs that effect.
```
lambda w:len(''.join(" x"[c in"aeiouy"]for c in(w[:-1]if'e'==w[-1]else w)).split())
```
Test program:
```
syll = lambda w:len(''.join(c if c in"aeiouy"else' 'for c in w.rstrip('e')).split())
overallCorrect = overallTotal = 0
for i in range(1, 7):
with open("%s-syllable-words.txt" % i) as f:
words = f.read().split()
correct = sum(syll(word) == i for word in words)
total = len(words)
print("%s: %s correct out of %s (%.2f%%)" % (i, correct, total, 100*correct/total))
overallCorrect += correct
overallTotal += total
print()
print("%s correct out of %s (%.2f%%)" % (overallCorrect, overallTotal, 100*overallCorrect/overallTotal))
```
Evidently this was too dirty and not quick enough to beat Sp3000's Ruby answer. ;^)
[Answer]
# Perl, 8145 - 3 \* 30 = 7845
Using the lists from before the recent commits.
```
#!perl -lp
$_=s/(?!e[ds]?$)[aeiouy]+//g
```
[Answer]
# Python, 5370-10\*19 = 5180
This program simply assumes that longer words means more syllables.
```
lambda x:len(x)/6+1
```
The tester program I use is:
```
correct = 0
y = lambda x:len(x)/6+1
for i in xrange(1,8):
f = file(str(i)+"-syllable-words.txt")
lines = f.read().split("\n")
f.close()
correct += len([1 for line in lines if y(line)==i])
print correct
```
] |
[Question]
[
## Background
You are a rich executive of a software empire. Your time is worth a lot of money. As such, you must always travel in the most efficient route possible. However, as an executive, you spend a lot of time participating in important phone calls. It is paramount that you never drop calls, so you must never travel through areas which don't have cell service!
## The Challenge
You'll be given a list of three-tuples, each of which represents the location and power of a cell tower. As an example, `[50, 25, 16]` would represent a cell tower located at `<x,y> = <50, 25>` with a circle of radius 16 representing its circle of influence. With this list in mind, you must travel from your starting position at `<0, 0>` to your destination at `<511, 511>`, in the shortest distance possible without losing cell service. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code wins!
## Input / Output
You are free to manipulate the input into a form that makes it easy to read, such as in a file, or as a nested array through STDIN using `eval`, etc. You may hardcode the input, so long as your code works for other inputs as well. The exact characters used to hardcode the input will not be counted, but the variable name and assignment characters will. You should not assume that the input is in any specific order, or that every cell tower is relevant to the problem. If you have any questions please leave a comment and I will try to clarify it.
The output is to be a list of coordinates, marking points that when connected in order form a path to the exit. The accuracy need only be rounded to the nearest integer, and if you are 1-2 units off of what I have in me output example, that is fine. I have included images below to clarify this.
Best of luck!
## Examples
```
input:
[ 32, 42, 64]
[112, 99, 59]
[141, 171, 34]
[157, 191, 28]
[177, 187, 35]
[244, 168, 57]
[289, 119, 20]
[299, 112, 27]
[354, 59, 58]
[402, 98, 23]
[429, 96, 29]
[424, 145, 34]
[435, 146, 20]
[455, 204, 57]
[430, 283, 37]
[432, 306, 48]
[445, 349, 52]
[424, 409, 59]
[507, 468, 64]
```

```
output:
0 0
154 139
169 152
189 153
325 110
381 110
400 120
511 511
```

```
input2
[ 32, 42, 64]
[112, 99, 59]
[141, 171, 34]
[157, 191, 28]
[177, 187, 35]
[244, 168, 57]
[289, 119, 20]
[299, 112, 27]
[354, 59, 58]
[402, 98, 23]
[429, 96, 29]
[424, 145, 34]
[435, 146, 20]
[455, 204, 57]
[430, 283, 37]
[432, 306, 48]
[445, 349, 52]
[424, 409, 59]
[507, 468, 64]
[180, 230, 39]
[162, 231, 39]
[157, 281, 23]
[189, 301, 53]
[216, 308, 27]
[213, 317, 35]
[219, 362, 61]
[242, 365, 42]
[288, 374, 64]
[314, 390, 53]
[378, 377, 30]
[393, 386, 34]
```

```
output2:
0 0
247 308
511 511
```
The previous path is highlighted in blue, but you can see the addition of more towers allows a more optimal route.

[Answer]
# Python, ~~1,291 1,271~~ 1,225 bytes
As Martin noted, this problem can be largely reduced to his excellent [rubber band challenge](https://codegolf.stackexchange.com/q/38576/31403).
Using that challenge's terminology, we can take as the second set of nails the points of intersection between the circles *on the boundary* of the enclosed area:

As the rubber band we can take any path *P* between the two endpoints that runs inside the enclosed area.
We can then invoke a solution to the rubber-band problem to produce a (locally) minimal path.
The challenge is, of course, to find such a path *P*, or more precisely, to find *enough* paths so that at least one of them produces the globally minimal path (note that in the first test-case we need at least one path to cover all possibilities, and in the second test-case at least two.)
A naive approach would be to just try all possible paths:
For every sequence of adjacent (i.e. intersecting) circles that connects the two endpoints, take the path along their centers (when two circles intersect, the segment between their centers is always within their union.)
Though this approach is technically correct, it can lead to a ridiculously large number of paths.
While I was able to solve the first test-case using this approach within a few seconds, the second one took forever.
Still, we can take this method as a starting point and try to minimize the number of paths we have to test.
This is what follows.
We construct our paths by basically performing a depth-first search on the graph of circles.
We're looking for a way to eliminate potential search directions at each step of the search.
Suppose that at some point we're at a circle *A*, that has two adjacent circles *B* and *C*, which are also adjacent to each other.
We can get from *A* to *C* by visiting *B* (and vice versa,) so we might think that visiting both *B* and *C* directly from *A* is unnecessary.
Unfortunately, this is wrong, as this illustration shows:

If the points in the illustration are the two endpoints, we can see that by going from *A* to *C* through *B* we get a longer path.
How about this one: if we're testing both the moves *A*→*B* and *A*→*C*, then it's unnecessary to test *A*→*B*→*C* or *A*→*C*→*B*, since they can't result in shorter paths.
Wrong again:

The point is that using purely adjacency-based arguments is not going to cut it; we have to use the geometry of the problem as well.
What the two above examples have in common (as well as the second test-case on a larger scale,) is that there's a "hole" in the enclosed area.
It manifests itself in the fact that some of the points-of-intersection on the boundary—our "nails"—are within the triangle △*ABC* whose vertices are the circles' centers:

When this happens, there's a chance that going from *A* to *B* and from *A* to *C* will result in different paths.
More importantly, when it *doesn't* happen (i.e. if there wasn't a gap between *A*, *B* and *C*) then it's guaranteed that all paths starting with *A*→*B*→*C* and with *A*→*C* and which are otherwise equivalent will result in the same locally minimal path, hence if we visit *B* we don't need to also visit *C* directly from *A*.
This leads us to our elimination method:
When we're at a circle *A*, we keep a list *H* of the adjacent circles we've visited.
This list is initially empty.
We visit an adjacent circle *B* if there are any "nails" in *all* the triangles formed by the centers of *A*, *B* and any of the circles in *H* adjacent to *B*.
This method dramatically drops the number of paths we have to test to just 1 in the first test-case and 10 in the second one.
A few more notes:
* It's possible to decrease the number of paths we test even further, but this method is good enough for the scale of this problem.
* I used the algorithm from [my solution](https://codegolf.stackexchange.com/a/38692/31403) to the rubber-band challenge.
Since this algorithm is incremental it can be pretty easily integrated into the path-finding process, so that we minimize the path as we go along.
Since many paths share a starting-segment, this can significantly improve performance when we have lots of paths.
It can also hurt performance if there are much more dead-ends than valid paths.
Either way, for the given test-cases performing the algorithm for each path separately is good enough.
* There's one edge-case where this solution may fail:
If any of the points on the boundary is the point of intersection of two tangent circles then under some conditions the result can be wrong.
This is due to the way rubber-band algorithm works.
With some modifications it's possible to handle these cases as well, but, hell, it's already long enough.
---
```
# First test case
I={((32.,42.),64.),((112.,99.),59.),((141.,171.),34.),((157.,191.),28.),((177.,187.),35.),((244.,168.),57.),((289.,119.),20.),((299.,112.),27.),((354.,59.),58.),((402.,98.),23.),((429.,96.),29.),((424.,145.),34.),((435.,146.),20.),((455.,204.),57.),((430.,283.),37.),((432.,306.),48.),((445.,349.),52.),((424.,409.),59.),((507.,468.),64.)}
# Second test case
#I={((32.,42.),64.),((112.,99.),59.),((141.,171.),34.),((157.,191.),28.),((177.,187.),35.),((244.,168.),57.),((289.,119.),20.),((299.,112.),27.),((354.,59.),58.),((402.,98.),23.),((429.,96.),29.),((424.,145.),34.),((435.,146.),20.),((455.,204.),57.),((430.,283.),37.),((432.,306.),48.),((445.,349.),52.),((424.,409.),59.),((507.,468.),64.),((180.,230.),39.),((162.,231.),39.),((157.,281.),23.),((189.,301.),53.),((216.,308.),27.),((213.,317.),35.),((219.,362.),61.),((242.,365.),42.),((288.,374.),64.),((314.,390.),53.),((378.,377.),30.),((393.,386.),34.)}
from numpy import*
V=array;X=lambda u,v:u[0]*v[1]-u[1]*v[0];L=lambda v:dot(v,v)
e=V([511]*2)
N=set()
for c,r in I:
for C,R in I:
v=V(C)-c;d=L(v)
if d:
a=(r*r-R*R+d)/2/d;q=r*r/d-a*a
if q>=0:w=V(c)+a*v;W=V([-v[1],v[0]])*q**.5;N|={tuple(t)for t in[w+W,w-W]if all([L(t-T)>=s**2-1e-9 for T,s in I])}
N=map(V,N)
def T(a,b,c,p):H=[X(p-a,b-a),X(p-b,c-b),X(p-c,a-c)];return min(H)*max(H)>=0
def E(a,c,b):
try:d=max((X(n-a,b-a)**2,id(n),n)for n in N if T(a,b,c,n)*X(n-b,c-b)*X(n-c,a-c))[2];A=E(a,c,d);B=E(d,c,b);return[A[0]+[d]+B[0],A[1]+[sign(X(c-a,b-c))]+B[1]]
except:return[[]]*2
def P(I,c,r,A):
H=[];M=[""]
if L(c-e)>r*r:
for C,R in I:
if L(C-c)<=L(r+R)and all([L(h-C)>L(R+s)or any([T(c,C,h,p)for p in N])for h,s in H]):v=V(C);H+=[(v,R)];M=min(M,P(I-{(C,R)},v,R,A+[v]))
return M
A+=[e]*2;W=[.5]*len(A)
try:
while 1:
i=[w%1*2or w==0for w in W[2:-2]].index(1);u,a,c,b,v=A[i:i+5];A[i+2:i+3],W[i+2:i+3]=t,_=E(a,c,b);t=[a]+t+[b]
for p,q,j,k in(u,a,1,i+1),(v,b,-2,i+len(t)):x=X(q-p,c-q);y=X(q-p,t[j]-q);z=X(c-q,t[j]-q);d=sign(j*z);W[k]+=(x*y<=0)*(x*z<0 or y*z>0)*(x!=0 or d*W[k]<=0)*(y!=0 or d*W[k]>=0)*d
except:return[sum(L(A[i+1]-A[i])**.5for i in range(len(A)-1)),id(A),A]
print V(P(I,e*0,0,[e*0]*2)[2][1:-1])
```
Input is given through the variable `I` as a set of tuples `((x, y), r)` where `(x, y)` is the center of the circle and `r` is its radius.
The values must be `float`s, not `int`s.
The result is printed to STDOUT.
## Example
```
# First test case
I={((32.,42.),64.),((112.,99.),59.),((141.,171.),34.),((157.,191.),28.),((177.,187.),35.),((244.,168.),57.),((289.,119.),20.),((299.,112.),27.),((354.,59.),58.),((402.,98.),23.),((429.,96.),29.),((424.,145.),34.),((435.,146.),20.),((455.,204.),57.),((430.,283.),37.),((432.,306.),48.),((445.,349.),52.),((424.,409.),59.),((507.,468.),64.)}
[[ 0. 0. ]
[ 154.58723733 139.8329183 ]
[ 169.69950891 152.76985495]
[ 188.7391093 154.02738541]
[ 325.90536774 109.74141936]
[ 382.19108518 109.68789517]
[ 400.00362897 120.91319495]
[ 511. 511. ]]
```
] |
[Question]
[
### Definitions:
* A triangle is considered a ***right triangle*** if one of the inner angles is exactly 90 degrees.
* A number is considered ***rational*** if it can be represented by a ratio of integers, i.e., `p/q`, where both `p` and `q` are integers.
* A number `n` is a [***congruent number***](https://en.wikipedia.org/wiki/Congruent_number) if there exists a right triangle of area `n` where all three sides are rational.
* This is OEIS [A003273](http://oeis.org/A003273).
### Challenge
This is a [decision-problem](/questions/tagged/decision-problem "show questions tagged 'decision-problem'") challenge. Given an input number, `x`, output a distinct and consistent value if `x` is a congruent number, and a separate distinct and consistent value if `x` is not a congruent number. The output values do not necessarily need to be truthy/falsey in your language.
### Special Rule
For the purposes of this challenge, you can assume that the [Birch and Swinnerton-Dyer conjecture](https://en.wikipedia.org/wiki/Birch_and_Swinnerton-Dyer_conjecture#Consequences) is true. Alternatively, if you can prove the Birch and Swinnerton-Dyer conjecture, go claim your $1,000,000 Millennium prize. ;-)
### Examples
(Using `True` for congruent numbers and `False` otherwise).
```
5 True
6 True
108 False
```
### Rules and Clarifications
* Input and output can be given by [any convenient method](http://meta.codegolf.stackexchange.com/q/2447/42963).
* You can print the result to STDOUT or return it as a function result. Please state in your submission what values the output can take.
* Either a full program or a function are acceptable.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
# R, ~~179~~ ~~173~~ ~~142~~ ~~141~~ ~~137~~ ~~135~~ 134 bytes
Using the same arguments based on [Tunnell's Theorem](https://en.wikipedia.org/wiki/Tunnell%27s_theorem), returns a `0` if `n`is not congruent and `1` otherwise. (It took me a long while to spot the constraint on [the condition](https://en.wikipedia.org/wiki/Tunnell%27s_theorem) only applying to [squared-free integers](https://en.wikipedia.org/wiki/Square-free_integer).)
```
function(n){b=(-n:n)^2
for(i in b^!!b)n=n/i^(!n%%i)
P=1+n%%2
o=outer
!sum(!o(y<-o(8/P*b,2*b,"+")/P-n,z<-16/P*b,"+"),-2*!o(y,4*z,"+"))}
```
[Try it online](https://tio.run/##TY7LasMwEEX3@go5ISAlI2LJsmwP8aKLdNVF6GNVGrCD0xqcsfFjkZR@u@sEGroYuJx74E47NnyjxuNAh76sSZD8zlOhCEnuDTvWrSh5STzfe14uKaV1uRceLRalZLtUr6ZkWJ3WQ1@0zOuGk/Bqcd6oWsTr3TIHM91sNZPrnSK4bJR2N3xFoMzyKoNdXm5A/ozzQ02f7VBQz2k45UXb8aroOt5/ZcS177Nrfyzbrk8PIsQIdIA6BOOjsWBiDDQEFoIIgwSsBhuijSA0GDpwProAXAguwUhDFGHsQ2wxjiExmDjJWFZVosuapjqL@w40UvI5nyr@@vy2ZRmd/xyhcXpJvqu7/PHPfnx4etmOvw)
Improvements brought by [Arnaud](https://tio.run/##TZDNbsIwEITvPIWlCsmGRY0dx3E29YHnqFqpQEwt0QUlQeJHPHu6aSvKbb/xzni07TAcQjzSuk97kqSucd/KJBLPaNS7USlKmk7Ti1YU6DnVv2zUdRNMHYOut8Hfml3XsOBZMCxod6uXIatXQS4IiWPqMfbEsWIzW6kRziOc5vEPLyNuGZZhOZfn@SUEUgsz49HOfoATQ3YbntZ72rbHhnpBx69V03Zi13Sd6D8/SOgsm4zvMbVdH9aywBJ0jroAk6GxYDzmGnILeYl5BVaDLdCWUBgsHLgMXQ6uAFdhqaEs0WfgLXoPlcHKqcmEqwpJY9f7N0qkKOSBb8f9lDi0iXqGh1WpkYup18Xd8/Zo0v@m4Rs) and [Giuseppe](https://tio.run/##TZBNa8MwDIbv/hUupWA3Do2/EzFfe@59rLCUZjNsakhSaDv22zO7jNLLa/mRXiFpmHv6Us7dGQ9TPCFD/tOdBhZpRMoQFN8rjgE3cc8WuFpFTnYhvYq0gZUImPIkGy7ZUG/MfrdueQbXDC6F2qgHumUk3T/Zhm3BrsUtBOSlWi@uhVnfSiSL7e@8PJzwYzgfcaJ4/m6Pw0i/juNIp8/31KGqyL2gi8M4hQOz4IXUIK1QFSgjVA1aCm2E9qAbYaQwFowXVoF1wlXgtHBWuAa8FN5DXYnaQF2LRkHjOOmZzXKPfBaZRWXRnCzTKuk0eZfHEJzGjrI@XS@EitN@iDilz3Mtk5AG56/lw/T27JJPrvkP) (the final code is mostly Guiseppe's!), with -3 thanks to [Robin](https://codegolf.stackexchange.com/users/86301/robin-ryder)
Syntax analysis:
```
for(i in b[b>0])n=n/i^(!n%%i) #eliminates all square divisors of n
P=2^(n%%2) #n odd (2) or even (1)
o=outer #saves 3 bytes
o(8/P*b,2*b,"+")/P-n #all sums of (8/P)x^2+(2/P)*y^2-n
o(...,16/P*b,"+") #all sums of above and (16/P)*z^2
o(...,4*z,"+")) #all sums of above and (64/P)*z^2
!o(...,4*z,"+")) #all sums of above equal to zero
!sum(!...,2*!...) #are zeroes twice one another (Tunnell)
```
with [Tunnell's Theorem](https://en.wikipedia.org/wiki/Tunnell%27s_theorem) stating that n is congruent if and only if the number of integer solutions to 2x²+y²+8z²=n is twice as much as the number of integer solutions to 2x²+y²+32z²=n if n is odd and the number of integer solutions to 8x²+y²+16z²=n is twice as much as the number of integer solutions to 8x²+y²+64z²=n if n is even.
[Answer]
# Rust - 282 bytes
```
fn is(mut n:i64)->bool{let(mut v,p)=(vec![0;4],n as usize%2);while let Some(l)=(2..n).filter(|i|n%(i*i)==0).nth(0){n/=l*l;}for x in -n..=n{for y in -n..=n{for z in -n..=n{for i in 0..2{if n-6*x*x*(n+1)%2==2*x*x+(2-n%2)*(y*y+(24*i as i64+8)*z*z){v[2*p+i]+=1};}}}}v[2*p]==2*v[2*p+1]}
```
* Use [Jerrold B. Tunnell](http://sites.math.rutgers.edu/%7Etunnell/)'s theorem, which I dont actually understand, but seems to work anyways.
* divide n by all its square factors, to make it 'square free', since in the papers below Tunnell's theorem is described for square-frees only.
+ I believe this might work because every congruent number, when multiplied by a square, creates a bigger congruent number, and vice versa. so by testing the smaller number, we can validate the larger, which in our case is n. (all the removed squares, can be multiplied together to make one big square).
* loop through all possible combinations of x,y,z integers, test Tunnell's equations:
$$\text{if n is odd, test if n = }2x^2 + y^2 + 32z^2\text{ and/or }
2x^2 + y^2 + 8z^2$$
$$\text{if n is even, test if n = }8x^2 + 2y^2 + 64z^2
\text { and/or } 8x^2 + 2y^2 + 16z^2$$
+ in the code itself, the four equations have been smooshed into one, inside a loop, using modulo for even/odd
* keep a tally count of which equations match n
* after looping, test the ratios of the tallies (per Tunnell)
See Also:
* [If you wish, try the code on the Rust Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=85b2e7a26402ccc9edfca88c0d79fd66)
* [Congruent Numbers, Elliptic Curves, and Modular Forms, by Guy Henniart, Bilkent University website, translated by Franz Lemmermeyer](http://www.fen.bilkent.edu.tr/%7Efranz/publ/guy.pdf)
* [The Congruent Number Problem, by Keith Conrad, University of Connecticut website](https://www.math.uconn.edu/%7Ekconrad/articles/congruentnumber.pdf)
* [Congruent numbers, by Brian Hayes, bit-palyer.org blog](http://bit-player.org/2009/congruent-numbers)
*corrected even/odd, thanks*@Level River St
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~251~~ 234 bytes
Thanks to @arnauld for pointing out a silly typo on my part.
-17 bytes thanks to @ceilingcat.
```
#import<cmath>
int a(int n){int s=sqrt(n),c,x=-s,y,z,i=1,X;for(;++i<n;)for(;n%(i*i)<1;n/=i*i);for(;x++<s;)for(y=-s;y++<s;)for(z=-s;z++<s;c+=n&1?2*(n==X+24*z*z)-(n==X):2*(n==4*x*x+2*X+48*z*z)-(n/2==2*x*x+X))X=2*x*x+y*y+8*z*z;return!c;}
```
[Try it online!](https://tio.run/##dVLNjtsgED6bp5jdqivjHyW2slJlzPZQ9dA3sFTtgSUki2RjF7DWdpRXbwq4SZVDGYTnm/nmh8F8GPIj55fLJ9kNvbY175h9f0FSWWCxPxU@@Y@h5pe2scIZzyaam2zOlkzSImvIodcxSVNZK4KDrj7HMpG4LojaUK@tlClNa7NSZpeBzP/w4vESME@peiq@lkmsKG3ScpcsyYLzgHC1mnfJlExpmTTp7svVvSkpLYO9wbj5q87JnAYG0cKOWj1wcnZXVbwd9wJq2RurBeteULhwx6SKMZxQtNmAsUxbA8yCpM8ECpAHsO8C1Ni9CQ3SAO/VUY9C2Qy20Duf/pBGoMin6kc7jNb8fAUKpyLzsr3JPS5usj0ThCI3DwiTly7WVZZQUyid4kYcmouM3VcVdyWgruHxh3KVKgjr0VukPwJHqH3r@BEE4vdpENyKfXUlXpuU@fPrf2K@sZaPLQtRIcb9FJg4v5tGLOHBd7Y2dd/VLdUd8IFn5DaK1veALUHny29@aNnRXPKPPw "C++ (gcc) – Try It Online")
Returns 1 if `n` is congruent, 0 otherwise.
Given that we can assume that the Birch and Swinnerton-Dyer conjecture is true, I used [Tunnel's Theorem](https://en.wikipedia.org/wiki/Tunnell%27s_theorem) as a test. Note that technically only nonzero x, y, and z need to be tested, as a set of positive (x, y, z) implies more sets for when each of those is negative, since the four numbers defined use the square of x, y, and z in their calculation. Additionally, since only the *ratio* of the two numbers A and B, or C and D, is desired, we need not even worry about these other sets. Thus, we only need to add 2 for every solution for A or C, and subtract 1 for every solution of B or D, and check if we end with 0. Also, the input is reduced to a squarefree integer, because if \$q\$ is a congruent number then \$s^2q\$ is also congruent (the algorithm seems to break on some square-containing numbers.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~73~~ 67 [bytes](https://github.com/abrudz/SBCS)
```
{e←2∨w←⍵÷×⍨⊃⌽⍒⍵|⍨×⍨⍳⍵⋄0=¯2⊥+/w=e×⍪(r∘.+⍨32 8∘.×r)∘.+2×e×r←0,2/×⍨⍳w}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///vzr1UdsEo0cdK8qB9KPerYe3H57@qHfFo67mRz17H/VOAgrVAPkQwd7NQO6j7hYD20PrjR51LdXWL7dNBUmt0ih61DFDTxuoyNhIwQLEPjy9SBMsZnR4OlBNEdB4Ax0jfZhB5bX/08A29gGtOrTe@FHbxEd9U4ODnIFkiIdn8P@0QysUTBXMFMwVDI0VDE0UDE0VjAwUjAwVjIwUjIwVjEy40hQMDSwA "APL (Dyalog Unicode) – Try It Online")
-6 bytes thanks to @ngn and @H.PWiz.
Essentially the same algorithm as others.
### Ungolfed and how it works
```
f←{
⍝ Extract squarefree part of ⍵
w←⍵÷×⍨⊃⌽⍒⍵|⍨×⍨⍳⍵
⍝ ×⍨⍳⍵ ⍝ Square of 1..⍵
⍝ ⍵|⍨ ⍝ Remainders of dividing ⍵ by each of the above
⍝ ⊃⌽⍒ ⍝ Last item of descending sort order; index of last 0
⍝ w←⍵÷×⍨ ⍝ Remove square term and name it w
⍝ 1 if odd, 2 if even; divide w by that
w÷←e←2∨w
⍝ e←2∨w ⍝ GCD of w with 2; name it e
⍝ w÷← ⍝ Divide w by e and overwrite to w
⍝ Square of plus-minus range
r←0,2/×⍨⍳w
⍝ ×⍨⍳w ⍝ Square of 1..w
⍝ r←0,2/ ⍝ Make two copies of each number, prepend 0 and name it r
⍝ y2+32z2 (A/C) and y2+8z2 (B/D), with y and z swapped
m←∘.(32 8⊥¨∘⊂,)⍨r
⍝ ∘.( )⍨r ⍝ Self outer product of r by...
⍝ , ⍝ Concatenate two input numbers and
32 8⊥¨∘⊂ ⍝ Interpret as base-32 and base-8
⍝ m← ⍝ Name it m
⍝ Add 2×e×x2
m←,m∘.+2×e×r
⍝ m∘.+2×e×r ⍝ Outer product by + with 2×e×x2
⍝ m←, ⍝ Flatten and overwrite m
⍝ count w in m and check if B/D is twice A/C
0=¯2⊥⊃+/w=m
⍝ w=m ⍝ Test for each sum being w
⍝ ⊃+/ ⍝ Count of 'w's in A/C and B/D
⍝ ¯2⊥ ⍝ (¯2×A/C) + B/D
⍝ 0= ⍝ Equals 0?
}
```
[Answer]
# JavaScript (ES7), 165 bytes
Much like [@NeilA.'s answer](https://codegolf.stackexchange.com/a/184845/58563), this is based on [Tunnell's theorem](https://en.wikipedia.org/wiki/Tunnell%27s_theorem) and therefore assumes that the Birch and Swinnerton-Dyer conjecture is true.
Returns a Boolean value.
```
n=>(r=(g=i=>i<n?g(i+!(n%i**2?0:n/=i*i)):n**.5|0)(s=2),g=(C,k=r)=>k+r&&g(C,k-1,C(k*k)))(x=>g(y=>g(z=>s+=2*(n==(X=(n&1?2:8)*x+(o=2-n%2)*y)+o*32*z)-(n==X+o*8*z))))|s==2
```
[Try it online!](https://tio.run/##FcrRaoNAEIXhV7EXMTOz6zZuaQnSWSl5iUApRVJdNtrZsIYSQ97d6rn44YNzbv6a8ZTC5VpI/GnnjmdhB4nBc2AX3qX2ENQTyCYQ2XpXyTMHCoiVEJnXxw5hZIvaMxx0zwnZ9SrluV9ZlPoAPfWICDd2HqY1d3ajYksgzHBkkLysbbVHuimIbAvZWKQJVaQXS3cs1t9x0X7BssfIbOdTlDEOrRmih09jzEdKzQSlfcMv89tcAL51JpixyyRTWYmmC8O1TdChOccgsNVbxPkf "JavaScript (Node.js) – Try It Online")
### How?
We first transform the input \$n\$ into its square-free counterpart \$n'\$, compute \$r=\lfloor\sqrt{n'}\rfloor\$ and initialize \$s\$ to \$2\$.
```
r = ( // we will eventually save isqrt(n) into r
g = i => // g = recursive function taking an integer i
i < n ? // if i is less than n:
g(i + !( // do a recursive call with either i or i + 1
n % i**2 ? // if n is not divisible by i²:
0 // yield 0 and therefore increment i
: // else:
n /= i * i // divide n by i² and leave i unchanged
)) // end of recursive call
: // else:
n ** .5 | 0 // stop recursion and return isqrt(n)
)(s = 2) // initial call to g with i = s = 2
```
We then define the helper function \$g\$ which invokes a callback function \$C\$ with \$k^2\$ for \$-r<k\le r\$.
```
g = (C, k = r) => // C = callback function, k = counter initialized to r
k + r && // if k is not equal to -r:
g( // do a recursive call:
C, // pass the callback function unchanged
k - 1, // decrement k
C(k * k) // invoke the callback function with k²
) // end of recursive call
```
We finally use 3 nested calls to \$g\$ to walk through all triplets \$(x,y,z) \in [-r+1,r]^3\$ and update \$s\$ to test whether \$2A\_n = B\_n\$ if \$n\$ is odd or \$2C\_n=D\_n\$ if \$n\$ is even, with:
$$\begin{align}
&A\_n=\#\{(x,y,z)\in [-r+1,r]^3 \mid n=2x^2+y^2+32z^2\}\\
&B\_n=\#\{(x,y,z)\in [-r+1,r]^3 \mid n=2x^2+y^2+8z^2\}\\
&C\_n=\#\{(x,y,z)\in [-r+1,r]^3 \mid n=8x^2+2y^2+64z^2\}\\
&D\_n=\#\{(x,y,z)\in [-r+1,r]^3 \mid n=8x^2+2y^2+16z^2\}
\end{align}$$
```
g(x => // for each x: \ NB:
g(y => // for each y: >-- all these values are
g(z => // for each z: / already squared by g
s += // add to s:
2 * ( // +2 if:
n == ( // n is equal to either
X = // An if n is odd (o = 1)
(n & 1 ? 2 : 8) * x + // or Cn if n is even (o = 2)
(o = 2 - n % 2) * y //
) + o * 32 * z //
) - ( // -1 if:
n == X + o * 8 * z // n is equal to either
) // Bn if n is odd
) // or Dn if n is even
) //
) // if s in unchanged, then n is (assumed to be) congruent
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 126 bytes
```
->n{[8,32].product(*[(-n..-t=1).map{|i|i*=i;n%i<1&&n/=i;i}*2+[0]]*3).map{|j|d=2-n%2
k,x,y,z=j
2*d*x+y+k*z==n/d&&t+=k-16}
t==1}
```
[Try it online!](https://tio.run/##PZDdaoQwEIXvfQoRVtwYXScxMdKmLyJetJWFrNTK1oX989ntGSi9mEG@cz5lPF8@btvRb8Xb9Oic1Kov5/P3cPlcMtFlxVSWxeJpX369z49neAbhw8u0C6@UptMBz2EVKu@qvhf6r3R6Dl4V005Fo7zKm7z7U6TEIK75LR/F3fvpMKTpkvuxILtGi/e0bvNl@UmMjK2MGxmTxtQYEFVhCKMw4ApcOUwrY41MI9NgGp4G1@A1WA23xutqcAPXwDXoGXADbuFa9Cwyi8zy1@E24A14A6/B@xowB@bgOnQcXIfMIWvhtnBbZC2yFhlVxEvx4jMq@EQVLw6IA@Ie8aHkeHGF7yQ@jpThZZMoo7I01f@/P3ahT9P5HKYlCzKRcbJft18 "Ruby – Try It Online")
found a place to initialize `t=1` and expanded the list of squares into a triplet instead of using `q` to make additional copies.
# [Ruby](https://www.ruby-lang.org/), 129 bytes
```
->n{t=0
[8,32].product(q=(-n..-1).map{|i|i*=i;n%i<1&&n/=i;i}*2+[0],q,q).map{|j|d=2-n%2
k,x,y,z=j
2*d*x+y+k*z==n/d&&t+=k-16}
t==0}
```
[Try it online!](https://tio.run/##Pc1LCsIwFEDReVYhhYY0vyYRRdDnRkoHahDSYmxLCv1l7dGBOLuDA3cY73N6QhJXvwZQqDrxvallN7zt@AikByK8lEIX8nXr1s1tjoI7@9xdNMa@/LaL1LBK1bzn/U81mwUjfG5Qyyc@8wUaZKilE5tZSxcAX1qMA4NW6GNEAUDFRLSUB/X/PCtXY9wNzgfieMZ3WRHTBw "Ruby – Try It Online")
Uses Tunnell's theorem like the other answers. I use a single equation as follows.
```
2*d*x^2 + y^2 + k*z^2 == n/d where d=2 for even n and d=1 for odd n
```
We check the cases `k=8` and `k=32` and check if there are twice as many solutions for `k=8` than `k=32`. This is done by adding `k-16` to `t` every time we find a solution. This is either +16 in the case `k=32` or -8 in the case `k=8`. Overall the number is congruent if `t` is the same as its initial value at the end of the function.
It is necessary to find all solutions to the test equation. I see many answers testing between +/-`sqrt n`. It is perfectly OK to test also outside these limits if it makes code shorter, but no solutions will be found because the left side of the equation will exceed `n`. The thing I missed in the beginning is that negative and positive `x,y,z` are considered separately. Thus `-3,0,3` yields three squares `9,0,9` and all solutions must be counted separately (0 must be counted once and `9` must be counted twice.)
**Ungolfed code**
```
->n{t=0 #counter for solutions
q=(-n..-1).map{|i|i*=i;n%i<1&&n/=i #make n square free by dividing by -n^2 to -1^2 as necessary
i}*2+[0] #return an array of squares, duplicate for 1^2 to n^2, and add the case 0
[8,32].product(q,q,q).map{|j| #make a cartesian product of all possible values for k,x,y,z and iterate
d=2-n%2 #d=1 for odd n, 2 for even n
k,x,y,z=j #unpack j. k=8,32. x,y,z are the squared values from q.
2*d*x+y+k*z==n/d&&t+=k-16} #test if the current values of k,x,y,z are a valid solution. If so, adjust t by k-16 as explained above.
t==0} #return true if t is the same as its initial value. otherwise false.
```
] |
[Question]
[
An addition chain is a sequence of integers starting with 1, where every integer other than the initial 1 is a sum of two previous integers.
For instance, here's an addition chain:
```
[1, 2, 3, 4, 7, 8, 16, 32, 39, 71]
```
Here are the sums that make it an addition chain:
```
1 + 1 = 2
1 + 2 = 3
1 + 3 = 4
3 + 4 = 7
1 + 7 = 8
8 + 8 = 16
16 + 16 = 32
7 + 32 = 39
32 + 39 = 71
```
In this challenge, you will be given a positive integer `n`, and you must output one of the shortest addition chains which ends in `n`.
Examples - note that there are many possible outputs, all that you are required to find is an addition chain that's just as short:
```
1: [1]
2: [1, 2]
3: [1, 2, 3]
4: [1, 2, 4]
5: [1, 2, 3, 5]
6: [1, 2, 3, 6]
7: [1, 2, 3, 4, 7]
11: [1, 2, 3, 4, 7, 11]
15: [1, 2, 3, 5, 10, 15]
19: [1, 2, 3, 4, 8, 11, 19]
29: [1, 2, 3, 4, 7, 11, 18, 29]
47: [1, 2, 3, 4, 7, 10, 20, 27, 47]
71: [1, 2, 3, 4, 7, 8, 16, 32, 39, 71]
```
Standard I/O rules, etc. Standard Loopholes banned. Code golf: Fewest bytes wins.
[Answer]
## [Haskell](https://www.haskell.org/), 57 bytes
```
c=[1]:[x++[a+b]|x<-c,a<-x,b<-x]
f n=[x|x<-c,last x==n]!!0
```
A brute force solution.
[Try it online!](https://tio.run/nexus/haskell#@59sG20YaxVdoa0dnaidFFtTYaObrJNoo1uhkwQkYrnSFPJsoysgwjmJxSUKFba2ebGKigb/cxMz8xRsFQqKMvNKFFQU0hQMTf8DAA "Haskell – TIO Nexus")
## Explanation
The infinite list `c` contains all addition chains, ordered by length.
It is defined inductively in terms of itself, by taking a list `x` from `c` and two elements from `x`, and appending their sum to `x`.
The function `f` finds the first list in `c` that ends with the desired number.
```
c= -- c is the list of lists
[1]: -- containing [1] and
[x -- each list x
++[a+b] -- extended with a+b
|x<-c, -- where x is drawn from c,
a<-x, -- a is drawn from x and
b<-x] -- b is drawn from x.
f n= -- f on input n is:
[x -- take list of those lists x
|x<-c, -- where x is drawn from c and
last x==n] -- x ends with n,
!!0 -- return its first element.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
∧≜;1{j⊇Ċ+}ᵃ⁽?∋
```
[Try it online!](https://tio.run/##AS0A0v9icmFjaHlsb2cy///iiKfiiZw7MXtq4oqHxIorfeG1g@KBvT/iiIv//1r/MTk "Brachylog – Try It Online")
A brute-force submission that builds all possible addition chains using iterative deepening, stopping when a chain containing its right argument is found. Unlike most Brachylog submissions, this is a function submission that inputs via its right argument (conventionally called the Output) and outputs via its left argument (conventionally called the Input); doing this is somewhat controversial, but the [highest-voted meta answer](https://codegolf.meta.stackexchange.com/a/11909/62131) on the subject says it's legal (and doing so is consistent with our normal I/O defaults for functions). If we used the input and output in a more conventional way, this would be 16 bytes (`∧≜;1{j⊇Ċ+}ᵃ⁽.∋?∧`), because the right-hand side of the program would not be able to make use of the implicit constraint (thus would need that disabled, and a new explicit constraint given, at a cost of 2 bytes).
## Explanation
```
∧≜;1{j⊇Ċ+}ᵃ⁽?∋
∧ Disable implicit constraint to read the left argument
≜; ⁽ Evaluation order hint: minimize number of iterations
{ }ᵃ Repeatedly run the following:
1 ᵃ From {1 on the first iteration, results seen so far otherwise}
j Make {two} copies of each list element
⊇ Find a subset of the elements
Ċ which has size 2
+ and which sums to {the new result for the next iteration}
∋ If the list of results seen so far contains {the right argument}
? Output it via the left argument {then terminate}
```
An interesting subtlety here is what happens on the first iteration, where the input is a number rather than a list like on the other iterations; we start with the number 1, make two copies of every digit (making the number 11), then find a 2-digit subsequence of it (also the number 11). Then we take its digit sum, which is 2, and as such the sequence starts `[1,2]` like we want. On future iterations, we're starting with a list like `[1,2]`, doubling it to `[1,2,1,2]`, then taking a two-element subsequence (`[1,1]`, `[1,2]`, `[2,1]`, or `[2,2]`); clearly, the sums of each of these will be valid next elements of the addition chain.
It's a little frustrating here that the evaluation order hint is needed here, especially the `≜` component (it appears that `ᵃ` takes its evaluation order hint from *inside* rather than outside by default, thus the rather crude use of `≜` in order to force the issue).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
’ŒP;€µ+þ;1Fḟ@µÐḟḢ
```
Outputs the lexicographically first solution in exponential time.
[Try it online!](https://tio.run/nexus/jelly#@/@oYebRSQHWj5rWHNqqfXiftaHbwx3zHQ5tPTwBSD/csei/oWnQoa0Fjxq3WSsdbgcqc/8PAA "Jelly – TIO Nexus")
### How it works
```
’ŒP;€µ+þ;1Fḟ@µÐḟḢ Main link. Argument: n (integer)
’ Decrement; n-1.
ŒP Powerset; generate all subarrays of [1, ..., n-1], sorted first
by length, then lexicographically.
;€ Append n to all generate subarrays.
µ µÐḟ Filterfalse; keep only subarrays for which the chain between the
two chain separators (µ) returns a falsy value.
µ Monadic chain. Argument: A (array of integers)
+þ Add table; compute the sums of all pairs of elements in x,
grouping the results by the right addend.
;1 Append 1 to the resulting 2D array.
F Flatten the result.
ḟ@ Filterfalse swapped; remove all elements of A that appear in
the result. This yields an empty list for addition chains.
Ḣ Head; select the first result.
```
[Answer]
## JavaScript (ES6), ~~83~~ 86 bytes
*Edit: fixed to output the list in non-reverse order*
```
n=>(g=(s,a=[1])=>s-n?s>n||a.map(v=>g(v+=s,a.concat(v))):r=1/r|r[a.length]?a:r)(r=1)&&r
```
### Demo
```
let f =
n=>(g=(s,a=[1])=>s-n?s>n||a.map(v=>g(v+=s,a.concat(v))):r=1/r|r[a.length]?a:r)(r=1)&&r
for(n = 1; n <= 15; n++) {
console.log(n, '-->', JSON.stringify(f(n)));
}
```
[Answer]
# PHP, 195 Bytes
```
function p($a){global$argn,$r;if(!$r||$a<$r)if(end($a)==$argn)$r=$a;else foreach($a as$x)foreach($a as$y)in_array($w=$x+$y,$a)||$w>$argn||$w<=max($a)?:p(array_merge($a,[$w]));}p([1]);print_r($r);
```
[Try it online!](https://tio.run/nexus/php#VY4xDoMwDEX3noJKHmKVhaFLQ8pBEEIuDRAJQmRAgErPTkO2bv/7Pz05zVzrLkDcWJXc5VHPtprMYCMngPDTdMOLujDHwNLU4gq870ApMPqm7fvklAoIAvsgdTfqqB5YU9X6NaIRVvzvGxpbEjNtAhYF6w222Hu8eXkG1ZlS1dN66rOHEwEue82N9qc4h6VAlF8n8qRA6djYqWThv5LH8QM "PHP – TIO Nexus")
[Answer]
# Mathematica, 140 bytes
```
t={};s={1};(Do[While[Last@s!=#,s={1};While[Last@s<#,AppendTo[s,RandomChoice@s+Last@s]]];t~AppendTo~s;s={1},10^4];First@SortBy[t,Length@#&])&
```
.
produces a different shortest addition chain everytime you run it
[Try it online](https://sandbox.open.wolframcloud.com/app/objects/)
paste the code with ctrl+v, place input i.e [71] at the end of the code and press shift+enter
[Answer]
# Pyth, 13 bytes
```
h-DsM^N2/#QyS
```
[Test suite](https://pyth.herokuapp.com/?code=h-DsM%5EN2%2F%23QyS&test_suite=1&test_suite_input=1%0A5%0A7%0A10%0A11&debug=0)
Gives the lexicographically first shortest chain. It's fairly slow, but not that bad - `19` completes in about 30 seconds using pypy.
Some ideas from @Dennis's solution.
I really like this one - there are a ton of neat tricks involved.
**Explanation:**
```
h-DsM^N2/#QyS
h-DsM^N2/#QySQ Implicit variable introduction
SQ Inclusive range, 1 to input.
y Subsets - all subsets of the input, sorted by length then lexicographically
Only sorted subsets will be generated.
Our addition chain will be one of these.
/#Q Filter for presence of the input.
D Order by
- What's left after we remove
^N2 All pairs of numbers in the input
sM Summed
h Output the list that got sorted to the front.
```
This is still a bit hard to understand, but let me try to explain in a bit more detail.
We start with `ySQ`, which gives all possible ordered subsets of `[1, 2, ... Q]`, in increasing order of size. The shortest addition chain is definitely one of these, but we need to find it.
The first thing we'll do is filter the list to only keep lists that contain a `Q`. We do this with `/#Q`.
Next, we order the list by what's left after we remove the result of a certain function. `-D` orders by the remainder after removing something.
The thing we remove is `sM^N2`, where `N` is the list we're removing things from. `^N2` gives the cartesian product of `N` with itself, all possible pairs of two elements in `N`. `sM` then sums each of the pairs.
What's the smallest possible result, after we do this removal? Well, the smallest element in the input list definitely will remain, because all the numbers are positive, so any sum of two numbers will be greater than the smallest number. And there will be at least one number, because we checked that the input was present in the list. Therefore, the smallest possible result will be when every number except the smallest number is the sum of two other numbers in the list, and the smallest number in the list is 1. In this case, the sorting key will be `[1]`. These requirements mean that the list must be an addition chain.
So, we sort the addition chains to the front. Remember that `y` gives its subsets in increasing order of size, so the list which is sorted to the front must be one of the shortest addition chains. `h` selects that list.
[Answer]
# [Python 3](https://docs.python.org/3/), 102 bytes
```
f=lambda n,s={(1,)}:next((p for p in s if n in p),0)or f(n,{p+(i+j,)for p in s for i in p for j in p})
```
[Try it online!](https://tio.run/##fZLBbsIwDIbvfQpPuyQiIAIFVqRe9wS7IYQ6mo6gkkZN2ECIZ2dOmlJAbJWi2t/v2G5tfbSbSo0vlyIts91nnoFiJj0Rzuh5rsTBEqKhqGrQIBUYkAUoZ2nKhhRxQRQ76R6RvS2jN3HOlD7Qm1tvnuklFwVIs/rOSpmv1ptMKkwA3qDzCPDBCt5d9PkSXlJQDXZPLey@VvCelUZEnvpISJv3YF3pI6Fe@NnIUjS4u3@4RupKkz6nVwWLHlwxDpnKQVUW30dygD4cXedNGfchnUu7vM97C@Sj3iOIrDB2nRlhsIeT1/kcFnzJvD1yNoNRcMfBZTAOJL6SOJBJF8NgEuD0Fk4DnN3CmMEscM4fBYasFe/zozLE09bhycPVN3cVT9J@UPIsNx4MHLVB8exJEJYZuYN23Hb6CrMnvbqaU/QdS5C41s9R5MbU7pSb1vXPD6QVO0PC4DJjRG3/XMZmhl9VWYig4eBMVVuRE1x6Sv9PcnuRtntdCkXuBLdyDj4ulK6lsg19TBV1OnqXXw "Python 3 – Try It Online")
] |
[Question]
[
# Intro
Reverse and add is as simple as it sounds, take `n` and add it to its digits in reverse order. (e.g. 234 + 432 = 666).
If you apply this process repeatedly some numbers will eventually hit a prime number, and some will never reach a prime.
# Example
I currently have
11431 rep.
```
11431 is not prime
11431 + 13411 = 24842 which is not prime
24842 + 24842 = 49684 which is not prime
49684 + 48694 = 98378 which is not prime
98378 + 87389 = 185767 which is prime!
```
This number hits a prime
In contrast any multiple of 3 will never hit a prime, this is because the all multiples of 3 have a digit sum that is a multiple of 3 and vice versa.
Thus reverse and add on a multiple of 3 will always result in a new multiple of 3 and thus never a prime.
# Task
Take a positive integer `n` and determine if repeatedly reversing and adding will ever result in a prime number. Output a truthy or falsy value. Either truthy for reaches a prime and falsy value for does not or the other way around both are acceptable.
Prime numbers will be considered to reach a prime number in zero iterations.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so try to make your code as short as possible.
# Test Cases
True for reaches a prime false for never reaches a prime
```
11 -> True
11431 -> True
13201 -> True
13360 -> True
13450 -> True
1019410 -> True
1019510 -> True
22 -> False
1431 -> False
15621 -> False
14641 -> False
```
# Hint
While I was writing this challenge I discovered a cool trick that makes this problem a good deal easier. It is not impossible without this trick and it is not trivial with it either but it does help. I had a lot of fun discovering this so I will leave it in a spoiler below.
>
> Repeated reverse and add will always hit a multiple of 11 in 6 iterations or less. If it does not hit a prime before it hits a multiple of 11 it will never hit a prime.
>
>
>
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~84 79 77~~ 74 bytes
```
->x{y=1;x+="#{x}".reverse.to_i while(2...x).any?{|z|0==y=x%z}&&x%11>0;y>0}
```
[Try it online!](https://tio.run/nexus/ruby#TcxLCsIwFIXhuasolRZFDLl5gZQbFyJFHKRYEJUqmjTt2iNSr3T0f2dyGkxb62NAqPwG82X0Y84693Ldw7Hn7dhm73N7cSvBGPNrdrqGfRz6gSMG9EU/lqUvACyvguVjumfNAerFN2KKnAJAVZIoBf9TGk5Umshhp2A2NA3xO5@daSOIyiio0wc "Ruby – TIO Nexus")
>
> If I got it right, when we reach a multiple of 11 we can stop (we will only get multiples of 11 after that)
>
>
>
[Answer]
# [Haskell](https://www.haskell.org/), 65 bytes
`f` takes an `Integer` and returns a `Bool`. `True` means it reaches a prime.
```
f n=gcd(product[2..n-1])n<2||gcd 33n<2&&f(n+read(reverse$show n))
```
[Try it online!](https://tio.run/nexus/haskell#JcxLCoMwEAbgvadwIZJQGjJJDAj1JKWLYJJWqKPE2G68ux3r5vuHeY1uwG7AHJLrc7Xie8CwiNHNbHlNXxFFCs5z8W/vscTu2Xs2p8mvfb4rIfAKD443tW00KLWmsq4jw8txx1L4hLSE6vhVIuf7DlAAGE1qJQ@1laRpSAmtgTMbSqWKc7OxijTWwA8 "Haskell – TIO Nexus")
Unfortunately the short but inefficient prime test means that the OP's `True` test cases other than `11` grow too big to finish. But for example 11432 is a `True` case that does finish.
You can also try this 3 bytes longer one, for which TIO can finish all the `True` test cases:
```
f n=and[mod n i>0|i<-[2..n-1]]||gcd 33n<2&&f(n+read(reverse$show n))
```
[Try it online!](https://tio.run/nexus/haskell#JcxBCoMwEAXQvafIQiRSDJkkCgXtRcRFMLEN1LEktt149zSpm/dh@H9W7XBwuFuv571849OhDWzVLxoe25ctzFttavY/x4XgoNGM62YIEnfjh@ubUTCGDUzTcdxnQ6TEXlTVQvGSp9Tbj/XBlvkdwbqOEaAAUDIpBc/KjidVm@RwVXBmm1KI4my2nUiqTsEP "Haskell – TIO Nexus")
Both versions' prime tests break on 1, but it so happens that it gets to a prime (2) anyway.
Otherwise, I noticed about the same thing as G.B. in the spoiler of the Ruby submission:
>
> Once a number grows to even length, the next iteration will be divisible by 11. Once a number is divisible by 11, so will all following iterations.
>
>
>
[Answer]
# Python 2, ~~123~~ 110 bytes
Saved 13 bytes thanks to [Ørjan Johansen](https://codegolf.stackexchange.com/users/66041/%C3%98rjan-johansen) and [Wheat Wizard](https://codegolf.stackexchange.com/users/56656/wheat-wizard)!
```
n=input()
while 1:
if all(n%m for m in range(2,n)):print 1;break
if n%11==0:print 0;break
n+=int(`n`[::-1])
```
Returns 1 if it reaches a prime, 0 if it doesn't.
[Try it online!](https://tio.run/nexus/python2#NcxBCoMwEEbhvaeYjZDQFjIuIzlJEYwQ62DyV0LE46dFdP09XoUTbHtRujkWiYHYNiQz@RgV2kTzN1MiAWWPT1DdE1rbLQsKcT/l4NczR8vsnLnE3ILH/17UiPFt7YsHXSvzDw)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~78~~ ~~70~~ 69 bytes
```
f=lambda x:all(x%a for a in range(2,x))or x%11and f(x+int(`x`[::-1]))
```
[Try it online!](https://tio.run/nexus/python2#DckxCoAwDADAr2QpJKhDXISCLxGhkVop1CjFIb@vXe9aWovcRxQwL6WgOYH0VBDIClX0OnEejaiTOWbRCAltyPphsLB5P/FO1N7apQ8v1H4 "Python 2 – TIO Nexus")
# Explanation
This program relies on the fact that
>
> Every number that loss forever will reach a multiple of 11 in less than 6 moves
>
>
>
This program is a recursive lambda with circuited logical comparatives. It first checks if n is prime.
```
all(x%a for a in range(2,x))
```
If this is true we return true.
If it is false we check if it is a multiple of 11.
```
x%11
```
If false we return false otherwise we return the result of `f` on the next iteration
```
f(x+int(`x`[::-1]))
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 11 bytes
```
ṚḌ$+$6СÆPS
```
[Try it online!](https://tio.run/nexus/jelly#@/9w56yHO3pUtFXMDk84tPBwW0Dw////DQ1NjA0B "Jelly – TIO Nexus")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
**EDIT**: Saved one byte because input is reused if there aren't enough elements on the stack
```
[Dp#D11Ö#R+]p
```
[Try it online!](https://tio.run/##MzBNTDJM/f8/2qVA2cXQ8PA05SDt2IL//w0NTYwNAQ "05AB1E – Try It Online")
Uses the hint in the question
How it works
```
[ # begin infinite loop
# implicit input
D # duplicate input
p # push primality of input
# # if prime, break
D # duplicate input
11 # push 11
Ö # push input % 11 == 0
# # if multiple of 11, break
# implicit push input
R # reverse input
+ # add both numbers
] # end infinite loop
p # push primality of result; 1 if prime, 0 if multiple of 11
# implicit print
```
[Answer]
# MATLAB, ~~88~~ 81 bytes
```
function r=f(n);r=0;for i=1:7 r=r+isprime(n);n=n+str2num(fliplr(num2str(n)));end;
```
[Answer]
## JavaScript (ES6), 73 bytes
Returns `0` or `true`.
```
f=n=>{for(d=n;n%--d;);return d<2||n%11&&f(+[...n+''].reverse().join``+n)}
```
### Commented
This is based on the magic-spoiler formula described by Wheat Wizard.
```
f = n => { // given n:
for(d = n; n % --d;); // find the highest divisor d of n
return //
d < 2 || // if this divisor is 1, return true (n is prime)
n % 11 && // else: if 11 is a divisor of n, return 0
f( // else: do a recursive call with
+[...n + ''] // the digits of n
.reverse().join`` // reversed, joined,
+ n // coerced to a number and added to n
) //
} //
```
### Test cases
I've removed the two largest inputs from the snippet, as they take a few seconds to complete. (But they do work as well.)
```
f=n=>{for(d=n;n%--d;);return d<2||n%11&&f(+[...n+''].reverse().join``+n)}
console.log(f(11)) // -> True
console.log(f(11431)) // -> True
console.log(f(13201)) // -> True
console.log(f(13360)) // -> True
console.log(f(13450)) // -> True
console.log(f(22)) // -> False
console.log(f(1431)) // -> False
console.log(f(15621)) // -> False
console.log(f(14641)) // -> False
```
[Answer]
# Mathematica, 45 bytes
```
Or@@PrimeQ@NestList[#+IntegerReverse@#&,#,6]&
```
[Answer]
## Microsoft Sql Server, 826 786\* bytes
\* I've recalled about the IIF function that was introduced in Microsoft Sql Server 2012
```
set nocount on
use rextester
go
if object_id('dbo.n','IF')is not null drop function dbo.n
go
create function dbo.n(@ bigint,@f bigint)returns table as return
with a as(select 0 c union all select 0),b as(select 0 c from a,a t),c as(select 0 c from b,b t),
d as(select 0 c from c,c t),e as(select 0 c from d,d t),f as(select 0 c from e,e t),
v as(select top(@f-@+1)0 c from f)select row_number()over(order by(select 0))+@-1 n from v
go
with u as(select cast(a as bigint)a from(values(11),(11431),(13201),(13360),(13450),(1019410),(1019510),(22),(1431),
(15621),(14641))u(a)),v as(select a,a c from u union all select a,c+reverse(str(c,38))from v
where 0=any(select c%n from dbo.n(2,c/2))and c%11>0)select a,iif(0=any(select max(c)%n from dbo.n(2,max(c)/2)),0,1)
from v group by a option(maxrecursion 0)
```
[Check it online](http://rextester.com/EVXTY29490)
**The more neat formatting**
```
SET NOCOUNT ON;
USE rextester;
GO
IF OBJECT_ID('dbo.n', 'IF') IS NOT NULL DROP FUNCTION dbo.n;
GO
CREATE FUNCTION dbo.n(@ BIGINT,@f BIGINT)RETURNS TABLE AS RETURN
WITH
a AS(SELECT 0 c UNION ALL SELECT 0),
b AS(SELECT 0 c FROM a,a t),
c AS(SELECT 0 c FROM b,b t),
d AS(SELECT 0 c FROM c,c t),
e AS(SELECT 0 c FROM d,d t),
f AS(SELECT 0 c FROM e,e t),
v AS(SELECT TOP(@f-@+1)0 c FROM f)
SELECT ROW_NUMBER()OVER(ORDER BY(SELECT 0))+@-1 n FROM v;
GO
WITH u AS(
SELECT CAST(a AS BIGINT) a
FROM(VALUES (11), (11431), (13201), (13360), (13450), (1019410), (1019510),
(22), (1431), (15621), (14641)) u(a)
),
v AS(
SELECT a, a c FROM u
UNION ALL
SELECT a, c + reverse(str(c, 38))
FROM v
WHERE 0 = ANY(SELECT c % n FROM dbo.n(2, c / 2)) AND c % 11 > 0
)
SELECT a, IIF(0 = ANY(SELECT MAX(c) % n FROM dbo.n(2, MAX(c) / 2)), 0, 1)
FROM v
GROUP BY a
OPTION (MAXRECURSION 0);
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ṚḌ+Ɗ6СẒẸ
```
[Try it online!](https://tio.run/##y0rNyan8///hzlkPd/RoH@syOzzh0MKHuyY93LXj/@H2R01r/v83NNQxNDQxBpLGRgYg0tjMAEiamAJJA0NLE0MIbQqkjYx0ICpNzYyApImZiSEA "Jelly – Try It Online")
### How it works
```
ṚḌ+Ɗ6СẒẸ Monadic main link.
ṚḌ+Ɗ Monad: Reverse and add to original.
6С Repeatedly apply the above 6 times, collecting all iterations
ẒẸ Is any of them a prime?
```
[Answer]
[PHP](http://php.net/) **114 bytes**
```
<?php function f($n){$n1=strrev((string)$n);$r=$n+(int)$n1;for($i=2;$i<$r;$i++){if($r%$i==0){die('0');}}die('1');}
```
More readable version:
```
<?php function f($n)
{
$n1 = strrev((string)$n);
$r = $n + (int)$n1;
for ($i = 2; $i < $r; $i++) {
if ($r % $i == 0) {
die('0');
}
}
die('1');
}
f(11431 );
```
[Try it online!](https://tio.run/##VYwxDsIwDEX3nMKDUR11aYCtjThMaYgXJwqFBfXswVGRKv7wLb9nOcdc63TLMZvwknnlJBAIxX4MaFAceHiupSxvIp0sD6t23G1RiQI9EMuq3O08pELI/jwiT1i0@/73r4X1fzkhg/cwWDhEyzLHBMP4x9q9PdBmjr7zQp3r1G7GBHLuenGgW631Cw)
I used [this](https://mothereff.in/byte-counter) thing for counting bytes.
] |
[Question]
[
This is a king of the hill challenge for Dots and Boxes (aka Pen the Pig). The game is simple, on your turn just draw a line on an empty fence. Every time you complete a square you get a point. Also, since we are playing by **championship rules**, if you complete at least one square on your turn you get an extra turn. This is a round robin tournament, where each bot plays each other bot ~~twice~~ 12 times on a 9x9 grid. Check out this match between two heavyweight titans, where ChainCollector makes mince meat of reigning co-champion Asdf:
[](https://i.stack.imgur.com/kCvg0.gif)
# Rules
1. 0.5 second time limit per move.
2. No interfering with other bots.
3. Use PigPen.random() and PigPen.random(int) for randomness.
4. No writing to files.
5. Bot and all its persistent data will be reset every time opponent changes (every 12 rounds).
# Bots
Every bot extends Player.java:
```
package pigpen;
public abstract class Player {
public abstract int[] pick(Board board, int id, int round);
}
```
`Board` is the game board, which mainly serves to give you access to `Pen` classes, and `id` is your playerID (tells you if you're first or second), `round` tells you which round your playing against the same opponent (1 or 2). The return value is an `int[]`, where the first element is the penID (1-indexed), and the second element is the fenceID (0-indexed). See `Pen.pick(int)` for an easy way to generate this return value. See the [Github](https://github.com/geokavel/pigpen) page for example players and JavaDoc. Since we are only using a square grid ignore any functions and fields related to hexagons.
# How to Run
1. Download Source from Github.
2. Write your controller bot (make sure to include `package pigpen.players`) and put it in the `src/` folder;
3. Compile with `javac -cp src/* -d . src/*.java`. Run with `java pigpen.Tournament 4 9 9 false` (the last two numbers can be changed to adjust grid size. The last variable should only be set to `true` if you wish to use the pp\_record software.)
# Scores
1. ChainCollector: 72
2. Asdf: 57
3. Lazybones: 51
4. Finisher: 36
5. =LinearPlayer: 18
6. =BackwardPlayer: 18
7. RandomPlayer: 0
## See Also:
* [Dots and Boxes fastest code](https://codegolf.stackexchange.com/questions/30313/fastest-player-for-dots-and-boxes)
* [Dots and Boxes Wikipedia page](https://en.wikipedia.org/wiki/Dots_and_Boxes)
**Note**: this game is a competitive challenge and not easily solvable, due to giving players an extra turn for completing a box.
Thanks to Nathan Merrill and Darrel Hoffman for consulting on this challenge!
**Updates**:
* Added a `moves(int player)` method to the Board class to get a list of every move a player has made.
>
> ### [Indefinite Bounty (100 Rep)](http://meta.codegolf.stackexchange.com/questions/5243/list-of-bounties-with-no-deadlines):
>
>
> First person to post a solution that wins every round, and uses **strategy** (adjusting play based on observing how the opponent plays).
>
>
>
[Answer]
# Lazybones
This bot is lazy. He picks a random spot and direction and continues to build in that direction without moving too much. There are only 2 cases where he does something different:
* "make money" by closing a peg with only 1 remaining fence
* choose a new spot and direction if placing the fence is not possible or would allow the other bot to "make money"
```
package pigpen.players;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
import pigpen.Board;
import pigpen.Pen;
import pigpen.PigPen;
import pigpen.Player;
public class Lazybones extends Player {
private static class Fence {
private static boolean isOk(Board board, boolean vertical, int row, int col) {
if (vertical) {
Pen left = board.getPenAt(row, col - 1);
Pen right = board.getPenAt(row, col);
if (left.id() < 0 && right.id() < 0 ||
left.fences()[Pen.RIGHT] > 0 ||
right.fences()[Pen.LEFT] > 0 ||
left.remaining() == 2 ||
right.remaining() == 2) {
return false;
}
} else {
Pen top = board.getPenAt(row - 1, col);
Pen bottom = board.getPenAt(row, col);
if (top.id() < 0 && bottom.id() < 0 ||
top.fences()[Pen.BOTTOM] > 0 ||
bottom.fences()[Pen.TOP] > 0 ||
top.remaining() == 2 ||
bottom.remaining() == 2) {
return false;
}
}
return true;
}
private static Fence pickRandom(Board board) {
List<Fence> ok = new ArrayList<>();
List<Fence> notOk = new ArrayList<>();
for (int row = 0; row < board.rows; row ++) {
for (int col = 0; col < board.cols; col ++) {
(isOk(board, false, row, col) ? ok : notOk)
.add(new Fence(false, row, col));
(isOk(board, true, row, col) ? ok : notOk)
.add(new Fence(true, row, col));
}
(isOk(board, true, row, board.cols) ? ok : notOk)
.add(new Fence(true, row, board.cols));
}
for (int col = 0; col < board.cols; col ++) {
(isOk(board, false, board.rows, col) ? ok : notOk)
.add(new Fence(false, board.rows, col));
}
if (ok.isEmpty()) {
return notOk.get(PigPen.random(notOk.size()));
} else {
return ok.get(PigPen.random(ok.size()));
}
}
private final boolean vertical;
private final int row;
private final int col;
public Fence(boolean vertical, int row, int col) {
super();
this.vertical = vertical;
this.row = row;
this.col = col;
}
private Fence next(Board board, boolean negative) {
int newRow = vertical ? (negative ? row - 1 : row + 1) : row;
int newCol = vertical ? col : (negative ? col - 1 : col + 1);
if (isOk(board, vertical, newRow, newCol)) {
return new Fence(vertical, newRow, newCol);
} else {
return null;
}
}
private int[] getResult(Board board) {
if (vertical) {
if (col < board.cols) {
return board.getPenAt(row, col).pick(Pen.LEFT);
} else {
return board.getPenAt(row, col - 1).pick(Pen.RIGHT);
}
} else {
if (row < board.rows) {
return board.getPenAt(row, col).pick(Pen.TOP);
} else {
return board.getPenAt(row - 1, col).pick(Pen.BOTTOM);
}
}
}
}
private Fence lastFence = null;
private boolean negative = false;
@Override
public int[] pick(Board board, int id, int round) {
List<Pen> money = board.getList().stream()
.filter(p -> p.remaining() == 1).collect(Collectors.toList());
if (!money.isEmpty()) {
return money.get(PigPen.random(money.size())).pick(Pen.TOP);
}
if (lastFence != null) {
lastFence = lastFence.next(board, negative);
}
if (lastFence == null) {
lastFence = Fence.pickRandom(board);
negative = PigPen.random(2) == 0;
}
return lastFence.getResult(board);
}
}
```
[Answer]
# ChainCollector
This bot likes chains1. He wants as much of them as possible. Sometimes he even sacrifices a small part of a chain to win a bigger one.
[1] A chain consists of pens connected by open fences, where each pen has 1 or 2 open fences. If a single pen belonging to the chain can be finished, then because of the championship rule the whole chain can be finished as well.
```
package pigpen.players;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.TreeMap;
import pigpen.Board;
import pigpen.Pen;
import pigpen.Player;
public class ChainCollector extends Player {
private enum Direction {
TOP, RIGHT, BOTTOM, LEFT;
public Direction opposite() {
return values()[(ordinal() + 2) % 4];
}
}
private enum ChainEndType {
OPEN, CLOSED, LOOP
}
private static class PenEx {
private final int id;
private final List<Fence> openFences = new ArrayList<>();
private boolean used = false;
public PenEx(int id) {
super();
this.id = id;
}
public void addOpenFence(Direction direction, PenEx child) {
openFences.add(new Fence(this, direction, child));
if (child != null) {
child.openFences.add(new Fence(child, direction.opposite(), this));
}
}
}
private static class Fence {
public final PenEx parent;
public final Direction direction;
public final PenEx child;
public Fence(PenEx parent, Direction direction, PenEx child) {
super();
this.parent = parent;
this.direction = direction;
this.child = child;
}
public int[] getMove() {
if (parent == null) {
return new int[] { child.id, direction.opposite().ordinal() };
} else {
return new int[] { parent.id, direction.ordinal() };
}
}
}
private static class Moves {
private final TreeMap<Integer, List<Fence>> map = new TreeMap<>();
public void add(int score, Fence move) {
List<Fence> list = map.get(score);
if (list == null) {
list = new ArrayList<>();
map.put(score, list);
}
list.add(move);
}
public boolean isEmpty() {
return map.isEmpty();
}
public boolean hasExactlyOne() {
return map.size() == 1 && map.firstEntry().getValue().size() == 1;
}
public int getLowestScore() {
return map.firstKey();
}
public int[] getLowMove() {
return map.firstEntry().getValue().get(0).getMove();
}
public int[] getHighMove() {
return map.lastEntry().getValue().get(0).getMove();
}
}
private static class BoardEx {
private final List<PenEx> pens = new ArrayList<>();
private final Moves neutralMoves = new Moves();
private final Moves finisherMoves = new Moves();
private final Moves safeFinisherMoves = new Moves();
private final Moves sacrificeMoves = new Moves();
private final Moves badMoves = new Moves();
public BoardEx(Board board) {
super();
PenEx[][] tmp = new PenEx[board.rows][board.cols];
for (int row = 0; row < board.rows; ++row) {
for (int col = 0; col < board.cols; ++col) {
Pen pen = board.getPenAt(row, col);
int[] fences = pen.fences();
PenEx penEx = new PenEx(pen.id());
tmp[row][col] = penEx;
pens.add(penEx);
if (fences[Pen.TOP] == 0) {
penEx.addOpenFence(Direction.TOP, row == 0 ? null : tmp[row - 1][col]);
}
if (row == board.rows - 1 && fences[Pen.BOTTOM] == 0) {
penEx.addOpenFence(Direction.BOTTOM, null);
}
if (fences[Pen.LEFT] == 0) {
penEx.addOpenFence(Direction.LEFT, col == 0 ? null : tmp[row][col - 1]);
}
if (col == board.cols - 1 && fences[Pen.RIGHT] == 0) {
penEx.addOpenFence(Direction.RIGHT, null);
}
}
}
}
private ChainEndType followChain(Fence begin, List<Fence> result) {
Fence current = begin;
for (;;) {
current.parent.used = true;
result.add(current);
if (current.child == null) {
return ChainEndType.OPEN;
}
List<Fence> childFences = current.child.openFences;
switch (childFences.size()) {
case 1:
current.child.used = true;
return ChainEndType.CLOSED;
case 2:
if (current.child == begin.parent) {
return ChainEndType.LOOP;
} else {
current = current.direction.opposite() == childFences.get(0).direction ?
childFences.get(1) : childFences.get(0);
}
break;
case 3:
case 4:
return ChainEndType.OPEN;
default:
throw new IllegalStateException();
}
}
}
public void findChains() {
for (PenEx pen : pens) {
if (!pen.used && pen.openFences.size() > 0) {
if (pen.openFences.size() < 3) {
List<Fence> fences = new ArrayList<>();
ChainEndType type1 = pen.openFences.size() == 1 ?
ChainEndType.CLOSED : followChain(pen.openFences.get(1), fences);
if (type1 == ChainEndType.LOOP) {
badMoves.add(fences.size(), fences.get(0));
} else {
Collections.reverse(fences);
ChainEndType type2 = followChain(pen.openFences.get(0), fences);
if (type1 == ChainEndType.OPEN && type2 == ChainEndType.CLOSED) {
type1 = ChainEndType.CLOSED;
type2 = ChainEndType.OPEN;
Collections.reverse(fences);
}
if (type1 == ChainEndType.OPEN) {
badMoves.add(fences.size() - 1, fences.get(fences.size() / 2));
} else if (type2 == ChainEndType.CLOSED) {
finisherMoves.add(fences.size() + 1, fences.get(0));
if (fences.size() == 3) {
sacrificeMoves.add(fences.size() + 1, fences.get(1));
} else {
safeFinisherMoves.add(fences.size() + 1, fences.get(0));
}
} else {
finisherMoves.add(fences.size(), fences.get(0));
if (fences.size() == 2) {
sacrificeMoves.add(fences.size(), fences.get(1));
} else {
safeFinisherMoves.add(fences.size(), fences.get(0));
}
}
}
} else {
pen.used = true;
for (Fence fence : pen.openFences) {
if (fence.child == null || fence.child.openFences.size() > 2) {
neutralMoves.add(fence.child == null ? 0 : fence.child.openFences.size(), fence);
}
}
}
}
}
}
public int[] bestMove() {
if (!neutralMoves.isEmpty()) {
if (!finisherMoves.isEmpty()) {
return finisherMoves.getHighMove();
}
return neutralMoves.getHighMove();
}
if (!safeFinisherMoves.isEmpty()) {
return safeFinisherMoves.getHighMove();
}
if (badMoves.isEmpty() && !finisherMoves.isEmpty()) {
return finisherMoves.getHighMove();
}
if (!sacrificeMoves.isEmpty()) {
if (sacrificeMoves.hasExactlyOne()) {
if (badMoves.getLowestScore() - sacrificeMoves.getLowestScore() >= 2) {
return sacrificeMoves.getLowMove();
} else {
return finisherMoves.getHighMove();
}
} else {
return finisherMoves.getHighMove();
}
}
if (!badMoves.isEmpty()) {
return badMoves.getLowMove();
}
return null;
}
}
@Override
public int[] pick(Board board, int id, int round) {
BoardEx boardEx = new BoardEx(board);
boardEx.findChains();
return boardEx.bestMove();
}
}
```
[Answer]
# Finisher
```
package pigpen.players;
import pigpen.*;
import java.util.*;
/**
* Picks a Pen with only one fence remaining.
* Otherwise picks one with the most fences remaining
*/
public class Finisher extends Player implements Comparator<Pen> {
public int[] pick(Board board, int id) {
return Collections.max(board.getList(),this).pick(Pen.TOP);
}
@Override
public int compare(Pen p1, Pen p2) {
//1 remaining is best, all remaining is second.
int r1 = p1.remaining();
int r2 = p2.remaining();
if(r1 == 1) r1 = 7;
if(r2 == 1) r2 = 7;
return Integer.compare(r1,r2);
}
}
```
Uses a Comparator to pick the Pen with the most available fences, but gives priority to Pen's with only 1 fence available. (7 is used rather than 5 to allow this code to work in hexagon mode as well)
[Answer]
# Asdf
Assigns a score to each fence and then picks the best out of them. For example: A pen with one open fence has a score of 10, while a pen with 2 open fences has a score of -8.
It seems like [Lazybones](https://codegolf.stackexchange.com/a/66486/15080) uses a similar strategy, because it ties with this bot.
```
package pigpen.players;
import java.util.*;
import pigpen.*;
public class Asdf extends Player {
private final List<Score> scores = new ArrayList<>();
@Override
public int[] pick(Board board, int id, int round) {
scores.clear();
List<Pen> pens = board.getList();
pens.stream().filter(x -> !x.closed()).forEach((Pen p) -> evaluate(p));
Optional<Score> best = scores.stream().max(Comparator.comparingInt(p -> p.points));
if (best.isPresent()) {
Score score = best.get();
return score.pen.pick(score.fence);
}
return null;
}
private void evaluate(Pen pen) {
int[] fences = pen.fences();
for (int i = 0; i < fences.length; i++) {
if (fences[i] == 0) {
int points = getPoints(pen);
Pen neighbour = pen.n(i);
if (neighbour.id() != -1) {
points += getPoints(neighbour);
}
scores.add(new Score(pen, i, points));
}
}
}
private int getPoints(Pen pen) {
switch (pen.remaining()) {
case 1: return 10;
case 2: return -1;
case 3: return 1;
}
return 0;
}
class Score {
private Pen pen;
private int fence;
private int points;
Score(Pen pen, int fence, int points) {
this.pen = pen;
this.fence = fence;
this.points = points;
}
}
}
```
[Answer]
# LinearPlayer
```
package pigpen.players;
import pigpen.*;
/**
* Picks the first available fence in the first available Pen
*/
public class LinearPlayer extends Player {
@Override
public int[] pick(Board board, int id) {
for(int p = 1;p<=board.size;p++) {
Pen pen = board.get(p);
if(!pen.closed()) {
int[] fences = pen.fences();
for(int i =0;i<fences.length;i++) {
if(fences[i] == 0) {
return new int[]{pen.id(),i};
}
}
}
}
return new int[]{1,0};
}
}
```
The easiest way to write this bot is actually `return null`, because an invalid entry will automatically select the first available fence. This code does not use any shortcut methods and manually generates the return value.
[Answer]
# BackwardPlayer
```
package pigpen.players;
import pigpen.*;
/**
* Picks the first available fence in the last available Pen
*/
public class BackwardPlayer extends Player {
public int[] pick(Board board, int id) {
for(int i = board.size;i>0;i--) {
Pen p = board.get(i);
if(!p.closed()) {
return p.pick(Pen.TOP);
}
}
return new int[] {1,0};
}
}
```
This code uses the shortcut method `Pen.pick(int)` to generate the return value. If the top fence is unavailable, it will pick the closest available fence going clockwise.
[Answer]
# RandomPlayer
```
package pigpen.players;
import pigpen.*;
/**
* Picks the first available fence in a random Pen
*/
public class RandomPlayer extends Player {
public int[] pick(Board board, int id) {
int pen = PigPen.random(board.size)+1;
return board.get(pen).pick(Pen.TOP);
}
}
```
Same idea as BackwardPlayer, but randomly selects a pen. Note the `+1` because Pen's are 1-indexed.
] |
[Question]
[
To mark the anniversary of [World IPv6 day](http://en.wikipedia.org/wiki/World_IPv6_Day_and_World_IPv6_Launch_Day), the Internet Society has published a campaign to [Turn Off IPv4 on 6 June 2014 for One Day](http://www.internetsociety.org/deploy360/blog/2013/12/campaign-turn-off-ipv4-on-6-june-2014-for-one-day/).
---
IPv6 addresses may be represented in their long form as eight colon-separated 16-bit hex values. Depending on the address, they may also be shortened as described in item 2 of [section 2.2 *Text Representation of Addresses* of RFC 3513](https://www.rfc-editor.org/rfc/rfc3513#section-2.2):
>
> In order to make writing addresses containing zero bits easier a special syntax is available to compress the zeros. The use of "::" indicates one or more groups of 16 bits of zeros. The "::" can only appear once in an address. The "::" can also be used to compress leading or trailing zeros in an address.
>
>
>
* Entries to this challenge will be programs that accept exactly one IPv6 address formatted in either the long or shortened format, and will display the same address in **both** the long and short formats, in that order.
* The input may come from command-line arguments, STDIN, or any other input source that suits your choice of language.
* Libraries or utilities specifically for parsing IPv6 addresses are banned (e.g. [inet\_{ntop,pton}()](http://pubs.opengroup.org/onlinepubs/009695399/functions/inet_ntop.html)).
* If the input address is invalid, the output will be empty (or some suitable error message **indicating the address is invalid** is given)
* In cases where `::` shortening occurs, only one shortening operation may happen for a given address. If there are more than one potential shortening operations for a given address, the operation that gives the overall shortest address must be used. If there is a tie in this regard, the first operation will be used. This is illustrated in the examples below.
* [Standard loopholes to be avoided](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny)
Examples:
```
Input Output
1080:0:0:0:8:800:200C:417A 1080:0:0:0:8:800:200C:417A
1080::8:800:200C:417A
FF01::101 FF01:0:0:0:0:0:0:101
FF01::101
0:0:0:0:0:0:0:1 0:0:0:0:0:0:0:1
::1
:: 0:0:0:0:0:0:0:0
::
1:0:0:2:0:0:0:3 1:0:0:2:0:0:0:3
1:0:0:2::3
1:0:0:8:8:0:0:3 1:0:0:8:8:0:0:3
1::8:8:0:0:3
1:2:3:4:5:6:7:8 1:2:3:4:5:6:7:8
1:2:3:4:5:6:7:8
ABCD:1234 <Invalid address format - no output>
ABCDE::1234 <Invalid address format - no output>
1:2:3:4:5:6:7:8:9 <Invalid address format - no output>
:::1 <Invalid address format - no output>
codegolf puzzle <Invalid address format - no output>
```
This is [codegolf](/questions/tagged/codegolf "show questions tagged 'codegolf'"), so the shortest answer in bytes on June 6th 2014 will be accepted as the winner.
[Answer]
# Javascript (E6) 246 ~~305 284 292 319~~
**Heavily revised**
Special case for :: specifically handled, compress phase avoids the for loop (but not very shorter indeed)
~~I'm sure that the final compress phase can be made shorter. Not now anyway~~
```
F=i=>(c=':',d=c+c,z=':0'.repeat(9-i.split(c,9).length)+c,i=i==d?0+z+0:i[R='replace'](/^::/,0+z)[R](/::$/,z+0)[R](d,z>c?z:d),/^(:[\da-f]{1,4}){8}:$/i.test(k=c+i+c)&&[i,k[R]((k.match(/:(0:)+/g)||[]).sort().pop(),d)[R](/^:([^:])|([^:]):$/g,'$1$2')])
```
Thanks to [nderscore](https://codegolf.stackexchange.com/users/20160/nderscore)
**As a program**
Input and output using js popup, basically: `p=prompt,p(F(p()))`
Rewriting with popup and without the function definition, the char count should be under 260
**Ungolfed**
and commented a bit
```
F = i => (
c = ':',
d = c+c,
z = ':0'.repeat(9-i.split(c,9).length) + c,
i = i == d ? 0+z+0 /* special case '::' */
: i.replace(/^::/,0+z) /* special case '::...' */
.replace(/::$/,z+0) /* special case '...::' */
.replace(d, z > c ? z : d), /* here, if z==c, not valid: too much colons */
/^(:[\da-f]{1,4}){8}:$/i.test(k = c+i+c) /* Check if valid */
&& [
i,
k.replace((k.match(/:(0:)+/g)||[]).sort().pop(),d) /* find longest 0: sequence and replace it */
.replace(/^:([^:])|([^:]):$/g,'$1$2') /* cut leading and trailing colons */
]
)
```
**Test**
In console
```
i=['1080:0:0:0:8:800:200C:417A'
, '::1:2:3:4:5:6:7', '1:2:3:4:5:6:7::'
, '1:2:3:4::5:6:7:8'
, ':1:2:3:4:5:6:7', '1:2:3:4:5:6:7:'
, 'FF01::101', '0:0:0:0:0:0:0:1'
, '::', '1::', '::1', ':::1', '1:::'
, '1:0:0:2:0:0:0:3', '1:0:0:0:2:0:0:3', '1::8:0:0:0:3'
, '1:2:3:4:5:6:7:8'
, 'ABCD:1234', 'ABCDE::1234', ':::', '::::::::::'
, '1:2:3:4:5:6:7:8:9', '::::1', 'codegolf puzzle'];
i.map(x=>x+' => '+F(x)).join('\n')
```
**Test output**
```
"1080:0:0:0:8:800:200C:417A => 1080:0:0:0:8:800:200C:417A,1080::8:800:200C:417A
::1:2:3:4:5:6:7 => 0:1:2:3:4:5:6:7,::1:2:3:4:5:6:7
1:2:3:4:5:6:7:: => 1:2:3:4:5:6:7:0,1:2:3:4:5:6:7::
1:2:3:4::5:6:7:8 => false
:1:2:3:4:5:6:7 => false
1:2:3:4:5:6:7: => false
FF01::101 => FF01:0:0:0:0:0:0:101,FF01::101
0:0:0:0:0:0:0:1 => 0:0:0:0:0:0:0:1,::1
:: => 0:0:0:0:0:0:0:0,::
1:: => 1:0:0:0:0:0:0:0,1::
::1 => 0:0:0:0:0:0:0:1,::1
:::1 => false
1::: => false
1:0:0:2:0:0:0:3 => 1:0:0:2:0:0:0:3,1:0:0:2::3
1:0:0:0:2:0:0:3 => 1:0:0:0:2:0:0:3,1::2:0:0:3
1::8:0:0:0:3 => 1:0:0:8:0:0:0:3,1:0:0:8::3
1:2:3:4:5:6:7:8 => 1:2:3:4:5:6:7:8,1:2:3:4:5:6:7:8
ABCD:1234 => false
ABCDE::1234 => false
::: => false
:::::::::: => false
1:2:3:4:5:6:7:8:9 => false
::::1 => false
codegolf puzzle => false"
```
[Answer]
## JavaScript (ES6) - 198, 183, 180, 188, 187 bytes
```
f=s=>/^(:[\da-f]{1,4}){8}$/i.test(':'+(s=s[r='replace'](d='::',':0'.repeat((n=8-s.split(/:+/).length%9)||1)+':')[r](/^:0|0:$/g,n?'0:0':0)))&&[s,s[r](/(\b0(:0)*)(?!.*\1:0)/,d)[r](/::+/,d)]
```
And, a bit longer, interactive version with some pop-ups (203 bytes):
```
/^(:[\da-f]{1,4}){8}$/i.test(':'+(s=(s=prompt())[r='replace'](d='::',':0'.repeat((n=8-s.split(/:+/).length%9)||1)+':')[r](/^:0|0:$/g,n?'0:0':0)))&&alert(s+'\n'+s[r](/(\b0(:0)*)(?!.*\1:0)/,d)[r](/::+/,d))
```
**Ungolfed:**
```
function ipv6(str) {
"use strict";
var zeros = 8 - str.split(/:+/).length % 9
,longIP = str
.replace('::', ':0'.repeat(zeros || 1) + ':')
.replace(/^:0|0:$/g, zeros ? '0:0' : '0')
,shortIP = longIP
.replace(/(\b0(:0)*)(?!.*\1:0)/,':')
.replace(/::+/,'::');
return /^(:[\da-f]{1,4}){8}$/i.test(':'+longIP) && [longIP, shortIP];
}
```
**Explanation:**
To calculate the long version of the IPv6 address:
`8 - str.split(/:+/).length % 9` - calculate how many zeros we need to insert. They are 8 - the number of the hex values. Here % 9 is a guard so it will never be a negative number.
`replace('::', ':0'.repeat(zeros || 1) + ':')` - replace the "::" with colon separated zeros. If there are no zeros to add it still adds one so the address won't be valid in the end
`replace(/^:0|0:$/g, zeros ? '0:0' : '0')` - this deals with the special case when the address starts or ends with "::" as the `split` function adds 1 to the number of hex values (::1 -> ["", "1"])
That's it! Now let's calculate the short form:
`replace(/(\b0(:0)*)(?!.*\1:0)/,':')` - replace longest row of zeros with colon(s) (It doesn't matter how many).
`replace(/::+/,'::')` - remove the extra colons if any
`return /^(:[\da-f]{1,4}){8}$/i.test(':'+longIP) && [longIP, shortIP];` - test if the long version is valid IPv6 and return both versions or `false` if the test fails.
**Tests in Firefox:**
```
>>> f('1080:0:0:0:8:800:200C:417A')
["1080:0:0:0:8:800:200C:417A", "1080::8:800:200C:417A"]
>>> f('FF01::101')
["FF01:0:0:0:0:0:0:101", "FF01::101"]
>>> f('0:0:0:0:0:0:0:1')
["0:0:0:0:0:0:0:1", "::1"]
>>> f('::')
["0:0:0:0:0:0:0:0", "::"]
>>> f('1:0:0:2:0:0:0:3')
["1:0:0:2:0:0:0:3", "1:0:0:2::3"]
>>> f('1:0:0:8:8:0:0:3')
["1:0:0:8:8:0:0:3", "1::8:8:0:0:3"]
>>> f('1:2:3:4:5:6:7:8')
["1:2:3:4:5:6:7:8", "1:2:3:4:5:6:7:8"]
>>> f('ABCD:1234')
false
>>> f('ABCDE::1234')
false
>>> f('1:2:3:4:5:6:7:8:9')
false
>>> f(':::1')
false
>>> f('1:2:3:4::a:b:c:d')
false
>>> f('codegolf puzzle')
false
```
[Answer]
# Perl - 204 ~~176 190 191 197~~
(202 chars + 2 for `-p` flag)
```
$_=uc;(9-split/:/)||/^:|:$/||last;s/^::/0::/;s/::$/::0/;s|::|':0'x(9-split/:/).':'|e;/::|^:|:$|\w{5}|[^A-F0-:].*\n/||(8-split/:/)and last;s/\b0*(?!\b)//g;print;s/\b((0:)*0)\b(?!.*\1:0\b)/::/;s/::::?/::/
```
### Example:
```
$ perl -p ipv6.pl <<< 1:0:2:0::3
1:0:2:0:0:0:0:3
1:0:2::3
$ perl -p ipv6.pl <<< somethinginvalid
$ perl -p ipv6.pl <<< 1:2:0:4:0:6::8
1:2:0:4:0:6:0:8
1:2::4:0:6:0:8
```
### Explanation:
```
# -p reads a line from stdin and stores in $_
#
# Convert to uppercase
$_ = uc;
# Detect the annoying case @kernigh pointed out
(9 - split /:/) || /^:|:$/ || last;
# Fix :: hanging on the beginning or the end of the string
s/^::/0::/;
s/::$/::0/;
# Replace :: with the appropriate number of 0 groups
s|::|':0' x (9 - split /:/) . ':'|e;
# Silently exit if found an extra ::, a hanging :, a 5-char group, an invalid
# character, or there's not 8 groups
/::|^:|:$|\w{5}|[^A-F0-:].*\n/ || (8 - split /:/) and last;
# Remove leading zeros from groups
s/\b0*(?!\b)//g;
# Output the ungolfed form
print;
# Find the longest sequence of 0 groups (a sequence not followed by something
# and a longer sequence) and replace with ::
# This doesn't replace the colons around the sequence because those are optional
# thus we are left with 4 or 3 colons in a row
s/\b((0:)*0)\b(?!.*\1:0\b)/::/;
# Fix the colons after previous transformation
s/::::?/::/
# -p then prints the golfed form of the address
```
[Answer]
# sed, 276
I have 275 bytes in ipshorten.sed, plus 1 byte for the `-r` switch in `sed -rf` to use extended regular expressions. I used OpenBSD [sed(1)](http://www.openbsd.org/cgi-bin/man.cgi?query=sed&sektion=1&manpath=OpenBSD%20Current&arch=i386&format=html).
**Usage:** `echo ::2:3:4:a:b:c:d | sed -rf ipshorten.sed`
```
s/^/:/
/^(:[0-9A-Fa-f]{0,4})*$/!d
s/:0*([^:])/:\1/g
s/://
s/::/:=/
s/(.:=)(.)/\10:\2/
s/^:=/0&/
s/=$/&0/
:E
/(.*:){7}/!{/=/!d
s//=0:/
bE
}
s/=//
/^:|::|:$|(.*:){8}/d
p
s/.*/:&:/
s/:((0:)+)/:<\1>/g
:C
s/0:>/>0:/g
/<0/{s/<>//g
bC
}
s/<>(0:)+/:/
s/<>//g
/^::/!s/://
/::$/!s/:$//
```
I use 22 regular expressions, as sed can't compare numbers or make arrays. For each line of input, sed runs the commands and prints the line. During testing, I put several lines of alleged IP addresses in a file, and fed this file to sed. A reference to extended regular expressions is in [re\_format(7)](http://www.openbsd.org/cgi-bin/man.cgi?query=re_format&sektion=7&manpath=OpenBSD%20Current&arch=i386&format=html).
1. `s/^/:/` adds an extra colon to the beginning of the line. I use this extra colon to golf the next two commands.
2. `/^(:[0-9A-Fa-f]{0,4})*$/!d` checks if the whole line matches zero or more groups of colons followed by zero to four hexadecimal digits. `!` negates the check, so `d` deletes lines with too big hexadecimal numbers or with invalid characters. When `d` deletes a line, sed runs no more commands on this line.
3. `s/:0*([^:])/:\1/g` deletes leading 0s from each number. It would change `:0000:0000:` to `:0:0:`. I must do this because my contraction loop only works with single-digit 0s.
4. `s/://` deletes the extra colon. It deletes only the first colon.
5. `s/::/:=/` changes the first `::` to `:=`. This is so later commands can match `=` rather than `::`, and so `=` does not count as a colon. If there is no `::`, this substitution safely does nothing.
* Now `::` must make at least one 0, but there are three different cases for placing this 0.
6. `s/(.:=)(.)/\10:\2/` is the first case. If `::` was between two other characters, then `:=` becomes `:=0:`. This is the only case that adds a colon.
7. `s/^:=/0&/` is the second case. If `::` was at beginning of line, then put 0 there.
8. `s/=$/&0/` is the third case, for `::` at end of line.
9. `:E` is the label for the expansion loop.
10. `/(.*:){7}/!{/=/!d` begins a conditional block if the line has fewer than 7 colons. `/=/!d` deletes lines that had no `::` and not enough colons.
11. `s//=0:/` adds one colon. Empty `//` repeats the last regular expression, so this is really `s/=/=0:/`.
12. `bE` branches to `:E` to continue the loop.
13. `}` closes the block. Now the line has at least seven colons.
14. `s/=//` deletes `=`.
15. `/^:|::|:$|(.*:){8}/d` is a final check after expansion. It deletes lines with a leading colon, an extra `::` that was not expanded, a trailing colon, or eight or more colons.
16. `p` prints the line, which is an IP address in long form.
17. `s/.*/:&:/` wraps the address in extra colons.
* The next task is to find the longest group of 0s, like `:0:0:0:`, and contract it into `::`.
18. `s/:((0:)+)/:<\1>/g` eats each group of 0s, so `:0:0:0:` would become `:<0:0:0:>`.
19. `:C` is the label for the contraction loop.
20. `s/0:>/>0:/g` moves one 0 from each mouth, so `:<0:0:0:>` would become `:<0:0:>0:`.
21. `/<0/{s/<>//g` opens a conditional block if any mouth is not empty. `s/<>//g` deletes all empty mouths, because those groups are too short.
22. `bC` continues the contraction loop.
23. `}` closes the block. Now any mouth is empty and marks the longest group of 0s.
24. `s/<>(0:)+/:/` contracts the longest group, so `:<>0:0:0:` would become `::`. In a tie, it picks the empty mouth on the left.
25. `s/<>//g` deletes any other empty mouths.
26. `/^::/!s/://` deletes the first extra colon unless it is part of `::`.
27. `/::$/!s/:$//` does so for the last extra colon. Then sed prints the IP address in short form.
[Answer]
## Python 3: 387 characters
Even works with improperly shortened input.
```
$ echo '1::2:0:0:0:3' | python3 ipv6.py
1:0:0:2:0:0:0:3
1:0:0:2::3
```
The double replace of `':::'` with `'::'` feels really bad but not sure how to cleanly deal with the longest string of 0's when it abuts one or both ends.
```
c=':'
p=print
try:
B=[int(x,16)if x else''for x in input().split(c)];L=len(B)
if any(B)-1:B=[''];L=1
if L!=8:s=B.index('');B[s:s+1]=[0]*(9-L)
for b in B:assert-1<b<2**16
H=[format(x,'X')for x in B];o=c.join(H);p(o);n=''.join(str(h=='0')[0]for h in H)
for i in range(8,0,-1):
s=n.find('T'*i)
if s>=0:H[s:s+i]=[c*2];p(c.join(H).replace(c*3,c*2).replace(c*3,c*2));q
p(o)
except:0
```
Replace the final `pass` with `raise` to see how it's crashing protecting against malformed input.
```
$ cat ipv6-test.sh
echo '1080:0:0:0:8:800:200C:417A' | python3 ipv6.py
echo '1:2:3:4:5:6:7:8' | python3 ipv6.py
echo 'FF01::101' | python3 ipv6.py
echo '0:0:0:0:0:0:0:1' | python3 ipv6.py
echo '0:0:0:0:1:0:0:0' | python3 ipv6.py
echo '1:0:0:0:0:0:0:0' | python3 ipv6.py
echo '::' | python3 ipv6.py
echo '1:0:0:2:0:0:0:3' | python3 ipv6.py
echo '1::2:0:0:0:3' | python3 ipv6.py
echo '1:0:0:8:8:0:0:3' | python3 ipv6.py
echo 'ABCD:1234' | python3 ipv6.py
echo 'ABCDE::1234' | python3 ipv6.py
echo '1:2:3:4:5:6:7:8:9' | python3 ipv6.py
echo ':::1' | python3 ipv6.py
echo 'codegolf puzzle' | python3 ipv6.py
$ ./ipv6-test.sh
1080:0:0:0:8:800:200C:417A
1080::8:800:200C:417A
1:2:3:4:5:6:7:8
1:2:3:4:5:6:7:8
FF01:0:0:0:0:0:0:101
FF01::101
0:0:0:0:0:0:0:1
::1
0:0:0:0:1:0:0:0
::1:0:0:0
1:0:0:0:0:0:0:0
1::
0:0:0:0:0:0:0:0
::
1:0:0:2:0:0:0:3
1:0:0:2::3
1:0:0:2:0:0:0:3
1:0:0:2::3
1:0:0:8:8:0:0:3
1::8:8:0:0:3
```
] |
[Question]
[
The [Four fours puzzle](http://en.wikipedia.org/wiki/Four_fours) is a popular recreational mathematical puzzle that involves using exactly four 4s (and no other number) and a defined set of operations to reach every number from 0 to a given maximum.
In this version, the only following operators are allowed:
* Any grouping symbols may be used
* Addition (`+`), Subtraction (`-`), Multiplication (`*`), Division (`/`)
* Factorial (`!`), [Gamma function](http://en.wikipedia.org/wiki/Gamma_function) (`Γ`)
* Exponentiation (`^`), Square root (`√`)
* Concatenation (eg. `44` is two `4`s)
* Decimal point (eg. `4.4` is two `4`s), Overbar (eg. `.4~ = 4/9`)
Standard order of operations applies.
Your program should generate, given an input between 0 and 100 inclusive, a correct solution for that input. If the program outputs an invalid solution to any input, that program is invalid.
For example, with an input of `0`, your program might generate `44-44`.
The use of external modules is not allowed. Only `_.4~` is allowed for the overbar operator - that is, only one `4` can be behind the decimal point.
This is code golf, so shortest solution wins.
---
**Edit**: To be extra clear, the program must output a set of the above operations applied to *exactly* four `4`s - no more, no less. Also, `.4 = 4/10` is a valid term, and counts as using only one `4`.
[Answer]
## Python 155 bytes
```
h={4:'4',24:'4!',6:'â4',.4:'.4',1:'âû4',4/9.:'.4~'}
f={}
def g(r,s='24',y='4!'):f[eval(s)]=y;[g(r-1,s+o+`k`,y+o+h[k])for k in h for o in'/*-+'if r]
g(3)
```
The first three bytes (`\xEF\xBB\xBF`) are the UTF-8 byte order mark, although the file should be saved in an ANSI format. The `û` and `â` will be interpretted as `√` and `Γ` respectively in [cp437](http://en.wikipedia.org/wiki/Code_page_437) and [cp850](http://en.wikipedia.org/wiki/Code_page_850), which should work on just about any Windows box.
Runtime is about 0.4s on my computer.
Sample usage (name the file `four_fours.py`):
```
$ python
>>> from four_fours import f
>>> f[39]
'4!+4!/.4/4'
>>> f[87]
'4!*4-4/.4~'
>>> for i in range(101): print i, f[i]
0 4!+4!-4!-4!
1 4!+4!/4!-4!
2 4!-4!+Γ4-4
3 4!-4!+4-Γ√4
4 4!+4!/Γ4-4!
.
.
.
96 4!+4!+4!+4!
97 4!*4!/Γ4+Γ√4
98 4!*4+Γ4-4
99 4!*4+4-Γ√4
100 4!*4!/Γ4+4
```
[Results for 0..100](http://codepad.org/6V0V8cz2). Due to the way the hash is iterated, it prefers to use `4!` as often as possible.
Edit: saved a number of bytes by adding `Γ√4 = 1`, which eliminates the need for any groupings, and by removing `√4 = 2`, which was no longer necessary.
[Answer]
## GolfScript (129 chars\*)
```
[4.`2'√4'24'4!'6'Γ4'1'Γ√4'120'ΓΓ4']2/:F{.F=[[44.`]]*\{`{+{'+*-'1/{:^;.[~@[\]{'()'1/*}%^*@@^~\]\}/}:|~2/~\+|;}+F/}%+}3*\{\0==}+?1=
```
Running time is on the order of 4 minutes on my PC. A moderate speed-up can be obtained at the cost of two characters by adding a uniqueness operation `.&` immediately after the `%+`.
I use pre-coded expressions for `1`, `2`, `4`, `6`, `24`, `120`, and `44`, and build the rest up from those using only `+`, `*`, and `-`. This way I don't need to do any non-integer arithmetic in the program itself. I've tried to get simpler expressions by placing the simpler pre-coded values at the start.
All of those values are required†, and it's necessary to support both directions of subtraction (`complex_expression - simple_expression` and vice versa). It's also necessary to include some operations which require parentheses (specifically, `a*(b-c)`), so I bracket all subexpressions indiscriminately.
\* I'm counting Unicode code points assuming the program to be UTF-8 encoded, and brushing under the carpet the fact that unless you're using a recent version of Ruby to run the interpreter it's really treating it as ASCII characters. If you're very worried about this, use `G` for Gamma and `v` for sqrt.
† Well, strictly I could remove `44` in exchange for `11` as `44/4` and `71` as `√(Γ√4+(ΓΓ4+Γ√4)!)`, but that's not a good trade-off.
[Answer]
## J, 175 161 chars
```
f=.')',~'(',;@((<;._2'+ - * % .4 .4~ g(r(4)) r(4) 4 g(4) 4! ( ) '){~(143402 A.i.9)
/:~(12,11,0,6$0 4 4)+(9$4 7 7)#:((,@(+/,-/,*/,%/)~)^:2,0.4 4r9 1 2 4 6 24)&i.)
f 1
(.4+.4)+(.4%r(4))
f 42
(r(4)+4)+(g(4)*g(4))
f 100
(r(4)+r(4))+(4*4!)
```
Checked format is `(v op v) op (v op v)` where `v={0.4 4/9 1 2 4 6 24}` and `op={+ - * /}`
[full 0..100 results](http://pastebin.com/PgGuQTN3)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~70~~ 69 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
•1OF•₂в"(4/9)"ª0.4ª©4ã"+-*/"3ãâε`.ιJ}.Δ.EQ}®¦¨ŽYyç"Γÿ4 Γ4 4! .4~"#:0K
```
[Try it online](https://tio.run/##AWkAlv9vc2FiaWX//@KAojFPRuKAouKCgtCyIig0LzkpIsKqMC40wqrCqTTDoyIrLSovIjPDo8OizrVgLs65Sn0uzpQuRVF9wq7CpsKoxb1ZecOnIs6Tw780IM6TNCA0ISAuNH4iIzowS///Njc) or [verify all test cases](https://tio.run/##AXkAhv9vc2FiaWX/0YLGkk4/IiDihpIgIj9OVf/igKIxT0bigKLigoLQsiIoNC85KSLCqjAuNMKqwqk0w6MiKy0qLyIzw6PDos61YC7OuUp9Ls6ULkVYUX3CrsKmwqjFvVl5w6cizpPDvzQgzpM0IDQhIC40fiIjOjBL/yz/).
**Explanation:**
Uses a similar approach as some of the other answers. Creates all possible combinations of four of the values \$[1,4,6,24,\frac{4}{9},0.4]\$ and three of the operators `+-*/` (both of course with duplicates).
```
•1OF• # Push compressed integer 71160
₂в # Convert it to base-26 as list: [4,1,6,24]
"(4/9)"ª # Append "(4/9)": [4,1,6,24,"(4/9)"]
0.4ª # As well as 0.4: [4,1,6,24,"(4/9)",0.4]
© # Store this list in variable `®` (without popping)
4ã # Create all possible quartets by using the cartesian product times 4
"+-*/" # Push the string "+-*/"
3ã # Create all possible triplets by using the cartesian product times 3
â # Create all possible pairs of both lists by using the cartesian product
ε } # Map each pair of lists by:
` # Push the list and string separated to the stack
.ι # Interleave them
J # And join them together
.Δ # Find the first which is truthy for:
.E # Evaluate the expression-string as Python code
# (NOTE: Unfortunately doesn't work with .4 instead of 0.4)
Q # And check if it equals the (implicit) input-integer
}® # After we've found our result: push the list from variable `®`
¦¨ # Remove the first and last items: [1,6,24,"(4/9)"]
ŽYy # Push compressed integer 8730
ç # Convert it to a character with this unicode: "√"
# (`√` isn't part of 05AB1E's codepage, hence why this is necessary)
"Γÿ4 Γ4 4! .4~" # Push this string, where the `ÿ` is automatically filled with the "√"
# # Split it on spaces: ["Γ√4","Γ4","4!",".4~"]
: # Replace the [1,6,24,"(4/9)"] with ["Γ√4","Γ4","4!",".4~"]
0K # And remove all 0s to convert the "0.4"s to ".4"s
# (after which the result is output implicitly)
```
[See this 05AB1E tip (section *How to compress large integers?* and *How to compress integer lists?*)](https://codegolf.stackexchange.com/a/166851/52210) to understand why `•1OF•` is `71160`; `•1OF•₂в` is `[4,1,6,24]`; and `ŽYy` is `8730`.
] |
[Question]
[
[SE Sandbox Link](https://codegolf.meta.stackexchange.com/a/20479/80214), [Codidact Sandbox Link](https://codegolf.codidact.com/articles/279223)
Inspired by [this video.](https://www.youtube.com/watch?v=9p55Qgt7Ciw&ab_channel=Numberphile)
Given a positive integer, draw its Cistercian representation as ascii art.
[](https://i.stack.imgur.com/JmmEq.png)
## The Challenge
Cistercian numerals are a decimal-based number representation system which use simple line based drawings to represent 4-digit numerals. Their structure is as follows:
```
Tens|Units
|
Thousands|Hundreds
```
The digits are represented as follows (in the units place):
```
1 ⌷ 2 ⌷ 3 ⌷ 4 ⌷ 5 ⌷ 6 ⌷ 7 ⌷ 8 ⌷ 9 ⌷ 0
___ ⌷ ⌷ ⌷ ⌷ ___ ⌷ . ⌷ ___. ⌷ . ⌷ ___. ⌷
⌷ ⌷ \ ⌷ / ⌷ / ⌷ | ⌷ | ⌷ | ⌷ | ⌷
⌷ ⌷ \ ⌷ / ⌷ / ⌷ | ⌷ | ⌷ | ⌷ | ⌷
⌷ ___ ⌷ \ ⌷ / ⌷ / ⌷ ' ⌷ ' ⌷ ___' ⌷ ___' ⌷
```
(all of these are 4 rows in height.)
As you can see, there are some repeating patterns within the symbols:
```
5 → 4 + 1
7 → 6 + 1
8 → 6 + 2
9 → 6 + 1 + 2
```
In order to represent a general Cistercian number, you will have to place the digits in the correct place for their value.
They should be mirrored horizontally if they are on the left.
They should be mirrored vertically if they are on the bottom i.e. the lines should be reversed, `\` and `/` should be swapped, and `.` and `'` should be swapped. [Here's how they should look.](https://dzaima.github.io/paste#0y80sKsovSk1RKEstKslMTszJqbTi4jJUUFB41LNdwQhKG0NpEyhtCqXNFKAMcxjDAsawhDEMFLhgzPj4eDCtoKAPpmOg4jAaCPRQGUAdqAy4WXBaH0rHoNEKCjUEGBhm6cP5MWg0YbMQflPASiPJq8ME1LGLcHFxAQA)
The fun part is when you stack a Cistercian representation on top of another one to accommodate more digits e.g.:
```
T|U
|
Th|H
|
Hth|Tth
|
TM|M
```
like a tower of sorts.
You will need to stack as many 4 part towers as the number requires, and you will need to prepend 0's to the input if it's length is not a multiple of 4.
Hence, given an input number, say, 12345, you should get the following:
`00012345 → 5432,1000`
which turns into:
```
4|5
|
2|3
|
0|1
|
0|0
```
which becomes:
```
|___
\ | /
\ | /
\|/
|
|
|
|
___| /
| /
|/
|
|
|
|
|
|___
|
|
|
|
|
|
|
|
|
|
|
```
Note that this is created by making two towers for the 4 digit numbers `2345` and `0001`, stacking them, and adding a link of 4 `|` characters between them.
# Scoring
This is code-golf. Shortest answer in each language wins.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 265 bytes
```
f=n=>n?`01238888765${n<1e4?4:48888}`.replace(e=/\d/g,y=>`4567|3210
`.replace(e,x=>"_ \\/.'|"[q=y/2&2|x>3,y&8?1:(k='40321123'[j=~~('0x'+(1e6+'1023405671567899AB99A899CB99C')[y%4+~-(n/10**q%10)*4])]^x%4?2045>>j&1:'0122233346545'[j])^0xCC6600>>k*4+q&1]))+f(n/1e4|0):''
```
[Try it online!](https://tio.run/##VVDRboJAEHz3KxpTuDtQ2btbEEjvSMtnKFajhykaEG0aSKm/Ts@3dpPNJLPZmdmtdl@72/76cfmc183BjGOpaqXrbAtcyNjWMgqfv@sXbjDDFB/Mz3ZxNZfzbm@oUcH6EBxnvdJbDKPlIAWHyZ/5rFN6@v60XgcLMkxXreoD4Yqh03LWu3HGU3pSBMGuWTuyqtT9Tgl0xKfcRD7hICSCFea24yR5fbNtMbeYE7bqHfTvc1oHHDyvdTgwDwtWbDoHMwEYal25PCX2FiGklBiFGFqXgm2gy/MoAtD65KHfurxgzC8fSgYHYCkh476pb83ZLM7NkZbU5sOQscl/Nnn8B218xsZf "JavaScript (Node.js) – Try It Online")
### Encoding
Each digit pattern is a 4x4 matrix consisting of 7 distinct characters. Each character is encoded as a single decimal digit from `0` to `6`:
```
0: "_"
1: " "
2: "\"
3: "/"
4: "."
5: "'"
6: "|"
```
All matrices are built with 13 distinct rows, encoded as a single hexadecimal digit from `0` to `C`:
```
0: 1111 for " "
1: 0001 for "___ "
2: 2111 for "\ "
3: 1211 for " \ "
4: 1121 for " \ "
5: 1131 for " / "
6: 1311 for " / "
7: 3111 for "/ "
8: 1114 for " ."
9: 1116 for " |"
A: 1115 for " '"
B: 0004 for "___."
C: 0005 for "___'"
```
So, each matrix is fully described by a sequence of 4 hexadecimal digits. For instance, the matrix for `7` is encoded as `B99A`:
```
B99A -> 0004 -> "___."
1116 " |"
1116 " |"
1115 " '"
```
The leading sequence is `0000` and is omitted. The other sequences are stored as:
```
1e6 + '1023405671567899AB99A899CB99C'
```
which expands to:
```
0 1 2 3 4 5 6 7 8 9
(0000) 1000 0001 0234 0567 1567 899A B99A 899C B99C
```
Each matrix row is made of a 'background' character appearing 3 times and a 'foreground' character appearing only once (or not at all). So the rows can be encoded as:
* the position of the 'foreground' character (0 for rightmost to 3 for leftmost, or 4 if none)
* the 'background' character (which is always either `0` for `"_"` or `1` for `" "`)
* the 'foreground' character
This is summarized in the following table:
```
ID | string | digits | FG position | BG char. | FG char.
----+--------+--------+-------------+----------+----------
0 | " " | 1111 | 4 | 1 | 0
1 | "___ " | 0001 | 0 | 0 | 1
2 | "\ " | 2111 | 3 | 1 | 2
3 | " \ " | 1211 | 2 | 1 | 2
4 | " \ " | 1121 | 1 | 1 | 2
5 | " / " | 1131 | 1 | 1 | 3
6 | " / " | 1311 | 2 | 1 | 3
7 | "/ " | 3111 | 3 | 1 | 3
8 | " ." | 1114 | 0 | 1 | 4
9 | " |" | 1116 | 0 | 1 | 6
A | " '" | 1115 | 0 | 1 | 5
B | "___." | 0004 | 0 | 0 | 4
C | "___'" | 0005 | 0 | 0 | 5
----+--------+--------+-------------+----------+----------
| | |
| | +--> stored as "0122233346545"
| +-------------> stored as the bit mask 2045
+-------------------------> stored as "40321123"
```
[Answer]
# [Perl 5](https://www.perl.org/), 573 bytes
With some newlines and indentation added:
```
sub f{
local$_=pop;
s//0/ while y///c%4;
$l=" |\n"x3;
/.{5}/?join$l,reverse map f($_),/.{4}/g:do{
@c{0..9}=map{join'',map{sprintf"%-4s\n",$_}(split'n')[0..3]}split$/,q(1
___
nnn___
n\n \n2\
n2/n /n/
___n2/n /n/
2.n2|n2|n2'
___.n3|n3|n3'
3.n3|n3|n___'
___.n3|n3|n___')=~s/\d/$"x$&/ger;
$c{$_.'00'}=join('',map"$_\n",reverse$c{$_}=~/.+/g)=~y|.'|'.|r=~y|/\\|\\/|r for 0..9;
$c{$_.0}=$c{$_}=~s,.+,reverse"|$&",ger=~y|/\\|\\/|r for map{$_,$_.'00'}0..9;
$_=[/.+/g]for values%c;
/(.)(.)(.)(.)/;
join'',
(map$c{$3.0}[$_].$c{$4}[$_].$/,0..3),
$l,
map$c{$1.'000'}[$_].$c{$2.'00'}[$_].$/,0..3
}
}
```
[Try it online!](https://tio.run/##ZVFhb5swEP3Or7Aspwb15iNAtnUIbf8jRBajTsZEDcNpmwrcv57ZhESdhk7ine/de@dzr4Z2c9Ydea0G3eiDIVydejU0T0ofq5bnQT80@kgooackBkqYpMAQ9iGTEdl3A4lhDQmkkMEGPsMX@AoPsE7SbJOfzfNPsh/brq5aJou@63ODGCN5/dW0irwhYr3KctYWlLhvKjU9pTmKcWPx@@@u0ayFQb2owSjyVPVk9gRXzywevj124496jIV4sIWrjr6Bc/DQzDPv6epTZpwoMGlD07fNkWsebV1LurNz7i7yJ1wHUspAaz3/Sk1KnZSBTlAT1OiLN5wInUxzcH8udDrNwYP0it3xPzWfR8W7wfIRGT2xOzyoIWf1yKTgccxt4QcPL5NTJv28y6Vnki3eUdzjwWm8TYJPXEyDh1iWU1niNFwewa1hEY1tcW00IO6vYnRidxSc9//NfmVMwnWgi5YstrPvzjNeqvZZmVWdYyiiW2C@7Dx0Ct4zdeZbJnfCJ9kCEfzCI3CPudDW3scZ3ajJxfgj39rz@S8 "Perl 5 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 125 bytes
```
≔⪪⮌S⁴θFLθ«↓∧ι⁴F⁴«→P§⪪”~∨VKT✂≦M›ζΦNF›ιO:υ⊘[⁸À1“ir⊞Py✳⪫℅⁰ψ"´dD?5¬→⁼σm‹1“"ξωT\⁵⁻Hïg”⸿Σ§◨§θι⁴κ←‖T¿﹪겫↓¹¹‖T↓»»↓¹²»UMKA⎇№βι§.'›ιdι
```
[Try it online!](https://tio.run/##bZJda8IwFIav218RerMEuonOfbmr4mAIFkS9LEi0aQ2mSU1Tt7H52@tJqjJRmpyU9zynnPOmqzXVK0VF00RVxXOJZ6XgBk/ZjumK4ZEsazMzmsscExKiPuwtefczpREeM5mbNd4Sgn59bwKQwYMP9SVDFMkUc4sD6zm47yAvVjuGB1Oer41NeXEtDC9daWRGMmXfxw6CRC8Wi0Qn0j6n1ySRyAUbtT07EGB3WvxCQAgtrYL@/sXSgTf1ax7Im7zVgxBBjwEYMquLc/MTmrrhzsI2RPxo3IYQ0g7tTBizrPVgyjLBVmauqazAqwI7lWcIxyqthcKbEPVak71Lm7tdh15/weVdbu/bdVnVg8zej2k5VEVB4aomjG0iITA0OWdaUv2Dh6qGimXb/WmY4OEOxv7UjBqm7QUHaWB/Cw5zNU2399h/en55fWvud@IA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪⮌S⁴θ
```
Split the reversed input into substrings of length 4.
```
FLθ«
```
Loop over each substring.
```
↓∧ι⁴
```
Except for the first substring, separate each quad of digits with a vertical line of length 4.
```
F⁴«
```
Loop over each digit in the quad.
```
→P§⪪”~∨VKT✂≦M›ζΦNF›ιO:υ⊘[⁸À1“ir⊞Py✳⪫℅⁰ψ"´dD?5¬→⁼σm‹1“"ξωT\⁵⁻Hïg”⸿Σ§◨§θι⁴κ←
```
Extract the relevant digit from a compressed string of all digits and print it without moving the cursor. (I tried printing the digits by parts but this was at least 16 bytes longer.) Note that at this point I print `b` instead of `.` and `p` instead of `'` as Charcoal knows how to reflect `b`, `d`, `p` and `q`.
```
‖T
```
Reflect the canvas horizontally, transforming the characters appropriately. There are four reflections in total, so that the units end up with their original orientation, but the tens end up horizontally reflected.
```
¿﹪겫
```
On alternate passes, ...
```
↓¹¹
```
... move down 11 lines (actually drawing is golfier, but moving would work), ...
```
‖T↓
```
... and reflect the canvas vertically. This happens twice, so the units and tens end up with their original reflection, but the hundreds and thousands are vertically reflected (and the thousands also get an overall horizontal reflection).
```
»»↓¹²
```
Print the vertical line down the middle of the four digits.
```
»UMKA⎇№βι§.'›ιdι
```
Translate the `b` (and its horizontal reflection `d`) to `.` and the `p` (and its horizontal reflection `q`) to `'`. `b` and `p` (and `d` and `q`) are also vertical reflections of each other, but we want that, otherwise the `.`s and `'`s would be exchanged by the vertical reflection.
] |
[Question]
[
What is a home prime?
For an example, take HP(4). First, find the prime factors. The prime factors of 4 (*in numerical order from least to greatest, always*) are 2, 2. Take those factors as a literal number. 2, 2 becomes 22. This process of factoring continues until you reach a prime number.
```
number prime factors
4 2, 2
22 2, 11
211 211 is prime
```
Once you reach a prime number, the sequence ends. HP(4)=211. Here's a longer example, with 14:
```
number prime factors
14 2, 7
27 3, 3, 3
333 3, 3, 37
3337 47, 71
4771 13, 367
13367 13367 is prime
```
Your challenge is to create a program that will calculate HP(x) given x, and do it *as quickly as possible*. You may use whatever resources you want, other than a list of known home primes.
Take note, these numbers become very large very fast. At x=8, HP(x) jumps all the way to 3331113965338635107. HP(49) has yet to be found.
Program speed will be tested on a Raspberry Pi 2, averaging the following inputs:
```
16
20
64
65
80
```
If you have a Raspberry Pi 2, time the program yourself, then average the times.
[Answer]
# Mathematica, HP(80) in ~0.88s
```
NestWhile[
FromDigits[
Flatten[IntegerDigits /@
ConstantArray @@@ FactorInteger[#]]] &, #, CompositeQ] &
```
Anonymous function. Takes a number as input and returns a number as output.
[Answer]
# PyPy 5.4.1 64bit (linux), HP(80) ~ 1.54s
*The 32bit version will time slightly slower.*
I use four different factorization methods, with empirically determined breakpoints:
* *n < 230* → factorization by trial division
* *n < 270* → [Pollard's Rho](https://en.wikipedia.org/wiki/Pollard%27s_rho_algorithm) (Brent's variant)
* *else* → [Lenstra ECF](https://en.wikipedia.org/wiki/Lenstra_elliptic_curve_factorization) (using Montgomery curves, Suyama's parameters), test ~100 curves
* *if ECF failed* → [Multiple Polynomial Quadratic Sieve](https://en.wikipedia.org/wiki/Quadratic_sieve#Multiple_polynomials) (using Montgomery's polynomials)
I tried for a while to find a clean break between ECF and MPQS, but there doesn't seem to be one. However, if *n* contains a small factor, ECF will usually find it almost immediately, so I've opted to test only a few curves, before moving on to MPQS.
Currently, it's only ~2x slower than Mathmatica, which I certainly consider a success.
---
**home-prime.py**
```
import math
import my_math
import mpqs
max_trial = 1e10
max_pollard = 1e22
def factor(n):
if n < max_trial:
return factor_trial(n)
for p in my_math.small_primes:
if n%p == 0:
return [p] + factor(n/p)
if my_math.is_prime(n):
return [n]
if n < max_pollard:
p = pollard_rho(n)
else:
p = lenstra_ecf(n) or mpqs.mpqs(n)
return factor(p) + factor(n/p)
def factor_trial(n):
a = []
for p in my_math.small_primes:
while n%p == 0:
a += [p]
n /= p
i = 211
while i*i < n:
for o in my_math.offsets:
i += o
while n%i == 0:
a += [i]
n /= i
if n > 1:
a += [n]
return a
def pollard_rho(n):
# Brent's variant
y, r, q = 0, 1, 1
c, m = 9, 40
g = 1
while g == 1:
x = y
for i in range(r):
y = (y*y + c) % n
k = 0
while k < r and g == 1:
ys = y
for j in range(min(m, r-k)):
y = (y*y + c) % n
q = q*abs(x-y) % n
g = my_math.gcd(q, n)
k += m
r *= 2
if g == n:
ys = (ys*ys + c) % n
g = gcd(n, abs(x-ys))
while g == 1:
ys = (ys*ys + c) % n
g = gcd(n, abs(x-ys))
return g
def ec_add((x1, z1), (x2, z2), (x0, z0), n):
t1, t2 = (x1-z1)*(x2+z2), (x1+z1)*(x2-z2)
x, z = t1+t2, t1-t2
return (z0*x*x % n, x0*z*z % n)
def ec_double((x, z), (a, b), n):
t1 = x+z; t1 *= t1
t2 = x-z; t2 *= t2
t3 = t1 - t2
t4 = 4*b*t2
return (t1*t4 % n, t3*(t4 + a*t3) % n)
def ec_multiply(k, p, C, n):
# Montgomery ladder algorithm
p0 = p
q, p = p, ec_double(p, C, n)
b = k >> 1
while b > (b & -b):
b ^= b & -b
while b:
if k&b:
q, p = ec_add(p, q, p0, n), ec_double(p, C, n)
else:
q, p = ec_double(q, C, n), ec_add(p, q, p0, n),
b >>= 1
return q
def lenstra_ecf(n, m = 5):
# Montgomery curves w/ Suyama parameterization.
# Based on pseudocode found in:
# "Implementing the Elliptic Curve Method of Factoring in Reconfigurable Hardware"
# Gaj, Kris et. al
# http://www.hyperelliptic.org/tanja/SHARCS/talks06/Gaj.pdf
# Phase 2 is not implemented.
B1, B2 = 8, 13
for i in range(m):
pg = my_math.primes()
p = pg.next()
k = 1
while p < B1:
k *= p**int(math.log(B1, p))
p = pg.next()
for s in range(B1, B2):
u, v = s*s-5, 4*s
x = u*u*u
z = v*v*v
t = pow(v-u, 3, n)
P = (x, z)
C = (t*(3*u+v) % n, 4*x*v % n)
Q = ec_multiply(k, P, C, n)
g = my_math.gcd(Q[1], n)
if 1 < g < n: return g
B1, B2 = B2, B1 + B2
if __name__ == '__main__':
import time
import sys
for n in sys.argv[1:]:
t0 = time.time()
i = int(n)
f = []
while len(f) != 1:
f = sorted(factor(i))
#print i, f
i = int(''.join(map(str, f)))
t1 = time.time()-t0
print n, i
print '%.3fs'%(t1)
print
```
**Sample Timings**
```
$ pypy home-prime.py 8 16 20 64 65 80
8 3331113965338635107
0.005s
16 31636373
0.001s
20 3318308475676071413
0.004s
64 1272505013723
0.000s
65 1381321118321175157763339900357651
0.397s
80 313169138727147145210044974146858220729781791489
1.537s
```
The average of the 5 is about 0.39s.
---
**Dependencies**
`mpqs.py` is taken directly from my answer to [Fastest semiprime factorization](https://codegolf.stackexchange.com/a/9088) with a few very minor modifications.
**mpqs.py**
```
import math
import my_math
import time
# Multiple Polynomial Quadratic Sieve
def mpqs(n, verbose=False):
if verbose:
time1 = time.time()
root_n = my_math.isqrt(n)
root_2n = my_math.isqrt(n+n)
# formula chosen by experimentation
# seems to be close to optimal for n < 10^50
bound = int(5 * math.log(n, 10)**2)
prime = []
mod_root = []
log_p = []
num_prime = 0
# find a number of small primes for which n is a quadratic residue
p = 2
while p < bound or num_prime < 3:
# legendre (n|p) is only defined for odd p
if p > 2:
leg = my_math.legendre(n, p)
else:
leg = n & 1
if leg == 1:
prime += [p]
mod_root += [int(my_math.mod_sqrt(n, p))]
log_p += [math.log(p, 10)]
num_prime += 1
elif leg == 0:
if verbose:
print 'trial division found factors:'
print p, 'x', n/p
return p
p = my_math.next_prime(p)
# size of the sieve
x_max = bound*8
# maximum value on the sieved range
m_val = (x_max * root_2n) >> 1
# fudging the threshold down a bit makes it easier to find powers of primes as factors
# as well as partial-partial relationships, but it also makes the smoothness check slower.
# there's a happy medium somewhere, depending on how efficient the smoothness check is
thresh = math.log(m_val, 10) * 0.735
# skip small primes. they contribute very little to the log sum
# and add a lot of unnecessary entries to the table
# instead, fudge the threshold down a bit, assuming ~1/4 of them pass
min_prime = int(thresh*3)
fudge = sum(log_p[i] for i,p in enumerate(prime) if p < min_prime)/4
thresh -= fudge
sieve_primes = [p for p in prime if p >= min_prime]
sp_idx = prime.index(sieve_primes[0])
if verbose:
print 'smoothness bound:', bound
print 'sieve size:', x_max
print 'log threshold:', thresh
print 'skipping primes less than:', min_prime
smooth = []
used_prime = set()
partial = {}
num_smooth = 0
prev_num_smooth = 0
num_used_prime = 0
num_partial = 0
num_poly = 0
root_A = my_math.isqrt(root_2n / x_max)
if verbose:
print 'sieving for smooths...'
while True:
# find an integer value A such that:
# A is =~ sqrt(2*n) / x_max
# A is a perfect square
# sqrt(A) is prime, and n is a quadratic residue mod sqrt(A)
while True:
root_A = my_math.next_prime(root_A)
leg = my_math.legendre(n, root_A)
if leg == 1:
break
elif leg == 0:
if verbose:
print 'dumb luck found factors:'
print root_A, 'x', n/root_A
return root_A
A = root_A * root_A
# solve for an adequate B
# B*B is a quadratic residue mod n, such that B*B-A*C = n
# this is unsolvable if n is not a quadratic residue mod sqrt(A)
b = my_math.mod_sqrt(n, root_A)
B = (b + (n - b*b) * my_math.mod_inv(b + b, root_A))%A
# B*B-A*C = n <=> C = (B*B-n)/A
C = (B*B - n) / A
num_poly += 1
# sieve for prime factors
sums = [0.0]*(2*x_max)
i = sp_idx
for p in sieve_primes:
logp = log_p[i]
inv_A = my_math.mod_inv(A, p)
# modular root of the quadratic
a = int(((mod_root[i] - B) * inv_A)%p)
b = int(((p - mod_root[i] - B) * inv_A)%p)
amx = a+x_max
bmx = b+x_max
ax = amx-p
bx = bmx-p
k = p
while k < x_max:
sums[k+ax] += logp
sums[k+bx] += logp
sums[amx-k] += logp
sums[bmx-k] += logp
k += p
if k+ax < x_max:
sums[k+ax] += logp
if k+bx < x_max:
sums[k+bx] += logp
if amx-k > 0:
sums[amx-k] += logp
if bmx-k > 0:
sums[bmx-k] += logp
i += 1
# check for smooths
x = -x_max
for v in sums:
if v > thresh:
vec = set()
sqr = []
# because B*B-n = A*C
# (A*x+B)^2 - n = A*A*x*x+2*A*B*x + B*B - n
# = A*(A*x*x+2*B*x+C)
# gives the congruency
# (A*x+B)^2 = A*(A*x*x+2*B*x+C) (mod n)
# because A is chosen to be square, it doesn't need to be sieved
sieve_val = (A*x + B+B)*x + C
if sieve_val < 0:
vec = {-1}
sieve_val = -sieve_val
for p in prime:
while sieve_val%p == 0:
if p in vec:
# keep track of perfect square factors
# to avoid taking the sqrt of a gigantic number at the end
sqr += [p]
vec ^= {p}
sieve_val = int(sieve_val / p)
if sieve_val == 1:
# smooth
smooth += [(vec, (sqr, (A*x+B), root_A))]
used_prime |= vec
elif sieve_val in partial:
# combine two partials to make a (xor) smooth
# that is, every prime factor with an odd power is in our factor base
pair_vec, pair_vals = partial[sieve_val]
sqr += list(vec & pair_vec) + [sieve_val]
vec ^= pair_vec
smooth += [(vec, (sqr + pair_vals[0], (A*x+B)*pair_vals[1], root_A*pair_vals[2]))]
used_prime |= vec
num_partial += 1
else:
# save partial for later pairing
partial[sieve_val] = (vec, (sqr, A*x+B, root_A))
x += 1
prev_num_smooth = num_smooth
num_smooth = len(smooth)
num_used_prime = len(used_prime)
if verbose:
print 100 * num_smooth / num_prime, 'percent complete\r',
if num_smooth > num_used_prime and num_smooth > prev_num_smooth:
if verbose:
print '%d polynomials sieved (%d values)'%(num_poly, num_poly*x_max*2)
print 'found %d smooths (%d from partials) in %f seconds'%(num_smooth, num_partial, time.time()-time1)
print 'solving for non-trivial congruencies...'
used_prime_list = sorted(list(used_prime))
# set up bit fields for gaussian elimination
masks = []
mask = 1
bit_fields = [0]*num_used_prime
for vec, vals in smooth:
masks += [mask]
i = 0
for p in used_prime_list:
if p in vec: bit_fields[i] |= mask
i += 1
mask <<= 1
# row echelon form
col_offset = 0
null_cols = []
for col in xrange(num_smooth):
pivot = col-col_offset == num_used_prime or bit_fields[col-col_offset] & masks[col] == 0
for row in xrange(col+1-col_offset, num_used_prime):
if bit_fields[row] & masks[col]:
if pivot:
bit_fields[col-col_offset], bit_fields[row] = bit_fields[row], bit_fields[col-col_offset]
pivot = False
else:
bit_fields[row] ^= bit_fields[col-col_offset]
if pivot:
null_cols += [col]
col_offset += 1
# reduced row echelon form
for row in xrange(num_used_prime):
# lowest set bit
mask = bit_fields[row] & -bit_fields[row]
for up_row in xrange(row):
if bit_fields[up_row] & mask:
bit_fields[up_row] ^= bit_fields[row]
# check for non-trivial congruencies
for col in null_cols:
all_vec, (lh, rh, rA) = smooth[col]
lhs = lh # sieved values (left hand side)
rhs = [rh] # sieved values - n (right hand side)
rAs = [rA] # root_As (cofactor of lhs)
i = 0
for field in bit_fields:
if field & masks[col]:
vec, (lh, rh, rA) = smooth[i]
lhs += list(all_vec & vec) + lh
all_vec ^= vec
rhs += [rh]
rAs += [rA]
i += 1
factor = my_math.gcd(my_math.list_prod(rAs)*my_math.list_prod(lhs) - my_math.list_prod(rhs), n)
if 1 < factor < n:
break
else:
if verbose:
print 'none found.'
continue
break
if verbose:
print 'factors found:'
print factor, 'x', n/factor
print 'time elapsed: %f seconds'%(time.time()-time1)
return factor
if __name__ == "__main__":
import argparse
parser = argparse.ArgumentParser(description='Uses a MPQS to factor a composite number')
parser.add_argument('composite', metavar='number_to_factor', type=long, help='the composite number to factor')
parser.add_argument('--verbose', dest='verbose', action='store_true', help="enable verbose output")
args = parser.parse_args()
if args.verbose:
mpqs(args.composite, args.verbose)
else:
time1 = time.time()
print mpqs(args.composite)
print 'time elapsed: %f seconds'%(time.time()-time1)
```
`my_math.py` is taken from the same post as `mpqs.py`, however I've also added in the unbounded prime number generator I used in my answer to [Find the largest gap between good primes](https://codegolf.stackexchange.com/a/66046).
**my\_math.py**
```
# primes less than 212
small_primes = [
2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37,
41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89,
97,101,103,107,109,113,127,131,137,139,149,151,
157,163,167,173,179,181,191,193,197,199,211]
# pre-calced sieve of eratosthenes for n = 2, 3, 5, 7
indices = [
1, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47,
53, 59, 61, 67, 71, 73, 79, 83, 89, 97,101,103,
107,109,113,121,127,131,137,139,143,149,151,157,
163,167,169,173,179,181,187,191,193,197,199,209]
# distances between sieve values
offsets = [
10, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6,
6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4,
2, 4, 8, 6, 4, 6, 2, 4, 6, 2, 6, 6,
4, 2, 4, 6, 2, 6, 4, 2, 4, 2,10, 2]
# tabulated, mod 105
dindices =[
0,10, 2, 0, 4, 0, 0, 0, 8, 0, 0, 2, 0, 4, 0,
0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 6, 0, 0, 2,
0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 2,
0, 6, 6, 0, 0, 0, 0, 6, 6, 0, 0, 0, 0, 4, 2,
0, 6, 2, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 6, 2,
0, 6, 0, 0, 4, 0, 0, 4, 6, 0, 0, 2, 0, 4, 8,
0, 0, 2, 0,10, 0, 0, 4, 0, 0, 0, 2, 0, 4, 2]
max_int = 2147483647
# returns the index of x in a sorted list a
# or the index of the next larger item if x is not present
# i.e. the proper insertion point for x in a
def binary_search(a, x):
s = 0
e = len(a)
m = e >> 1
while m != e:
if a[m] < x:
s = m
m = (s + e + 1) >> 1
else:
e = m
m = (s + e) >> 1
return m
# divide and conquer list product
def list_prod(a):
size = len(a)
if size == 1:
return a[0]
return list_prod(a[:size>>1]) * list_prod(a[size>>1:])
# greatest common divisor of a and b
def gcd(a, b):
while b:
a, b = b, a%b
return a
# extended gcd
def ext_gcd(a, m):
a = int(a%m)
x, u = 0, 1
while a:
x, u = u, x - (m/a)*u
m, a = a, m%a
return (m, x, u)
# legendre symbol (a|m)
# note: returns m-1 if a is a non-residue, instead of -1
def legendre(a, m):
return pow(a, (m-1) >> 1, m)
# modular inverse of a mod m
def mod_inv(a, m):
return ext_gcd(a, m)[1]
# modular sqrt(n) mod p
# p must be prime
def mod_sqrt(n, p):
a = n%p
if p%4 == 3:
return pow(a, (p+1) >> 2, p)
elif p%8 == 5:
v = pow(a << 1, (p-5) >> 3, p)
i = ((a*v*v << 1) % p) - 1
return (a*v*i)%p
elif p%8 == 1:
# Shank's method
q = p-1
e = 0
while q&1 == 0:
e += 1
q >>= 1
n = 2
while legendre(n, p) != p-1:
n += 1
w = pow(a, q, p)
x = pow(a, (q+1) >> 1, p)
y = pow(n, q, p)
r = e
while True:
if w == 1:
return x
v = w
k = 0
while v != 1 and k+1 < r:
v = (v*v)%p
k += 1
if k == 0:
return x
d = pow(y, 1 << (r-k-1), p)
x = (x*d)%p
y = (d*d)%p
w = (w*y)%p
r = k
else: # p == 2
return a
#integer sqrt of n
def isqrt(n):
c = n*4/3
d = c.bit_length()
a = d>>1
if d&1:
x = 1 << a
y = (x + (n >> a)) >> 1
else:
x = (3 << a) >> 2
y = (x + (c >> a)) >> 1
if x != y:
x = y
y = (x + n/x) >> 1
while y < x:
x = y
y = (x + n/x) >> 1
return x
# integer cbrt of n
def icbrt(n):
d = n.bit_length()
if d%3 == 2:
x = 3 << d/3-1
else:
x = 1 << d/3
y = (2*x + n/(x*x))/3
if x != y:
x = y
y = (2*x + n/(x*x))/3
while y < x:
x = y
y = (2*x + n/(x*x))/3
return x
# strong probable prime
def is_sprp(n, b=2):
if n < 2: return False
d = n-1
s = 0
while d&1 == 0:
s += 1
d >>= 1
x = pow(b, d, n)
if x == 1 or x == n-1:
return True
for r in xrange(1, s):
x = (x * x)%n
if x == 1:
return False
elif x == n-1:
return True
return False
# lucas probable prime
# assumes D = 1 (mod 4), (D|n) = -1
def is_lucas_prp(n, D):
P = 1
Q = (1-D) >> 2
# n+1 = 2**r*s where s is odd
s = n+1
r = 0
while s&1 == 0:
r += 1
s >>= 1
# calculate the bit reversal of (odd) s
# e.g. 19 (10011) <=> 25 (11001)
t = 0
while s:
if s&1:
t += 1
s -= 1
else:
t <<= 1
s >>= 1
# use the same bit reversal process to calculate the sth Lucas number
# keep track of q = Q**n as we go
U = 0
V = 2
q = 1
# mod_inv(2, n)
inv_2 = (n+1) >> 1
while t:
if t&1:
# U, V of n+1
U, V = ((U + V) * inv_2)%n, ((D*U + V) * inv_2)%n
q = (q * Q)%n
t -= 1
else:
# U, V of n*2
U, V = (U * V)%n, (V * V - 2 * q)%n
q = (q * q)%n
t >>= 1
# double s until we have the 2**r*sth Lucas number
while r:
U, V = (U * V)%n, (V * V - 2 * q)%n
q = (q * q)%n
r -= 1
# primality check
# if n is prime, n divides the n+1st Lucas number, given the assumptions
return U == 0
## Baillie-PSW ##
# this is technically a probabalistic test, but there are no known pseudoprimes
def is_bpsw(n):
if not is_sprp(n, 2): return False
# idea shamelessly stolen from Mathmatica's PrimeQ
# if n is a 2-sprp and a 3-sprp, n is necessarily square-free
if not is_sprp(n, 3): return False
a = 5
s = 2
# if n is a perfect square, this will never terminate
while legendre(a, n) != n-1:
s = -s
a = s-a
return is_lucas_prp(n, a)
# an 'almost certain' primality check
def is_prime(n):
if n < 212:
m = binary_search(small_primes, n)
return n == small_primes[m]
for p in small_primes:
if n%p == 0:
return False
# if n is a 32-bit integer, perform full trial division
if n <= max_int:
p = 211
while p*p < n:
for o in offsets:
p += o
if n%p == 0:
return False
return True
return is_bpsw(n)
# next prime strictly larger than n
def next_prime(n):
if n < 2:
return 2
# first odd larger than n
n = (n + 1) | 1
if n < 212:
m = binary_search(small_primes, n)
return small_primes[m]
# find our position in the sieve rotation via binary search
x = int(n%210)
m = binary_search(indices, x)
i = int(n + (indices[m] - x))
# adjust offsets
offs = offsets[m:] + offsets[:m]
while True:
for o in offs:
if is_prime(i):
return i
i += o
# an infinite prime number generator
def primes(start = 0):
for n in small_primes[start:]: yield n
pg = primes(6)
p = pg.next()
q = p*p
sieve = {221: 13, 253: 11}
n = 211
while True:
for o in offsets:
n += o
stp = sieve.pop(n, 0)
if stp:
nxt = n/stp
nxt += dindices[nxt%105]
while nxt*stp in sieve:
nxt += dindices[nxt%105]
sieve[nxt*stp] = stp
elif n < q:
yield n
else:
sieve[q + dindices[p%105]*p] = p
p = pg.next()
q = p*p
# true if n is a prime power > 0
def is_prime_power(n):
if n > 1:
for p in small_primes:
if n%p == 0:
n /= p
while n%p == 0: n /= p
return n == 1
r = isqrt(n)
if r*r == n:
return is_prime_power(r)
s = icbrt(n)
if s*s*s == n:
return is_prime_power(s)
p = 211
while p*p < r:
for o in offsets:
p += o
if n%p == 0:
n /= p
while n%p == 0: n /= p
return n == 1
if n <= max_int:
while p*p < n:
for o in offsets:
p += o
if n%p == 0:
return False
return True
return is_bpsw(n)
return False
```
[Answer]
# Python 2 + [primefac 1.1](https://pypi.python.org/pypi/primefac)
I don't have a Raspberry Pi to test it on.
```
from primefac import primefac
def HP(n):
factors = list(primefac(n))
#print n, factors
if len(factors) == 1 and n in factors:
return n
n = ""
for f in sorted(factors):
n += str(f)
return HP(int(n))
```
[**Try it online**](https://repl.it/FWBt/1)
The `primefac` function returns a list of all prime factors of `n`. In its definition, it calls `isprime(n)`, which uses a combination of trial division, Euler's method, and the Miller-Rabin primality test. I'd recommend downloading the package and viewing the source.
I tried using `n = n * 10 ** int(floor(log10(f))+1) + f` instead of string concatenation, but it's much slower.
[Answer]
# C#
```
using System;
using System.Linq;
public class Program
{
public static void Main(string[] args) {
Console.Write("Enter Number: ");
Int64 n = Convert.ToInt64(Console.ReadLine());
Console.WriteLine("Start Time: " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
Console.WriteLine("Number, Factors");
HomePrime(n);
Console.WriteLine("End Time: " + DateTime.Now.ToString("HH:mm:ss.ffffff"));
Console.ReadLine();
}
public static void HomePrime(Int64 num) {
string s = FindFactors(num);
if (CheckPrime(num,s) == true) {
Console.WriteLine("{0} is prime", num);
} else {
Console.WriteLine("{0}, {1}", num, s);
HomePrime(Convert.ToInt64(RemSp(s)));
}
}
public static string FindFactors(Int64 num) {
Int64 n, r, t = num;
string f = "";
for (n = num; n >= 2; n--) {
r = CalcP(n, t);
if (r != 0) {
f = f + " " + r.ToString();
t = n / r;
n = n / r + 1;
}
}
return f;
}
public static Int64 CalcP(Int64 num, Int64 tot) {
for (Int64 i = 2; i <= tot; i++) {
if (num % i == 0) {
return i;
}
}
return 0;
}
public static string RemSp(string str) {
return new string(str.ToCharArray().Where(c => !Char.IsWhiteSpace(c)).ToArray());
}
public static bool CheckPrime(Int64 num, string s) {
if (s == "") {
return false;
} else if (num == Convert.ToInt64(RemSp(s))) {
return true;
}
return false;
}
}
```
This is a more optimized version of the previous code, with some unnecessary redundant parts removed.
Output (on my i7 laptop):
```
Enter Number: 16
Start Time: 18:09:51.636445
Number, Factors
16, 2 2 2 2
2222, 2 11 101
211101, 3 11 6397
3116397, 3 163 6373
31636373 is prime
End Time: 18:09:51.637954
```
[Test online](https://dotnetfiddle.net/OmcnZL)
[Answer]
# Perl + ntheory, HP(80) in 0.35s on PC
No Raspberry Pi on hand.
```
use ntheory ":all";
use feature "say";
sub hp {
my $n = shift;
while (!is_prime($n)) {
$n = join "",factor($n);
}
$n;
}
say hp($_) for (16,20,64,65,80);
```
The primality test is ES BPSW, plus a single random-base M-R for larger numbers. At this size we could use `is_provable_prime` (n-1 and/or ECPP) with no noticeable difference in speed, but that would change for >300-digit values with no real benefit. Factoring includes trial, power, Rho-Brent, P-1, SQUFOF, ECM, QS depending on the size.
For these inputs it runs about the same speed as Charles' Pari/GP code on the OEIS site. ntheory has faster factoring for small numbers, and my P-1 and ECM are pretty good, but the QS isn't great so I would expect Pari to be faster at some point.
[Answer]
# [pari/gp](http://pari.math.u-bordeaux.fr/), HP(80) in 0.279 s on my laptop
[Try it online!](https://tio.run/##bVLRboMwDHznKzz2ErR0g2qrJlX9ij0CqjIW2myQoMSs2qp@O3OAFlotEoriO5/PNo2warFrum5vatlYVUumI9jAMQA6h72qJLtT7ozwPuxPKQoknr@MJWR9QfTWoSUoDKdYSRy1STjUAp36lcznRWmST4Jn2qeneThVfHmDz@ULowuBrH9yeEPLxiRI8mhmx5/Zc26UVOS3qAaNERgvK7G1uu/rFARKNy1uK@V8y2my4rCMOaye6Xvh8Brn6@AYXHq8n@iDfV9oiqUqH2qgQVERFD/GQ6AwrfYVkngNWQZOIuBegm7rd2nBlIC0BQc/poWDICYa8tlIMdDKVheojIZCVFVwNc5eeBolxlRkJ9HLsdlAaMsa2fxPmIGY/J@E4kv6BhkRFiQd9d4vxHGSDmpVUfeS1vbhpuR@BA@bQeVqA4OZMMMMQz4Sn8ZOIMx0SLwoOHXdHw)
```
homeprime(n) = {
while(!isprime(n),
fact = factor(n);
n_str = "";
for(i=1, matsize(fact)[1],
for(j=1, fact[i,2],
n_str = concat(n_str, Str(fact[i, 1]));
);
);
n = eval(n_str);
);
return(n);
}
input_list = [16, 20, 64, 65, 80];
{
for(i=1, #input_list,
n = input_list[i];
total = 0.0;
count = 10; \\ set the number of times you want to repeat the function call
for(j=1, count,
t0 = gettime();
print(homeprime(n));
t1 = gettime();
taken = (t1 - t0); \\ gettime() returns milliseconds
total += taken;
);
print("\t\t", total / count, "\n");
)
}
```
] |
[Question]
[
# Generate me a QFP chip!
[From the sandbox!](http://meta.codegolf.stackexchange.com/a/10619/60951)
QFP is a type of form factor for an electrical component where pins come out the sides of a chip. Here are is a picture of a typical QFP component:
[](https://i.stack.imgur.com/VF0tx.png)
you can see that the general formula is to have 4 sides of equal numbers of pins.
Your challenge is to create a program that takes in an integer, thich represents the number of pins on one side, and creates an ASCII QFP component with numbered pins.
## Input:
a single integer which represents the number of pins on one side
## Output:
An ASCII QFP chip with an apropriate pinout.
## Example:
input:1
```
4
┌┴┐
1┤ ├3
└┬┘
2
```
input:2
```
87
┌┴┴┐
1┤ ├6
2┤ ├5
└┬┬┘
34
```
input:12
```
444444444333
876543210987
┌┴┴┴┴┴┴┴┴┴┴┴┴┐
1┤ ├36
2┤ ├35
3┤ ├34
4┤ ├33
5┤ ├32
6┤ ├31
7┤ ├30
8┤ ├29
9┤ ├28
10┤ ├27
11┤ ├26
12┤ ├25
└┬┬┬┬┬┬┬┬┬┬┬┬┘
111111122222
345678901234
```
## Rules:
* all QFP chips must be enclosed and sealed as well as ascii provides. spacing is of utmost importance. Dust inside a microprocessor is bad stuff!
* pin numbering must be done as in the examples (Read left to right, top to bottom, numbered counter clockwise)
* You may start numbering at 0, but this must not affect the chip (an input of 12 still needs 12 pins per side)
* The only valid characers in your output are `1,2,3,4,5,6,7,8,9,0,┌,┴,┐,├,┘,┬,└,┤`, spaces, and newlines.
* all encodings for languages are allowed, but your output MUST be consistent with the rules above.
This is a codegolf, and as such, The code with the least number of bytes wins! Good Luck!
[Answer]
# [Kotlin](https://kotlinlang.org), 397 393 bytes
Unnamed lambda.
You can try it [here](http://try.kotlinlang.org/), but you'll have to paste the source in yourself because the editor doesn't seem to save programs in UTF-8 encoding. The ungolfed version is a full program, so you should be able to use that in its entirety.
**Golfed**
```
{n:Int->operator fun String.mod(x:Int){(1..x).map{print(this)}};val l={s:String->s.padStart(n/10+2)};var s=(1..n).map{"${n*4+1-it}".reversed()};val z={i:Int->l(" ")%1;s.map{print(it.getOrElse(i,{' '}))};"\n"%1};(s[0].length-1 downTo 0).map(z);l("┌")%1;"┴"%n;"┐\n"%1;(1..n).map{l("$it┤")%1;" "%n;"├${n*3+1-it}\n"%1};l("└")%1;"┬"%n;"┘\n"%1;s=(1..n).map{"${n+it}"};(0..s.last().length-1).map(z)}
```
**(Sort of) Ungolfed**
```
fun main(args: Array<String>) {
var q = { n: Int ->
operator fun String.mod(x: Int) {
(1..x).map { print(this) }
}
val l = { s: String ->
s.padStart(n / 10 + 2)
}
var s = (1..n).map { "${n * 4 + 1 - it}".reversed() }
val z = { i: Int ->
l(" ")%1
s.map { print(it.getOrElse(i, { ' ' })) }
"\n"%1
}
(s[0].length - 1 downTo 0).map(z)
l("┌")%1
"┴"%n
"┐\n"%1
(1..n).map { l("$it┤") % 1;" " % n;"├${n * 3 + 1 - it}\n" % 1 }
l("└")%1
"┬"%n
"┘\n"%1
s = (1..n).map { "${n + it}" }
(0..s.last().length - 1).map(z)
}
q(30)
}
```
Saved a bunch of bytes by overloading the `%` operator and using it to print. I'll probably revisit this later - I think I can save quite a few bytes if I use `mod` or some other operator as a concatenation function. More interpolation and less print calls.
[Answer]
# Mathematica, 271 bytes
```
c=Table;d=StringPadLeft[#<>"\n",(b=IntegerLength[4a])+a+2]&/@(#)&;d@Reverse@#4<>{e=" "~c~b,"┌"<>"┴"~c~a,"┐
",({#,"┤"," "~c~a,"├",#2,"
"}&)~MapThread~{#,Reverse@#3},e,"└","┬"~c~a,"┘
",d@#2}&@@Partition[Characters@StringPadLeft[ToString/@Range[4#]],a=#]&
```
Anonymous function. Takes a number as input and returns a string as output. The non-box-drawing Unicode character is U+F3C7 (private use) for `\[Transpose]`.
[Answer]
## Python 2, ~~352~~ ~~343~~ 331 bytes
```
def q(n,j=''.join,k='\n'.join,m=map):a,b,c,d=zip(*[iter(m(str,range(n*4)))]*n);l=len(`n-1`);r=lambda x:k(m(lambda s:' '*(l+1)+j(s),m(j,[m(lambda t:t or' ',v)for v in m(None,*x)])));return k([r(d[::-1]),' '*l+u'┌'+u'┴'*n+u'┐',k(x.rjust(l)+u'┤'+' '*n+u'├'+y for x,y in zip(a,c[::-1])),' '*l+u'└'+u'┬'*n+u'┘',r(b)])
```
[Try it here.](https://repl.it/Ekcm/1 "Try it here") Note the file must start with the UTF-8 BOM `\xef\xbb\xbf` for the unicode literals to work in the standard CPython interpreter. These 3 bytes are counted against the size here. `repl.it` is already using unicode so the link just has the code shown here.
Thanks @tuskiomi for the encoding idea that saved ~~9~~ 21 bytes.
Partially ungolfed:
```
def q(n):
a,b,c,d = zip(*[iter(map(str,range(n*4)))]*n) # get numbers for sides
l = len(`n-1`) # left padding
r = lambda x: '\n'.join(
map(lambda s: ' '*(l+1) + ''.join(s), # padding and row of digits
map(''.join,
[map(lambda t: t or ' ', v) # rows of digits with spaces where missing
for v in map(None, *x)]))
)
return '\n'.join([
r(d[::-1]), # top row in reverse order
' '*l+u'\u250c'+u'\u2534'*n+u'\u2510', # top border
# 1st, 3rd (reversed) side numbers
'\n'.join(x.rjust(l) + u'\u2524'+ ' '*n + u'\u251c' + y for x,y in zip(a,c[::-1])),
' '*l+u'\u2514'+u'\u252c'*n+u'\u2518', # bottom border
r(b) # bottom numbers
])
```
[Answer]
## JavaScript (ES6), ~~295~~ 284 bytes (268 chars), non-competing
```
n=>(a=[...(' '[r='repeat'](W=n+6)+`
`)[r](W++)],a.map((_,i)=>i<n*2&&([p,s,L,R,C]=i<n?[(i+3)*W-1,1,i+1,n*3-i,0]:[i-n+3-W,W,n*5-i,i+1,1],[...(' '+L).slice(-2)+'┤┴'[C]+' '[r](n)+'├┬'[C]+R].map(c=>a[p+=s]=c))),[2,3,W-4,W-3].map((p,i)=>a[W*p+2-6*(i&1)]='┌┐└┘'[i]),a.join``)
```
This code doesn't support pin numbers above 99 and therefore probably doesn't qualify as a fully valid entry. That's why I mark it as non-competing for now.
It could be easily modify to support an arbitrary large number of pins by using wider static margins around the chip. However, that may infringe the rules as well (not sure about that). Fully dynamic margins would cost significantly more bytes.
## Demo
```
let f =
n=>(a=[...(' '[r='repeat'](W=n+6)+`
`)[r](W++)],a.map((_,i)=>i<n*2&&([p,s,L,R,C]=i<n?[(i+3)*W-1,1,i+1,n*3-i,0]:[i-n+3-W,W,n*5-i,i+1,1],[...(' '+L).slice(-2)+'┤┴'[C]+' '[r](n)+'├┬'[C]+R].map(c=>a[p+=s]=c))),[2,3,W-4,W-3].map((p,i)=>a[W*p+2-6*(i&1)]='┌┐└┘'[i]),a.join``)
console.log(f(2))
console.log(f(4))
console.log(f(12))
```
[Answer]
# Java 11, ~~451~~ ~~425~~ 393 bytes
```
n->{int d=(n+"").length(),i,j=-1,l=(int)Math.log10(n*4);String p=" ".repeat(d),P=p+" ",r=P;for(;j++<l;r+="\n"+(j<l?P:p))for(i=n*4;i>n*3;)r+=(i--+"").charAt(j);r+="┌"+"┴".repeat(n)+"┐\n";for(i=0;i<n;r+="├"+(n*3-i+++1)+"\n")r+=p.substring((i+"").length())+i+"┤"+" ".repeat(n);r+=p+"└"+"┬".repeat(i)+"┘\n"+P;for(j=-1;j++<l;r+="\n"+P)for(i=n;i<n*2;)r+=(++i+"").charAt(j);return r;}
```
-26 bytes thanks to *@ceilingcat*.
**Explanation:**
[Try it online.](https://tio.run/##hVKxTsMwFNz5CiuTXSdR0zLhuogPaBWJERjcJG0d3JfIcSqhqn/AwNCBgZGRkS/iR4KdhAoqoUpJJPvOd@98ycVWBHn62CRKVBWaCQm7C4QkmEwvRZKhuVsidGu0hBVKsEUQEGY39/a1T2WEkQmaI0AcNRBMd46ScgzU80ioMliZNSa@9HMeRL7iToLMhFmHqlhFQwyDS8J6/ZJ7yAt1VmbC4JT4MS@p3fE1j9my0JjllE4U05R79@BRnE/UdXxVEuJAya0Uk1MYjBmxFCyDoJ0hWQt9Y3BO2oNfh2eP2u/n0QiIW79YRdbpDJmcQE9@szZWMZCU0sgSLcuJl2FVL6p2aozln6iESqf37tFfYaA1Lx1waO0/jpBs7V9doC6lu6iTpPFPQjfZYNTlo1Se5stMrQFptm9YV09ZL5Stp29pW8gUbWzJuLvwuwdB@oKfKpNtwqI2YWkRowBDmOCItF3/i4/O4NF5wpj0v9O@@QY)
```
n->{ // Method with integer parameter and String return-type
int d=(n+"").length(), // The amount of digits of the input
i,j=-1, // Index integers
l=(int)Math.log10(n*4);
// Amount of digits of 4x the input, minus 1
String p=" ".repeat(d), // Padding String for the corners, set to `d` amount of spaces
P=x+" ", // Padding String for the numbers, set to one additional space
r=P; // Result-String, starting at `P` to pad the number
for(;j++<l; // Loop `j` in the range (-1, l]:
; // After every iteration:
r+="\n" // Append a new-line, and padding spaces:
+(j<l?P:p)) // `p` if it's the last iteration; `P` otherwise
for(i=n*4;i>n*3; // Inner loop `i` in the range [4n, 3n):
r+=(i--+"") // Convert the current number to a String,
.charAt(j)); // and append the `j`'th digit to the result-String
r+="┌" // Append the top-left corner of the chip
+"┴".repeat(n) // Append the top row of the chip
+"┐\n"; // Append the top-right corner of the chip, plus a new-line
for(i=0;i<n // Loop `i` in the range [0, n):
; // After every iteration:
r+="├" // Append the right border of the chip
+(n*3-i+++1) // Append the number
+"\n") // And a trailing newline
r+=p.substring((i+"").length())
// Append padding spaces in front of the left number
+i // Append the current number
+"┤" // Append the left border of the chip
+" ".repeat(n); // Append the inner spaces
r+=p // Append padding spaces in front of the corner
+"└" // Append the bottom-left corner of the chip
+"┬".repeat(i) // Append the bottom part of the chip
+"┘\n" // Append the bottom-right corner of the chip, plus a new-line
+P; // Append padding spaces in front of the bottom number
for(j=-1;j++<l; // Loop `j` in the range (-1, l]:
; // After every iteration:
r+="\n" // Append a new-line
+P) // Append padding spaces for the number
for(i=n;i<n*2; // Inner loop `i` in the range [n, 2n):
r+=(++i+"") // Convert the current number to a String,
.charAt(j)); // and append the `j`'th digit to the result-String
return r;} // Return the result-String
```
] |
[Question]
[
# Brief Problem Explanation
Write a program to find the minimum distance between two points traveling only on rays emanating from the origin and circles centered on the origin.
# Explanation of Premise
Now let's imagine we are on a plane, and on this plane we are only allowed to travel in special ways. We are allowed to travel on any ray emanating from the origin.
[](https://i.stack.imgur.com/9joWo.png)
We can also travel on any circle centered at a circle
[](https://i.stack.imgur.com/3pXmM.png)
Now our goal is to travel from one point on this plane to another. However, we can't just travel in a simple Euclidian path, we can only do this if the points happen to fall on a ray emanating from the center.
[](https://i.stack.imgur.com/sIKca.png)
We can travel on this one because it falls on a one of our rays.
[](https://i.stack.imgur.com/tWa2n.png)
We can also travel on circles centered at the origin.
[](https://i.stack.imgur.com/x8Me0.png)
# Examples
Now here is the challenge:
We've got to get from one point to another in the shortest path; often this is a combination of traveling on circles and rays.
[](https://i.stack.imgur.com/Lp1YE.png)
This, however, it could also be traveling on two rays.
[](https://i.stack.imgur.com/w0nQH.png)
Sometimes there exist two paths that travel the minimum distance.
[](https://i.stack.imgur.com/kMoqW.png)
# Problem
Your challenge is to write a program that when given two points will give us the minimum distance between them if we follow these rules. The inputs can be given in either rectangular or polar forms and the output ought to be one number, the distance between.
# Test Cases
(with rectangular input)
```
(1,1) (1,-1) -> ~ 2.22144
(0,0) (1, 1) -> ~ 1.41421
(1,0) (-0.4161 , 0.90929) -> ~ 2
(1,1) (1, 0) -> ~ 1.19961
(1,2) (3, 4) -> ~ 3.16609
```
[Answer]
# Haskell, ~~49~~ 48 bytes
```
(a!q)c r=min(q+r)$abs(q-r)+acos(cos$a-c)*min q r
```
Usage:
```
> let rect2polar (x,y)=(atan2 y x, sqrt(x^2+y^2))
> let test c1 c2=let [(a1,r1),(a2,r2)]=rect2polar<$>[c1,c2] in (a1!r1)a2 r2
> test (1,0) (-0.4161, 0.90929)
1.9999342590038496
```
Thanks to @Zgarb for saving a byte
[Answer]
## JavaScript (ES6), 65 bytes
```
with(Math)(r,t,s,u,v=acos(cos(t-u)))=>v<2?abs(r-s)+v*min(r,s):r+s
```
Takes polar coordinates. Uses @Angs' trick for reducing an angle to between 0 and π. For rectangular coordinates, something like this works:
```
with(Math)g=(r,t,s,u,v=acos(cos(t-u)))=>v<2?abs(r-s)+v*min(r,s):r+s
with(Math)f=(x,y,v,w)=>g(hypot(y,x),atan2(y,x),hypot(w,v),atan2(y,v))
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 22 bytes
```
|ttsGZ}/X/bX<*|bd|+hX<
```
Input is an array of two complex numbers.
[Try it online!](http://matl.tryitonline.net/#code=fHR0c0dafS9YL2JYPCp8YmR8K2hYPA&input=WzErMWosIDEtMWpd) Or [verify all test cases](http://matl.tryitonline.net/#code=YFhLCnx0dHNLWn0vWC9iWDwqfGJkfCtoWDwKRFQ&input=WzErMWosIDEtMWpdClswKzBqLCAxKzFqXQpbMSswaiwgLTAuNDE2MSswLjkwOTI5al0KWzErMWosIDErMGpdClsxKzJqLCAzKzRqXQ).
### Explanation
```
| % Implicitly input array and take absolute value of its entries
tt % Duplicate twice
s % Sum. This is the length of the path that follows the two radii
GZ} % Push input again and split into the two numbers
/X/ % Divide and compute angle. This gives the difference of the angles
% of the two points, between -pi and pi
bX< % Bubble up a copy of the array of radii and compute minimum
*| % Multiply and take absolute value. This is the arc part of the
% path that follows one arc and the difference of radii
bd| % Bubble up a copy of the array of radii and compute absolute
% difference. This is the other part of the second path
+ % Add. This gives the length of second path
hX< % Concatenate and take minimum to produce the smallest length.
% Implicitly display
```
[Answer]
# Ruby, 64 bytes
First, my submission. Lambda function with arguments `distance 1, angle 1, distance 2, angle2`.
```
->r,a,s,b{([d=(b-a).abs,?i.to_c.arg*4-d,2].min-2)*[r,s].min+s+r}
```
Now here's two different solutions of 66 bytes (excluding assignment `f=`) followed by my actual submission again at 64 bytes.
```
Solution 1:Using include Math, 66 bytes excluding f=
include Math;f=->r,a,s,b{[acos(cos(b-a)),2].min*[r,s].min+(s-r).abs}
Solution 2:Using complex number to define PI instead, 66 bytes excluding f=
f=->r,a,s,b{[d=(b-a).abs,?i.to_c.arg*4-d,2].min*[r,s].min+(s-r).abs}
SUBMISSION AGAIN, 64 bytes excluding f=
f=->r,a,s,b{([d=(b-a).abs,?i.to_c.arg*4-d,2].min-2)*[r,s].min+s+r}
```
The Submission is based on solution 2, but uses the identity `(s-r).abs`=`s+r-[s,r].min*2` to shorten the code by 2 bytes, hence the `-2` inside the brackets.
The other notable feature is the expression `?i.to_c.arg*4` = 2\*PI without using `include Math`. If lower precision is acceptable this can be replaced by a literal.
**Solution 2 commented in test program**
```
f=->r,a,s,b{ #r,s are distances, a,b are angles for points 1 and 2 respectively.
[d=(b-a).abs, #From nearer point we can take arc of length d radians perhaps crossing zero angle to the ray of the further point
?i.to_c.arg*4-d, #or go the other way round which may be shorter (?i.to_c.arg*4 == 2*PI, subtract d from this.)
2].min* #or go through the centre if the angle exceeds 2 radians.
[r,s].min+ #Multiply the radians by the distance of the nearer point from the origin to get the distance travelled.
(s-r).abs #Now add the distance to move along the ray out to the further point.
}
#test cases per question (given as complex numbers, converted to arrays of [distance,angle]+[distance,angle] (+ concatenates.)
#the "splat" operator * converts the array to 4 separate arguments for the function.
p f[*("1+i".to_c.polar + "1-i".to_c.polar)]
p f[*("0".to_c.polar + "1+i".to_c.polar)]
p f[*("1".to_c.polar + "-0.4161+0.90929i".to_c.polar)]
p f[*("1+i".to_c.polar + "1".to_c.polar)]
p f[*("1+2i".to_c.polar + "3+4i".to_c.polar)]
```
**Output**
```
2.221441469079183
1.4142135623730951
1.9999342590038496
1.1996117257705434
3.1660966740274357
```
[Answer]
## Mathematica 66 Bytes
This takes rectangular coordinates and can output an exact symbolic solution
```
Min[If[(m=Min[{p,q}=Norm/@#])>0,m*VectorAngle@@#,0]+Abs[p-q],p+q]&
```
Usage:
```
%/@{
{{1,1},{1,-1}},
{{0,0},{1,1}},
{{1,0},{-.4161,.90929}},
{{1,1},{1,0}},
{{1,2},{3,4}}
}
```
yields:
[](https://i.stack.imgur.com/b7tEb.png)
N@% yields:
{2.221441469, 1.414213562, 1.999934259, 1.199611726, 3.166096674}
[Answer]
# Python 2, ~~164~~ ~~126~~ ~~125~~ 132 bytes:
```
def A(a,b,c,d,p=3.1415926535):z=abs(a-c);M=lambda f:2*p*f*abs(b-d)/360.0;print min((a==c)*min(a+c,M(a))+(b==d)*z or'',M(a)+z,M(c)+z)
```
I am currently looking into golfing this more, though. Accepts polar coordinates. Should be called in the format `A(r1,θ1,r2,θ2)`. Outputs a floating point value accurate up to `12` significant figures.
[Try It Online! (Ideone)](http://ideone.com/hB84b3)
A simple, straightforward implementation that calculates and outputs to STDOUT the minimum value out of an array of at most 3 values containing:
1. the minimum value out of either the sum of the two lengths (`r1+r2`) or the length of the arc connecting the two points *iff* `r1==r2`;
2. the *difference* between the two distances (`abs(r1-r2)`) *iff* `θ1==θ2` (i.e. the two points are collinear);
3. if none of the previous 2 items are added, then an empty string (`''`) as apparently in Python a string is *greater than* any integer;
4. and 2 final values given from the distances traveled along a circle and a ray and vice-versa between the two points.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 47 bytes
```
MinMax@Abs@{##}.{Min[Abs[Arg@#-Arg@#2]-1,1],1}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73zczzzexwsExqdihWlm5Vq8aKBAN5EU7FqU7KOuCSaNYXUMdw1gdw1q1/wFFmXklCg4KwZm5BTmZaZVAZlq0oYK2gqeOgqGCroJnLBdWJQYgaW2c0oY6CroGeiaGZiBFBnqWBpZGllo4FUOtwyNtpAVUYAxkmIBM@Q8A "Wolfram Language (Mathematica) – Try It Online")
(beats the current 66-byte answer)
Take input as 2 complex numbers.
May have some issues if the input is symbolic. (e.g., `Cos@2 + I Sin@2`)
] |
[Question]
[
## The task
In this challenge, your task is to write three programs that form a kind of mutual quine-like system.
Let's call the programs `A`, `B` and `C`.
If one of the programs is given the source of another program as input, it shall output the source of the third program.
For example, if `A` is given `B` as input, it outputs `C`.
If the programs are given their own source as input, they shall output the three strings `"three"`, `"mutual"`, and `"quines"` (without quotes).
In all cases, they may output one additional trailing newline.
For any other inputs, the programs may do anything, including crash.
## Example
For example, suppose that the source codes of `A`, `B` and `C` are `aSdf`, `ghJk` and `zxcV`.
Then the programs should behave as follows.
```
Source Input Output
--------------------
aSdf aSdf three
aSdf ghJk zxcV
aSdf zxcV ghJk
ghJk aSdf zxcV
ghJk ghJk mutual
ghJk zxcV aSdf
zxcV aSdf ghJk
zxcV ghJk aSdf
zxcV zxcV quines
```
## Rules and scoring
The solutions `A`, `B` and `C` can be either functions or full programs, but they must be completely independent: **no** shared code is allowed.
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) and [quine rules](http://meta.codegolf.stackexchange.com/questions/4877/what-counts-as-a-proper-quine) apply, so the programs can't access their own source codes in any way.
Your score is the combined byte count of `A`, `B` and `C`, lower score being better.
[Answer]
# CJam, ~~165~~ ~~147~~ ~~114~~ ~~108~~ 99 bytes
```
2 _ri^_q+@"quinesmutualthree"6/=?
```
```
1 _ri^_q+@"quinesmutualthree"6/=?
```
```
3 _ri^_q+@"quinesmutualthree"6/=?
```
*Thanks to @MartinBüttner for a suggestion that helped save 48 bytes!*
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=2%20_ri%5E_q%2B%40%22quinesmutualthree%226%2F%3D%3F&input=2%20_ri%5E_q%2B%40%22quinesmutualthree%226%2F%3D%3F).
### Verification
```
$ cat A
2 _ri^_q+@"quinesmutualthree"6/=?
$ cat B
1 _ri^_q+@"quinesmutualthree"6/=?
$ cat C
3 _ri^_q+@"quinesmutualthree"6/=?
$
$ cjam A < A
three
$ cjam A < B
3 _ri^_q+@"quinesmutualthree"6/=?
$ cjam A < C
1 _ri^_q+@"quinesmutualthree"6/=?
$
$ cjam B < A
3 _ri^_q+@"quinesmutualthree"6/=?
$ cjam B < B
mutual
$ cjam B < C
2 _ri^_q+@"quinesmutualthree"6/=?
$
$ cjam C < A
1 _ri^_q+@"quinesmutualthree"6/=?
$ cjam C < B
2 _ri^_q+@"quinesmutualthree"6/=?
$ cjam C < C
quines
```
### Idea
The set **{0, 1, 2, 3}** is a group under the operation **^** (binary exclusive OR), where each element is its own inverse.
If all three programs are identical except for the the first character (an element of **{0, 1, 2, 3}**), we can distinguish and print them easily:
* We start by XORing the digit at the beginning of the source code and the input.
* If the result is in **0**, source and input match.
Thus, we print one of the three words, selected by this common digit.
* If the result is not **0**, it is the element of **{1, 2, 3}** that is neither in the source nor in the input.
Thus, we prints it, followed by the rest of the input.
### How it works
```
2 e# Push the number N on the stack.
_ e# Push a copy.
r e# Read a token from STDIN, i.e., the input up
e# to and excluding the next whitespace char.
i e# Cast to integer.
^ e# XOR it with the copy of N. Result: X
_ e# Push a copy of the result.
q+ e# Append the rest of the input.
@ e# Rotate N on top of the stack.
"quinesmutualthree"6/ e# Push ["quines" "mutual" "three"].
= e# Select the word at index N.
? e# If X is non-zero, select the modified input;
e# otherwise, select the word.
```
] |
[Question]
[
This is the ASCII version of [this challenge](https://codegolf.stackexchange.com/questions/105258/generate-a-padovan-spiral). The initial post was separated per request by [Martin Ender](https://codegolf.stackexchange.com/questions/105258/generate-a-padovan-spiral#comment255895_105258)
## Introduction
Similar to the Fibonacci Sequence, the [Padovan Sequence](https://en.wikipedia.org/wiki/Padovan_sequence) ([OEIS A000931](https://oeis.org/A000931)) is a sequence of numbers that is produced by adding previous terms in the sequence. The initial values are defined as:
```
P(0) = P(1) = P(2) = 1
```
The 0th, 1st, and 2nd terms are all 1. The recurrence relation is stated below:
```
P(n) = P(n - 2) + P(n - 3)
```
Thus, it yields the following sequence:
```
1, 1, 1, 2, 2, 3, 4, 5, 7, 9, 12, 16, 21, 28, 37, 49, 65, 86, 114, 151, 200, 265, 351, ...
```
Using these numbers as side lengths of equilateral triangles yields a nice spiral when you place them all together, much like the Fibonacci Spiral:
[](https://i.stack.imgur.com/pSDh5.png)
Image courtesy of [Wikipedia](https://en.wikipedia.org/wiki/Padovan_sequence#/media/File:Padovan_triangles_(1).png)
---
## Task
Your task is to write a program that recreates this spiral by ASCII art, with input corresponding to which term. Since a triangle of side length 1 (1 character) is impossible to represent nicely in ASCII, the side lengths have been dilated by a factor of 2. Thus, the triangle of side length 1 is actually represented like so:
```
/\
/__\
```
So, for example, if the input was 5 (the 5th term), the output should be:
```
/\
/ \
/ \
/______\
\ /\
\ /__\
\ /\ /
\/__\/
```
The first 5 terms were 1, 1, 1, 2, 2, so the triangle had side lengths 2, 2, 2, 4, 4 due to dilation. Another example for input 8:
```
__________
/\ /\
/ \ / \
/ \ / \
/______\ / \
\ /\ / \
\ /__\/ \
\ /\ / \
\/__\/______________\
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\ /
\/
```
## Rules
* You must print the result, and input must be an integer corresponding to term number
* Trailing and leading newlines are allowed, trailing spaces after lines are allowed also
* Your submission must be able to handle at least up to the 10th term (9)
* Your submission must be a full program or function that takes input and prints the result
* Rotations of the output are allowed, in 60 degree multiples, but the size of the triangles must remain the same, along with the representation
* Going counter-clockwise is also allowed
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden
You may assume that input will be >0 and that correct format of input will be given.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins. Happy New Years everyone!
[Answer]
# Befunge, ~~871~~ ~~836~~ 798 bytes
```
&00p45*:10p20p030p240p050p060p9010gp9110gp1910gp1-91+10gpv
<v-g03+g06*2g041g055_v#!:%6:p06p05+p04g05g06:g04<p*54+292<
->10g:1\g3+:70p110gv >:5- #v_550g:01-\2*40g+1-30g
/\110:\-g03:\1:g055 _v#!-4:<vp01:-1g01-g03-1\-
^1<v07+1:g07< p08p < >:1-#v_550g:01-\40g+60g+1-30g-50g>v
_0>p80gp:5-|v1\+66\:p\0\9:$<:p02:+1g02-g03+g06-\g04\1:<
0v|-g00:+1$$<>\p907^>p:!7v>3-#v_550g:30g+:30p1\0\-
1>10g+::0\g3-:70p\0^^07<v<>50#<g::30g+:30p-1-01-\
v >\$0gg> :1+10gg1- #v_^>0g10gg*+\:!2*-70g2+10gv>:#->#,"_"$#1_:1#<p
+1+g03$_^#`gg011+3:+3<g07\+*2+*`0:-\gg01+5g07:g<>1#,-#*:#8>#4_$#:^#
>55+,p30g40p10gg10g1>#v_
#v:#p0$#8_:$#<g!#@_0^ >
>>:180gg`>>#|_:2+80gg:!v
3+^g\0p08:<vgg08+2::+3<$_100p1-v>g,\80gg+\80gp:2+90g:!01p\80gp
!#^_80g:1+^>\180gg`+!#^_20g80g`
5*g10!g09p04-1-\0\+g04:gg08:p09<^3`0:gg08+1:::$$_1#!-#\\:,#\<g
```
[Try it online!](http://befunge.tryitonline.net/#code=JjAwcDQ1KjoxMHAyMHAwMzBwMjQwcDA1MHAwNjBwOTAxMGdwOTExMGdwMTkxMGdwMS05MSsxMGdwdgo8di1nMDMrZzA2KjJnMDQxZzA1NV92IyE6JTY6cDA2cDA1K3AwNGcwNWcwNjpnMDQ8cCo1NCsyOTI8Ci0+MTBnOjFcZzMrOjcwcDExMGd2ID46NS0gI3ZfNTUwZzowMS1cMio0MGcrMS0zMGcKL1wxMTA6XC1nMDM6XDE6ZzA1NSBfdiMhLTQ6PHZwMDE6LTFnMDEtZzAzLTFcLQpeMTx2MDcrMTpnMDc8IHAwOHAgPCA+OjEtI3ZfNTUwZzowMS1cNDBnKzYwZysxLTMwZy01MGc+dgogXzA+cDgwZ3A6NS18djFcKzY2XDpwXDBcOTokPDpwMDI6KzFnMDItZzAzK2cwNi1cZzA0XDE6PAowdnwtZzAwOisxJCQ8PlxwOTA3Xj5wOiE3dj4zLSN2XzU1MGc6MzBnKzozMHAxXDBcLQoxPjEwZys6OjBcZzMtOjcwcFwwXl4wNzx2PD41MCM8Zzo6MzBnKzozMHAtMS0wMS1cCnYgPlwkMGdnPiA6MSsxMGdnMS0gI3ZfXj4wZzEwZ2cqK1w6ITIqLTcwZzIrMTBndj46Iy0+IywiXyIkIzFfOjEjPHAKKzErZzAzJF9eI2BnZzAxMSszOiszPGcwN1wrKjIrKmAwOi1cZ2cwMSs1ZzA3Omc8PjEjLC0jKjojOD4jNF8kIzpeIwo+NTUrLHAzMGc0MHAxMGdnMTBnMT4jdl8KI3Y6I3AwJCM4XzokIzxnISNAXzBeID4KID4+OjE4MGdnYD4+I3xfOjIrODBnZzohdgozK15nXDBwMDg6PHZnZzA4KzI6OiszPCRfMTAwcDEtdj5nLFw4MGdnK1w4MGdwOjIrOTBnOiEwMXBcODBncAohI15fODBnOjErXj5cMTgwZ2dgKyEjXl8yMGc4MGdgCjUqZzEwIWcwOXAwNC0xLVwwXCtnMDQ6Z2cwODpwMDk8XjNgMDpnZzA4KzE6OjokJF8xIyEtI1xcOiwjXDxn&input=OA)
As is often the case with Befunge, the trick is coming up with an algorithm that allows us to render the pattern from top to bottom, since it's just not feasible to render it into memory first with the limited space available.
The way this works is by first building up a simple data structure representing the edges needed to draw the spiral. The second stage then parses that structure from top to bottom, rendering the edge fragments required for each line of output.
Using this technique, we can support up to n=15 in the reference implementation before we start having overflow issue in the 8-bit memory cells. Interpreters with a larger cell size should be able to support up to n=25 before running out of the memory.
[Answer]
# go, 768 bytes
```
func 卷(n int){
数:=0
p:=[]int{1,1,1}
for i:=3;i<n;i++ {p=append(p,p[i-2]+p[i-3])}
宽:=p[len(p)-1]*10+10
素:=make([]int,宽*宽)
for 数=range 素 {素[数]=32}
for i:=0;i<数;i+=宽 {素[i]=10}
态:=[]int{1,1,宽/2,宽/2,92}
表:=[70]int{}
s:="SRSQTSPQQ!QOQP~QQQQQQSQR~ORQR!OPOPTSQRQ$QPPQNQPPPXQQQQQQRRQXQRRRNOQPQ$"
for i:=range s {表[i]=int(s[i])-33-48}
表[49],表[59]=48,48
for i:=0;i<4*n;i++ {
梴:=p[i/4]*2
if 态[1]==0 {梴=梴*2-2}
for k:=0;k<梴;k++ {
址:=(态[2]+态[3]*宽)%len(素)
if 素[址]==32 {素[址]=态[4]}
态[2]+=态[0]
态[3]+=态[1]
}
数=((态[0]+1)*2+态[1]+1)*5
if i%4>2 {数+=35}
for k:=0;k<5;k++ {态[k]+=表[数+k]}
}
for i:=0;i<宽*宽;i++ {fmt.Printf("%c",rune(素[i]))}
}
```
This is of course not optimal, but it's not a bad start. I know it's probably a bit simple for the golfing standards, but it was fun and I hope it's not minded if I leave some notes to future self.
How it works
Basically I simulate a 'drawing turtle' like in LOGO on an ASCII pixel grid, but the turtle can only do these three commands:
```
rt - right turn, turn 120 degrees right (1/3 of a Turn)
rth - right turn half, turn 60 degrees right (1/6 of a Turn)
fd n - forward, go forward n steps, drawing a trail of _, /, or \
```
Now for each triangle, I go like this, where P is 2x the nth Padovan number:
```
fd P
rt
fd P
rt
fd P
rt
fd P
rth
```
The fourth 'fd' means I am re-tracing the first side of each triangle. This helps get back to a nice starting point for the next triangle. The half-right-turn makes sure that the next triangle will be in the proper orientation.
---
To golf the turtle I store 5 state variables in array 态 : x position, y position, x velocity, y velocity, and 'drawing rune'. At each animation frame, x+= x velocity, y += y velocity, and the rune is drawn.
Then I set up table 表 which tells how to actually perform the turn. The turn code is tricky because of the way ASCII art works. It is not a straightforward movement like on a pixel display. The direction of the turtle, determined by x and y velocity, determine the changes necessary to get the turn to look proper.
To turn, it looks at the current x and y velocity, and combines them into an index.
```
xv = x velocity, yv = y velocity.
i.e. a turtle facing down and to the right has
xv of 1, and yv of 1. It can only face 6
different directions. Formula is (xv+1)*2+yv+1
xv yv index
-1 -1 0
-1 0 1
-1 1 2
1 -1 4
1 0 5
1 1 6
```
This index is used to lookup a set of 5 values in table 表. Those 5 values in table 表 are then added to each of the 5 variables in state 态. The turtle is then effectively turned, and ready for the next 'fd'.
For rth, half the right turn, there is a separate section of the 表 table. It is offset by 7\*5, or 35, entries from the first table in 表.
Lastly I did some simple encoding of the table's integers into an ascii string.
I know I could 'save bytes' by removing the Hanzi but like I said, this is not optimal and there is more golfing possible... I will remove them when there is no other possible optimization. Those Hanzi actually have meaning loosely based on their actual meaning, and even though I don't know Chinese, it helps me think about the program.
```
数 index number
宽 screen width
素 pixel data
梴 length of side of triangle
态 current state
址 address of pixel
表 state transition table
```
To test the code you will need full golang file, with this header
```
package main
import "fmt"
```
and this footer
```
func main () {
for i := 0; i<15; i++ {
卷(i)
}
}
```
thanks
] |
[Question]
[
Everyone knows that the news is boring. *Really boring*. Unless if it's about Politicians and their scandals. That is fun! But alas, Politicians can commit only so many scandals. So, I am employing you to make the news more interesting.
**Objective** Given an HTML snippet, perform all the substitutions found [here](https://xkcd.com/1288/), that is, in this picture: 
BUT you should not edit any HTML tags themselves. I call a valid word any word that is not found within any HTML tag or their attributes. That is, you shouldn't replace `<div class="smartphone">iPhone</div>` with `<div class="pokedex">iPhone</div>`, but should replace `<div>election</div>` with `<div>eating contest</div>`.
# Parsing rules
* **EDIT** You should only match words delineated by a non-word. That is, you should only match full words. (E.g., match "Hello witness" but not "Hellowitness", "Hellow itness", or "Witnesspacelection."
* If you can't type out the character on your keyboard, you should display the closest equivalent. (E.g., "Smartphone" would really become "Pokedex")
* First-letter case or all-letter case must be retained. (E.g., "Allegedly, they died" becomes "Kinda probably, they died", "They allegedly died" becomes "They kinda probably died", and "THE ELECTION!" becomes "THE EATING CONTEST!", while "SpAcE" becomes "Spaaace" and "nEW STUDY" becomes "tumblr post")
* All cases must be matched. (I.e., you must match a word, regardless of its capitalization.)
* Any instance in which `a <vowel>` is met should become `an <vowel>` and *vice versa*. (E.g., "A senator" becomes "An elf-lord") You do not have to do this for every instance, but at least for your own replacements.
* Anything plural must also retain pluralization in the translation (E.g., "Smartphones" becomes "pokedex" and "Spaces" becomes "Spaaaces")
* Anything in a certain tense must remain in that tense in the translation. (E.g., "Rebuilt" becomes "Avenged", "Rebuilds" becomes "Avenges", etc.)
* Anything in the singular must remain singular in the translation (E.g., "Congressional leader" becomes "River spirit")
* If the entry spans multiple HTML elements, you should still match it, but you may "throw away" any intermediate elements. (E.g., `S<b>pa</b>ace` should become simply "spaaace"). If the entry is self-contained within a single element, it should be matched properly and the tag retained.
* "The witnesses" should become "Those dudes I know"
* "witness" should become "This dude I know"
* "The witness" should become "That dude I know"
* "Couldn't be reached for comment" should become "Is guilty and everyone knows it"
* "Cannot be reached for comment" should become "Are guilty and everyone knows it"
# Bonuses
If you meet a `-N%` bonus, your `new amount = (old amount) * (1 - N/100)`. So, if you met a `-5%` bonus with a 500 byte code, your `new amount = 500 * (1 - 5/100) = 500 * .95 = 475`.
* -5% bonus if, for every instance of "space" after the first replacement, an extra "a" is added. So, the first replacement would be "spaaace", the second would be "spaaaace", the third would be "spaaaaace", etc.
* -5% bonus if, for every valid number, you replace that number with a link to the respective XKCD comic. (It doesn't have to yet exist). If you do go for this bonus, you should match numbers such as `500`, `3,000`, `4 523`, and `5.324`. (You may opt to replace, instead, the number with the image of the comic. If you do this, instead of a `-5%` bonus, you will get a `-15% bonus`. Another extra `-15%` bonus if you can add the title-text to the picture, if any.)
* -25% bonus if you can replace simultaneously all instances on the right side of the image with those on the left. (E.g., "spaaace" becomes "space", "eating contest" becomes "election", etc.) If you opt for any of the bonuses, you should be able to revert those to their respective entries. (E.g., `http://www.xkcd.com/542` should become "542", and "spaaaaaaaace" should become "space".)
* ***You may choose to do a minimum of 6 substitutions, but for each substitution not done (exclusive of bonus substitutions), you will receive an additional +10% penalty.***
# Example IOs (no bonuses)
```
Input: Witnesses allegedly used their smartphones to commit the crime.
Output: These dudes I know kinda probably used their pokedex to commit the crime.
Input: Mayor Golfalot rebuilt the city after the fatal election.
Output: Mayor Golfalot avenged the city after the fatal eating contest.
Input: This <b>new study</b> shows that people in <span class="space">space</span> cannot be reached for comment.
Output: This <b>tumblr post</b> shows that people in <span class="space">spaaace</span> are guilty and everyone knows it.
Input: <b>g</b><i>oo</i><s>g</s><u>le</u> glass is terrible. :(
Output: virtual boy is terrible. :(
Input: Electric SMARTPHONES have been shown to be more productive when not used by Senators and when not used in cars.
Output: Atomic POKEDEX have been shown to be more productive when not used by Elf-lords and when not used in cats.
Input: Homeland Security has been established as an evil foundation, especially in space.
Output: Homestar runner has been established as an evil foundation, especially in spaaace.
Input: The congressional leaders are testy today.
Output: The river spirits are testy today.
Input: SPACE is not a Senator or a cAR.
Output: SPAAACE is not an Elf-lord or a cat.
Input: Mr. Biz is running for reelection.
Output: Mr. Biz is running for reelection.
Input: Google glass !
Output: Virtual boy !
Input: New (or old) study
Output: New (or old) study
```
---
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program in bytes wins.
[Answer]
## JavaScript ES6, 954 bytes
I thought this was going to be a lot easier than it was! I originally used JavaScript so I could easily descend only into text nodes and replace the text there, but that wasn't what the question was after, so I've ended up with this monstrosity! It passes all the test cases except for `<b>g</b><i>oo</i><s>g</s><u>le</u> glass is terrible. :(` where the whole string comes back in a `<b>` tag due to the tags getting balanced. The bulk of the code is the lookup table, and I'm probably still missing some edge cases, but I couldn't come up with a nicer way to handle the tense correctly and I'm sure I could compress that more, but I'm running out of ideas... I'm sure I'll come back to this later though. Should've used Perl, better choice [@LukStorms](https://codegolf.stackexchange.com/users/42827/luk-storms)!
```
d=document.createElement`div`,u='toUpperCase'
d[i='innerHTML']=prompt``;`the ${w='witness'}es,those dudes I know|${w}es,these dudes I know|the ${w},this dude I know|${w},dude I know|allegedly,kinda probably|new study,tumblr post|new studies,tumblr posts|rebuild,avenge|rebuilt,avenged|space,spaaace|${g='google glass'},virtual boy|${g}es,virtual boys|smartphones,pokédex|smartphone,pokédex|electric,atomic|senator,elf-lord|car,cat|election,eating contest|congressional leader,river spirit|homeland security,homestar runner|could not ${b='be reached for comment'},is${g=' guilty and everyone knows it'}|couldn't be reached for comment,is${g}|cannot be reached for comment,are${g}`[v='split']`|`.map(w=>d[i]=d[i][r='replace'](eval(`/(<[^>]+)?\\b${(w=w[v]`,`)[0][v]``.join`(?:<\\/?[^>]+>)*`[r](/ /g,'\\s+')}(s?)\\b/gi`),(s,q,t)=>[q?s:((!s.match(/[^A-Z]/)?w[1][u]():s.match(/^[A-Z]/)?w[1][r](/^./,q=>q[u]()):w[1])+t),q?0:w[1]=w[1][r](/ce$/,'ace')][0])[r](/\ba(?= [aeiou])/gi,s=>s=="a"?"an":"AN"))
alert(d[i])
```
I applied one bonus for 5% of `spaaace` getting an additional `a` after each successful match. Uses `alert()` as suggested by [@sysreq](https://codegolf.stackexchange.com/users/46231/sysreq), thanks!
### Examples
```
Input: <b>g</b><i>oo</i><s>g</s><u>le</u> glass is terrible. :(
Output: <b>virtual boy is terrible. :(</b>
```
```
Input: space. Space? Space! SPACE!
Output: spaaace. Spaaaace? Spaaaaace! SPAAAAAACE!
```
```
Input: Smartphones aren't really smart phones, but: SMARTPHONES!
Output: Pokédex aren't really smart phones, but: POKÉDEX!
```
```
Input: Senator John Doe was arrested today after attempting to write a new study on the danger of smartphones being used in the car, on his smartphone whilst driving his car. A witness testified to having seen the senator committing the crime. When questioned, Senator Doe "could not be reached for comment". It's unknown if his reputation can be rebuilt and this puts new doubts on the upcoming election. Congressional leaders have yet to comment.
Output: Elf-lord John Doe was arrested today after attempting to write a tumblr post on the danger of pokédex being used in the cat, on his pokédex whilst driving his cat. A dude I know testified to having seen the elf-lord committing the crime. When questioned, Elf-lord Doe "is guilty and everyone knows it". It's unknown if his reputation can be avenged and this puts new doubts on the upcoming eating contest. River spirits have yet to comment.
```
---
### Bonus: bookmarklet
Run this in your console to have the body text updated in-place:
```
d=document.body;`the ${w='witness'}es,those dudes I know|${w}es,these dudes I know|the ${w},this dude I know|${w},dude I know|allegedly,kinda probably|new study,tumblr post|new studies,tumblr posts|rebuild,avenge|rebuilt,avenged|space,spaaace|${g='google glass'},virtual boy|${g}es,virtual boys|smartphones,pokédex|smartphone,pokédex|electric,atomic|senator,elf-lord|car,cat|election,eating contest|congressional leader,river spirit|homeland security,homestar runner|could not ${b='be reached for comment'},is${g=' guilty and everyone knows it'}|couldn't be reached for comment,is${g}|cannot be reached for comment,are${g}`[v='split']`|`.map(w=>d[i='innerHTML']=d[i][r='replace'](eval('/(<[^>]+)?\\b'+(w=w[v]`,`)[0][v]``.join`(?:<\\/?[^>]+>)*`[r](/ /g,'\\s+')+'(s)?\\b/gi'),(s,q,t)=>[q?s:((s.match(/^[A-Z]+$/)?w[1].toUpperCase():s.match(/^[A-Z]/)?w[1][r](/^./,q=>q.toUpperCase()):w[1])+(t||"")),q?0:w[1]=w[1][r](/ce$/,'ace')][0])[r](/\ba ([aeiou])/gi,(s,t)=>s[0]=="a"?"an "+t:"AN "+t))
```
[Answer]
# [Perl 5](https://www.perl.org/), 850
Lots of regex used or generated.
The %l hash is used for repeated words.
```
%l=qw(A avenge B _be_reached_for_comment C could D dude E pokedex G google_glass I _I_know K river_spirit L congressional_leader P smartphone 4 rebuil N new_stud T tumblr_post V virtual_boy W witness Y _guilty_and_everyone_knows_it);$t="G,V;Ges,Vs;Ps,E;P,E;4d,A;4t,Ad;Nies,Ts;Ny,T;Wes,these DsI;W,this DI;allegedly,kinda probably;cannotB,areY;car,cat;cars,cats;Ls,Ks;L,K;C notB,isY;Cn'tB,isY;election,eating contest;electric,atomic;homeland Security,homestar runner;senator,elf-lord;senators,elf-lords;space,spaaace";$o=$s=$_;$s=~s/\s\s*/ /g;map{$t=~s/$_/$l{$_}/g}keys%l;$t=~s/_/ /g;@L=split/;/,$t;map{my@T=split/,/;push@W,\@T}@L;map{$e=$a=$W[$_][0];$b=$W[$_][1];$U=uc$a;$u=ucfirst$a;$s=~s/(?<![\w"])$U(?![\w"])/\U$b/g;$s=~s/(?<![\w"])$u(?![\w"])/\u$b/g;$s=~s/(?<![\w"])$a(?![\w"])/$b/gi;$e=~s@.@(<.*?>)?$&(</.*?>)?@g;$s=~s/$e /$b /ig;}0..@W;$_=$s.$/
```
### Test
```
$ cat news.txt |perl -p readingnews.pl
These dudes I know kinda probably used their pokedex to commit the crime.
Mayor Golfalot avenged the city after the fatal eating contest.
This <b>tumblr post</b> shows that people in <span class="space">spaaace</span> are guilty and everyone knows it.
virtual boy is terrible. :(
Atomic POKEDEX have been shown to be more productive when not used by Elf-lords and when not used in cats.
Homestar runner has been established as an evil foundation, especially in spaaace.
The river spirits are testy today.
SPAAACE is not a Elf-lord or a cat.
Mr. Biz is running for reelection.
Virtual boy !
New (or old) study
```
] |
[Question]
[
# Challenge
You will be given an input string, anywhere the word `"Lemon"` is found it should be converted to `"Lemonade"` *but* the `a`, `d`, and `e` must be borrowed from somewhere else in the sentence.
---
# Example
Example Input:
>
> I found a **lemon** when I was a kid
>
>
>
Example Output:
>
> I foun a **lemonade** whn I was kid
>
>
>
The **Lemonade** was created by stealing the following superscript letters from the original
>
> I foun~~**d**~~ a lemonade wh~~**e**~~n I was ~~**a**~~ kid
>
>
>
This is just one possible output example, the "e", "d", and "a", could have been taken from anywhere (*except for from the word `lemon` of course*)
---
# Comments
•If there are not enough `e`, `a`, or `d`s you must output what was do-able with the letters given. For example the input `bdblemon` would output `bblemond`
•The `lemon` text might not always be standalone (space on each side). For example you may have the word `lemons` somewhere in the input and the output should be `lemonades`
•The input may contain any number of `lemon`s, even 0 `lemon`s (in which case the output would be identical to the input)
•You can make your lemonade with uppercase and lowercase letters, for example `leMon` could become `leMonade`, and the `ade` borrowed can be any case (so it could also have become `leMonADe`).
The case of the letter you borrowed must remain what it was when you borrowed it.
(Example input -> output, `he hAD lemOn` -> `h h lemOnADe`)
•Does not have to be a full program, a function alone is fine.
•You may assume input will be only the [CP437 Character Set](https://en.wikipedia.org/wiki/Code_page_437)
---
# Code Golf
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the lowest number of bytes wins!
---
# Pseudo-TestCases
\*Note: For any given input there might be **multiple possible outputs** so your program may not output exactly as these test cases do, this is more just so people can understand the logic:
>
> Input: EpaD leMons
>
> Output: p LeMonaDEs
>
>
> Input: hello world
>
> Output: hello world
>
>
> Input: lemon lemon
>
> Output: lemon lemon
>
> \*(*The `e`, `a`, `d` letters should never be taken from another "Lemon")*
>
>
> Input: HE HAD lemonade
>
> Output: H H lemonADEade
>
>
> Input: Do you like lemons? You hAd me at lemon!
>
> Output: o you lik lemonADes? You h m t lemonade!
>
>
> Input: AE lemon
>
> Output: lemonAE
>
>
> Input: 55bad lemon
>
> Output: 55b lemonad
>
>
>
[Answer]
## JavaScript (ES6), ~~159~~ ~~157~~ ~~155~~ 162 bytes
*Edit: +7 bytes to "output what was do-able with the letters given" rather than throwing out an error*
---
A recursive function that returns the modified string.
```
f=(s,a=s.split(/(lemon)/i),n=(a.length-1)*1.5)=>n?f(n,a.map((s,i)=>i&1|!n||(a[i]=s.replace([/a/i,/e/i,/d/i][n%3],c=>(a[--n/3<<1|1]+=c,''))))&&a,n-(n==s)):a.join``
```
### How it works
The expression `s.split(/(lemon)/i)` splits the input string on `lemon` but preserves the capture groups in the result.
For instance, `"foo lemon bar LEMON baz".split(/(lemon)/i)` will produce the array `[ 'foo ', 'lemon', ' bar ', 'LEMON', ' baz' ]`.
We recursively iterate on this array, extracting the characters `a`, `d` and `e` or their uppercase counterparts from the entries located at an even position, and appending them to the entries located at an odd position.
### Commented
```
f = ( // given:
s, // s = input string or previous value of 'n'
a = s.split(/(lemon)/i), // a = split array, as described above
n = (a.length - 1) * 1.5 // n = total number of characters to be found
) => //
n ? // if there's still at least one character to find:
f( // do a recursive call with:
n, // 1) the current value of 'n'
a.map((s, i) => // 2) an updated version of 'a', where
i & 1 | !n || ( // for even positions:
a[i] = s.replace( // we look for the next character
[/a/i, /e/i, /d/i][n % 3], // 'a', 'e' or 'd' (case insensitive)
c => ( // append it to
a[--n / 3 << 1 | 1] += c, // one of the entries at an odd position
'' // and remove it from the original entry
) // end of replace() callback
) // end of replace()
) // end of position condition
) && a, // end of map() -> yield the updated 'a'
n - // 3) the updated value of 'n', skipping the
(n == s) // current character if not found at all
) // end of recursive call
: // else:
a.join`` // success: join 'a' and return it
```
### Demo
```
f=(s,a=s.split(/(lemon)/i),n=(a.length-1)*1.5)=>n?f(n,a.map((s,i)=>i&1|!n||(a[i]=s.replace([/a/i,/e/i,/d/i][n%3],c=>(a[--n/3<<1|1]+=c,''))))&&a,n-(n==s)):a.join``
console.log(f("I found a lemon when I was a kid"))
console.log(f("I found a lemon when I was a kid. I found another lemon when I was older."))
console.log(f("bdblemon"))
console.log(f("he hAD lemOn"))
```
[Answer]
## CJam, 130 bytes
```
LqY5m*{"lemon"_eu}%3/:z{~?}f%{_@\/_:,[{1$+}*]);@f{[\]}@+\1a*}/\{1
=}$0f=\1$,{"ade"{__C#)\Ceu#)|(\0+We\)@_N=@+N\t\}fC}fN0a/L*1a/\.{}
```
This is split across two lines for clarity; the newline is not counted.
### Pseudocode:
```
FLAG_1 = object()
FLAG_2 = object()
lemon_instances = [] # CJam: L
input_chars = list(all_input()) # CJam: q
lemons = [
"LEMON", "LEMOn", "LEMoN", "LEMon", "LEmON", "LEmOn", "LEmoN", "LEmon",
"LeMON", "LeMOn", "LeMoN", "LeMon", "LemON", "LemOn", "LemoN", "Lemon",
"lEMON", "lEMOn", "lEMoN", "lEMon", "lEmON", "lEmOn", "lEmoN", "lEmon",
"leMON", "leMOn", "leMoN", "leMon", "lemON", "lemOn", "lemoN", "lemon"
] # CJam: Y5m*{"lemon"_eu}%3/:z{~?}f%
for i in lemons: # CJam: { ... }/
temp = input_chars.split(i) # CJam: _@\/
lengths = temp.map(len) # CJam: _:,
# Here, accum turns an array like [1,2,3] into [1,3,6].
indices = accum(lengths) # CJam: [{1$+}*]
indices.pop() # CJam: );
temp2 = zip(temp, indices) # CJam: @f{[\]}
lemon_instances = temp2 + lemon_instances # CJam: @+
input_chars = join_array(temp, FLAG_1) # CJam: 1a*
lemon_instances.sort(key=lambda x: x[1]) # CJam: {1=}$
lemon_instances = [i[0] for i in lemon_instances] # CJam: 0f=
for i in range(len(lemon_instances)): # CJam: \1$,{...}fN
for c in "ade": # CJam: "ade"{...}fC
# list_index returns -1 if not found
lower = list_index(input_chars, c)+1 # CJam: __C#)
upper = list_index(input_chars, upper(c))+1 # CJam: \Ceu#)
char_index = (lower or upper) - 1 # CJam: |(
input_chars.append(FLAG_2) # CJam: \0+
# -1 refers to the last element in the list
swap_list_elements(input_chars, char_index, -1) # CJam: e\
extracted = input_chars.pop() # CJam: )
lemon_instances[i] += extracted # CJam: @_N=@+N\t\
remove_all(input_chars, FLAG_2) # CJam: 0a/L*
temp1 = input_chars.split(FLAG_1) # CJam: 1a/
# interleave([1, 2, 3], ["a", "b"]) gives [1, "a", 2, "b", 3]
temp2 = interleave(temp1, lemon_instances) # CJam: \.{}
print("".join(temp2))
```
[Answer]
# [Retina](https://github.com/m-ender/retina), 303 bytes
```
i+`(?<!lemon)(a)(.*)(lemon)(?!a)
$2$3$1
i+`(lemon)(?!a)(.*)(?<!lemon)(a)
$1$3$2
i+(?<!lemona?)(d)(.*)(lemona?)(?![ad])
$2$3$1
i+`(lemona?)(?![ad])(.*)(?<!lemona?)(d)
$1$3$2
i+(?<!lemona?d?)(e)(?!(?<=le)mon)(.*)(lemona?d?)(?![ade])
$2$3$1
i+`(lemona?d?)(?![ade])(.*)(?<!lemona?d?)(e)(?!(?<=le)mon)
$1$3$2
```
[Try it online!](https://tio.run/nexus/retina#bY7NCsIwEITveYotREhUhNarkqP0CTyI0IVsNfTvEGrx6WuSVona48zOfLMrcSpGsymEOiQ1NV0rBUqxW0sxK5WgZDzje54yn4vsEIt7jKcul7ncx0YlhY6AXqvkgvr6T41uX@iJsQjX7kS@5bxjTTI8Eo3pN5IW9@Lzz@QSeX5hHM93aqE2JcHNPMjCs@sh9OwWGqxoEg7Lcii7vtWAkwWDb@YwoHVWZfQL "Retina – TIO Nexus")
Surely I'm doing something wrong here.
] |
[Question]
[
Find the max number of Xs you can fit onto a rectangular tic-tac-toe board of length *l* and height *h* without ever having 3 consecutive Xs in a row **diagonally**, horizontally, or vertically.
This is a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge so shortest code wins!
## Input
A single line containing values *l* and *h*, representing the length and height of the tic-tac-toe board, separated by a space.
## Constraints
```
1 ≤ l ≤ 2,147,483,647
1 ≤ h ≤ 2,147,483,647
```
## Output
A single number representing the number of Xs that can fit on the tic-tac-toe
board without three in a row
## Sample Inputs and Outputs
```
Input -> Output
2 2 -> 4
3 3 -> 6
2 3 -> 4
4 4 -> 9
```
## Explanation
4 Xs can fit on a 2x2 tic-tac-toe board without having 3 Xs in a row anywhere
6 Xs can fit on a 3x3 tic-tac-toe board without having 3 Xs in a row anywhere
4 Xs can fit on a 2x3 tic-tac-toe board without having 3 Xs in a row anywhere
9 Xs can fit on a 4x4 tic-tac-toe board without having 3 Xs in a row anywhere
## Credits
Lukas Zenick for creating the problem
## Extra Data
<https://docs.google.com/spreadsheets/d/1qJvlxdGm8TocR3sh3leRIpqdzmN3bB_z8N-VrEKSCwI/edit>
[](https://i.stack.imgur.com/B4y2Z.png) [](https://i.stack.imgur.com/nWB0e.png)
[Answer]
# [R](https://www.r-project.org/), 270 bytes
```
function(x,y,z=expand.grid(rep(list(1:0),x*y)),l=lapply(1:2^(x*y),function(i)matrix(unlist(z[i,]),x)))max(sapply(l[sapply(l,function(m,f=function(m)apply(cbind(m,2,matrix(rbind(2,m),nrow(m))),1,function(x)max((y=rle(x))$l[!!y$v])))max(f(m),f(t(m[nrow(m):1,])))<3)],sum))
```
[Try it online!](https://tio.run/##bZDbboMwEETf8xWOkgdvta3KpY2CypcgKhEwqSVjkDGtnZ@ny6UllfrmOeOZXa0ZrSxtUdpWpGM96NLKVnOHHm@pcF2hq6erkRU3ouNK9pYHyTOge/AAqFJVdJ3yxMJ3PjH8bZDQFNZIxwc9x26ZxJyCAGQ43i9Blf08tmSDdboJWPzyInVFVohrrZkBSUBt2i/6SAsFW4ubx3CfGiVIwFFl@70/fubrAjUlsOaWN9maTwKczLcIcuwH6tsuQ3NCYAcW7zYU/YeiCb3eoXhBpz8ontB5d7hnLxMLQsbNoNnFs0Yw1ZaFUj5hVjaif2wHyz6EETB@Aw "R – Try It Online")
Unfortunately I didn't notice the 'fastest code' tag and started working on this assuming that it was 'code golf', so this isn't very fast (and I won't golf it any further). But it at least calculates the test cases without timing-out...
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 402 bytes
Saved 250 bytes thanks to [@py3\_and\_c\_programmer](https://codegolf.stackexchange.com/users/110681/py3-and-c-programmer).
This was originally a [fastest-code](/questions/tagged/fastest-code "show questions tagged 'fastest-code'") challenge. Now it became a [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), but I'm too lazy to golf it.
```
f[m_,n_]:=Total@LinearProgramming[Table[-1,m*n],SparseArray[Flatten@MapIndexed[{#2[[1]],#}->1&,Flatten[{Table[m*i+j+k+1,{i,0,n-1},{j,0,m-3},{k,0,2}],Table[m*(i+k)+j+1,{i,0,n-3},{j,0,m-1},{k,0,2}],Table[m*(i+k)+j+k+1,{i,0,n-3},{j,0,m-3},{k,0,2}],Table[m*(i+k)+j-k+1,{i,0,n-3},{j,2,m-1},{k,0,2}]},2],{2}],{(m-2)n+m(n-2)+2(m-2)(n-2),m*n}],Table[{2,-1},(m-2)n+m(n-2)+2(m-2)(n-2)],Table[{0,1},m*n],Integers]
```
[Try it online!](https://tio.run/##fZBBSwMxEIX/ykJBts0EmvSkYKkgQkGhYG9DKKlN13Q3syXNQQn57Wu26oKoPc2b8L034TkdXo3Twb7ortuj2wBt1M3tug26WTxaMtqvfFt57ZylCtd62xjkAtyEFDwftT@ZO@/1Oz40OgRDiyd9XNLOvJkdxpFEFErBKPG5uIIvBONniptYdmA1ExAtTIG4SBAPWTk@y6rOSiYF33BpWT3OhgGfDbi4gNd/GS7k818G@fNCAqkg9s5YOi7HxFxJeTJ5Xs@6r2eIjhJ6/7/wwE0hY@dilxRMZfxJdfctrrylgPlLhU0Fnxd77GWutejfBBTXSXUf "Wolfram Language (Mathematica) – Try It Online")
Using the built-in [`LinearProgramming`](http://reference.wolfram.com/language/ref/LinearProgramming.html). Gives the results from `1x1` to `9x9` in 40 seconds on TIO.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 311 bytes
```
->m,n{(0...1<<(m*n)).map{|z|
k=("%0#{m*n}b"%z).scan(/#{"(.)"*n}/)
}.reject{|w|
(w.map(&:join).grep(/111/)[0]||w.transpose.map(&:join).grep(/111/)[0])||
w.each_cons(3).any?{|x|x.transpose.each_cons(3).any?{|z|
k=z.join.to_i(2)
[273,84].any?{|z|k&z==z}
}
}}.map{|c|c.flatten.count ?1}.max}
```
[Try it online!](https://tio.run/##3ZFhT4MwEIa/8ysatpkW8RjbEo0Z8jdMkCxdw3CbFAYlbND@dix2MzNR42e/Xe/e93r3XFmvT/0m6O@eMpd3eAoA/nKJM4cTAhktOtlKC6F9gO3JdNTpvFrbk5ZAxSjH3qizMRBbZz1iKSiTXcJEJ5vBgxBuhhb45nGXbzmBtEwK7Pm@75FoGkvZgCgpr4q8Sn7REWmaNZBQ9rpiOa/wnADlp7CTR3m8avKNoDXmYYMWhvYg8tUWz8g5Hc3u5@7DIv6U72/aIGiVLitLKYOASQabNypEwoHlNRco9IfSUfVpYMhp/SHYRDqMdfgjxz@S1J//I5ZIXozNV4w49MnyMGx7IU2Nkl7v4Iy927HnzMxJLKuoRYWwD7A4k83k9YtLcwbl2C/CVtr94TC2NFq489gMn1b1Wk/ghs@kfwc "Ruby – Try It Online")
Nothing particular, still using brute force.
[Answer]
# [R](https://www.r-project.org/) + `lpSolve`, ~~202~~ ~~194~~ 149 bytes
```
function(m,n,`[`=`for`,x=outer(1:m,1:n*1i,`+`)){i[x,j[c(1,1i,1+1i,1i-1),F<-rbind(F,x%in%(0:2*j+i))]]
lpSolve::lp("max",!!x,F,"<",min(m*n,2),,seq(x))}
```
[Try it online!](https://tio.run/##FY7BCoJAFEX3fYUKwXt6g8ZVDLr1B1pKMGUKT/Rpk8VA9O1mm7s4i3OuX7uoXLuXNotMSiMUrnal6ybvEMrptbSejB1hrKZG4DLH/JE6oK8bMtiQyf4jB8OoioO/id6pQtiL7ulo87TPhPly2Q3zeRrerbXDTMl4DQniOKBCUiQYZWunipyBZ/ugwPxdtw8kkWhk7IlnL7pQR4LNtv4A "R – Try It Online")
A golfed version of an external ILP solver-based solution, which I started working on when this was a fastest code challenge, but got closed. Works slower than Wolfram though, but still manages 8x8 on TIO.
In lieu of a proper explanation, here is an outdated, but somewhat ungolfed version:
```
library('lpSolve')
f = function(m, n, p = m*n, r = -1:1, l = {})
{
if(p == 1) return(1) # Edge case for 1x1
for(i in 1:m) for(j in 1:n) for(k in 1:4)
{
d = list( # Directions
cbind(i+r, j), # Vertical
cbind(i, j+r), # Horizontal
cbind(i+r, j+r), # Diagonal
cbind(i-r, j+r) # Antidiagonal
)
x = matrix(0, m, n)
try(x[d[[k]]] <- 1)
l = rbind(l, c(x))
}
lp(direction = "max", objective.in = rep(1, p), const.mat = l, const.dir = "<=", const.rhs = 2, all.bin = T)
}
```
[Answer]
# [Python 3 (PyPy)](http://pypy.org/), ~~262~~ ~~254~~ 212 bytes
```
def f(x,y,D={}):
R=[i for i in range(2**x)if'111'not in bin(i)]
for _ in[0]*y:D={(a,b):bin(a).count('1')+max(D.get((b,c),0)for c in R if(a&b|a>>2&b>>1|a*4&b*2)&c<1)for a in R for b in R}
return max(D.values())
```
[Try it online!](https://tio.run/##XZDRaoQwEEXf/YqBgmbsdDExCCtdn/YL9lWkJNZsA20Uq0Xp7rdb47YU9u1y5swdmG4e3lqXPnVzNy/La2PAsIlmOh6@r5gHcDqUFkzbgwXroFfu3DARxxNaE3HOI9cOfqCtYxarYFNfVlImVTznawtTpDH3c4W7uh3dwCIe4eOHmthxd24GxjTVSAn61dqXncAapkJ9UUUhQl0U/KJiGepYYFg/801UN9FHvcVrAH0zjL2DW/OXeh@bT4a4dL1djxomSCDCA8jgj6SUbiQL/p30zpEkN7L/JaVhlize/4QT8AQrb5acJGW0J56RSEhklGYkRbX8AA "Python 3 (PyPy) – Try It Online")
-8 bytes thanks to 12944qwerty
Rows are encoded in binary, and `R` is the list of all possible rows.
In any given iteration `i` of the second for loop (starting from 0), `D` is a dictionary where `D[a,b]` is the largest number of Xs that can fit in an `X` by `i` board where the first two rows are `a` and `b`.
The new `D` is calculated by iterating over every possible first 2 rows `a,b`, and setting `D[a,b]` to the number of Xs in row `a` plus the maximum value of `D[b,c]` where `c` is every row that could follow `a,b`.
This algorithm takes time \$y\cdot8^x\$ and space \$4^x\$, solving 1x1 to 9x9 in 20s on TIO.
[Answer]
# JavaScript (ES7), 149 bytes
Expects `(width)(height)`.
```
w=>h=>eval("for(o=0,m=1<<w*h;M=--m;o=M|(g=k=>v=k&&1+g(k&k-1))(m)<o?o:v)for(p=q=0;(v=M&2**w-1)&v/2&v/4|v&p&q|v&p/2&q/4|q&(q=p)/2&(p=v)/4?0:M>>=w;);o")
```
[Try it online!](https://tio.run/##bYtLDoJAEET3noK4mHSjyEdiokOPJ@AQRPkoYDNiho13x9ad0aSqk5fqdy1cMZ7ul@ER3PhczhXNE5mGTOmKDpYV34EpWvcUZ9nkNzqnIOg1U/6Emloyjlql4lUNrWqDGBF6zPjIB4dvdSBLkQZHuUp8f5IH5cJEmj6dGpR9X2ErbBVYGlBILIdheowOuTE0adS8xPnEt5G7ctNxDRUkKEEvDL108b1sUfJZdosfZ/vfSVHyWfbzCw "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Can you imagine solving the New York Times crossword puzzle without any clues? Maybe not with all of the creativity and new words and phrases appearing in modern crosswords, but with a fixed word list there's some hope. In this challenge, you create a crossword puzzle grid in which this is theoretically possible.
# The challenge
Maximize the number of white squares in a white- and black-shaded 15x15 crossword puzzle grid, such that the white squares can be *uniquely* filled with letters so that every across and down word appears in the international Scrabble word list.
# Grid construction clarifications
In US newspapers, [crossword](https://en.wikipedia.org/wiki/Crossword) grids are usually constructed so that every letter is "checked", meaning it is part of both an "across" word and a "down" word. In the UK and elsewhere (especially in [cryptic crosswords](https://en.wikipedia.org/wiki/Cryptic_crossword)), this is not necessarily the case: if an "across" or "down" word would only be one letter, it need not be an actual word (like "A" or "I"). For this challenge, follow the more relaxed rules: single-letter words need not appear in the word list.
There are various other traditions (in the US and elsewhere), none of which need to be followed in this challenge. For example, words can be only two letters long, words are allowed to repeat, and the grid need not have (rotational) symmetry.
# Is this even possible?
Yes! One can write a short script to verify that the unique solution to the following blank grid on the left is the filled grid on the right:
[](https://i.stack.imgur.com/ctOqV.png)
One can display the filled grid in a computer-readable format as follows:
```
###CH##########
###YE##########
###AM##########
CYANOCOBALAMINE
HEMOCHROMATOSES
###CH##########
###OR##########
###BO##########
###AM##########
###LA##########
###AT##########
###MO##########
###IS##########
###NE##########
###ES##########
```
# Your solution
The grid above has 56 white squares out of the 225 squares total in the 15x15 grid. This serves as a baseline for this challenge. Grids with fewer white squares may also be interesting for reasons other than their score, for example if they satisfy some of the aesthetic traditions mentioned above.
Please submit your solution in the same format as the computer-readable baseline above. Please include code that verifies that there is a unique solution to your grid.
Interesting code snippets (eg for searching the space of possibilities) and discussion of how you found your grid are appreciated.
# The word list
The international Scrabble word list was previously known as SOWPODS and is now called [Collins Scrabble Words](https://en.wikipedia.org/wiki/Collins_Scrabble_Words) (CSW). It is used in most countries (except notably the US). We prefer to use this list because it includes British spellings and generally has significantly many words than the American word list. There are multiple editions of this list which differ slightly. You can find different versions of this list [linked from Wikipedia](https://www.wordgamedictionary.com/sowpods/), on [Github](https://raw.githubusercontent.com/jesstess/Scrabble/master/scrabble/sowpods.txt), in [Peter Norvig's Natural Language Corpus](https://norvig.com/ngrams/) and elsewhere, often still called "SOWPODS".
This challenge is highly sensitive to the broad nature of the choice of word list, but less so to smaller details. For example, the baseline example above works with any edition of CSW, but `CH` is not a word in the American Scrabble word list. In the event of a discrepancy, we prefer to use CSW19, the most recent edition of CSW. (If we use this list, which was released this year, we can expect answers to this challenge to remain valid longer). You may query this list interactively on the official [Scrabble word finder](https://www.collinsdictionary.com/scrabble/scrabble-word-finder/) site or download it (as well as the previous edition, CSW15) from the [Board & Card Games Stack Exchange](https://boardgames.stackexchange.com/a/38386/5407) or [Reddit's r/scrabble](https://www.reddit.com/r/scrabble/comments/cibq3u/csw19_new_words_and_deletions/).
*Tldr*: the authoritative word list for this challenge is available as a plain text file (279,496 words, one per line) over on the [Board & Card Games Stack Exchange](https://boardgames.stackexchange.com/a/38386/5407).
# Further discussion
One issue raised in an early answer and comment is why existing crosswords (eg, in the NYT) don't answer this question. Specifically, the record for fewest number of black squares (and thus largest number of white squares) for a published NYT crossword is already the most famous record in crosswords. Why can't we use [the record grid](https://www.xwordinfo.com/Crossword?date=7/27/2012)? There are a few issues:
* Many of the answers in NYT crosswords do not appear on our word list. For example, the record grid includes `PEPCID` (a brand name), `APASSAGETOINDIA` (a four-word proper name for a film and novel, written without spaces), and `STE` (an abbreviation for "Sainte"). It appears that the record grid is not solvable with Scrabble words.
* Merely expanding the word list to include more words does not necessarily help with this challenge: even if all of the words in the record grid appeared on our word list, the solution would not be *unique* without the clues. It is often possible to alter some letters at the ends of answers while keeping everything a word. (For example, the bottom-right-most letter can be changed from a `D` to an `R`.) Indeed, this is part of the (human) construction process when writing a crossword, trying to obtain "better" words.
The reason ordinary crosswords (usually) have a unique solution is that the *clues* help narrow down the correct answers. If you simply try to fill the grid with words *without* using clues, it's likely that there will either be no possibilities or *many* possibilities. Here's an example of three different fills (using the word list for this challenge!) for the same grid (one that's relatively frequently used in the NYT):
[](https://i.stack.imgur.com/qvfmY.png)
* Another issue raised in the comments is some amount of disbelief that this question is a *coding challenge*. Perhaps it is not immediately clear, but **it is hard to even find a single valid answer to this challenge**. Finding the baseline above involved multiple, specially-crafted search programs that were not guaranteed to find an answer. I do not personally even know of a *general* way to solve an arbitrary grid, if you want the answer in reasonable time. Existing crossword construction programs can help, but I assume (perhaps incorrectly) that they do not actually do a full search of the possibilities. (I used such a program for the three side-by-side grids above; this worked because that particular grid allows for many solutions.)
[Answer]
# 180 white squares
[](https://i.stack.imgur.com/EKZ5Gm.png) [](https://i.stack.imgur.com/mbgVRm.png)
My strategy was simply to find a smaller rectangle with no black squares, such that it can be filled in uniquely. All `2√ók` rectangles have multiple solutions. For `3√ók` rectangles, there are multiple solutions for `k` between 3 and 14, but there is a exactly one solution for `k=15`.
I then fit 4 such rectangles in the grid. This means that each word appears 4 times in the solution, which is usually frowned upon in crossword construction, but OK for this challenge. On the other hand, this solution has both left/right and top/down symmetry!
Computer-readable grid:
```
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
###############
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
###############
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
###############
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
```
Here is the R code I used to find all solutions for a given grid size. Looping over all triples of 15-letter words is too slow. Instead, I try to fill in rectangles by
* setting the first two columns (two 3-letter words)
* then looping through all 15-letter words starting with the first two letters which are now settled.
* for each possible choice of the 15-letter words, I then verify whether all 3-letter words generated are in the dictionary.
For example, for the eventual solution, the code first put in `HOP` and `EVO`, then completed into `HETERNORMATIVE`, `OVEROPINIONATED` and `POSSESSEDNESSES`, and finally verified all the 3-letter words (`HOP`, `EVO`, `TES`, `ERS`, `ROE`, `OPS`, `NIS`, `ONE`, `RID`, `MON`, `ANE`, `TAS`, `ITS`, `VEE`, `EDS`).
## R code
```
library(fastmatch)
f = "scrabble-wordlist.txt"
d = read.table(f, skip=2, as.is=T, na.strings=NULL)
d$l = apply(d, 2, nchar)
d3 = d[d$l==3, 1]
sp = function(s) strsplit(s, "")[[1]]
cm = function(v) paste0(v, collapse="")
d3s = sapply(d3, sp)
f3 = function(l){
m = matrix("", 3, l)
md = sapply(d[d$l == l, 1], sp)
nf = 0
a1 = seq(1, 3*l, by=3); a2 = a1 + 1; a3 = a1 + 2
for(i in 1:ncol(d3s)){
m[, 1] = d3s[, i]
id1 = as.matrix(md[, md[1, ] == m[1, 1]])
id2 = as.matrix(md[, md[1, ] == m[2, 1]])
id3 = as.matrix(md[, md[1, ] == m[3, 1]])
if(any(ncol(id1) == 0, ncol(id2) == 0, ncol(id3) == 0)) next
for(j in 1:ncol(d3s)){
m[, 2] = d3s[, j]
jd1 = as.matrix(id1[, id1[2, ] == m[1, 2]])
jd2 = as.matrix(id2[, id2[2, ] == m[2, 2]])
jd3 = as.matrix(id3[, id3[2, ] == m[3, 2]])
if(any(ncol(jd1) == 0, ncol(jd2) == 0, ncol(jd3) == 0)) next
for(k1 in 1:ncol(jd1)){
m[1, ] = jd1[, k1]
for(k2 in 1:ncol(jd2)){
m[2, ] = jd2[, k2]
for(k3 in 1:ncol(jd3)){
m[3, ] = jd3[, k3]
w = paste0(m[a1], m[a2], m[a3])
if(all(w %fin% d3)){
nf = nf + 1
print(m)
}
if(nf >= 2){
print(c(l, nf))
return()
}
}
}
}
}
}
return(nf)
}
```
Called as `f3(15)`. Took a few hours on my personal computer.
[Answer]
# 182 white squares
[](https://i.stack.imgur.com/mtkeA.png)
Inspired by [Robin Ryder's answer](https://codegolf.stackexchange.com/a/193625/49643), I tried to squeeze in a couple more white squares. I believe this solution is unique, and I will soon post verification code accordingly.
Computer-readable grid:
```
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
B##############
INCOMMUNICATIVE
NEUROANATOMICAL
DETERMINATENESS
###############
HETERONORMATIVE
OVEROPINIONATED
POSSESSEDNESSES
B##############
INCOMMUNICATIVE
NEUROANATOMICAL
DETERMINATENESS
```
] |
[Question]
[
You are going to participate in a gameshow. One of the challenges works as follows:
* The first room contains a large number of identical balls.
* The second room contains a series of chutes, each of which has a sensor which counts how many balls have been placed in it. A ball which is placed in a chute cannot then be recovered.
* Each chute will trigger after a certain number of balls (its *trigger count*) have been placed into it. When it triggers it flashes lights, makes a noise, and leaves you in no doubt that it has triggered.
* You must trigger `N` chutes to continue to the next challenge.
* You know the trigger counts, but not the correspondence between count and chute.
* You have one opportunity to take balls from the first room into the second. Once you put a ball into a chute, you cannot go back for more balls.
* Each ball which you take deducts money from the jackpot.
Obviously you want to ensure that you will pass the challenge, but you want to minimise the jackpot money loss. Write a program, function, verb, etc. to tell you how many balls you need.
### Example
Suppose the trigger counts are 2, 4, and 10, and you need to trigger 2 chutes to pass. There is a strategy to pass with 10 balls: place up to 4 balls in the first chute, up to 4 balls in the second chute, and up to 4 balls in the third chute. Since one of the three chutes will trigger after only 2 balls, you only use a total of 10. There is no strategy which is guaranteed to work with fewer than 10, so that is the correct output.
### Input
The input consists of an array of integer trigger counts and a integer giving the number of chutes to trigger. You may take the two inputs in either order, and if needed you may take a third input with the length of the array.
You may assume that all of the inputs are greater than zero, and that the number of chutes which must be triggered does not exceed the number of chutes.
You may also assume that the counts are sorted (ascending or descending), as long as you state that clearly in your answer.
### Output
The output should be a single integer, giving the number of balls required by the optimum strategy.
### Test cases
Format: `N counts solution`
```
1 [2 4 10] 6
2 [2 4 10] 10
3 [2 4 10] 16
1 [3 5 5 5 5 5 5 5 5 5] 5
2 [1 2 2 2 2 2 2 2 2 2 2 2 2 2 2 2 8 11] 8
2 [1 2 6 6 6 6 6 6 6 10] 16
2 [1 2 3 3 4 4 6 6 6 11] 17
3 [1 2 3 4 5 5 6] 16
3 [2 4 7 7 7 7 7 7 7] 21
5 [1 2 2 3 3 3 3 3 5 9 9 11] 27
2 [5 15 15] 25
1 [4 5 15] 10
3 [1 4 4 4] 10
2 [1 3 4] 6
2 [1 3 3 8] 8
```
[Answer]
# Python, 222 198 bytes
```
def S(G,P,T=0):
T=T or[0]*len(P);r=[0]*(sum(t>=p for t,p in zip(T,P))>=G)
for i,t in enumerate(T):
if t<max(P):a=next(p for p in P if p>t)-t;T[i]+=a;r+=[a+S(G,P,sorted(T))];T[i]-=a
return min(r)
```
Usage is `S(2, (2, 4, 10))`.
In order to test this program at any decent speed, add memoization by putting this after the function definition:
```
old_s = S
mem = {}
def S(G, P, T=0):
k = (G, tuple(P), T and tuple(T) or 0)
if k in mem: return mem[k]
r = old_s(G, P, T)
mem[k] = r
return r
```
---
We do dynamic programming on an array T that contains the number of balls we've thrown into each chute, initially all zeroes. Without providing a rigorous proof, I claim that we can keep T sorted at all times, that is, assume we always throw the most balls into the last chute, which in turn we will assume was the largest chute.
If then T, when matched element for element with P (which is our problem input), has at least G (which is our goal) elements bigger, we've found a solution, and we return 0, because we need to throw 0 more balls to find a solution. This means that if G is 1 our least thrown into chute must contain an equal or more amount of balls than the smallest chute requirement, and so on for bigger G.
Otherwise, for each position we throw in enough balls to upgrade to the next chute requirement (anything in between would never be observable) and recurse. We then return the minimum of these recursive calls.
[Answer]
# Haskell, ~~124~~ ~~117~~ ~~100~~ ~~98~~ ~~91~~ ~~80~~ 78 bytes
Saved 11 bytes thanks to @Peter Taylor
```
0#_=0
n#a=minimum$zipWith(\x y->x*y+(n-1)#(snd.splitAt y$a))a[1..length a-n+1]
```
[Try it online!](https://tio.run/##fZFBboMwEEX3OcVIsIDGIMbGJl24Uk/RRRpVlhIVq@Ci4kqhl6euE6oYaP29e9/zZzy16t9OTTOORfQii42JlGy10e1nG3/p7knbOnk@w5A9nO@GbWIyTKOkN8e87xptHy0MsUpTtcc8b07m1dagMrPFw9gqbUDC8X0D7nQf2liIAaM9FqQk9ABSgggYDRgWAWQhFPOqnMzFvJMvIpDsCP1X6F/uVpoTgSYnipWQi6V0Yk6/1mo@lfDNlrceMfdU5FbTJ1AMfNzH3jtxH8muwVNZWi265MRdfqF8sSff1x@7KP1kuEbpD2VXJsZv)
(#) takes an integer and a list of integers in descending order as arguments
Usage is `1#[10,4,2]`
### Explaination:
For each value, x, in position i (1-idexed) in the list, the best tactic to remove that element (or some amount of elements less than or equal to x) is to pour x balls into i chutes.
For each element, x, in position i in the list, (n#) calculates x\*i + ((n-1)#) of the list beyond position i (until n is 0). Then it takes the minimum of all the possibilities checked.
[Answer]
# [Haskell](https://www.haskell.org/), 54 bytes
```
(%)0
(p%l)n|h:t<-l=p+min(p%t$n)(h%t$n-1)|n<1=p|1>0=1/0
```
[Try it online!](https://tio.run/##lZG9DoIwFIV3nuIOmrSxKBfwN9Qn0MmRMDBgMJbaSI0L7461KCLqYPI1TU/Pbc9t87Q8ZkLU9Z6TIfUcooaCyipf6cgVXI2KgzSSHkhK8vvkIq1khFxVuPY4TrxaZ6UugUNMkEHsMwgZoJdQBsTvC0FfuJcYcfqL9hhj9P9hYa7AXvXsG52ojSuwhJaXC9v8rSt8ppz1ept/Yh3Tbh/BO2ZvaemkNhra0T5Vc@VDeIRpkobdLgK7ThynSA/SfE2Rqi0QddE7fd7IcZmfrhQGEO9BgKyIZIJGrv3HpL4B "Haskell – Try It Online")
Takes the list in ascending order.
[Answer]
# Python, 73 bytes
```
f=lambda n,c:n and min(c[i]*-~i+f(n-1,c[-~i:])for i in range(len(c)-n+1))
```
Port of H.PWiz's Haskell answer. Requires the input to be in descending order.
[Answer]
## CJam (35 bytes)
```
{:A,,e!f<{$__(;A,+.-\Af=.*1bz}%:e<}
```
[Online demo](https://tio.run/##S85KzP1f6KdaXWflav2/2spRRydVMc2mWiU@XsPaUUdbTzfGMc1WT8swqapW1SrVpvZ/nattfq3@f0OFaCMFEwVDg1gFMy4jBMfQgMsYiWcG4hkqGCkYA0VMgdAMLAjUYKpgCEKxCkamXEDDQLIgHkS/IVA1EIK5RiCuMYhjBmMbK1jEKlgAAA)
Takes input as `N counts` assuming that `counts` is sorted in ascending order.
### Dissection
Denote the counts in descending order as a 1-indexed array `C` (so the second element of `C` is the second largest count). Suppose that we end up winning by triggering chutes `C[a_0], C[a_1], ... C[a_{N-1}]`. Then in the worst case, for each `C[a_i]` we have put at least `C[a_i]` balls into each of chutes `1` to `a_i`. So we put `C[a_{N-1}]` balls into `a_{N-1}` chutes, an additional `C[a_{N-2}]` balls into `a_{N-2}` of them, ...
Over each subset of `N` counts, which gives us the smallest sum? Then we should aim to win with that subset of counts.
NB The code actually uses the counts in ascending order, but I think descending order is more intuitive.
```
{ e# Define a block
:A e# Store the sorted counts as A
,,e!f< e# Get all N-element subsets of A's indices
{ e# Map over these subsets S:
$__ e# Sort the subset and get a couple of copies
(;A,+ e# Remove the first element from one copy and append len(A)
.- e# Pointwise subtraction, giving [S[0]-S[1] S[1]-S[2] ...]
\Af= e# Get the counts [A[S[0]] A[S[1]] ...]
.* e# Pointwise multiplication
1bz e# Sum and take absolute value, giving the worst case score
}%
:e< e# Select the minimum worst case score
}
```
] |
[Question]
[
You mission today is to invent a text compressor.
# Task
You'll write two functions:
* The **packer** is a function that accepts a string of ASCII characters (U+0000 to U+007F) and outputs a Unicode string (U+0000 to U+10FFFF), containing the fewest characters possible.
* The **unpacker** is a function that accepts an encoded Unicode string and outputs exactly the original ASCII string.
# Input
The only authorized input is the ASCII string (for the packer) and the packed Unicode string (for the unpacker). No user input, no internet connection, no use of file system.
Your functions can have access to [this list of english words](https://raw.githubusercontent.com/atebits/Words/master/Words/en.txt). You can use this list as a local txt file, or copy its content in your source code as a string or [an array of strings](http://m.uploadedit.com/b037/1405752644555.txt).
You can't hardcode the snippets below in your functions.
# Output
The only authorized output for both functions is a string.
The output of the unpacker must contain exactly the same characters as the input of the packer.
Your inputs and outputs can use any character encoding supporting all Unicode (UTF-8/16/32, GB18030, ...), as your score will only depend on the number of Unicode characters in the output. Please precise which encoding you're using, though.
To count the number of Unicode characters in your output, you can use this tool: <http://mothereff.in/byte-counter>
# Scoring
Your entry must be able to pack and unpack the 10 following text snippets (that I took on this forum).
Your score will be the sum of the sizes of your 10 packed strings (in Unicode characters) + the size of your two functions (in Unicode characters, too)
Don't count the size of the dictionnary if you use it.
Please include in your entries the "score" of each snippet and their packed version.
Lowest score wins.
# Data
Here are the snippets to encode to compute your score:
1: Rick Roll lyrics (1870b): [We're no strangers to code golf, you know the rules, and so do I](https://codegolf.stackexchange.com/questions/6043/were-no-strangers-to-code-golf-you-know-the-rules-and-so-do-i)
```
We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
You wouldn't get this from any other guy
I just wanna tell you how I'm feeling
Gotta make you understand
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
We've known each other for so long
Your heart's been aching but
You're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it
And if you ask me how I'm feeling
Don't tell me you're too blind to see
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
(Ooh, give you up)
(Ooh, give you up)
(Ooh)
Never gonna give, never gonna give
(Give you up)
(Ooh)
Never gonna give, never gonna give
(Give you up)
We've know each other for so long
Your heart's been aching but
You're too shy to say it
Inside we both know what's been going on
We know the game and we're gonna play it
I just wanna tell you how I'm feeling
Gotta make you understand
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
Never gonna give you up
Never gonna let you down
Never gonna run around and desert you
Never gonna make you cry
Never gonna say goodbye
Never gonna tell a lie and hurt you
```
2: The Golfer (412b): [Golfing ASCII-art](https://codegolf.stackexchange.com/questions/32955/golfing-ascii-art)
```
'\ . . |>18>>
\ . ' . |
O>> . 'o |
\ . |
/\ . |
/ / .' |
jgs^^^^^^^`^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
```
3: the number diamond (233b): [Print this diamond](https://codegolf.stackexchange.com/questions/8696/print-this-diamond)
```
1
121
12321
1234321
123454321
12345654321
1234567654321
123456787654321
12345678987654321
123456787654321
1234567654321
12345654321
123454321
1234321
12321
121
1
```
4: the alphabet four times (107b): [Print the alphabet four times](https://codegolf.stackexchange.com/questions/2167/print-the-alphabet-four-times)
```
abcdefghijklmnopqrstuvwxyz
qwertyuiopasdfghjklzxcvbnm
pyfgcrlaoeuidhtnsqjkxbmwvz
zyxwvutsrqponmlkjihgfedcba
```
5: Old McDonald's lyrics (203b): [Old MacDonald function](https://codegolf.stackexchange.com/questions/26612/old-macdonald-function)
```
Old MacDonald had a farm, E-I-E-I-O,
And on that farm he had a cow, E-I-E-I-O,
With a moo moo here and a moo moo there,
Here a moo, there a moo, everywhere a moo moo,
Old MacDonald had a farm, E-I-E-I-O!
```
6: Rock around the clock lyrics (144b): [Rock Around the Clock](https://codegolf.stackexchange.com/questions/34663/rock-around-the-clock)
```
1, 2, 3 o'clock, 4 o'clock rock,
5, 6, 7 o'clock, 8 o'clock rock,
9, 10, 11 o'clock, 12 o'clock rock,
We're gonna rock around the clock tonight.
```
7: Hello World (296b): [Say "Hello" to the world in ASCII art](https://codegolf.stackexchange.com/questions/4356/say-hello-to-the-world-in-ascii-art)
```
_ _ _ _ _ _ _
| | | | ___| | | ___ __ _____ _ __| | __| | |
| |_| |/ _ \ | |/ _ \ \ \ /\ / / _ \| '__| |/ _` | |
| _ | __/ | | (_) | \ V V / (_) | | | | (_| |_|
|_| |_|\___|_|_|\___( ) \_/\_/ \___/|_| |_|\__,_(_)
|/
```
8: Irish blessing (210b): [An Old Irish Blessing](https://codegolf.stackexchange.com/questions/1682/an-old-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
```
9: There was an old lady lyrics (1208b): [There Was an Old Lady](https://codegolf.stackexchange.com/questions/3697/there-was-an-old-lady)
```
There was an old lady who swallowed a fly.
I don't know why she swallowed that fly,
Perhaps she'll die.
There was an old lady who swallowed a spider,
That wriggled and iggled and jiggled inside her.
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.
There was an old lady who swallowed a bird,
How absurd to swallow a bird.
She swallowed the bird to catch the spider,
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.
There was an old lady who swallowed a cat,
Imagine that to swallow a cat.
She swallowed the cat to catch the bird,
She swallowed the bird to catch the spider,
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.
There was an old lady who swallowed a dog,
What a hog to swallow a dog.
She swallowed the dog to catch the cat,
She swallowed the cat to catch the bird,
She swallowed the bird to catch the spider,
She swallowed the spider to catch the fly,
I don't know why she swallowed that fly,
Perhaps she'll die.
There was an old lady who swallowed a horse,
She died of course.
```
10: gettysburg address (1452b): [How random is the Gettysburg Address](https://codegolf.stackexchange.com/questions/15395/how-random-is-the-gettysburg-address)
```
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.
```
Total (uncompressed): 6135 chars/bytes.
Have fun!
[Answer]
# Haskell - 5322 points
Bytes of code : `686`
Original size : `6147` `= 1871+415+234+108+204+145+297+211+1209+1453`
Encoded size : `4636` `= 1396+233+163+92+153+115+197+164+979+1144`
Score : `686+ 4636`
Character count compression : `~25%`
## Code
Optimizations aside, this stores values between `0` and `7f` in unicode characters as their prime factors.
It does not lower the number of bytes of the encoded output, it only lowers the number of unicode characters. For instance, test #4 contains `108` characters and the encoded output, `92`. Their respective sizes are however `108` and `364` bytes.
```
import Data.Bits
import Data.List
import Data.Numbers.Primes
import qualified Data.Text as T
a=nub$concat$map(primeFactors)[0..127]
d(a:r)c=let s=shift c 5in if s<=0x10ffffthen d r(s+a)else c:d r a
d[]c=[c]
f(a:r)=let o=a.&.0x1fin(if o/=a then f((shiftR a 5):r)else f r)++[o]
f[]=[]
g=T.pack.map(toEnum).(\(a:r)->d r a).concatMap j.map(map(\x->head$elemIndices x a)).map(primeFactors.fromEnum).T.unpack
h=T.pack.map(toEnum.product.map((!!)a)).i.f.reverse.map(fromEnum).T.unpack
i(a:r)=let z=a`clearBit`4;x=if a`testBit`4then(take z$repeat$head r,tail r)else splitAt z r in[fst x]++i(snd x)
i[]=[]
j x@(a:_)=let l=length x in if(take l(repeat a))==x then[l`setBit`4,a]else[l]++x
j[]=[0]
```
## How it works
* Encoding
1. Each character is converted to its numeric equivalent, lets call this number `n`.
2. `n` is then converted into a list of its prime factors, `ps`.
+ It conveniently happens that the numbers 0 through 127 have 32 common prime factors, excluding `1`. This mean they, the factors, can be stored as indexes on as little as 5 bits.
+ `1` is a special case and is represented by an empty list.
3. With `ps` the encoding can now start.
1. Each number of `ps` is converted into its index in the list of 32 unique factors (In the above code this list is identified as `a`).
2. (Keep in mind at this point we are dealing with a list of list of indexes of prime factors) To proceed to the next step, `ps` needs to be flattened. To preserve the integrity of the data, each list is converted into another list of two parts
1. The first element stores its length and if the it is composed of the same factor.
+ There are at most 6 prime factors per list, this information is stored on the rightmost 3 bits. The fifth bit is used as a flag to indicate if the list is comprised of a single factor.
2. The remaining elements are the indexes themselves or a single index if there is less than two different factors in the list.
3. These lists are then concatenated into a single flattened list, `fs`.
4. The elements of `fs` can then be packed into unicode characters using bit shifting.
* Decoding
+ Do the encoding steps in reverse.
+ If you are wondering how `1` fits into this, I would like to remind you that `product [] == 1`.
## Tests
Using this interface for testing would be painful so I used this function to provide the results below.
```
edTest f = do
t <- readFile f
let txt = T.pack t
enc = g txt
dec = h enc
tst = txt == dec
putStrLn $ (show $ T.length txt) ++ "," ++ (show $ T.length enc) ++ "," ++ (show $ T.length dec)++","++(show tst)
putStrLn $ if not tst then T.unpack txt ++ "\n---NEXT---\n" ++ T.unpack dec else ""
```
```
λ> edTest "1"
1871,1396,1871,True
λ> edTest "2"
412,233,412,True
λ> edTest "3"
234,163,234,True
λ> edTest "4"
108,92,108,True
λ> edTest "5"
204,153,204,True
λ> edTest "6"
145,115,145,True
λ> edTest "7"
297,197,297,True
λ> edTest "8"
211,164,211,True
λ> edTest "9"
1209,979,1209,True
λ> edTest "10"
1453,1144,1453,True
```
## Sample
The output of the encoding function `g` for test #4 is this
`"\99429\582753\135266\70785\35953\855074\247652\1082563\68738\49724\164898\68157\99429\67973\1082404\587873\73795\298017\330818\198705\69861\1082435\595009\607426\36414\69873\855074\265249\346275\67779\68738\77985\1082513\821353\132131\101410\247652\1082562\49724\164898\67649\594977\34915\67746\50273\135265\103997\563265\103457\1086021\99399\584802\70753\73889\34882\582722\411459\67779\68740\1084516\1082563\1091681\103491\313282\49724\164897\68705\135741\69858\50241\607426\35905\608421\1082435\69858\50274\71777\43075\298018\280517\1082404\67971\36017\955425\67665\919600\100452\132129\214883\35057\856097\101474\70753\135737"`
or if you are an adept of gibberish, this
`òë•Úéë°°Å¢ëíÅ˱±Ûê∞¢ºù§ÙàìÉê≤ÇÏຮê¢ê®Ωòë•ê¶ÖÙàê§Úè°°íÅÉÒà∞°Òê±Ç∞†±ëÉ•ÙàëÉÚëëÅÚîìÇË∏æëɱÛê∞¢ÒÄ∞°Òê£Éê≤ÇìǰÙàíëÛà°©†ê£ò∞¢ºù§ÙàìÇÏຮê¢ê°ÅÚëê°Ë°£ê¢¢Ï배ŰôòΩÚâ°Åôê°ÙââÖòëáÚé±¢ëë°íǰ˰ÇÚéëÇÒ§ùÉê£Éê≤ÑÙà±§ÙàìÉÙä°°ôëÉÒåüÇÏຮê°ê±°°àΩëÉ¢ÏëÅÚîìÇ˱ÅÚÙàëÉëÉ¢Ïë¢ë°°Í°ÉÒà∞¢ÒÑüÖÙàê§ê¶ÉË≤±Û©ê°ê°ëÛ††∞ò°§†ê°¥ù£Ë£±Ûëİò±¢ëë°°àπ`
## Additionnal notes
* Using <http://mothereff.in/byte-counter>, directory listings and `edTest` the size of the tests are all consistent but still differs from the indicated size in the question.
* Test #10 contains a couple of EM DASHes (`—`) that I replaced with `-` since they are outside of the `0`-`7f` range.
* Further compression could be achieved using the remaining fourth bit while flattening, for instance, `00` base case, `01` repeat all, `10` repeat except last, `11` repeat except last two.
* The test files and the code are all available here <https://github.com/gxtaillon/codegolf/tree/master/Kolmogorov>
[Answer]
# C++ (C++11), 2741 points
This answer uses UTF-32 as the encoding for the compressed text.
```
#include <cstdio>
#include <iostream>
#include <locale>
#include <string>
#define L locale
using namespace std;long b,n,i,l;void c(){string d;char x;while((x=cin.get())!=EOF)d+=x;b=(d.size()*7)%20;n=5;wcout.imbue(L());for(char y:d){b=b<<7|y&127;n+=7;if(n>=20)wcout.put(b>>(n-=20)&0xFFFFF);}if(n)wcout.put(b<<20-n&0xFFFFF);}void d(){wstring d;wchar_t w;wcin.imbue(L());while((w=wcin.get())!=EOF)d+=w;l=-1;for(wchar_t y:d){b=b<<20|y;n+=20;if(l<0)l=b>>15&31,n-=5;while(n>=7&(i<d.size()-1|n>20-l))cout.put(b>>(n-=7)&127);++i;}}int main(int t,char**a){L::global(L("en_US.utf8"));**++a<'d'?c():d();}
```
## Char counts and scoring
**Code: 593 chars** (the trailing newline is stripped)
**Compressed texts (unicode characters)**: 654 + 145 + 82 + 38 + 51 + 104 + 73 + 423 + 506 = **2148** (counted with `wc -m` for the number of unicode characters rather than bytes, the byte counts are, as as with @gxtaillon's answer, higher than the originals, 8413 bytes in total, as counted with `wc -c`).
**Compression ratio (ASCII to unicode)**: 35.01% (using the 6135 bytes from the question (same as `wc -c`))
## Beware:
A lot of shells cannot handle the unicode characters this program produces. Thus, decompressing may lead to the text being cut off somewhere when the shell cannot handle a character, as input is taken via `stdin` from the shell.
## Compiling
It should compile with `clang++` and `g++ -std=c++11`, but it will show some warnings about operator precedence, as an expression like `b<<20-n&0xFFFFF` will not be treated as `((b << 20) - n) & 0xFFFFF`, as one might expect, but rather as `(b << (20 - n)) & 0xFFFFF`.
## Usage
* Compile the program into an executable, e.g. `./compress`.
* Run the program as `./compress c` to compress or `./compress d` to decompress. (Careful, leaving out the option gives a *SEGFAULT* (error checking is so character expensive...) and other options (such as using `D` instead of `d`) may give unexpected results
* Input is read from `stdin` and output written to `stdout`
## How it works
### Ungolfed
```
#include <cstdio>
#include <iostream>
#include <locale>
#include <string>
using namespace std;
long b, n, i, l;
// Compress
void c() {
string d;
char x;
// Read from STDIN until EOF
while((x = cin.get()) != EOF)
d += x;
// Calculate the number of bits used from the last unicode character
// (maximum 19) and store it into the first 5 bits
b = (d.size() * 7) % 20;
n = 5;
// Set the output locale to allow unicode
wcout.imbue(locale());
// For each character in the input...
for (char y : d) {
// Add its bit representation (7 bits) to the right of the buffer
// by shifting the buffer left and ORing with the character code
b = (b << 7) | (y & 127);
// Add 7 to the bit counter
n += 7;
// If enough data is present (20 bits per output character),
// calculate the output character by shifting the buffer right,
// so that the last 20 bits are the left 20 bits of the buffer.
// Also decrement the bit counter by 20, as 20 bits are removed.
if (n >= 20)
wcout.put((b >> (n -= 20)) & 0xFFFFF);
}
// If there are still bits in the buffer, write them to the front of
// another unicode character
if (n)
wcout.put((b << (20 - n)) & 0xFFFFF);
}
// Decompress
void d() {
wstring d;
wchar_t w;
// Set STDIN to UNICODE
wcin.imbue(locale());
// Read wide characters from STDIN (std::wcin) until EOF
while ((w = wcin.get()) != EOF)
d += w;
// `l' represents the number of bits used in the last unicode character.
// It will be set later
l = -1;
// For each input character...
for (wchar_t y : d) {
// Add it to the buffer and add 20 to the bit counter
b = (b << 20) | y;
n += 20;
// If the number of bits in the last unicode character has not been
// set yet, read the first 5 buffer bits into `l'. This is
// necessary because the last character may contain more than 7
// (one entire uncompressed character) unused bits which may
// otherwise be interpreted as garbage.
if (l < 0) {
l = (b >> 15) & 31;
n -= 5;
}
// As long as there is data to turn into output characters
// (at least 7 bits in the buffer and either not the last
// unicode character or before the unused bits)
while (n >= 7 && ((i < d.size() - 1) || (n > (20 - l)))
cout.put((b >> (n -= 7)) & 127); // Output the left 7 bits in the buffer as an ASCII character
++i; // Increment the character index, so that we know when we reach the last input character
}
}
int main(int t, char**a) {
// Set the default locale to en_US.utf8 (with unicode)
locale::global(locale("en_US.utf8"));
// Decide whether to compress or decompress.
// This is just fancy pointer stuff for a[1][0] < 'd' ? c() : d()
(**(++a) < 'd') ? c() : d();
}
```
### Explanation
As all unicode characters from `U+0000` to `U+10FFFF` are allowed, we can use 20 bits per unicode char: `U+FFFFF` uses 20 bits and is still included in the allowed range. Thus, we just try to cram all the individual ASCII char bits into the unicode characters to store multiple ASCII characters in one unicode character. However, we also need to store the number of bits used in the last unicode character, because unused garbage bits may otherwise be interpreted as proper compressed ASCII characters. As the maximum number of used bits in the last unicode character is 20, we will need 5 bits for that, which are placed in the beginning of the compressed data.
### Example output
This is the output for example #4 (as given by `less`):
```
<U+4E1C5><U+8F265><U+CD9F4><U+69D5A><U+F66DD><U+DBF87><U+1E5CF><U+A75ED>
<U+DFC79><U+F42B8><U+F7CBC><U+BA79E><U+BA77F>Ïèè¶õè<U+A356B><U+D9EBC><U+63ED8>
<U+B76D1><U+5C3CE><U+6CF8F><U+96CC3><U+BF2F5><U+D3934><U+74DDC><U+F8EAD>
<U+7E316><U+DEFDB><U+D0AF5><U+E7C77><U+EDD7A><U+73E5C><U+786FD><U+DB766>
<U+BD5A7><U+467CD><U+97263><U+C5840>
```
(`Ïèè¶õè` give `<U+C3CF><U+266CF>` as character codes, but I might have gotten that wrong)
[Answer]
# Python 3, 289+818=1107 points
Only lightly golfed.
```
import zlib as Z
def p(s):
z=int.from_bytes(Z.compress(s),'big');o=''
while z:
z,d=divmod(z,1<<20)
if d>0xd000:d+=1<<16
o+=chr(d)
return o[::-1]
def u(s):
i=0
for c in s:
d=ord(c)
if d>0xe000:d-=1<<16
i=(i<<20)+d
return Z.decompress(i.to_bytes(i.bit_length()//8+1,'big'))
```
The total code size is 289 bytes, and encodes the given 6135 bytes into 818 Unicode characters -- the total output byte count is 3201 bytes, significantly smaller than the original inputs.
Encodes using zlib, then secondarily using unicode encoding. Some extra logic was needed to avoid surrogates (which Python really hates).
Example output from #4, as seen by `less` (37 Unicode chars):
```
x<U+AC0DC><U+BB701><U+D0200><U+D00B0><U+AD2F4><U+EEFC5>§Ü∫<U+F4F34>Ωç<U+3C63A><U+2F62C><U+BA5B6><U+4E70A><U+F7D88><U+FF138><U+40CAE>
<U+CB43E><U+C30F5><U+6FFEF>•†ù<U+698BE><U+9D73A><U+95199><U+BD941><U+10B55E><U+88889><U+75A1F><U+4C4BB><U+5C67A><U+1089A3><U+C75A7>
<U+38AC1><U+4B6BB><U+592F0>·öã<U+F2C9B>
```
Driver program for testing:
```
if __name__ == '__main__':
import os
total = 0
for i in range(1,10+1):
out = p(open('data/%d.txt'%i,'rb').read())
total += len(out)
open('out/%d.bin'%i,'w',encoding='utf8').write(out)
print(total)
for i in range(1,10+1):
out = u(open('out/%d.bin'%i,'r',encoding='utf8').read())
open('data2/%d.txt'%i,'wb').write(out)
```
Output byte counts:
```
607 out/1.bin
128 out/2.bin
101 out/3.bin
143 out/4.bin
177 out/5.bin
145 out/6.bin
186 out/7.bin
222 out/8.bin
389 out/9.bin
1103 out/10.bin
3201 total
```
[Answer]
# Python 2 - 1141 points
```
from zlib import *;v=256
def e(b):
x=0
for c in compress(b,9):x=(x*v)+ord(c)
b=bin(x)[2:]
return "".join(unichr(int("1"+b[a:a+19],2))for a in range(0,len(b),19))
def d(s):
y=int("".join(bin(ord(a))[3:]for a in s),2);x=""
while y:y,d=(y/v,chr(y%v));x=d+x
return decompress(x)
```
Code size is `281` bytes and it encodes the `6135` bytes into `860` unicode characters.
How it works:
To Encode:
1. Compress the string to be encoded.
2. Interpret the compressed string as a base 256 number.
3. Convert the number to binary.
4. Split the binary into groups of `19` bits, add a `1` bit to the beginning of each of them, and then convert to Unicode characters.
Decoding is the reverse.
Note that some versions of python can only handle unicode characters up to `0xFFFF`, and thus this code will raise a `ValueError`.
] |
[Question]
[
I'm building a giant lego robot and I need to generate some particular gear ratios using a set of gears. I have lots of gears with the common lego gear sizes: 8, 16, 24, or 40 teeth. Write a program I can use where I input a gearing ratio and the program tells me what combination of gears I should use to get the requested ratio.
The input ratio will be specified on standard input (or your language's equivalent) with two integers separated by a colon. A ratio of `a:b` means that the output shaft should turn `a/b` times as fast as the input shaft.
The output to standard output should be a single line containing a space-separated list of gear ratios, in the form of `x:y` where `x` is the size of the gear on the input shaft and `y` is the size of the gear on the output shaft. You must use the minimum possible number of gears for the given ratio. Each `x` and `y` must be one of `8,16,24,40`.
examples:
```
1:5 -> 8:40
10:1 -> 40:8 16:8
9:4 -> 24:16 24:16
7:1 -> IMPOSSIBLE
7:7 ->
6:15 -> 16:40
```
If the desired gear ratio is impossible, print "IMPOSSIBLE". If no gears are required, print the empty string.
This is code golf, shortest answer wins.
[Answer]
# Python - 204
Ok, I'll go first:
```
def p(n,a=[1]*9):
n=int(n)
for i in(2,3,5):
while n%i<1:n/=i;a=[i]+a
return a,n
(x,i),(y,j)=map(p,raw_input().split(':'))
print[' '.join(`a*8`+':'+`b*8`for a,b in zip(x,y)if a!=b),'IMPOSSIBLE'][i!=j]
```
edit:
To 'optimize' the output, this can be added before the `print` statement,
```
for e in x:
if e in y:x.remove(e);y.remove(e)
```
bringing the total up to **266 characters**, I believe.
[Answer]
# Perl - 310 306 294 288 272
I'm a little rusty with perl and never did a code-golf... but no excuses. Char-count is without line-breaks. Using perl v5.14.2 .
```
($v,$n)=<>=~/(.+):(.+)/;
($x,$y)=($v,$n);($x,$y)=($y,$x%$y)while$y;
sub f{$p=shift;$p/=$x;for(5,3,2){
while(!($p%$_)){$p/=$_;push@_,$_*8}}
$o="IMPOSSIBLE"if$p!=1;
@_}
@a=f($v);@b=f($n);
if(!$o){for(0..($#b>$#a?$#b:$#a)){
$a[$_]||=8;
$b[$_]||=8;
push@_,"$a[$_]:$b[$_]"}}
print"$o@_\n"
```
I'm looking forward to critics and hints. It's not so easy to find tips and tricks for code-golf (in perl).
[Answer]
# swi-prolog, 324 250 248 204 bytes
Prolog does pretty well at solving a problem like this.
```
m(P):-(g(P,L),!;L='IMPOSSIBLE'),write(L).
g(A:A,''):-!.
g(A:B,L):-A/C/X,C>1,B/C/Y,!,g(X:Y,L);A/C/X,!,B/D/Y,C*D>1,g(X:Y,T),format(atom(L),'~D:~D ~a',[C*8,D*8,T]).
X/Y/Z:-(Y=5;Y=3;Y=2;Y=1),Z is X//Y,Y*Z>=X.
```
Input is passed as a term parameter to predicate `m`. Output is written to stdout. Sorry about the trailing 'true'; that's just the interpreter's way of letting me know everything was fine.
```
?- m(54:20).
24:40 24:16 24:8
true.
?- m(7:7).
true.
?- m(7:1).
IMPOSSIBLE
true.
```
[Answer]
# C, 246 216 213 bytes
In a (futile) attempt to beat my own Prolog solution, I completely rewrote the C solution.
```
b,c,d;f(a,b,p){while(c=a%5?a%3?a%2?1:2:3:5,d=b%5?b%3?b%2?1:2:3:5,c*d>1)c<2|b%c?d<2|a%d?p&&printf("%d:%d ",8*c,8*d):(c=d):(d=c),a/=c,b/=d;c=a-b;}main(a){scanf("%d:%d",&a,&b);f(a,b,0);c?puts("IMPOSSIBLE"):f(a,b,1);}
```
My original C solution (246 bytes):
```
#define f(c,d) for(;a%d<1;a/=d)c++;for(;b%d<1;b/=d)c--;
b,x,y,z;main(a){scanf("%d:%d",&a,&b);f(x,2)f(y,3)f(z,5)if(a-b)puts("IMPOSSIBLE");else
while((a=x>0?--x,2:y>0?--y,3:z>0?--z,5:1)-(b=x<0?++x,2:y<0?++y,3:z<0?++z,5:1))printf("%d:%d ",a*8,b*8);}
```
It was a nice exercise to prove it can be done without building lists.
[Answer]
## Pyth, 101 bytes
```
D'HJH=Y[)VP30W!%JN=/JN=Y+NY))R,YJ;IneKhm'vdcz\:J"IMPOSSIBLE").?V.t,.-Y.-hK=J.-hKYJ1In.*Npj\:m*8d_Np\
```
An implementation of [@daniero' python answer](https://codegolf.stackexchange.com/a/7148/32686) but semi-optimised for Pyth.
```
D'H - Define a function (') which takes an argument, H.
JH - J = H (H can't be changed in the function)
=Y[) - Y = []
V - For N in ...
P30 - Prime factors of 30 (2,3,5)
W!%JN - While not J%N
=/JN - J /= N
=Y+NY - Y = N + Y
))R,YJ - To start of function, return [Y,J]
ENDFUNCTION
If
cz\: - Split the input by the ':'
m'vd - ['(eval(d)) for d in ^]
Kh - Set K to the first element of the map (before the :)
e - The second returned value
J - The second returned value after the : (The variables are globals)
n - Are not equal
Then
"IMPOSSIBLE" - Print "IMPOSSIBLE"
Else
V - For N in
.t 1 - transpose, padded with 1's
.-hKY - 1st function first return - 2nd function first return
=J - Set this to J
.-hK - 1st function first return - ^
.-Y - 2nd function first return - ^
, J - [^, J]
(Effectively XOR the 2 lists with each other)
I - If
n.*N - __ne__(*N) (if n[0]!=n[1])
pj\:m*8d_N - print ":".join([`d*8` for d in reversed(N)])
p\ - print a space seperator
```
[Try it here](http://pyth.herokuapp.com/?code=D%27HJH%3DY%5B%29VP30W!%25JN%3D%2FJN%3DY%2BNY%29%29R%2CYJ%3BIneKhm%27vdcz%3AJ%22IMPOSSIBLE%22%29.%3FV.t%2C.-Y.-hK%3DJ.-hKYJ1In.*Npj%3Am*8d_Np+&input=9%3A4&test_suite=1&test_suite_input=1%3A5&debug=0)
[Or test every case](http://pyth.herokuapp.com/?code=D%27HJH%3DY%5B%29VP30W!%25JN%3D%2FJN%3DY%2BNY%29%29R%2CYJ%3BIneKhm%27vdcz%3AJ%22IMPOSSIBLE%22%29.%3FV.t%2C.-Y.-hK%3DJ.-hKYJ1In.*Npj%3Am*8d_Np+&input=9%3A4&test_suite=1&test_suite_input=1%3A5%0A10%3A1%0A9%3A4%0A7%3A1%0A7%3A7%0A6%3A15&debug=1)
[Answer]
## ES6, 230 bytes
```
x=>([a,b]=x.split`:`,f=(x,y)=>y?f(y,x%y):x,g=f(a,b),d=[],a/=g,f=x=>{while(!(a%x))a/=x,d.push(x*8)},[5,3,2].map(f),c=d,d=[],a*=b/g,[5,3,2].map(f),a>1?'IMPOSSIBLE':(c.length<d.length?d:c).map((_,i)=>(c[i]||8)+':'+(d[i]||8)).join` `)
```
One of my longest golfs, so I must have done something wrong... Ungolfed:
```
x => {
[a, b] = x.split(":");
f = (x, y) => y ? f(y, x % y) : x; // GCD
g = f(a, b);
f = x => {
r = [];
while (!(x % 5)) { x /= 5; r.push(5); }
while (!(x % 3)) { x /= 3; r.push(3); }
while (!(x % 2)) { x /= 2; r.push(2); }
if (x > 1) throw "IMPOSSIBLE!";
return r;
}
c = f(a);
d = f(b);
r = [];
for (i = 0; c[i] || d[i]; i++) {
if (!c[i]) c[i] = 8;
if (!d[i]) d[i] = 8;
r[i] = c[i] + ":" + d[i];
}
return r.join(" ");
}
```
] |
[Question]
[
## The picture:
[](https://i.stack.imgur.com/n1TkD.png)
Sick of the same old grid where the answer is simply a square pyramidal number?
Accept the challenge and write a program that given a positive integer \$n\$ counts how many squares are in the \$n^{\text{th}}\$ iteration of the [Harter-Heighway dragon](https://en.wikipedia.org/wiki/Dragon_curve#Heighway_dragon)!
* The sequence of squares of size **1** is [A003230](https://oeis.org/A003230)
* Your code must count all the squares of any size (the first of size **2** show up in \$7^{\text{th}}\$ iteration)
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")
Here's the beginning of the resulting sequence:
```
0, 0, 0, 1, 4, 11, 30, 78, 205, 546, 1455, 4062, 11192, 31889, 88487, 254594
```
And my un-golfed [reference program](https://tio.run/##dVTbbhoxEH3nK0ZdKc3FtFnUp5JEoLapmhYpTSP1waKVAQNWFntjm2QR5dvTM96FJL2sEOudsWfOnDnjhYpzvVDRjNXDw/4hXc9VfBlIUeEiLZzXFN298pNAodR6QnGuLM1cMaXDg1arNfFq5uwlgsibn0N6e0p9Oyt0Muxfmtedg8MLNXYj8221GLlCtnNBV8rOtOz8uBkOBX13/sbY2aXXYxOMs9Q@o092aqyJq2GrBUQftdVeRc2gFqossZvcFEA05e1wu1QerqnzyWLbcU7jpb/Tr@jDnfYrKp2xkbwqsU3byFGWCE71Sa6iiTFQ5baGgZssCy3XJcqgU3paJCBHvShhXW8EVYJW@KkQYDj59esMHzBsUfGmjWgR0Xsn@YXn01TStYuqkBxdSjMcUpuaNVb5EIbTUwJR/bLUdnLtJGcUf@z5nxuuYbfJJdZG0BdtZ3HeY/dm51kDZbUBQD4rZUbdLvWLgl8d5N@j1z1aA0Jnsz1RYfM356OsdkH6IbixQWuAgTkQqbjPevWhMiGGr40xk7KTANcL7nANPflllu/8WOW7VbN1nSXjZotqVWd/TmjFvBwxL2CnqkkFh@tjQfmGewLwKRn7BGfrpnMDvRhpD6BMB7sS@3t7/3SkBE9ob7osmoR4/qYdbHG/GuKbEy2qlX0O0eok0qeKHLsly3Tu7iF3u6KRmc2032nqRUDLwguaercgnDIWip6aCrM5MZiiyEP0qOp3HG2r633UfHPyRlzpuPRWHjMNW62HW3D0dBRQKu4FQVbUkMAj15DW2NrIKtw2lcGUodT1ufEh9up/WNss5IGxWKOPjcxE6i1oqVvaxEA2BLnSZaHGuEEgtXfOhqhs7HuvVhLNrKPLLwp/4ZaVMlCV/DM0xMIzyOrJa@KfqwVw0hnzOGrIFI1davk4PBZg8i41X9/nBiztdAGsmJpcZPW09Ho92m9CorCsrusCV4/McOFxk4NmU5Z207UaMeeQSQZa@X3My9ppD/CZgJ2rImixhcBju2vG0dHW@g/VgexGcWkz9Ia7@tLjIpTPZJFD1Q8PvwE) in Mathematica.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 96 bytes
```
F…¹X²N«F¬⁼KK#⊞υ⟦ⅉⅈ⟧##¿&ι⊗&ι±ι↷↶»↷≔⁰ζFυ«J⊟ι⊟ι≔¹ηW⬤ur⁼№KD⊗η✳λ#⊗η≦⊕ηFη¿κ«↗↗≧⁺⬤dl⁼№KD⊗κ✳λ#⊗κζ»»⎚Iζ
```
[Try it online!](https://tio.run/##jZFRS8MwFIWf118RupcbiKC@CO5pbj5M3ChDQREfsvauDc2SmiYbTPbba5J1DEXQvpR7OL33fKd5xU2uuey6tTYEllyVCFeMZHqHBq4ZmanG2YXbrPxI/UM@k0G0LrSF@w/HZQsZYg2UkXSYBkfm2gocI2@vQXwB@k5HySAzQllIh97jJ7EmcCfsTrQ4VgUIRqbarSQWP9QFltwiCBpvZ2Kr7VKUlQU6IihbPEqPuA5Kcki@OZJx24pSwSUjez/F2C4SPLhN86Qh041fHWjDO@Tqv/ANVGHcVUIigbGUkDqTMtITT7TzMIF7KgzmVmgFJ4DKLzyrkvbFnAmryDLnTX9spnKDG1QWi/5sTFpRElqqY@DBXG8Rbp@byBY8vymnlccCMulaRmL2Qv4ve/1X9poGLbQ5OPi6JxK5CU0f/@6Etxb2vsiuu@kutvIL "Charcoal – Try It Online") Link is to verbose version of code. Explaantion:
```
F…¹X²N«
```
Loop over all the turns of the nᵗʰ iteration of the dragon.
```
F¬⁼KK#⊞υ⟦ⅉⅈ⟧
```
If we haven't visited this cell yet then record its position.
```
##
```
Print a segment of the dragon.
```
¿&ι⊗&ι±ι↷↶
```
Rotate appropriately for the next segment.
```
»↷
```
At the end of the dragon, rotate back to horizontal. (`Clear()` doesn't do this; maybe it should?)
```
≔⁰ζ
```
Start counting squares.
```
Fυ«J⊟ι⊟ι
```
Loop over and jump to each visited cell.
```
≔¹η
```
Start searching for squares.
```
W⬤ur⁼№KD⊗η✳λ#⊗η≦⊕η
```
While there are enough `#`s in both the upwards and rightwards directions increase the size of square being searched for.
```
Fη¿κ«
```
Check all sizes of squares from 1 to the largest potential size found.
```
↗↗≧⁺⬤dl⁼№KD⊗κ✳λ#⊗κζ
```
Move diagonally up and right two cells, then check downwards and leftwards for the other two sides of the square of this size and keep a running total of squares found.
```
»»⎚Iζ
```
Once all potential squares have been checked clear the canvas and output the final number found.
[Answer]
# JavaScript (ES6), ~~272 ... 244~~ 239 bytes
This is quite slow for \$n>6\$ but was verified locally up to \$n=8\$.
```
k=>(b=[],k=1<<k,g=d=>k--?g(d+(g[b.push(n++,n++),x+=--d%2,y+=--d%2,[x-!d,y-(d>0)]]|=d&1||2,n&-n&n/2?1:3)&3):b.map(y=>b.map(x=>b.map(w=>o+=(h=d=>d--?g[[X=x-n/2+d,Y=y-n/2]]&g[[X,Y+w]]&2&&g[[X-=d,Y+=d]]&g[[X+w,Y]]&h(d):1)(++w))))|o)(n=x=y=o=0)
```
[Try it online!](https://tio.run/##NY/baoNAEIbv8xRbSJdZdtdGA70wjnmNigjRrIdWuysxrYr67HZtm4Hh/@bEz3yk32l3vb23d6mNytcC1xpDyDBORI1uENSiRIVhLeW5BMWhjDOn/eoq0JwLm0wMHKVUz54YHxAP8kmJUYIKDyxJZlTUnWdPaCo11S/e2fWPjB6ZnzmfaQsjhn8wPKDH0HCEanNWm3Mcv@Eg7SlXIsJxoyShW1tEvLfo0d9Kop1zVP9D3ovIYgWK@S4DzntmYzYMNA44osEDWwtzgya/E02QuCcrAZJXq/Y3Mu0IuRrdmSZ3GlPCJYX9pBdmV/dTAZotF3baLesP "JavaScript (Node.js) – Try It Online")
## Commented
### Step 1
We first build the grid.
```
k => ( // k = input
b = [], // initialize b[] to an empty array
k = 1 << k, // turn k into 2 ** k
g = d => // g is a recursive function taking a direction d
k-- ? // decrement k; if it was not equal to 0:
g( // do a recursive call:
d + ( // using the updated direction
g[ //
b.push(n++, n++), // append n and n + 1 to b[]
x += --d % 2, // add dx to x
y += --d % 2, // add dy to y
[x - !d, y - (d > 0)] // use either [x, y], [x-1, y] or [x, y-1]
] |= // as a key to identify the cell
d & 1 // that is updated with either a horizontal
|| 2, // or a vertical border (using the two least
// significant bits as flags)
n & -n & n / 2 ? // determine whether it's a left or right turn
1 // and add either 1 or 3 to d
: //
3 //
) & 3 // force d into [0 .. 3]
) // end of recursive call
: // else:
... // stop the recursion and process step #2
)(n = x = y = o = 0) // initial call to g
```
### Step 2
The array `b[]` is now filled with `[0, 1, ..., 2k-1]` and the underlying object of `g` describes the horizontal and vertical borders that are set for each cell in the grid.
```
b.map(y => // for y = 0 to y = 2k-1:
b.map(x => // for x = 0 to x = 2k-1:
b.map(w => // for w = 0 to w = 2k-1:
o += // update the output counter o:
( h = d => // h is a function taking a distance d
d-- ? // decrement d; if it was not equal to 0:
g[[ X = x - n / 2 + d, // test the vertical border at
Y = y - n / 2 // (x - n/2 + d, y - n/2)
]] & //
g[[ X, // test the vertical border at
Y + w // (x - n/2 + d, y - n/2 + w)
]] & 2 //
&& //
g[[ X -= d, // test the horizontal border at
Y += d // (x - n/2, y - n/2 + d)
]] & //
g[[ X + w, // test the horizontal border at
Y // (x - n/2 + w, y - n/2 + d)
]] & //
h(d) // and do a recursive call
: // else:
1 // stop the recursion
)(++w) // increment w; initial call to h with d = w
) // end of map()
) // end of map()
) | o // end of map(); return o
```
] |
[Question]
[
The J language has a [very silly syntax for specifying constants](http://www.jsoftware.com/help/dictionary/dcons.htm). I want to focus on one cool feature in particular: the ability to write in arbitrary bases.
If you write `XbY` for `X` any number and `Y` any string of alphanumerics, then J will interpret `Y` as a base `X` number, where `0` through `9` have their usual meaning and `a` through `z` represent 10 through 35.
And when I say `X` any number, I mean *any* number. For the purposes of this question, I'll constrain `X` to be a positive integer, but in J you can use anything: negative numbers, fractions, complex numbers, whatever.
The thing that's weird is that **you can only use the numbers from 0 to 35** as your base-whatever digits, because your collection of usable symbols consists *only* of 0-9 and a-z.
## The problem
I want a program to help me golf magic numbers like [2,933,774,030,998](https://codegolf.stackexchange.com/a/20989/5138) using this method. Well, okay, maybe not that big, I'll go easy on you. So...
>
> Your task is to write a program or function which takes a (usually large) decimal number `N` between 1 and 4,294,967,295 (= 232-1) as input, and outputs/returns the shortest representation of the form `XbY`, where `X` is a positive integer, `Y` is a string consisting of alphanumerics (0-9 and a-z, case insensitive), and `Y` interpreted in base `X` equals `N`.
>
>
> If the length of every representation `XbY` representation is greater than or equal to the number of digits of `N`, then output `N` instead. In all other ties, you may output any nonempty subset of the shortest representations.
>
>
>
This is code golf, so shorter is better.
## Test cases
```
Input | Acceptable outputs (case-insensitive)
------------+-------------------------------------------------------
5 | 5
|
10000000 | 79bkmom 82bibhi 85bgo75 99bauua 577buld
| 620bq9k 999baka
|
10000030 | 85bgo7z
|
10000031 | 10000031
|
12345678 | 76bs9va 79bp3cw 82bmw54 86bjzky 641buui
|
34307000 | 99bzzzz
|
34307001 | 34307001
|
1557626714 | 84bvo07e 87brgzpt 99bglush 420blaze
|
1892332260 | 35bzzzzzz 36bvan8x0 37brapre5 38bnxkbfe 40bij7rqk
| 41bgdrm7f 42bek5su0 45bablf30 49b6ycriz 56b3onmfs
| 57b38f9gx 62b244244 69b1expkf 71b13xbj3
|
2147483647 | 36bzik0zj 38br3y91l 39bnvabca 42bgi5of1 48b8kq3qv
(= 2^31-1) | 53b578t6k 63b2akka1 1022b2cof 1023b2661 10922bio7
| 16382b8wv 16383b8g7 32764b2gv 32765b2ch 32766b287
| 32767b241
|
2147483648 | 512bg000 8192bw00
|
4294967295 | 45bnchvmu 60b5vo6sf 71b2r1708 84b12mxf3 112brx8iv
(= 2^32-1) | 126bh5aa3 254b18owf 255b14640 1023b4cc3 13107bpa0
| 16383bgwf 21844b9of 21845b960 32765b4oz 32766b4gf
| 32767b483 65530b1cz 65531b1ao 65532b18f 65533b168
| 65534b143 65535b120
```
If you're ever unsure about whether some representation is equal to some number, you can use any J interpreter, like the one on [Try It Online](https://tio.run/nexus/j). Just type in [`stdout 0":87brgzpt`](https://tio.run/nexus/j#@19ckpJfWqJgoGRlYZ5UlF5VUPL/PwA) and J will spit back out `1557626714`. Note that J only accepts lowercase, even though this problem is case-insensitive.
## Some possibly helpful theory
* For all `N` less than 10,000,000, the decimal representation is as short as any other and hence is the only acceptable output. To save anything you would need to be at least four digits shorter in the new base, and even more if the base is greater than 99.
* It suffices to check bases up to the ceiling of the square root of `N`. For any larger base *B*, `N` will be at most two digits in base *B*, so the first time you'll get something with a valid first digit is at around *B* ≈ `N`/35. But at that size you will always be at least as large as the decimal representation, so there's no point in trying. That in mind, ceil(sqrt(largest number I'll ask you to solve this problem for)) = 65536.
* If you have any representation in a base less than 36, then the base 36 representation will be at least as short. So you don't have to worry about accidentally short solutions in bases less than 36. For example, the representation `35bzzzzzz` for 1,892,332,260 uses an unusual digit for that base, but `36bvan8x0` has the same length.
[Answer]
## JavaScript (ES6), ~~103~~ 101 bytes
Takes input as a string.
```
n=>[...Array(7e4)].reduce(p=>p[(r=++b+(g=x=>x?g(x/b|0)+(x%b).toString(36):'b')(n)).length]?r:p,n,b=2)
```
### Test cases
*NB: The number of iterations in the snippet function is limited to 600 so that the test cases complete faster. (It would take a few seconds otherwise.)*
```
let f =
n=>[...Array(6e2)].reduce(p=>p[(r=++b+(g=x=>x?g(x/b|0)+(x%b).toString(36):'b')(n)).length]?r:p,n,b=2)
console.log(f("5"))
console.log(f("10000000"))
console.log(f("10000030"))
console.log(f("10000031"))
console.log(f("12345678"))
console.log(f("34307000"))
console.log(f("34307001"))
console.log(f("1557626714"))
console.log(f("1892332260"))
console.log(f("2147483647"))
console.log(f("2147483648"))
console.log(f("4294967295"))
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 118 bytes
This was linked in another question and I noticed there aren't many answers here, so I decided to give it a shot.
Walk through *all bases* up to and including the input to construct all valid J number constructions. It skips 1-8 though, because there's no way those will be shorter than the base-10 representation anyways. It's a pretty naive solution, all things considered, since it calls the `digits` builtin to get the digits, but since that starts with the least significant digit first we have to `reverse` it to get the actual number, so it could possibly be improved.
It's slow. So, soooooo incredibly slow. TIO times out on 34307000, for example. We *could* go with the square root or even Arnauld's choice of `7e4` to save time, but that costs extra bytes, so why bother?
```
->n{([n.to_s]+(9..n).map{|b|d=n.digits b;"#{b}b"+d.reverse.map{|i|i.to_s 36}*''if d.all?{|i|i<36}}-[p]).min_by &:size}
```
[Try it online!](https://tio.run/##PY3vCoIwFMW/@xRDIy1xJFLQH@tBRMS1qRd0itPC5p59DY3Op3PPvfd3@pFMuoh1cOfSSzge2kykvnfGmO9wk3dyJjONOaZQwiAQudqOJIrYPsU9e7FesPUKZlh@UXRSe9eFAlGc1/Vj2dxMqIKkSw0SeEYmtL0I@DCl3xXUDJVsEBbqRlNg8JsMP6u26RRyZJGYyXAhVbbFONVHKzys@pnob8Iv "Ruby – Try It Online")
[Try it online w/ sqrt so everything finishes on time](https://tio.run/##RY3tboIwFIb/9yoaNNNBbOg3dXO7EEKIHUWbYCWAWxz02lmnZju/nnPek@ftLvo617t58@bGde7QcC77IlkrhHDi4jhF/Bmd9u046anaOVTZgx16qF@ixai9jpIKdebTdL25f9nJ3hSQCh@vVraGFdo3zfsteQ1Hv8nbIiitK/UVPm17@238/HW0jYEHM/QAtpdQEPTLEn0cz6fWw8VY52ELXlv4CBhXzRzg9D4PoH@AASaUcSEzQBlN5e/PA0LEuRRESMwAzhShlBCRAoKZZBkVTP5jBhhRTAlJFAdEUSolCy1KZT8 "Ruby – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 37 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
[¼35ݾãvtîEyNβQižhA«yèJ'bìNìDgIg@i\}q
```
Should work in theory, but times out for all non-trivial test cases, even `10000000`. The cartesian product builtin `ã` is extremely slow for \$\geq4\$..
Without the final if-statement `DgIg@i\}` it can still be tested for lower values, to verify that it does in fact work: [**Try it online.**](https://tio.run/##ATYAyf9vc2FiaWX//1vCvDM1w53CvsOjdnTDrkV5Ts6yUWnFvmhBwqt5w6hKJ2LDrE7DrHH//zEyMzQ)
Will see if I can come up with a (probably much longer but) more efficient solution later on.
**Explanation:**
```
[ # Start an infinite loop:
¼ # Increase the counter variable by 1 (0 by default)
35Ý # Push a list in the range [0, 35]
¾ã # Take the cartesian product of this list with itself,
# with chunks-sizes equal to the counter variable
v # Loop `y` over each of these lists:
t # Take the square-root of the (implicit) input-integer
î # Ceil it
E # Loop `N` in the range [1, ceil(square(input))]:
yNβ # Convert list `y` to base-`N`
Qi # If it's equal to the (implicit) input-integer:
žh # Push string "0123456789"
A« # Append the lowercase alphabet
yè # Index each value in list `y` into this string
J # Join the characters to a single string
'bì '# Prepend a "b"
Nì # Prepend the number `N`
D # Duplicate it
g # And pop and push the length of this string
Ig # Also push the length of the input
@i } # If the length of the string is >= the input-length:
\ # Discard the duplicated string
q # Stop the program
# (after which the result is output implicitly;
# or if the string was discarded and the stack is empty, it will
# implicitly output the implicit input as result instead)
```
] |
[Question]
[
This challenge is related to [Flipping Pancakes](https://codegolf.stackexchange.com/questions/12028/flipping-pancakes).
You may have heard of [pancake sorting](https://en.wikipedia.org/wiki/Pancake_sorting), where a stack of pancakes is sorted by size by inserting spatula into the stack and flipping all of the pancakes above the spatula, until the pancakes are sorted smallest to largest on the plate. The burnt pancake problem is slightly different. All pancakes now have one side that is burnt, and the burnt side of each pancake must face the plate once the sorting is completed.
For example, given the following stack (size of pancake on the left. `0` meaning burnt-side down and `1` meaning burnt-side up on the right):
```
1 0
3 1
2 1
```
You may flip the whole stack to get `20 30 11`, flip the top two to get `31 21 11` and flip the whole stack again to get `10 20 30`, a sorted stack of burnt pancakes. This sequence of moves, flip 3, flip 2, flip 3, could be represented as `3 2 3`.
**The Challenge**
* Given an array of pancakes sizes (not necessarily unique) and their orientations, output any valid burnt pancake sorting sequence, that is, a sequence of flips that leads to the stack of pancakes being sorted from smallest to largest with burnt sides down.
* Input and output may be any sane format with separators, but please specify which formats you use and state which end of your input format is the top of the stack (TOS).
* Flipping zero pancakes is allowed.
* Mixing separators in the input/output is allowed.
**Test cases**
For all of the following test cases, input is a list and output is a space-separated string, and TOS is on the left.
```
[[1, 0], [3, 1], [2, 1]]
"3 2 3"
[[5, 1], [3, 0], [4, 1], [2, 1], [1, 0]]
"5 3 4 1 3 2 1"
[[5, 1], [3, 0], [3, 0], [1, 1]]
"4 3 2 3"
```
As always, if anything is unclear or incorrect, please let me know in the comments. Good luck and good golfing!
[Answer]
# Python 2, 83
Input is expected to be the list of (size, orientation) tuples with the stack's top at the end. The output is a list of sizes to flip separated by various kinds of whitespace.
```
a=input()
while a:i=a.index(max(a));print len(a)-i,a[i][1],len(a),i;a=a[i+1:]+a[:i]
```
[Answer]
## CJam (37 bytes)
```
q~{__$W>#)_p/(W%\M*2,f.^+(1=p_,)pW%}h
```
Input is an array in CJam format on stdin; output is a newline-separated list of flip lengths on stdout. The top of stack is at index `0`; `0` indicates burnt side up, and `1` indicates burnt side down.
[Online demo](http://cjam.aditsu.net/#code=q~%7B__%24W%3E%23)_p%2F(W%25%5CM*2%2Cf.%5E%2B(1%3Dp_%2C)pW%25%7Dh&input=%5B%5B5%200%5D%20%5B3%201%5D%20%5B4%200%5D%20%5B2%200%5D%20%5B1%201%5D%5D)
### Dissection
The output is always `3n` flips long, where `n` is the number of pancakes. First we flip the largest remaining pancake to the top; then if it's burnt side down we flip that one pancake; and then we flip it to the bottom and repeat as though the stack of pancakes were one shorter.
```
q~ e# Parse input into array
{ e# Loop...
__$W>#) e# Find 1-based index of largest element in array
_p e# Dup and print
/( e# Split into chunks that long, and pull off the first
W% e# Reverse the first chunk. Note that we don't flip the burnt/unburnt bit
\M* e# Merge the remaining chunks into a single array
2,f.^ e# Flip *their* burnt/unburnt bits
+ e# Concatenate, prepending the first chunk
(1=p e# Pull off the first (largest) element and print its burnt/unburnt bit
_,)p e# Print the number of remaining elements plus 1 (to account for the largest)
W% e# Reverse. Note that the first chunk has now been flipped twice, which is
e# why we have left its burnt/unburnt bit alone
}h e# ... until we get down to an empty array
```
[Answer]
# Ruby, ~~101~~ ~~95~~ 93 bytes
Not very golfy, I just wanted to make a bogo-sort variant. It's an anonymous function that takes an array of arrays and prints random flips to stdout until the pancakes are sorted.
```
->a{(p r=-~rand(a.size)
a[0,r]=a[0,r].reverse.map{|x,b|[x,1-b]})while a!=a.sort||a.rassoc(1)}
```
You can for example assign it to `f` and say `f.call [[1, 0], [3, 1], [2, 1]]`
-5 bytes from @Jordan with the brilliant use of `rassoc`
-2 bytes from @Sherlock9
] |
[Question]
[
Given a pattern of squares on a grid, determine if it is possible to create that pattern with non-overlapping dominoes. In case you are not familiar, a domino is a rectangular shape created by joining exactly two squares at their edges.
## Examples
For the pattern on the left, `O` represents an occupied cell on the grid and `.` represents an empty cell. For the pattern to the right of the first `|`, numbers and letters will be used to mark individual dominoes in a possible solution
### Possible
```
O | 1 | This is the trivial case:
O | 1 | a single domino laid vertically
```
```
. O . . | . 2 . . | This can be created with three
O O O O | 1 2 3 3 | dominoes in a simple pattern
O . . . | 1 . . . |
```
```
O O O O | 1 1 2 2 | A simple rectangular grid with
O O O O | 3 3 4 4 | even width is easily tiled with
O O O O | 5 5 6 6 | horizontally-laid dominoes
```
```
O O O | 1 1 2 | Four dominoes laid radially
O . O | 3 . 2 |
O O O | 3 4 4 |
```
```
. O O . | . 1 1 . | Dominoes do not need to touch
O . O . | 2 . 3 . | and the grid may contain empty
O . O . | 2 . 3 . | cells along an edge
```
```
. O . . O O O O O . | . K . . R R S S N . | A 10x10 test case and
O O O . . O . . O . | U K J . . 5 . . N . | one of its solutions
O . O . . O . O O O | U . J . . 5 . C C Q |
O O O O O O . O . O | T B B 4 1 1 . 7 . Q |
O . . O O O . O . . | T . . 4 6 6 . 7 . . |
. . O O O . O O O . | . . 2 3 3 . 8 8 D . |
O O O . . O . . O . | I I 2 . . 9 . . D . |
. . O O O O . O O O | . . G O O 9 . E E L |
. . O . . O O O . O | . . G . . A F F . L |
O O . O O O . . O O | M M . H H A . . P P |
```
### Not Possible
```
O | You need at least two occupied cells to fit a domino
```
```
O . | Dominoes are squares joined by edges, not corners
. O |
```
```
O | It is always impossible to create a pattern with an odd
O | number of squares with dominoes
O |
```
```
O O . O | No matter how you lay the first few dominoes,
. O O O | at least two squares are always separated
. O . O |
```
```
O O O . | This is a slightly more complicated version of the above
O . O O |
O O O . |
. O O O |
```
```
. O . . . . | A small test case that cannot be decided with
O O O O O O | a chessboard painting algorithm
. . . . O . |
```
```
. O O O O O . O O O | A 10x10 example test case
O O O . . O . . . O |
. . O . O . O O O . | This pattern is almost possible
. O . . O . . . O O | except that the bottom-left corner
. O O O O O O O . O | contains an arrangement which is
. . . . O . . O O O | impossible to make with dominoes
O O O O O . O . . . |
O . O . . . O . . O |
. O O O . O O . O O |
. . . O O . O O O . |
```
```
. O O O O O O O O O | A pathological case for a chessboard
O O O O O O O O O . | painting algorithm.
O O O O O O O O O O |
O O O O O O O O O O | This is also a pathological case for
O O O O O O O O O O | a backtracking algorithm.
O O O O O O O O O O |
O O O O O O O O O O |
O O O O O O O O O O |
O O O O O O O O O O |
O O O O O O O O O O |
```
## Rules and Scoring
* This is Code Golf, so shortest code wins
* Use any convenient I/O method.
* Valid input formats for the grid include, but are not limited to:
+ Array of arrays
+ Height, width, array
+ Array of integers representing each row (or column) in binary
+ A string representation similar to the examples above
+ A PNG image
* You may assume input grids are rectangular (not jagged)
* Your solution should return answers within a reasonable amount of time (it should not time out on Try It Online, for example) for inputs up to 10x10 and be able to theoretically work for a grid of any size if given enough time and space.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 120 bytes
```
WS⊞υιυFLυFL§υι«Jκι¿⁼KKO«≔⟦ω⟧θWθ«≔Φurdl№⪪α¹⊟KD²✳μλ¿λ«≔§λ⁰λ✳λλ≔KKηP§dlur⌕urdlλ¿⁼ηO≔⟦⟧θ«M✳η⊞θη⊞θKK»»«≔⊟θλ✳λ↧λ✳KK↧⊟θ»»UMKA↥λ
```
[Try it online!](https://tio.run/##hVFNa4QwED0nvyJ4imCl7bWnpe3Cll0Utj2VHkSza9jR@JHsFoq/3SYmWW2hNGJMZt68efPMy6zLRQbjeCk5MEI3daPkXna8PtIwJKnqS6oiwsMHnOqgpEqfDqIjdMvqo9RJjVreV3JTF@zTFuncF0YvqmpeBT1ZGsQPhD63KoOepoydaBiRIAksFK36nh9r@n75iEhr0MgJa23eA9YcJOtooLoCgog8CqW17RvgkmYRudOcqWgm/ifesVxyUdP7iMyXKjQrIjA1mUSBa@F7@FEgIrczElkfZiZY5Fyln6t04Z0CyZupzpMGBahOK1/zuriOAVqSrViYVHp/vDdXaxBi0DMnGu3EmS1klZ4KTT@xndVcA1amiw5mH8iC0Q@jjWz/mX8rLqzLs57p2x8w12yJtcyuwPQ37y5rHkVVZdoWU7ICME6@Nc2PBgMexjFO4jgxK8Zmm676aL86ghOb1Q@2UJPC7vSrzFJNZXHs0dgB9YbHmzN8Aw "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a newline-terminated list of strings. Outputs a completed board or throws an exception if it can't find a solution. Note: While I know that the algorithm definitely fails on an illegal board, my golfing may mean that it's not 100% successful on legal boards, so feel free to find a counterexample and I'll adapt the code. Explanation: Based on the maximum flow algorithm, so should run in polynomial time (possibly O(n²) in the number of dominoes, as each of the `n` dominoes might decide to rotate all of the `n-1` dominoes already placed).
```
WS⊞υιυ
```
Read and print the input.
```
FLυFL§υι«
```
Loop over all cells of the input.
```
Jκι¿⁼KKO«
```
If the current cell is an `O`, then:
```
≔⟦ω⟧θWθ«
```
Start a depth-first search of the board.
```
≔Φurdl№⪪α¹⊟KD²✳μλ
```
Find `O`s and already placed dominoes in adjacent cells.
```
¿λ«
```
If there is at least one `O` or domino, then:
```
≔§λ⁰λ
```
Choose the first direction.
```
✳λλ
```
Overwrite the current cell with that direction, and move in that direction.
```
≔KKη
```
Grab the adjacent cell.
```
P§dlur⌕urdlλ
```
Overwrite it with the reverse direction, creating a domino.
```
¿⁼ηO≔⟦⟧θ«
```
If this was an `O`, then we successfully placed a domino, so terminate the search.
```
M✳η⊞θη⊞θKK»»
```
Otherwise we just rotated a domino, so move to where its other end used to be, and save its direction.
```
«≔⊟θλ✳λ↧λ✳KK↧⊟θ
```
If there were no valid moves, then rotate the last domino on the stack back and back up to the previous position.
```
»»UMKA↥λ
```
After successfully placing a domino, uppercase all the dominoes. This allows them to participate in rotations for the next pair of `O`s. (Sadly `MapAssign(Uppercase, PeekAll());` doesn't work.
Example: Consider the following grid:
```
OOOO
O..O
```
The first `O` is readily covered with an `rl` domino, resulting in this:
```
rlOO
O..O
```
Another `rl` domino is then placed, resulting in this:
```
RLrl
O..O
```
The next `O` doesn't have an adjacent `O`, but there is an adjacent domino, so we try rotating it:
```
dORL
u..O
```
We still don't have an adjacent `O`, but there is now another domino that we can rotate (180° around the `R`):
```
drlO
u..O
```
Finally we can place a domino to cover the now adjacent `O`s:
```
drld
u..u
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 129 bytes
```
f=(g,p=d=>(n=2,v=g.map((r,i)=>r.map((c,j)=>c*n&&(n>1?~(y=i+d,x=j+!d):i==y&j==x)?!n--:c)),n?n>1:f(v)))=>g in f?f[g]:f[g]=p(0)|p(1)
```
[Try it online!](https://tio.run/##rVZbU9w2FH7XrzjMZMAuxgFC2pSMYWgobXrJtg156AAzaG3ZK2JLrqTdZQv0r9MjyVc2PLVzdrWy9twvn3VDF1SnitdmZ/Hm8TFPgiKqkyw5CkSyHy2SIq5oHQQq4mFypPxDGt3gQ/qV2NwMxNHe8T/BKuHbWXSb3GxvZOEhT5LV5k2S3IbHG2Jn5zANw0gcI@dhHizCEGUL4ALy4/yiuDq0S1IHu@F9HeyFj6kU2kBKNdPnas4ggWsyAbgH2HPr@YxrwI@ZMTCKLzgtHfchjNgoaC6KkkEmKy4klJRnsGDK8JSW5YqQGCYQI1nmGPa7vdOfUgFTBqli1LAMltzM0KBiDG148pb24RWS3XszTNvArO2qRts1NYYpQbyluBFq9@SJMqtu3@1PWgWKpYaKYl5SBYXi3pORmLV/gGT3bMEEcmToLMbAqOblCgwv2RfkXiN9jWT3M6n431IYm5gdl6g2mtbF3kG7O5Nz1QfsBBTNuMurDbX1LHb8ZOisd9Vnf9Jlf89lxe5PW62ZBCENCIbOG4mfeTprlHtOW7FXzZ6KzPWDS1FFV5DaaLASrKrN6lmxlJWlBlpKUaAKYFnB@r6YdNR6@bM7/wPpI9KH5vwE9nZv93bBsKZtrTeklYwHq@X@hFp@ciev3dpqkYKBzIEbDVqWc8NxCjq//dqn8RM@9UreIf3e57m13BfiHL5DOmiy/A1@G/Y@zOEwnLvdgesOz@6adcw8zEvcjEEMb5BOPftzCXiP5IftW7eePtU@DtWe/@CeLPv3SL/07GOXena7nsAZUuzZx17HnfZfkWL4EenEnf@GhOzXbwkZwNAZLfUQh/6Uc9@X1ECJU2bALCXINJ3XHE99V2HP5twgFPg5IWTytMOpYqD/muOPhhvJBYpOV64JdeR6P5VKMKWJD4401t8bO9y0XNIVgk1VS635FKECDXq4QpsN7njcws6WWdZIi3k1Zcq2Wmva8XTzPulwqU3pB4kTZdUhTCxhhbGXOGB22nKuMPacLTvxiAxrN0pPa85G3TivWU2VxVfSdyshw95qsR4BteTFzCCcVRIVpBLREYHcYjNiusZpsSFZp@hULhiZdEUe6Bs4R0j8ZFhap9txZrfUIXA31msd3SaI9AM6ngznfVsKV7NKorK2YiReU@cVstuU1Zi1GTUupKk0RlY7Jcvbnhh5PyxWg3vaFp0qha8OVjFhYDnjqX0pkLizFY/CHjdSRT@ztcaYPMEKFySZjALoskLGYNFVo490mCuyFlBfDkzgTJaysO9tj6@5VNgR6YxpPZVUZWRd1BegxlQYbsG9LPAVZ2ZV/AXeyVPsHNrvOrDU0g/WujPPClOY0vSzUbj8Fy/@n2MLajZzgUe2CwdtETZbjXcMll3ZAbq46O5dEV6u5uwqahgdBkaQ25@rqxDuCMBAm@X5aByuOPZY43yaYOtSXIqt0LO77kRe95JOWpEY73BVEPYCW6G7ZJYIiJAcwUUcx3YfK1aXNGXBS7i/vI@3XxYRbG2FV47ZQq5l9r9JAlsTtPp2YBShZ14aNJsH1n7zH88haP7ZSLpUhFArbJzg@sWd//MBgqXCS0LoQnaXzUvx4m4cwcOluG7UMvu@WNeBs2vvc6FneyAPj/8C "JavaScript (V8) – Try It Online")
Receives the input as a 2-dimensional array of booleans and returns 0 for false or 1 for true.
## Explanation
Solves the problem recursively calling itself with a single domino removed from the grid. If it is called with an empty grid (which will happen if the initial grid only contained valid domino positions) then it returns true. At each call it tries removing the top-left position containing a domino, calling itself with either the horizontal or vertical orientation removed.
```
f=(g,
// p = function to remove the top-left domino and recurse if the remove succeeded
p=d=>(
// n = squares remaining for removal
n=2,
// v = grid after removal
v=g.map((r,i)=>r.map((c,j)=>c*n&&(n>1?~(y=i+d,x=j+!d):i==y&j==x)?!n--:c)),
// if n=2 the grid was empty so we return true, if n=1 we could not remove the domino
// if n=0 the domino was successfully removed and we recurse
n?n>1:f(v))
// try removing the top-left square with a horizontal or vertical domino
// and cache results
)=>g in f?f[g]:f[g]=p(0)|p(1)
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 103 bytes
```
a=>a.reduce((p,v)=>p.map(u=>u&~v||(S=(m,i)=>m<i?q[m]=m:S(m,i+i,~m&i||S(m-i,i)))(v-u,3),q=[])&&q,[0])[0]
```
[Try it online!](https://tio.run/##lVZJc9s2FL7jV7yTRU1leE9dt3LGrZPWaWumtXPoOJ4JREISEpKgAVBLR5O/7j4ABBc5OnSeBEHg25cP/MwWTCdKlGZ/cf48HT@z8SWjiqdVwqOoHC2G48uS5qyMqvFltfd1sdlEd@MoHwl8kP8kXj895I/j/OLOHn0nRl/zPbHZ4L99gSzDYbTYr0Ynw9HT@OFxuLf3NHo4fBzi99lwbRKmuYYxfCIxwAbgyK33c6EBP2bOwSixECwDy3kBPTYGWhSzjEMqc1FIyJhIYcGVEQnLsjUhFGKgSJaZwnGzd/oTVsCEQ6I4MzyFpTBzNKg4RxuevKVjOEGye28G/RWFs52XaLtkxnBVEG@J1kJhT7aUWXXHbn8VFCieGFbMqowpmCnhPemJWfunSHbPF7xAjhSdxRg40yJbgxEZ/4bcGdIrJLufSyX@lYWxidl3iQrRBBdbB@3uraxUG7ATUCwVLq821OAZdfyk66x31Wc/brJ/5LJi99dBayqhkAYKjs4biZ8qmdfKPaet2Em9Z0Xq@sGlKGdrSGw0WAmel2a9UyzhWaaBZbKYoQrg6Yy3fRE3FLz83Z3/jXSHdFufX8HR4eroEGzHuka03pAgSTur5f6AWt65kzO3Bi2y4CCnIIwGLbPKCFnoxm@/tmn8gP9aJb8g/dXmOVhuC3EPPyOd1ln@Hr81extmdxju3e7UdYdnd83aZ@7mhdZjQOEc6dqz70rADZIfth/cer2tvR@qPf/V/bPsb5D@aNn7LrXsdr2Ct0jUs/e9po32P5Eo/IZ05c7fI/m5tE//kZXvP2Ygw2kyYJYSZJJUpcBT3z3Ym1NhcOT9PBASb3cyUxz0U4U/Gj5LUaDoZO2aTY9cjydSFVxp4oMI1m@MHWKWLdkaQSUvpdZigpCABj0soc0aXzw@YQfLNK2liyqfcGVbKph2PM1cxw3@hNTdSpwcqw7hYAlrjD3DQbJTNRUKY5/yZSM@It0a9dITzNmoa@c1L5myOErariSk20MB0xE4MzGbG4StXKKCRCIKImBbDEbs1jgVNiTrFJvIBSdxU8yOvo5zhNCtoQhOh7HlK@aQthnfF50bEkTaQexPgPM@lMLVLJeoLFSM0BfqvEK@SniJWZsz40KaSGNkvp/xaeiJnvfdYtX4pm3RmVJ4RfCcFwaWc5FY8Ce0sUV7YfcbKWdf@IvGiLcwwQVJ4l4ATVZIHxSaarSRdnNFXgQU/HqP0Ri8stB7O1feqUnGki9wYKMynLwUrFFcZlLhNSQwlmTOtZ5IpuwVRrEyXH1LsO5b7LCzw9pKfRfgRXJ67g36o53SAQcs1NTvGEuBntdNn2B7qt2mOyacUdZxg8Kd3ClpBxPfTixuTK05022@3i2/LRlKTHdw/M/jT1TjbJpo8LH4WAyG7iVwBeNLWFF8LcujYfu8fprZp7cOmCgiguY3hYmywLYZ2Bc/ZDTJPDp4oPHjwczLLawcLmMYxAN4jbfYBRwOqcXSaDAYjuAY3yR/JKR5Z6RTqd5gK0XGSpYKWyuaRga5nv8D "JavaScript (V8) – Try It Online")
Input array of binaries, output `0` to accept, `undefined` to reject. It can be convert to truthy / falsy by +2 bytes (append `+1`), but I believe returning two distinct constant values may be acceptable.
```
// We use 1 to denote occupied cells, while 0 for empty cells
// And convert above binary as a single number to represent the row
// So `0b1100010` is as same as `OO...O.`
// And specially, `0` is used for an empty row
a=> // input matrix as described above
a.reduce( // for each row
(p, // p is an array of rows
// `1` is used if some cells on last row need to be filled with
// vertical dominoes cross last row and this row
// `0` is used if some cells is empty or already filled with
// dominoes used before
// `p` store value `n` with index `n`
// or in other words `p[n]` will always equals `n`
// `p[m]` will be a hole of array if some value `m` is not
// presented in `p`
v // current row
)=>p.map(
u=> // one possible pattern while unfilled last row
u&~v|| // if you can use vertical dominoes to fill unfilled
// cells on last row, you need to fill these cells
// and check if there are some horizontal dominoes
// may be used in following recursive function
// if you cannot fell these cells
// you do not ever need to search
(S=(
m, // unfilled cells on current row
i // a horizontal dominoes
)=>
m<i? // if this horizontal domino already moved out the
// boundary of current row, we stop search
q[m]=m: // store current unfilled cells pattern to `q` the
// variable will be used for next iteration
S(m,i+i, // move the horizontal domino a cell left
// and have it a try by recursion
~m&i|| // if current domino may be placed (if cells under
// current domino are occupied)
S(m-i,i) // fill these cells and search recursively
))(
v-u, // fill last row by vertical dominoes and see what left
3 // a horizontal domino placed on right most
),
q=[] // possible patterns left after current row
)&&q,
[0] // nothing is required to be filled before first row
// so `0` is a valid pattern here
)[0] // check if everything may be just filled
```
For matrix with \$p\cdot q\$ size, its time complexity seems to be \$O\left(\left(\sqrt{5}+1\right)^{p}\cdot q\right)\$.
[Answer]
# [Wolfram Language](https://www.wolfram.com/language/), 82 bytes
```
(v=Join@@Position[#,1])==Sort[List@@Join@@FindEdgeCover@Subgraph[GridGraph@#2,v]]&
```
[Try it online!](https://tio.run/##XYzNCsIwEITvfQqhIAp7Se01EBAtiIdCjyGEaP/20ETS2Evx2WPaomh3YBmGb6ZTrq065fCufE39bqAXg5qx3PTo0GgeAxF7SgtjHb9i7xhbgDPq8lQ21dEMlWXF89ZY9Wh5ZrHMJsfiBAYhtj63qB2v@UiAvGBMwhci@qYSCMigaPO5wM36TSZChnYKh7/2QsoVu26vmYUg814a9vwb "Wolfram Language (Mathematica) – Try It Online")
Takes two inputs: an array where 1 represents an occupied cell (unoccupied may be anything else), and a list of the width followed by the height.
This answer takes a graph theory approach using built-in language features. The core of my method is generating a [minimum edge cover](https://en.wikipedia.org/wiki/Edge_cover) over a graph representing the occupied spaces (placing the dominoes) and checking whether any vertices are repeated (seeing whether any dominoes overlap).
Part-by-part rundown:
```
(v=Join@@Position[#,1]) (*generate list of vertices*)
== (*check if equal to*)
Sort[List@@Join@@ (*the sorted list of vertices from*)
FindEdgeCover@ (*a minimal edge cover of*)
Subgraph[GridGraph@#2,v] (*the graph, generated as a subgraph of a grid graph*)
]&
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~94~~ 82 bytes
12 bytes saved thanks to Dingus!
```
f=->s{n=s=~/O/
n&&[0,s=~/,/].all?{|i|t=s+?.*i;t[j=i-~n]>?.?(t[n]=t[j]=?.;f[t]):1}}
```
[Try it online!](https://tio.run/##XVDLboMwELzzFYhDlLSbob02cvgEfwDyIZGCSkUpis0hyuPX6dprE1rLsnfHs@udOY/HyzQ1aru3115Z9Sh1mfWrVf1GPqHS4NB11fXW3pyyrxVe2p2rv1S7ffRmX6Fau7o3iiGjKuya2pnNx/v9Pg2js3kx/FjbHrsT5c2hs5d87a/TpsiyIW/qQpOmwuSSQAOkeREHYDxyAjIfC5h5AZwxaA0PxuMJA75Wh/YIqVB4p8ba5@FrCUEx@lcmrUIZkNgUidCih5fob7@fDrjz6D7ZAr6XDsyCuPciI/EmieUn@VPjjwdBR1AAISy8SHOm6SEjR01IoHQWNhOSKkqmIHoVcIqmhDIgGRRET78 "Ruby – Try It Online")
A recursive function taking input as a comma separated string (this saves one byte over a newline separated string.) A terminating comma is required, at least for single line input, to enable the function to determine the width of the rectangle.
Works by finding the first available `O` and checking if another `O` exists to the right or below. If so, both are deleted and the function calls itself to try to eliminate all remaining `O`s
Returns `false` if a solution is possible and `true` if not.
**Commented code**
```
f=->s{n=s=~/O/ #n=index of first O. If there are none, return nil (board is blank)
n&& #if an O was found, look for another O to the right and below it
[0,s=~/,/].all?{|i| #iterate twice, 0+1 is offset for second O to right, (s=~/,/ the index of the first comma)+1 is offset for second O below
t=s+?.*i #make a copy of argument s, with some additional .'s added to the end of it to ensure check for an O below doesn't go out of bounds.
t[j=i-~n]>?. ? #if a second O (any ASCII character after ".") is found (to the right or below the first)... [Note: i-~n = i+1+n]
(t[n]=t[j]=?.;f[t]):1 #...overwrite both of them with .'s and then call the function recursively to eliminate the remaining O's.
} #otherwise return 1 (truthy) to indicate it was not possible to match an entire domino in this direction
} #return n&& [0,s=~/,/].all?{...} (n false if already solved, loop false if a solution found by deleting domino in either vertical or horizontal direction.
```
] |
[Question]
[
This is a [fewest-operations](/questions/tagged/fewest-operations "show questions tagged 'fewest-operations'") challenge where the objective is to sort a vector into ascending order using the fewest reversals. Your algorithm can only sort the vector using "sub-vector reversals"1, but it can use other operations for arithmetic operations, loops, checking if it's sorted etc. **The number of sub-vector reversals your algorithm performs is its score.**
---
1**A "sub-vector reversal":**
* Select a range of numbers in the vector, and reverse the elements in that range.
To give a simple example, if you start with the vector `{4,3,2,1}`, then you can sort it in a lot of different ways:
1. Reverse the entire vector. This is obviously the shortest approach as it only requires one reversal: `{4,3,2,1} -> {1,2,3,4}`
2. You can do a version of the bubble sort, which requires 6 reversals: `{4,3,2,1} -> {3,4,2,1} -> {3,2,4,1} -> {2,3,4,1} -> {2,3,1,4} -> {2,1,3,4} -> {1,2,3,4}`
3. You can start with the first 3 elements, then the three last, and finally the two first and the two last, which requires 4 swaps: `{4,3,2,1} -> {2,3,4,1} -> {2,1,4,3} -> {1,2,4,3} -> {1,2,3,4}`
4. ... and so on. There are an infinite amount of options available (you may repeat any operation if you like).
---
**Rules and requirements:**
* Your code must finish in less than one minute for a list with 100 numbers. You may time this yourself, but please play fair2.
* You must store the start and end indices of all swaps you perform, so that the solution might be verified. (I'll explain what this means below).
* The code must be deterministic.
* You can take the input on any format you want: Numeric vector, linked-list, array with length ... whatever you like.
* You can do whatever you like on a *copy* of the vector. That includes attempting different reversals and check which is most efficient. Brute-forcing is perfectly fine, but stick to the time limit.
* The score is the total number of flips for the 5 test vectors. Tie-breaker will the date stamp.
---
**Example:**
```
4 1 23 21 49 2 7 9 2 | Initial vector / list
4 1 **2 9 7 2 49 21 23** | (2, 8) (flipped the elements between indices 2 and 8)
4 1 2 **2 7 9** 49 21 23 | (3, 5)
4 1 2 2 7 9 **23 21 49** | (6, 8)
4 1 2 2 7 9 **21 23** 49 | (6, 7)
**2 2 1 4** 7 9 21 23 49 | (0, 3)
**1 2 2** 4 7 9 21 23 49 | (0, 2)
```
The score would be 6, since you performed 6 reversals. You must store (not print) the indices listed on the right side on a suitable format that can easily be printed/outputted for verification purposes.
**Test vectors:**
```
133, 319, 80, 70, 194, 333, 65, 21, 345, 142, 82, 491, 92, 167, 281, 386, 48, 101, 394, 130, 111, 139, 214, 337, 180, 24, 443, 35, 376, 13, 166, 59, 452, 429, 406, 256, 133, 435, 446, 304, 350, 364, 447, 471, 236, 177, 317, 342, 294, 146, 280, 32, 135, 399, 78, 251, 467, 305, 366, 309, 162, 473, 27, 67, 305, 497, 112, 399, 103, 178, 386, 343, 33, 134, 480, 147, 466, 244, 370, 140, 227, 292, 28, 357, 156, 367, 157, 60, 214, 280, 153, 445, 301, 108, 77, 404, 496, 3, 226, 37
468, 494, 294, 42, 19, 23, 201, 47, 165, 118, 414, 371, 163, 430, 295, 333, 147, 336, 403, 490, 370, 128, 261, 91, 173, 339, 40, 54, 331, 236, 255, 33, 237, 272, 193, 91, 232, 452, 79, 435, 160, 328, 47, 179, 162, 239, 315, 73, 160, 266, 83, 451, 317, 255, 491, 70, 18, 275, 339, 298, 117, 145, 17, 178, 232, 59, 109, 271, 301, 437, 63, 103, 130, 15, 265, 281, 365, 444, 180, 257, 99, 248, 378, 158, 210, 466, 404, 263, 29, 117, 417, 357, 44, 495, 303, 428, 146, 215, 164, 99
132, 167, 361, 145, 36, 56, 343, 330, 14, 412, 345, 263, 306, 462, 101, 453, 364, 389, 432, 32, 200, 76, 268, 291, 35, 13, 448, 188, 11, 235, 184, 439, 175, 159, 360, 46, 193, 440, 334, 128, 346, 192, 263, 466, 175, 407, 340, 393, 231, 472, 122, 254, 451, 485, 257, 67, 200, 135, 132, 421, 205, 398, 251, 286, 292, 488, 480, 56, 284, 484, 157, 264, 459, 6, 289, 311, 116, 138, 92, 21, 307, 172, 352, 199, 55, 38, 427, 214, 233, 404, 330, 105, 223, 495, 334, 169, 168, 444, 268, 248
367, 334, 296, 59, 18, 193, 118, 10, 276, 180, 242, 115, 233, 40, 225, 244, 147, 439, 297, 115, 354, 248, 89, 423, 47, 458, 64, 33, 463, 142, 5, 13, 89, 282, 186, 12, 70, 289, 385, 289, 274, 136, 39, 424, 174, 186, 489, 73, 296, 39, 445, 308, 451, 384, 451, 446, 282, 419, 479, 220, 35, 419, 161, 14, 42, 321, 202, 30, 32, 162, 444, 215, 218, 102, 140, 473, 500, 480, 402, 1, 1, 79, 50, 54, 111, 189, 147, 352, 61, 460, 196, 77, 315, 304, 385, 275, 65, 145, 434, 39
311, 202, 126, 494, 321, 330, 290, 28, 400, 84, 6, 160, 432, 308, 469, 459, 80, 48, 292, 229, 191, 240, 491, 231, 286, 413, 170, 486, 59, 54, 36, 334, 135, 39, 393, 201, 127, 95, 456, 497, 429, 139, 81, 293, 359, 477, 404, 129, 129, 297, 298, 495, 424, 446, 57, 296, 10, 269, 350, 337, 39, 386, 142, 327, 22, 352, 421, 32, 171, 452, 2, 484, 337, 359, 444, 246, 174, 23, 115, 102, 427, 439, 71, 478, 89, 225, 7, 118, 453, 350, 109, 277, 338, 474, 405, 380, 256, 228, 277, 3
```
I'm fairly certain that finding an optimal solution is NP-hard (since regular pancake sorting is).
2Yes, people with very fast computers might have a benefit, due to the time limit of one minute. After much discussion I've figured it's best if everyone does their own benchmarking, it's not a fastest code challenge.
[Answer]
## Java, genetic-ish algorithm, 80+81+79+78+80=398 (previously ~~418~~)
After trying a bunch of different ideas and mostly failing, I settled on this algorithm: start with the input array, try all possible reversals and keep a certain number of results with the smallest number of runs, then do the same for those results, until we get a sorted array.
By "runs" I mean maximal subarrays that appear exactly or reversed in the sorted array. Basically they are maximal sorted subarrays, but in case of repeated elements, the number of elements in the middle should match. E.g. if the sorted array is `2, 2, 3, 3, 4, 4` then `4, 3, 3, 2` is a run but `2, 2, 3, 4` is not (and neither is `2, 3, 2`).
In this version I optimized the algorithm to reverse only at run boundaries and only if a reversed run can be joined with a newly-adjacent run. Also, the runs are adjusted and joined at each step, to avoid recalculating them from the modified array. This allowed me to increase the "population size" from 30 to about 3000, and to run multiple simulations at various sizes.
```
import java.io.*;
import java.util.*;
public class SubReversal {
static int n;
static int[] a;
static int[] srt;
static List<int[]> rev;
static Map<Integer, Integer> idx;
static Map<Integer, Integer> count;
static final int NB = 2000;
static State[] best = new State[NB + 1];
static int ns;
static class Run {
int start;
int end;
int dir;
int nstart = 1;
int nend = 1;
Run(final int start) {
this.start = start;
}
Run(final Run r) {
start = r.start;
end = r.end;
dir = r.dir;
nstart = r.nstart;
nend = r.nend;
}
Run copy() {
return new Run(this);
}
Run reverse() {
int t = start;
start = end;
end = t;
t = nstart;
nstart = nend;
nend = t;
dir = -dir;
return this;
}
boolean canJoin(final Run r) {
if (dir * r.dir == -1) {
return false;
}
final int t = idx.get(a[r.start]) - idx.get(a[end]);
if (Math.abs(t) > 1) {
return false;
}
if (t != 0 && dir + r.dir != 0 && t != dir && t != r.dir) {
return false;
}
if (t == 0) {
if (dir * r.dir == 0) {
return true;
}
return nend + r.nstart == count.get(a[end]);
}
return (dir == 0 || nend == count.get(a[end])) && (r.dir == 0 || r.nstart == count.get(a[r.start]));
}
Run join(final Run r) {
if (a[start] == a[r.start]) {
nstart += r.nstart;
}
if (a[end] == a[r.end]) {
nend += r.nend;
}
else {
nend = r.nend;
}
end = r.end;
if (dir == 0) {
dir = r.dir;
}
if (dir == 0 && a[start] != a[end]) {
dir = idx.get(a[end]) - idx.get(a[start]);
}
return this;
}
@Override
public String toString() {
return start + "(" + nstart + ") - " + end + '(' + nend + "): " + dir;
}
}
static class State implements Comparable<State> {
int[] b;
int[] rv;
State p;
List<Run> runs;
public State(final int[] b, final int[] rv, final State p, final List<Run> runs) {
this.b = Arrays.copyOf(b, b.length);
this.rv = rv;
this.p = p;
this.runs = runs;
}
@Override
public int compareTo(final State o) {
return runs.size() - o.runs.size();
}
@Override
public String toString() {
return Arrays.toString(b) + " - " + Arrays.toString(rv) + " - " + runs.size();
}
int getCount() {
return p == null ? 0 : p.getCount() + 1;
}
}
static void reverse(int x, int y) {
while (x < y) {
int t = a[x];
a[x] = a[y];
a[y] = t;
x++;
y--;
}
}
static List<Run> runs() {
final List<Run> l = new ArrayList<>();
Run run = new Run(0);
for (int i = 1; i < n; ++i) {
final int t = idx.get(a[i]) - idx.get(a[i - 1]);
if (Math.abs(t) > 1) {
run.end = i - 1;
l.add(run);
run = new Run(i);
}
else if (t == 0) {
run.nend++;
if (run.dir == 0) {
run.nstart++;
}
}
else {
if (run.dir == 0) {
run.dir = t;
}
else if (run.dir != t || run.nend != count.get(a[i - 1])) {
run.end = i - 1;
l.add(run);
run = new Run(i);
}
run.nend = 1;
}
}
run.end = n - 1;
l.add(run);
return l;
}
static void show() {
if (!Arrays.equals(a, srt)) {
System.out.println("bug!");
System.out.println(Arrays.toString(a));
throw new RuntimeException();
}
System.out.println("Sorted: " + Arrays.toString(a));
System.out.println(rev.size() + " reversal(s):");
for (int[] x : rev) {
System.out.println(Arrays.toString(x));
}
}
static void sort() {
State bestest = null;
final int[] a1 = Arrays.copyOf(a, n);
final int[] sizes = {10, 20, 30, 50, 100, 200, 300, 500, 1000, 2000};
for (int nb : sizes) {
System.arraycopy(a1, 0, a, 0, n);
ns = 1;
best[0] = new State(a, null, null, runs());
while (best[0].runs.size() > 1) {
final State[] s = Arrays.copyOf(best, ns);
ns = 0;
for (State x : s) {
System.arraycopy(x.b, 0, a, 0, n);
final int m = x.runs.size();
for (int i = 0; i < m; ++i) {
for (int j = i; j < m; ++j) {
boolean b = false;
if (i > 0) {
final Run r = x.runs.get(j);
r.reverse();
b = x.runs.get(i - 1).canJoin(r);
r.reverse();
}
if (!b && j < m - 1) {
final Run r = x.runs.get(i);
r.reverse();
b = r.canJoin(x.runs.get(j + 1));
r.reverse();
}
if (!b) {
continue;
}
final List<Run> l = new ArrayList<>(x.runs);
final int rstart = l.get(i).start;
final int rend = l.get(j).end;
final int t = rstart + rend;
reverse(rstart, rend);
for (int k = i; k <= j; ++k) {
final Run r = x.runs.get(i + j - k).copy().reverse();
r.start = t - r.start;
r.end = t - r.end;
l.set(k, r);
}
if (j < m - 1 && l.get(j).canJoin(l.get(j + 1))) {
l.get(j).join(l.get(j + 1));
l.remove(j + 1);
}
if (i > 0 && l.get(i - 1).canJoin(l.get(i))) {
l.set(i - 1, l.get(i - 1).copy().join(l.get(i)));
l.remove(i);
}
if (ns < nb || l.size() < best[ns - 1].runs.size()) {
best[ns++] = new State(a, new int[]{rstart, rend}, x, l);
Arrays.sort(best, 0, ns);
if (ns > nb) {
ns = nb;
}
}
reverse(rstart, rend);
}
}
}
if (ns == 0) {
for (State x : s) {
System.arraycopy(x.b, 0, a, 0, n);
final List<Run> l = new ArrayList<>(x.runs);
final int rstart = l.get(0).start;
final int rend = l.get(0).end;
final int t = rstart + rend;
reverse(rstart, rend);
final Run r = x.runs.get(0).copy().reverse();
r.start = t - r.start;
r.end = t - r.end;
l.set(0, r);
best[ns++] = new State(a, new int[]{rstart, rend}, x, l);
reverse(rstart, rend);
}
Arrays.sort(best, 0, ns);
}
}
State r = null;
for (int i = 0; i < ns; ++i) {
if (Arrays.equals(best[i].b, srt)) {
r = best[i];
break;
}
}
if (r == null) {
final State x = best[0];
System.arraycopy(x.b, 0, a, 0, n);
reverse(0, n - 1);
r = new State(a, new int[]{0, n - 1}, x, runs());
}
if (!Arrays.equals(r.b, srt)) {
throw new RuntimeException("bug");
}
if (bestest == null || r.getCount() < bestest.getCount()) {
bestest = r;
}
}
while (bestest.p != null) {
rev.add(bestest.rv);
bestest = bestest.p;
}
Collections.reverse(rev);
a = a1;
for (int[] x : rev) {
reverse(x[0], x[1]);
}
if (!Arrays.equals(a, srt)) {
throw new RuntimeException("bug");
}
}
static void init(final String s) {
final String[] b = s.split(s.contains(",") ? "," : " ");
n = b.length;
a = new int[n];
count = new HashMap<>();
for (int i = 0; i < n; ++i) {
a[i] = Integer.parseInt(b[i].trim());
final Integer x = count.get(a[i]);
count.put(a[i], x == null ? 1 : x + 1);
}
srt = Arrays.copyOf(a, n);
Arrays.sort(srt);
idx = new HashMap<>();
int j = 0;
for (int i = 0; i < n; ++i) {
if (i == 0 || srt[i] != srt[i - 1]) {
idx.put(srt[i], j++);
}
}
rev = new ArrayList<>();
}
static void test5() {
final String[] t = {"133, 319, 80, 70, 194, 333, 65, 21, 345, 142, 82, 491, 92, 167, 281, 386, 48, 101, 394, 130, 111, 139, 214, 337, 180, 24, 443, 35, 376, 13, 166, 59, 452, 429, 406, 256, 133, 435, 446, 304, 350, 364, 447, 471, 236, 177, 317, 342, 294, 146, 280, 32, 135, 399, 78, 251, 467, 305, 366, 309, 162, 473, 27, 67, 305, 497, 112, 399, 103, 178, 386, 343, 33, 134, 480, 147, 466, 244, 370, 140, 227, 292, 28, 357, 156, 367, 157, 60, 214, 280, 153, 445, 301, 108, 77, 404, 496, 3, 226, 37",
"468, 494, 294, 42, 19, 23, 201, 47, 165, 118, 414, 371, 163, 430, 295, 333, 147, 336, 403, 490, 370, 128, 261, 91, 173, 339, 40, 54, 331, 236, 255, 33, 237, 272, 193, 91, 232, 452, 79, 435, 160, 328, 47, 179, 162, 239, 315, 73, 160, 266, 83, 451, 317, 255, 491, 70, 18, 275, 339, 298, 117, 145, 17, 178, 232, 59, 109, 271, 301, 437, 63, 103, 130, 15, 265, 281, 365, 444, 180, 257, 99, 248, 378, 158, 210, 466, 404, 263, 29, 117, 417, 357, 44, 495, 303, 428, 146, 215, 164, 99",
"132, 167, 361, 145, 36, 56, 343, 330, 14, 412, 345, 263, 306, 462, 101, 453, 364, 389, 432, 32, 200, 76, 268, 291, 35, 13, 448, 188, 11, 235, 184, 439, 175, 159, 360, 46, 193, 440, 334, 128, 346, 192, 263, 466, 175, 407, 340, 393, 231, 472, 122, 254, 451, 485, 257, 67, 200, 135, 132, 421, 205, 398, 251, 286, 292, 488, 480, 56, 284, 484, 157, 264, 459, 6, 289, 311, 116, 138, 92, 21, 307, 172, 352, 199, 55, 38, 427, 214, 233, 404, 330, 105, 223, 495, 334, 169, 168, 444, 268, 248",
"367, 334, 296, 59, 18, 193, 118, 10, 276, 180, 242, 115, 233, 40, 225, 244, 147, 439, 297, 115, 354, 248, 89, 423, 47, 458, 64, 33, 463, 142, 5, 13, 89, 282, 186, 12, 70, 289, 385, 289, 274, 136, 39, 424, 174, 186, 489, 73, 296, 39, 445, 308, 451, 384, 451, 446, 282, 419, 479, 220, 35, 419, 161, 14, 42, 321, 202, 30, 32, 162, 444, 215, 218, 102, 140, 473, 500, 480, 402, 1, 1, 79, 50, 54, 111, 189, 147, 352, 61, 460, 196, 77, 315, 304, 385, 275, 65, 145, 434, 39",
"311, 202, 126, 494, 321, 330, 290, 28, 400, 84, 6, 160, 432, 308, 469, 459, 80, 48, 292, 229, 191, 240, 491, 231, 286, 413, 170, 486, 59, 54, 36, 334, 135, 39, 393, 201, 127, 95, 456, 497, 429, 139, 81, 293, 359, 477, 404, 129, 129, 297, 298, 495, 424, 446, 57, 296, 10, 269, 350, 337, 39, 386, 142, 327, 22, 352, 421, 32, 171, 452, 2, 484, 337, 359, 444, 246, 174, 23, 115, 102, 427, 439, 71, 478, 89, 225, 7, 118, 453, 350, 109, 277, 338, 474, 405, 380, 256, 228, 277, 3"};
int r = 0;
for (String s : t) {
init(s);
sort();
System.out.println(rev.size());
r += rev.size();
}
System.out.println("total: " + r);
}
public static void main(final String... args) throws IOException {
System.out.print("Input: ");
final BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
final String s = br.readLine();
final long t = System.currentTimeMillis();
if (s.isEmpty()) {
System.out.println("Running tests");
test5();
}
else {
init(s);
sort();
show();
}
System.out.println("Time: " + (System.currentTimeMillis() - t + 500) / 1000 + " sec");
}
}
```
Input is a list of numbers separated by comma and/or space (from stdin). If the input is empty, the program runs the 5 tests. Each one takes about 40 sec here.
[Answer]
# One move brute-force then selection sort (also naive solution), 90 + 89 + 88 + 87 + 89 = 443 moves
```
let doReverse = (a, l, r) => {
a.splice(l, r - l, ...a.slice(l, r).reverse());
};
let selectSubVectorReverseSort = a => {
let log = [];
for (let i = 0, l = a.length; i < l; i++) {
let j, p = i;
for (j = i; j < l; j++) {
if (a[j] < a[p]) p = j;
}
if (p === i) continue;
log.push([i, p + 1]);
doReverse(a, i, p + 1);
}
return log;
};
let a = JSON.parse(`[${readline()}]`);
let copiedArray = a => a.map(x => x);
let minLog = selectSubVectorReverseSort(copiedArray(a));
for (let i = 0, l = a.length; i < l; i++) {
for (let j = i + 1; j < l; j++) {
let b = copiedArray(a);
doReverse(b, i, j + 1);
let log = [[i, j + 1], ...selectSubVectorReverseSort(b)];
if (log.length < minLog.length) minLog = log;
}
}
print(minLog.length);
```
for every possible first move, try it, and then, do a selection sort.
Yes, this is another naive solution.
I'm not sure this should be an edit or another post, but it seems the solution is too simple, so editing is chosen.
---
# Selection Sort (Naive Solution), 92 + 93 + 95 + 93 + 96 = 469 moves
```
let log = [];
let doReverse = (a, l, r) => {
log.push([l, r]);
a.splice(l, r - l, ...a.slice(l, r).reverse());
}
let a = JSON.parse(`[${readline()}]`);
for (let i = 0, l = a.length; i < l; i++) {
let j, p = i;
for (j = i; j < l; j++) {
if (a[j] < a[p]) p = j;
}
if (p === i) continue;
doReverse(a, i, p + 1);
}
print(log.length)
```
A naive solution use selection sort.
There *MUST* be some better solutions, but post this since I did not find a better one (without brute-force search).
(Above code is [JavaScript Shell](https://developer.mozilla.org/en-US/docs/Mozilla/Projects/SpiderMonkey/Introduction_to_the_JavaScript_shell))
] |
[Question]
[
Write a program or function that takes a mathematical expression in Morse code as input, and returns the solution in Morse code.
Valid operations are plus: `+` and minus: `_` (underscore). You can assume you will only receive non-negative integer input, and that the result will be non-negative.
The expression will contain at least two terms, and maximum ten terms. There won't be two adjacent operators i.e. `.----+_-....`, and there won't be parentheses.
Digits are seperated by single spaces. You can choose to have the operators separated from the numbers by a single space on each side (see examples).
The Morse equivalent for the digits 0-9 are:
```
0 -----
1 .----
2 ..---
3 ...--
4 ....-
5 .....
6 -....
7 --...
8 ---..
9 ----.
```
**Examples:**
```
Input
Output
.----+.---- (1+1=2) Optional input: .---- + .----
..---
-...._...-- (6-3=3) Optional input: -.... _ ...--
...--
..---_...--+..--- (2-3+2=1)
1
..---+...--_....-+---.._..... (2+3-4+8-5=4)
....-
.---- ..---_-....+...-- ...-- (12-6+33=39)
...-- ----.
----. -----+----.+..--- ----._..... .....+---..+-...._.----+----.+----._..--- ----- (90+9+29-55+8+6-1+9+9-20=84)
---.. ....-
```
Standard rules regarding I/O formats etc. apply. A few trailing spaces, and a single newline are accepted. You can't split the number over several lines. You can't use `eval` or equivalent.
This is code golf, so the shortest code in bytes win.
[Answer]
# Retina, 132 bytes
A messy, first pass solution.
```
(-)+\.+
5$*.$#1$*.
(-|(\.))+ ?
$#2
\d+
$*
+`(1(_)1|(_1+)|_|\+)(.*)
$2$4$3
1+
$.0
\d
$*x5$*-
(x)+x{5}-*
$#1$*-xxxx
(\S{5})\S*
$1
x
.
```
[Try it online!](http://retina.tryitonline.net/#code=KC0pK1wuKwo1JCouJCMxJCouCigtfChcLikpKyA_CiQjMgpcZCsKJCoKK2AoMShfKTF8KF8xKyl8X3xcKykoLiopCiQyJDQkMwoxKwokLjAKXGQKJCp4NSQqLSAKKHgpK3h7NX0tKgokIzEkKi14eHh4CihcU3s1fSlcUyoKJDEKeAou&input=Li0tLS0rLi0tLS0KLi4tLS0KCi0uLi4uXy4uLi0tCi4uLi0tCgouLi0tLSsuLi4tLV8uLi4uLSstLS0uLl8uLi4uLgouLi4uLQoKLi0tLS0gLi4tLS1fLS4uLi4rLi4uLS0gLi4uLS0KLi4uLS0gLS0tLS4KCi0tLS0uIC0tLS0tKy0tLS0uKy4uLS0tIC0tLS0uXy4uLi4uIC4uLi4uKy0tLS4uKy0uLi4uXy4tLS0tKy0tLS0uKy0tLS0uXy4uLS0tIC0tLS0tCi0tLS4uIC4uLi4t)
[Answer]
## Pyth, ~~69~~ 63 bytes
```
J_.:s*R5"-.-"5jdm@Jsd`s*MC,mssdc`MKmxJdcz)"-1"+1mtyq\+@cz)dx_1K
```
[Try it here](http://pyth.herokuapp.com/?code=J_.%3As%2aR5%22-.-%225jdm%40Jsd%60s%2aMC%2Cmssdc%60MKmxJdcz%29%22-1%22%2B1mtyq%5C%2B%40cz%29dx_1K&input=.----+..---+_+-....+%2B+...--+...--&test_suite_input=.----+%2B+.----%0A-....+_+...--%0A..---+%2B+...--+_+....-+%2B+---..+_+.....%0A.----+..---+_+-....+%2B+...--+...--%0A----.+-----+%2B+----.+%2B+..---+----.+_+.....+.....+%2B+---..+%2B+-....+_+.----+%2B+----.+%2B+----.+_+..---+-----&debug=0)
[Or use a test suite](http://pyth.herokuapp.com/?code=J_.%3As%2aR5%22-.-%225jdm%40Jsd%60s%2aMC%2Cmssdc%60MKmxJdcz%29%22-1%22%2B1mtyq%5C%2B%40cz%29dx_1K&input=.----+..---+_+-....+%2B+...--+...--&test_suite=1&test_suite_input=.----+%2B+.----%0A-....+_+...--%0A..---+%2B+...--+_+....-+%2B+---..+_+.....%0A.----+..---+_+-....+%2B+...--+...--%0A----.+-----+%2B+----.+%2B+..---+----.+_+.....+.....+%2B+---..+%2B+-....+_+.----+%2B+----.+%2B+----.+_+..---+-----&debug=0)
Explanation
```
J_.:s*R5"-.-"5 - Construct the morse sequence 0-10
jd - Prettify output (join by spaces)
m@Jsd - Get the morse for each character in output
`s - Convert to a string
C,mssdc`MKmxJdcz)"-1" - Get the numbers
*M - Multiply the numbers by the operators
+1mtyq\+@cz)dx_1K - Turn `+` and `_` to +-1
```
Saved 6 bytes thanks to @Jakube!
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~75~~ ~~71~~ ~~69~~ 68 bytes
```
5:t!<t~v45+cXIO1Oj6ZC"@2#0)Iw!Xmfqb+wXK32=?10*}*+K?K9\6-O}V47-Y)Z{Zc
```
[**Try it online!**](http://matl.tryitonline.net/#code=NTp0ITx0fnY0NStjWElPMU9qNlpDIkAyIzApSXchWG1mcWIrd1hLMzI9PzEwKn0qK0s_SzlcNi1PfVY0Ny1ZKVp7WmM&input=LS0tLS4gLS0tLS0rLS0tLS4rLi4tLS0gLS0tLS5fLi4uLi4gLi4uLi4rLS0tLi4rLS4uLi5fLi0tLS0rLS0tLS4rLS0tLS5fLi4tLS0gLS0tLS0)
### General explanation
I use code format in the following so that indentation expresses the nesting of operations.
```
The input is split into chunks of 6 characters. The last chunk will have
5 characters padded by a 0 char.
A 0 is initially pushed. This will contain the accumulated global result.
Each operand (sequence of digits) is processed as follows. A "sign digit",
1 or -1, has been previously pushed according to whether the preceding
operator was + or - (for the first operand 1 is used as sign digit).
Then a 0 is pushed. This will contain the accumulated operand value.
Each digit of the operand is transformed into the a number `0`...`9` and
accumulated to the operand value, with successive multiplications by `10`.
When a + or - is detected, the current operand is finished. So it is
multiplied by its sign digit, and added to the acumulated global result.
A new sign digit is pushed (1 for +, -1 for -), and a new 0 is pushed
as initial accumulated operand value for the next operand.
When a 0 char is detected instead of + or -, this marks the end of the input.
The current global accumulated result is the definitive value. This is
tranformed into Morse digits and displayed.
```
### Detailed explanation
```
5:t!< % first half of the 10x5 array of Morse digits, with 0 for - and 1 for .
t~v % vertically concat second half, i.e. first half vertically flipped
45+cXI % transform 0 1 to chars - . Copy this "digit table" to clipboard I
O % push 0: initial value for accumulated global result
1 % push 1: sign digit for first operand
O % push 0: initial value of operand
j % input string
6ZC % arrange 6-length non-overlapping blocks as columns. Last is 0-padded
" % for each column
@ % push column
2#0) % split into last element and vector or remaining elements
I % push digit table
w! % swap and transposed into a row
Xmfq % index of that row in the digit table. Subtract 1: gives the digit
b+ % bubble up current operand value to top. Add to the new found digit
wXK % swap last char of column (+,-,space,0) to top. Copy to clipboard K
32= % is it space?
? % if so
10* % multiply by 10. The operand will continue with next digit
} % else: the operand is done
* % multiply by sign digit
+ % add this operand with its sign to accumulated global result
K % push last char of column again
? % if it's not 0
K9\6- % push 1 if it's a +, -1 if it's a -: sign digit of next operand
O % push 0 to initiallize accumulated operand value of next operand
} % else: it's a 0: we're done computing the result
V % convert result to string to get its digits
47-Y) % index the rows of the digit table that was initially pushed
Z{Zc % join rows by spaces
% end if, implicit
% end if, implicit
% end for each, implicit
% display, implicit
```
[Answer]
# Javascript (es6) 236 bytes
plenty of room for improvement
```
q=>(q.replace(/[.-]{5}/g,q=>(a=q.split`.`.length)&&q[4]=='-'?a-1:11-a).replace(/ /g,'').split(/([_+])/).reduce((l,o)=>l+(+o?(n=='_'?-(+o):+o):(n=o)&&0),0,n='')+[]).split``.map(u=>(((a='.....')+'-----').slice(5-u)+a).substr(0,5)).join` `
```
---
broken up
```
q=>
(
//grab each set of 5 dits/dahs
q.replace(/[.-]{5}/g,
//count dits
//if last digit is '-' return dits-1
//else return 11-dits
q=>(a=q.split`.`.length)&&q[4]=='-'?a-1:11-a)
//remove spaces and split on operators + and _
.replace(/ /g,'').split(/([_+])/)
//reduce the array into one element
//start with 0;
//when we come across a number add it to the total
//when we come across an operator change current op to it
.reduce((l,o)=>l+(+o?(n=='_'?-(+o):+o):(n=o)&&0),0,n='')
//cast to string
+[])
//turn to array
.split``
//turn each digit back to morse
.map(u=>(".....-----".slice(5-u)+'.....').substr(0,5)).join` `
```
*usage*
```
f=q=>(q.replace(/[.-]{5}/g,q=>(a=q.split`.`.length)&&q[4]=='-'?a-1:11-a).replace(/ /g,'').split(/([_+])/).reduce((l,o)=>l+(+o?(n=='_'?-(+o):+o):(n=o)&&0),0,n='')+[]).split``.map(u=>(((a='.....')+'-----').slice(5-u)+a).substr(0,5)).join` `
f("----. -----+----.+..--- ----._..... .....+---..+-...._.----+----.+----._..--- -----")
```
[Answer]
### Pure bash, ~~366~~ 317
```
a=----- p='v+=($a);a=${a/-/.}';q=${p/-?././-};. <(echo $p{,,,,} $q{,,,,});p(){
[ ${1:0:1} = . ]&&{ b=${1%%-*};o+=${#b};}||{ b=${1%%.*} o+=$[(5+${#b})%10];};}
s=${1//[-.]/};for i in ${1//[+_]/ };do p $i;t=${s:0:1};o+=${t// };s=${s:1};done
r=$[${o//_/-}];for ((i=0;i<${#r};i++));do w+=(${v[${r:i:1}]});done;echo ${w[@]}
```
Ok, I could save 10 bytes to reach **307** by written 1st line:
```
v=(----- .---- ..--- ...-- ....- ..... -.... --... ---.. ----.);p(){
```
instead of (but I like):
```
a=----- p='v+=($a);a=${a/-/.}';q=${p/-?././-};. <(echo $p{,,,,} $q{,,,,});p(){
```
Sample:
```
cat >/tmp/morseCalc.sh <<'eof'
#!/bin/bash
a=----- p='v+=($a);a=${a/-/.}';q=${p/-?././-};. <(echo $p{,,,,} $q{,,,,});p(){
[ ${1:0:1} = . ]&&{ b=${1%%-*};o+=${#b};}||{ b=${1%%.*} o+=$[(5+${#b})%10];};}
s=${1//[-.]/};for i in ${1//[+_]/ };do p $i;t=${s:0:1};o+=${t// };s=${s:1};done
r=$[${o//_/-}];for ((i=0;i<${#r};i++));do w+=(${v[${r:i:1}]});done;echo ${w[@]}
eof
chmod +x /tmp/morseCalc.sh
for test in 1+1 6-3 2-3+2 2+3-4+8-5 12-6+33 90+9+29-55+8+6-1+9+9-20 ;do
string="$(sed 's/ \.\.\.-\.-$//;s/ \.-\.-\. /+/g;s/ -\.\.\.\.- /_/g' <(
xargs < <(morse -s -- $test)))"
out="$(/tmp/morseCalc.sh "$string")"
res=$(morse -sd <<< "$out")
echo "$test: $string = $out -> $res"
done |
fold -w 80 -s
1+1: .----+.---- = ..--- -> 2
6-3: -...._...-- = ...-- -> 3
2-3+2: ..---_...--+..--- = .---- -> 1
2+3-4+8-5: ..---+...--_....-+---.._..... = ....- -> 4
12-6+33: .---- ..---_-....+...-- ...-- = ...-- ----. -> 39
90+9+29-55+8+6-1+9+9-20: ----. -----+----.+..--- ----._.....
.....+---..+-...._.----+----.+----._..--- ----- = ---.. ....- -> 84
```
or if `morse` converter is not installed:
```
for test in .----+.---- -...._...-- ..---_...--+..--- \
..---+...--_....-+---.._..... ".---- ..---_-....+...-- ...--" "----. -----+\
----.+..--- ----._..... .....+---..+-...._.----+----.+----._..--- -----" ;do
echo $test $(
bash <(sed '$s/;f/;echo "(${o\/\/_\/-}=$r)";f/' /tmp/morseCalc.sh
) "$test" )
done |
fold -w80 -s
.----+.---- (1+1=2) ..---
-...._...-- (6-3=3) ...--
..---_...--+..--- (2-3+2=1) .----
..---+...--_....-+---.._..... (2+3-4+8-5=4) ....-
.---- ..---_-....+...-- ...-- (12-6+33=39) ...-- ----.
----. -----+----.+..--- ----._..... .....+---..+-...._.----+----.+----._..---
----- (90+9+29-55+8+6-1+9+9-20=84) ---.. ....-
```
] |
[Question]
[
First, some terminology ([source](https://en.wikipedia.org/wiki/Roof#/media/File:Roof_diagram.jpg)):
* A [hip roof](https://en.wikipedia.org/wiki/Hip_roof) is (quoting Wikipedia) "a type of roof where all sides slope downwards to the walls, usually with a fairly gentle slope"
* A slope is a planar surface that is a part of the roof
* A ridge is an edge where two opposite roof slopes meet
* A hip is a convex edge where two slopes belonging to perpendicular walls meet
* A valley is a concave edge where two slopes belonging to perpendicular walls meet
* Hips and valleys shall be collectively referred to as diagonal edges.
Possible input:
```
** * ***
********
** * **
```
Corresponding output:
```
+-------+ +---+ +-----------+
|\ /| |\ /| |\ /|
| \ / | | V | | \ ^---< |
| \ / | | | | | \ / \ \|
+---+ V +---+ | +---+ X +---+
|\ \ | / \|/ \ / \ |
| >---> | <-------X-------V > |
|/ / | \ /|\ /| |
+---+ ^ +---+ | +-------+ | +---+
| / \ | | | | | |/ /|
| / \ | | ^ | | /---< |
|/ \| |/ \| |/ \|
+-------+ +---+ +-------+
```
A couple more test cases:
```
** *** * * * *
* *** *****
** ***** *****
* * * *** *** ***
* **** * * *
```
Corresponding outputs :
```
+-------+ +-----------+ +---+ +---+ +---+ +---+
|\ /| |\ /| |\ /| |\ /| |\ /| |\ /|
| \---< | | >-------< | | V | | V | | V | | X |
| |\ \| |/ \| | | | | | | | | | |/ \|
| | +---+ +-----------+ +---+ | +---+ | | +-----------+ | | +---+
| | | |\ \|/ /| | |/ \| |
| ^ | | \ V / | | < > |
|/ \| | \ / | | \ / |
+---+ +-------+ +---+ \ / +---+ | \-----------/ |
|\ /| |\ \ \ / / /| | |\ /| |
| >---/ | | >---> X <---< | | | \ / | |
|/ /| | |/ / / \ \ \| | | \ / | |
+---+ +---+ +---+ | | +---+ / \ +---+ +---+ ^ +---+ ^ +---+
|\ /| |\ /| | | | | / \ | |\ \ / \ | | / \ / /|
| V | | V | | | | | / ^ \ | | >---V > | | < V---< |
| | | | | | | | | |/ /|\ \| |/ /| | | |\ \|
| | | | | +-------+ | | +---+ | +---+ +-------+ | | | | +-------+
| | | | |/ \| | | | | | | | | | |
| ^ | | /-----------\ | | ^ | | ^ | | ^ |
|/ \| |/ \| |/ \| |/ \| |/ \|
+---+ +---------------+ +---+ +---+ +---+
```
Your **input** will be a bitmap - a 2D array of square pixels - of the area that should be covered by roof. You may assume the boundary of this area will be a Jordan curve - that is, continuous and non-self-intersecting - that is, the roofed area will be continuous, without holes and there will never be four walls meeting at a single point. Valid input formats include a single string with newline separators, a list of strings and a 2D array of chars or booleans.
**The rules of building the roof** are:
* Each straight segment of the roofed area (henceforth referred to as a wall) shall have exactly one adjoining slope. The slope shall rise away from the wall. Each slope shall have at least one adjoining wall, and all walls adjoining to a slope must be collinear.
* All slopes shall have the same (nonzero) angle against the horizontal surface. That is, they must have the same pitch.
* The slopes shall form a surface whose boundary is the boundary of the roofed area. That is, no surfaces other than the slopes may be used.
* Any scenario where more than one solution (up to vertical scaling) is allowed by this specification is considered a bug in the specification. Any corrections apply retroactively.
Equivalently, the roof may be defined by the rule that each point of the roof is placed as high as possible without exceeding the maximum slope for that roof as measured using the [Chebyshev distance](https://en.wikipedia.org/wiki/Chebyshev_distance) in top-down view.
Your **output** shall be an ASCII art representation of the roof - either a single string containing newline characters or an array of strings, each denoting a single line of the output. The roof shall be rendered in top-down view at a 4x scale - that is, each square of the floor-plan should affect a 5x5 area of the output such that the corners of this 5x5 area are shared with neighboring squares (such that each corner character is affected by four different input squares), as indicated by the example output. Extra whitespace is allowed as long as the output shape is preserved. The characters in output shall be:
* an environment-defined newline marker shall be used (usually U+000A, U+000D or a pair of both) if the output is in the form of a single string
* (U+0020 space) represents a point outside a roofed area or a point interior to a slope
* `+` (U+002B plus sign) represents a point with two perpendicular walls adjoined to it
* `-` (U+002D hyphen-minus) represents a wall or a ridge oriented horizontally (east-west)
* `/` (U+002F solidus) represents a hip or a valley oriented north-east to south-east, or a point adjoined to two of those
* `<` (U+003C less-than sign) represents a point with two diagonal edges adjoined to it on the east
* `>` (U+003E greater-than sign) represents a point with two diagonal edges adjoined to it on the west
* `\` (U+005C reverse solidus) represents a hip or a valley oriented north-west to south-east, or a point adjoined to two of those
* `^` (U+005E circumflex accent) represents a point with two diagonal edges adjoined to it on the south
* `V` (U+0056 latin capital letter v) represents a point with two diagonal edges adjoined to it on the north
* `X` (U+0058 latin capital letter x) represents a point with diagonal edges adjoined to it on all four sides
* `|` (U+007C vertical bar) represents a wall or a ridge oriented vertically (north-south)
Note that it is not possible for an odd number of diagonal edges to end at the same point (except on walls). We can visualize that by partitioning the neighborhood of each point into north slope + south slope and into east slope + west slope. The boundary between both partitions has to be composed of diagonal edges.
If your environment uses a character encoding incompatible with ASCII, you may use the equivalent characters (same glyph or closest available) in the character encoding your environment uses.
The following (ugly) **reference implementation** in Ruby is normative with respect to the non-whitespace output. Note particularly the `render` method:
```
def pad ary
row = ary.first.map{-1}
([row] + ary + [row]).map{|r| [-1] + r + [-1]}
end
def parse str
str.split("\n").map{|r| r.chars.map(&{" " => -1, "*" => Float::INFINITY})}
end
def squares ary, size
ary.each_cons(size).map do |rows|
rows.map{|row| row.each_cons(size).to_a}.transpose
end
end
def consmap2d ary, size
squares(ary, size).map{|sqrow| sqrow.map{|sq| yield sq}}
end
def relax ary
loop do
new = consmap2d(pad(ary), 3){|sq| sq[1][1] == -1 ? -1 : sq.flatten.min + 1}
return new if new == ary
ary = new
end
end
def semidouble ary, op
ary.zip(ary.each_cons(2).map{|r1,r2|r1.zip(r2).map(&op)}).flatten(1).compact.transpose
end
def heightmap str
relax(semidouble(semidouble(semidouble(semidouble(pad(parse str),:max),:max),:min),:min))
end
def render heightmap
puts consmap2d(heightmap, 3){|sq|
next " " if sq[1][1] == -1
hwall = sq[0][1] == -1 || sq[2][1] == -1
vwall = sq[1][0] == -1 || sq[1][2] == -1
next "+" if hwall && vwall
next "-" if hwall
next "|" if vwall
next "+" if sq.flatten.min == -1
nws = sq[0][1] == sq[1][0]
nes = sq[0][1] == sq[1][2]
sws = sq[2][1] == sq[1][0]
ses = sq[2][1] == sq[1][2]
next "X" if nws && nes && sws && ses
next "V" if nws && nes
next "^" if sws && ses
next ">" if nws && sws
next "<" if nes && ses
next "/" if nes && sws
next "\\" if nws && ses
next " " if sq[0][1] != sq[2][1] || sq[1][0] != sq[1][2]
next "|" if sq[0][1] == sq[1][1]
next "-" if sq[1][0] == sq[1][1]
??
}.map(&:join)
end
render heightmap $<.read if __FILE__ == $0
```
[Answer]
# Python 2, 500 bytes
```
z=input()
W=4*len(z[0])+1
H=4*len(z)+1
R=range
s=[-~W*[0]for _ in R(-~H)]
for y in R(H/4):
for x in R(W/4):
for h in R(25):s[y*4+h%5][x*4+h/5]|=z[y][x]
F=[(x/3-1,x%3-1)for x in[1,7,3,5,0,6,8,2]]
exec'for y in R(H):\n for x in R(W):s[y][x]+=0<s[y][x]<=min(s[y+d][x+e]for(e,d)in F)\n'*H
for y in R(H):
l=''
for x in R(W):h=s[y][x];a=[s[y+d][x+e]for(e,d)in F[:4]];l+=r' XabcVde^f ||g>h\\+//+<<jk<l//+\\+>>m --^^oVVqrX'[h and int(''.join(`int(n==h)`for n in a),2)*3+((h==1)*2or max(a)==h)+1]
print l
```
Tired of golfing it down, and I got to a nice round score, so here it is.
The eight-space indentation is a tab.
Pass a binary matrix over STDIN, like so:
```
python2.7 roof.py <<<"[[1,1,0,1,1,1,0,0,0,1,0,0,0,0,1,0,0,0,1,0], [1,0,0,0,0,0,0,0,1,1,1,0,0,0,1,1,1,1,1,0], [0,0,0,0,1,1,0,1,1,1,1,1,0,0,1,1,1,1,1,0], [1,0,1,0,0,1,0,0,1,1,1,0,0,1,1,1,0,1,1,1], [1,0,1,1,1,1,0,0,0,1,0,0,0,0,0,1,0,1,0,0]]"
```
] |
[Question]
[
Have a look at this ascii art diagram of various boxes:
```
+--------------------------------------------------------------+
| |
| +-------------------------------+ +-------+ |
| | | | | |
| | | | | |
| | +----------------+ | | | |
| | | | | +-------+ |
| | | | | |
| | | | | +-------+ |
| | +----------------+ | | | |
| | | | | |
| | | | | |
| +-------------------------------+ +-------+ |
| |
+--------------------------------------------------------------+
```
Each box is formed with pipe characters for the vertical parts (`|`), dashes for the horizontal parts (`-`), and pluses for the corners (`+`).
The diagram also shows boxes inside other boxes. We'll call the number of boxes that a box is contained within that box's *layer*. Here's the diagram again with the layer of each box annotated:
```
+--------------------------------------------------------------+
| |
| +-------------------------------+ +-------+ |
| | | | | |
| | | | 1 | |
| | +----------------+ | | | |
| | | | | 0 +-------+ |
| | | 2 | 1 | |
| | | | | +-------+ |
| | +----------------+ | | | |
| | | | 1 | |
| | | | | |
| +-------------------------------+ +-------+ |
| |
+--------------------------------------------------------------+
```
Your program will take in a box diagram similiar to the one at the top as input. As output, your program should output the box diagram with:
* The box on layer 0 should be filled with the character `#` (NB: There will only ever be one box on layer 0);
* Boxes on layer 1 should be filled with the character `=`;
* Boxes on layer 2 should be filled with the character `-`;
* Boxes on layer 3 should be filled with the character `.`;
* Boxes on layer 4 and above should not be filled.
Here is what the output of the example input should look like:
```
+--------------------------------------------------------------+
|##############################################################|
|###+-------------------------------+##########+-------+#######|
|###|===============================|##########|=======|#######|
|###|===============================|##########|=======|#######|
|###|=====+----------------+========|##########|=======|#######|
|###|=====|----------------|========|##########+-------+#######|
|###|=====|----------------|========|##########################|
|###|=====|----------------|========|##########+-------+#######|
|###|=====+----------------+========|##########|=======|#######|
|###|===============================|##########|=======|#######|
|###|===============================|##########|=======|#######|
|###+-------------------------------+##########+-------+#######|
|##############################################################|
+--------------------------------------------------------------+
```
Here is another input and output showing layers 3, 4, and 5. Note the horizontal lines at the top that are very close together. In these cases there is not enough space to fill any characters there.
```
+-----------------------------------------------------------------------+
| +--------------------------------------------------------------+ |
| | +-----------------------------------------------------+ | |
| | | +-----------------------------------------+ | | |
| | | | +---------------------------+ | | | |
| | | | | +-------------+ | | | | |
| | | | | | | | | | | |
| | | | | +-------------+ | | | | |
| | | | +---------------------------+ | | | |
| | | | | | | |
| | | +-----------------------------------------+ | | |
| | | | | |
| | | | | |
| | +-----------------------------------------------------+ | |
| | | |
| +--------------------------------------------------------------+ |
| |
| |
| |
+-----------------------------------------------------------------------+
```
The output:
```
+-----------------------------------------------------------------------+
|#####+--------------------------------------------------------------+##|
|#####|======+-----------------------------------------------------+=|##|
|#####|======|---------+-----------------------------------------+-|=|##|
|#####|======|---------|...........+---------------------------+.|-|=|##|
|#####|======|---------|...........| +-------------+ |.|-|=|##|
|#####|======|---------|...........| | | |.|-|=|##|
|#####|======|---------|...........| +-------------+ |.|-|=|##|
|#####|======|---------|...........+---------------------------+.|-|=|##|
|#####|======|---------|.........................................|-|=|##|
|#####|======|---------+-----------------------------------------+-|=|##|
|#####|======|-----------------------------------------------------|=|##|
|#####|======|-----------------------------------------------------|=|##|
|#####|======+-----------------------------------------------------+=|##|
|#####|==============================================================|##|
|#####+--------------------------------------------------------------+##|
|#######################################################################|
|#######################################################################|
|#######################################################################|
+-----------------------------------------------------------------------+
```
Another input, this time with the vertical lines close together as well:
```
+-------------+
|+-----------+|
|| ||
|| ||
|| ||
|+-----------+|
+-------------+
```
The output:
```
+-------------+
|+-----------+|
||===========||
||===========||
||===========||
|+-----------+|
+-------------+
```
**Additional Notes**
* There can be whitespace around the outermost box.
* Boxes cannot have an internal width or height of 0 (so they'll always be some space inside them)
* Boxes on the same layer can touch each other.
[Answer]
# Ruby 163 ~~164~~
```
w=l=-1
x=$<.map{|l|w=l.size;l}.join
b=[]
x.size.times{|i|c=x[i]
x[i..i+1]=='+-'&&(x[i+w]!=?|?b-=[i%w]:b<<i%w)
c>?z&&l+=b&[i%w]!=[]?1:-1
$><<(c==' '&&'#=-.'[l]||c)}
```
Try online: [test case #1](http://ideone.com/H1VsGh), [test case #2](http://ideone.com/EX6wjK).
The ungolfed program:
```
# read all lines from STDIN
input = $<.map{|l|l}.join
width = input.index(?\n)+1
box_left_margins = []
current_layer = -1
input.size.times{|i|
c = input[i]
if c == ?+ && input[i+1] == ?-
#we're at a box's left margin
if input[i+width] == ?|
# we're at the box's top - mark this index as a left margin
box_left_margins << i%width
else
# we're at the box's bottom - this index is no longer a left margin
box_left_margins-=[i%width]
end
end
if c == ?|
if box_left_margins.include? (i%width)
current_layer += 1
else
current_layer -= 1
end
end
if c == ' '
$><< ('#=-.'[current_layer]||' ')
else
$><<c
end
}
```
[Answer]
# Java, ~~476~~ 466 bytes
```
import java.util.*;class H{public static void main(String[]a){Scanner p=new Scanner(System.in);char[]l=p.nextLine().toCharArray(),d={'#','=','-','.'};int s=l.length,b,i;int[]m=new int[s];String o=new String(l);for(;;){o+='\n';l=p.nextLine().toCharArray();if(l[0]=='+')break;o+='|';b=0;for(i=1;i<s;++i){char c=l[i];switch(c){case' ':c=b>3?' ':d[b];break;case'+':m[i]=l[i-1]=='-'?-++m[i]:- --m[i];break;case'|':b+=m[i];}o+=c;}}o+=new String(l);System.out.println(o);}}
```
This reads the first line to determine the width (s) of the outermost box. With this it keeps an array of length s. This array stores from left to right where boxes begin and end and is initialized with 0s. It also stores the box-height.
The program reads the input line by line and watches for the following characters:
* '+' is, as we know, the edge of a box. If the input char to the left is a '-', it is the end of the box, else it is the beginning. The marker array gets updated as follows:
+ If the marker at this index is 0, set the value to 1 (beginning) or -1 (end).
+ Else set the value to 0. (We reached the bottom of the box, it is not important anymore)
* '|' changes the current box-height by the marker at the current index.
* ' ' Every char gets output as it was, except for blanks, which are replaced according to the current box-height.
Edit: Thanks to TheNumberOne for the suggestion.
I also replaced while(true) with for(;;).
[Answer]
# CJam, ~~114~~ ~~111~~ ~~108~~ ~~104~~ ~~103~~ ~~102~~ 98 bytes
```
q"-+":R/Ws*N/z{_,{"|1"/Bs*}*}%z{_,,{_I=S&{_I>_1sf&s,\"|+"f&s,m5e<" #=2."=I\t}&}fI}%N*Ws/R*Cs"|-"er
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%22-%2B%22%3AR%2FWs*N%2Fz%7B_%2C%7B%22%7C1%22%2FBs*%7D*%7D%25z%7B_%2C%2C%7B_I%3DS%26%7B_I%3E_1sf%26s%2C%5C%22%7C%2B%22f%26s%2Cm5e%3C%22%20%23%3D2.%22%3DI%5Ct%7D%26%7DfI%7D%25N*Ws%2FR*Cs%22%7C-%22er&input=%2B--------------------------------------------------------------%2B%0A%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%2B-------------------------------%2B%20%20%20%20%20%20%20%20%20%20%2B-------%2B%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%2B----------------%2B%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%2B-------%2B%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%2B-------%2B%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%2B----------------%2B%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%2B-------------------------------%2B%20%20%20%20%20%20%20%20%20%20%2B-------%2B%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%0A%2B--------------------------------------------------------------%2B).
### How it works
```
q e# Read all input from STDIN.
"-+":R/Ws* e# Replace each "-+" with "-1".
N/z e# Split at linefeeds and zip. Pushes the array of columns.
{ e# For each column:
_, e# Push its length.
{ e# Do that many times:
"|1"/Bs* e# Replace each "|1" with "11".
}* e#
}% e#
z e# Transpose. Goes back to array of rows.
{ e# For each row:
_,, e# Push the array of its indexes.
{ e# For each index I:
_I= e# Get the Ith character of the row.
S&{ e# If it is a space:
_I> e# Get the characters after the Ith.
_1sf&s, e# Count how many characters are 1's.
\"|+"f&s, e# Count how many are |'s or +'s.
m5e< e# Subtract and truncate at 5.
" #=2."= e# Retrieve the corresponding character.
I\t e# Replace the Ith character of the row with that one.
}& e#
}fI e#
}% e#
N* e# Join the rows, separating by linefeeds.
Ws/R* e# Turn "-1"s back to "-+"s.
Cs"|-"er e# Turn 1's and 2's into |'s and -'s.
```
[Answer]
# JavaScript (*ES6*) 156
Run snippet in Firefox to test
```
F=b=>(
r=b.split(/\n/),q=[n=0],
r.map((r,i)=>(
[...r].map((c,p)=>c=='+'?(q[p]=r[p-1]=='-'?-1:1,c):c<'!'?' #=-.'[n]||' ':((n+=q[p]|0),c)).join(''))
).join('\n')
)
// TEST
o=x=>O.innerHTML += x+'\n\n'
;[`+--------------------------------------------------------------+
| |
| +-------------------------------+ +-------+ |
| | | | | |
| | | | | |
| | +----------------+ | | | |
| | | | | +-------+ |
| | | | | |
| | | | | +-------+ |
| | +----------------+ | | | |
| | | | | |
| | | | | |
| +-------------------------------+ +-------+ |
| |
+--------------------------------------------------------------+`
,`+-----------------------------------------------------------------------+
| +--------------------------------------------------------------+ |
| | +-----------------------------------------------------+ | |
| | | +-----------------------------------------+ | | |
| | | | +---------------------------+ | | | |
| | | | | +-------------+ | | | | |
| | | | | | | | | | | |
| | | | | +-------------+ | | | | |
| | | | +---------------------------+ | | | |
| | | | | | | |
| | | +-----------------------------------------+ | | |
| | | | | |
| | | | | |
| | +-----------------------------------------------------+ | |
| | | |
| +--------------------------------------------------------------+ |
| |
| |
| |
+-----------------------------------------------------------------------+`
,`+-------------+
|+-----------+|
|| ||
|| ||
|| ||
|+-----------+|
+-------------+`
].forEach(t=>o(t+'\n'+F(t)+'\n'))
```
```
pre { font-size:10px;}
```
```
<pre id=O></pre>
```
[Answer]
# CJam, ~~76~~ 74 bytes
```
q:Q"-+":R/Ws*{_"| "#"]_QN#~%'|m0='+=2*(U+:U+~; \"#=-.\"+U5e<= "S/=~}%Ws/R*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q%3AQ%22-%2B%22%3AR%2FWs*%7B_%22%7C%20%22%23%22%5D_QN%23~%25'%7Cm0%3D'%2B%3D2*(U%2B%3AU%2B~%3B%20%5C%22%23%3D-.%5C%22%2BU5e%3C%3D%20%22S%2F%3D~%7D%25Ws%2FR*&input=%2B--------------------------------------------------------------%2B%0A%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%2B-------------------------------%2B%20%20%20%20%20%20%20%20%20%20%2B-------%2B%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%2B----------------%2B%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%2B-------%2B%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%2B-------%2B%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%2B----------------%2B%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%2B-------------------------------%2B%20%20%20%20%20%20%20%20%20%20%2B-------%2B%20%20%20%20%20%20%20%7C%0A%7C%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%7C%0A%2B--------------------------------------------------------------%2B).
### How it works
```
q:Q e# Read all input from STDIN and save it in the variable Q.
"-+":R/Ws* e# Replace each "-+" with "-1".
e# This allows us to easily keep track of right corners.
{ e# For each charcter in the modified input:
_"| "# e# Push its index in the string (0 for '|', 1 for ' ', -1 otherwise).
"]_QN#~%'|m0='+=2*(U+:U+~; \"#=-.\"+U5e<= "S/
e# Split the pushed string at spaces, which results in three chunks:
e# ] Turn the entire stack into a string.
e# _QN# Compute the first index of a linefeed (row length).
e# ~% Retrieve every previous character in the current column,
e# starting with the last.
e# '|m0= Get the first character that is not a vertical bar.
e# '+=2*( Push 1 if it's a plus sign and -1 otherwise.
e# U+:U Add to U (initially 0) to keep track of the layer.
e# +~; Add U to the string (casts to Array), dump and discard U.
e# "#=-."+ Concatenate this string with the space on the stack.
e# U5e< Truncate U at 5.
e# = Retrieve the corresponding character to replace the space.
e# (empty)
=~ e# Select and execute the proper chunk.
}% e#
Ws/R* e# Replace each "-1" with "-+".
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 50 bytes[SBCS](https://github.com/abrudz/SBCS)
```
s[⊃¨0~¨⍨a,¨5|5⌊+⍀+\(⊢ׯ1*+⍀++\)5=a←⎕⍳⍨s←' #=-.+|']
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qZv6jtgkGXI862tP@F0c/6mo@tMKg7tCKR70rEnUOrTCtMX3U06X9qLdBO0bjUdeiw9MPrTfUAvO1YzRNbROBmoGGPOrdDNRQDOSoKyjb6upp16jH/gcaCTK2CChalJqY4ptYUpRZwQXiVh@e/qhzEUj5o955VkA1j3q36jzqaip@1N3yqG0ikFf7qHcNSPP/NC4kvdq6FAFtrhoFikAN2ABCrtBGaNBGE4IYQMgVNZjMGloYoI3T5UQaUIPT4hriwoAoA7DHApVcQHEYDGQ0UpwSKcoLFOdGLmpmboxcTqnzEGFUo0CBgdog7Wgm1WBEC3Hm4DMJOTq1CZpDrEm4XKoNliPPpBqMRF4zQG6iXjgRysg1dEoFJOVgmppEvdxCdgmFMIl6ZQHlYHCaRL3SF1@pDiybkQW0gT5AydlE8NH0o5sPAA "APL (Dyalog Unicode) – Try It Online")
`s←' #=-.+|'` assign a string to variable `s`
`⎕` evaluated input, it must be a character matrix
`⎕⍳⍨s` replace every element of `⎕` with its index in `s`
`a←` assign to `a`
`5=` return a boolean matrix of where the `+`-es are in `a` (`s[5]` is `'+'`)
`(⊢ׯ1*+⍀++\)` this is a [train](https://codegolf.stackexchange.com/questions/17665/tips-for-golfing-in-apl#answer-43084) of functions:
* `+\` matrix of partial sums by row
* `+` plus
* `+⍀` matrix of partial sums by column
* `¯1*` negative one to the power of - turn odds into ¯1 and evens into 1
* `⊢×` multiply by the train's argument - zero out everything except box corners
`+⍀+\` partial sums by column of partial sums by row
`5⌊` minimum of that and 5
`5|` modulo 5
`a,¨` pair up the elements of `a` and of the current matrix
`0~¨⍨` remove 0 from the pairs
`⊃¨` first each of what's remaining
`s[ ]` use every element as an index in `s`
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~118 115~~ 87 bytes
```
]0{i:0(?;:"-"=?\:"+"=?\:" "=?\$3l$g+}:ob(?
~$?:g2.10p1+4f:<p3l+10/.16@:$/>.!0"#"$
#=-.
```
[Try it online!](https://tio.run/##zZTPDoIwDMbvPAWOHUwacIjxMEV8EL14AElMNPFo9dWRPwd0iEw61F4GI/3xpe3XOD3vs2wrLqkU42ghmcvCaCMZVIddHDw48ASu8rgbR9aNRzKZer44@TCL5fIUHMAXE8@fryWfrLyRYA7jlu2Erpdl4JICLLRJgSWgSwXUCaBcVYAuFdh8xCEA0KpcE4CtP0a9GmgBXnfBkAJyDX7ZRvIkkrxAdiOV0DA2VVFdFrQJQCjSFRI2OqHHeUd67CB0cnRJbUqh/NaPhI25xh9pMlenLu/il6bgI9MOSjLnlt5LqSaZ2wX0@E@Sue2roPJ1/HgBuegnM2u8K/kK/w4 "><> – Try It Online")
~~If one of the symbols wasn't a `-` then this could be 6 bytes shorter.~~ Eh, made it a ~~bit~~ lot smaller anyway
### How It Works:
```
] Resets the stack
0{ Pushes a 0 and rotates the stack
If the stack is empty, this initialises 0 as the counter
Otherwise it adds an extra 0 to the stack and pushes the counter to the top
i:0(?; Gets input and ends if it is EOF
:"-"=?\ If the inputted character is a -
p1+4f:< Put a - at cell (19, 1)
.10 And skip to the end of this line
:"+"=?\ Else if the inputted character is +
?10/ Generate either -1 or 1, depending on what was last put into cell (19,1)
The question mark represents cell (19,1), which is either + or -
p3l Put this number on (3, length of the stack)
.10p1+4f:< Repeat the exact same code as with the -, except we put a + at cell (19,1)
:" "=?\ Else if the character is a space
@:$/ Create a copy of the counter
.16 Skip to cell (1,6)
g2 Get the cell (2, counter) (the #=-.)
~$? If that cell is a zero, pop it, leaving the initial space.
Else pop the space, leaving the fetched character
Else if the character is a | or a newline
$3l$g+ Get the cell at (3, length of the stack) and add it to the counter
For everything but the last else, we are at the end of the second line
>.!0"#"$ Skip to the 35th instruction on the first line
} Push the counter to the bottom of the stack
:o Output the current character
b(? If the character is smaller than 11 (a newline)
] Skip the clear stack at the start of the line
Repeat this until EOF
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~190~~ 179 bytes
-11 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)
Fails if sizeof(int) > 9, but then you can take solace in the fact that your computer is from the future.
```
l;*H,*h,d;f(S){h=H=calloc(l=index(S,10)-S,9);for(char*s=S;*s;s++)h=*s^10?h:H-1,d=*s-43?d:s!=S&s[-1]==45|s-S>l&s[~l]=='|'?-1:1,*h+=*s^45?0:d,h+=write(1,*s^32|*h>4?s:" #=-."+*h,1);}
```
[Try it online!](https://tio.run/##1ZVPT4MwGMbP8CkQE9dSaqhjB2k6rtw5OpeQMoQEmaEYTdb51bHOLSOKTv5E43N7n4Zfn7elLcd3nNd1Tq3AtlI7pgkI4SZlAeNRnq85yFlWxKtnENrEgTi0ryFN1iXgaVRagoXUElQgBFNmiSVx/NQLMLFjVWF36seeOGPhhbjB5JYxdyYFDue5ql9yVU/kxMfEI2pi9Pa5O/MdL7ZV8VRm1QqoAbGcXkkrnbu@8EzjnOFLE6mYBNJtnRWVcR9lBYD6RtcSoGsmwk2hRWEqUzZdJPemNI6S3c025ufZIdV17eGxEsBcFMo7WC1h@@vQ5i7gQChSLTZx@95RT5hsxx1XFHWCncQ1twqdhHXCfZUZ7cYG4JrueyX/PN3Ia/e9foQb@Ufpot/CjXzI@uojbuQbZbj@BW7My109Gdv6FQ "C (gcc) – Try It Online")
] |
[Question]
[
Write the shortest program to turn any piece of ASCII art into an animated snow scene that begins to form from the falling snow (**[non-golfed JavaScript example](http://jsfiddle.net/plstand/GD2Dk/)** last updated 2011-12-19).
**Input specification**:
Your program must accept arbitrary combinations of spaces, asterisks, and newlines. The input will contain at most 23 lines and 80 characters per line. There will be no empty lines, yet lines may consist of only whitespace. A single trailing newline will be included and must be ignored.
**Output**:
Output ASCII characters (spaces, asterisks) and control codes (carriage returns, linefeeds, ANSI escape codes, etc.) for your operating system's text console or terminal emulator until the user manually terminates the program. You may assume the terminal window is 80x24 characters if your operating system allows that setting.
**Rules**:
* The animation must be smooth and fast (15 fps preferred).
* Snow density must be between 5% and 15%.
* No more than one screen of snow may scroll per second. (That means no more than 24 lines of new snow may be added in any one second time period.)
* The snow must not display any obvious pattern as it enters the top of the screen; it must look random.
* The program must fill all rows of the screen with snow as quickly as possible when it starts; initial filling of the screen's individual rows must not be obvious to the viewer.
* The lower left corner of the input ASCII art must be at the lower left corner of the screen (Figure 1 for further clarification).
* The area inside or under the ASCII art must not be permanently filled with asterisks. However, asterisks may (but are not required to) scroll through this area.
* Snow must not accumulate at the bottom of the screen or on top of existing snow except as shown in the input.
* Lower spaces must be filled before upper ones, as filling spaces in the opposite order makes the Christmas tree animation look very different from my original code's output. (added 2011-12-20)
Happy holidays!
## Figure 1: labeled areas of an 80x24 screen
```
---------------------------New snow added on this line--------------------------
|
|
----------------------------------------------------------+ |
**** | |
Snow MUST fall Snow MAY fall ----------------> **** | |
through this through these **** **** | Snow MUST fall |
area. areas of a **** **** | through this |
completed \---------> **** ****| area. |
ASCII art scene. \ *** **** ****| |
area \ \ ******* **** ****| |
\ \ ******** *** ***| (ALL CAPS terms |
(located in \ \--> ********* *** | have standard |
lower left \ ******* ****** MAY | RFC 2119 |
corner of \ ************* ** fall | meanings.) |
screen) \ *********** here | |
*** +---> **** *** | |
*** | **************** *** | |
| Snow MUST fall *** | **************** *** | |
| through this *** +---> *** | |
| area. *** | **************** *** | |
--+---------------------+*** +---> ***+----+------------------+--
| Snow MUST NOT |****************************| Snow MUST NOT |
V accumulate here. |****************************| accumulate here. V
```
## Example inputs
### Code Golf Banner
```
****** ******* ******** ******** ****** ******* ** ********
** ** ** ** ** ** ** ** ** ** ** ** **
** ** ** ** ** ** ** ** ** ** **
** ** ** ** ** ****** ** **** ** ** ** ******
** ** ** ** ** ** ** ** ** ** ** **
** ** ** ** ** ** ** ** ** ** ** ** **
****** ******* ******** ******** ****** ******* ******** **
```
### Stack Overflow Logo
```
****
****
**** ****
**** ****
**** ****
*** **** ****
******* **** ****
******** *** ***
********* ***
******* ******
************* **
***********
*** **** ***
*** **************** ***
*** **************** ***
*** ***
*** **************** ***
*** ***
****************************
****************************
```
### Christmas Trees
```
*
*** *
* ***** ***
*** ******* * *****
***** ********* *** *
* *********** *****
* ************* *******
* *** *************** * *
*** ***** ***************** ***
***** ******* ******************* *****
******* * ********************* *******
********* * *********
* *
```
[Answer]
## Perl, 196 / 239 chars
```
chomp(@p=(@f=($"x80)x24,<>)[-24..-1]);{@s=(join("",map rand>.1?$":"*",1..80),@s);if(@s>23){$t=$f[$_],print$_?$/:"\e[H",($f[$_]|=$s[$_]&$p[$_])|($s[$_]&=~$t^$f[$_])for 0..23;select"","","",.1}redo}
```
This solution differs from your JS example in that the pattern is filled from top down rather than from bottom up, but I assume that's OK since you didn't say anything about it in the rules.
A trivial 1-char reduction can be obtained by replacing `\e` with a literal ESC character, but that makes the code much harder to read and edit.
---
**Update:** I *did* manage to come up with a version that fills the pattern from bottom up, and doesn't allow snow to fall through the filled parts of the pattern, as in the example JS implementation, at the cost of 43 extra chars:
```
chomp(@p=(@q=@f=($"x80)x24,<>)[-24..-1]);{@s=(join("",map rand>.1?$":"*",1..80),@s);if(@s>23){my$q;$q[-1-$_]=($q|=$p[-$_]&~$f[-$_])for@a=0..23;print$_?$/:"\e[H",($f[$_]|=$s[$_]&$p[$_]&~$q[$_])|($s[$_]&=~$f[$_])for@a;select"","","",.1}redo}
```
Replacing `($s[$_]&=~$f[$_])` with just `$s[$_]` would save 11 chars by letting falling snow pass through the filled parts of the pattern (which matches the spec, but not the example implementation).
---
OK, since I still seem to be leading the race after a week, I guess I should explain how my solution works to encourage more competition. (Note: This explanation is for the 196-char top-down filling version. I may amend it to include the other version later.)
First of all, the one big trick my solution is based on is that, due to the way ASCII character codes are arranged, the 1-bits in the ASCII code for a space just happen to be a subset of those in the code for an asterisk.
Thus, the following expressions are true: `" " & "*" eq " "` and `" " | "*" eq "*"`. This is what lets me use bitwise string operations for combining the static and moving parts of the scene without having to loop over individual characters.
So, with that out of the way, let's go over the code. Here's a de-golfed version of it:
```
chomp(@p = (@f = ($" x 80) x 24, <ARGV>)[-24..-1]);
{
@s = (join('', map((rand > 0.1 ? $" : '*'), 1..80)), @s);
if (@s > 23) {
foreach (0 .. 23) {
$t = $f[$_];
print( $_ ? $/ : "\e[H" );
print( ($f[$_] |= $s[$_] & $p[$_]) | ($s[$_] &= ~$t ^ $f[$_]) );
}
select '', '', '', 0.1;
}
redo;
}
```
The first line sets up the arrays `@f` (for "fixed") and `@p` (for "pattern"). `@f` will form the fixed part of the display, and starts out containing nothing but spaces, while `@p`, which is not shown directly, contains the input pattern; as the animation proceeds, we'll add more and more asterisks to `@f` until it eventually looks just like `@p`.
Specifically, `@f = ($" x 80) x 23` sets `@f` to 24 strings of 80 spaces each. (`$"` is a special Perl variable whose default value just happens to be a space.) We then take this list, append the input lines to it using the readline operator `<>`, take the last 24 lines of this combined list and assign it to `@p`: this is a compact way to pad `@p` with blank lines so that the pattern appears where it should. Finally, we `chomp` the input lines in `@p` to remove any trailing newlines so that they won't cause problems later.
Now, let's look at the main loop. It turns out that `{...;redo}` is a shorter way to write an infinite loop than `while(1){...}` or even `for(;;){...}`, especially if we get to omit the semicolon before `redo` because it immediately follows an `if` block.
The first line of the main loop introduces the array `@s` (for "snow", of course), to which it prepends a random 80-character string of 90% spaces and 10% asterisks on every iteration. (To save a few chars, I never actually pop extra lines off the end of the `@s` array, so it keeps getting longer and longer. Eventually that will grind the program to a halt as the array gets too long to fit in memory, but that will take much longer than most people would ever watch this animation for. Adding a `pop@s;` statement before the `select` would fix that at the cost of seven chars.)
The rest of the main loop is wrapped in an `if` block, so that it only runs once the `@s` array contains at least 24 lines. This is a simple way to comply with the spec, which requires the whole display to be filled with falling snow from the start, and also simplifies the bitwise operations a bit.
Next comes a `foreach` loop, which in the golfed version is actually a single statement with a `for 0..23` modifier. Since the content of the loop probably needs some explanation, I'm going to unpack it a bit more below:
```
foreach (0 .. 23) {
print $_ ? $/ : "\e[H"; # move cursor top left before first line, else print newline
$t = $f[$_]; # save the previous fixed snowflakes
$f[$_] |= $s[$_] & $p[$_]; # snowflakes that hit the pattern become fixed
$s[$_] &= ~$t ^ $f[$_]; # ...and are removed from the moving part
print $f[$_] | $s[$_]; # print both moving and fixed snowflakes ORed together
}
```
First of all, `$_` is the default loop counter variable in Perl unless another variable is specified. Here it runs from 0 to 23, i.e. over the 24 lines in the display frame. `$foo[$_]` denotes the element indexed by `$_` in the array `@foo`.
On the first line of the de-golfed loop, we print either a newline (conveniently obtained from the `$/` special variable) or, when `$_` equals 0, the string `"\e[H"`, where `\e` denotes an ESC character. This is an [ANSI terminal control code](http://en.wikipedia.org/wiki/ANSI_escape_code) that moves the cursor to the top left corner of the screen. Technically, we could omit that if we assumed a specific screen size, but I kept it in this version since it means I don't have to resize my terminal to run the animation.
On the `$t = $f[$_]` line, we just save the current value of `$f[$_]` in a "temporary" variable (hence `$t`) before potentially changing it in the next line, where `$s[$_] & $p[$_]` gives the intersection (bitwise AND) of the falling snow and the input pattern, and the `|=` operator ORs that into the fixed output line `$f[$_]`.
On the line below that, `$t ^ $f[$_]` gives the bitwise XOR of the previous and current values of `$f[$_]`, i.e. a list of the bits we changed in the previous line, if any, and negating either of the input strings with `~` negates the output. Thus, what we get is a bitmask with all bits set to 1 *except* those that we just added to `$f[$_]` on the previous line. ANDing that bitmask onto `$s[$_]` removes those bits from it; in effect, this means that when a falling snowflake fills in a hole in the fixed pattern, it gets removed from the falling snow array.
Finally, `print $f[$_] | $s[$_]` (which in the golfed version is implemented by just ORing the two previous lines together) just prints the union (bitwise OR) of the fixed and moving snowflakes on the current line.
One more thing left to explain is the `select '', '', '', 0.1` below the inner loop. This is just a klugy way to sleep 0.1 seconds in Perl; for some silly historical reason, the standard Perl `sleep` command has one-second resolution, and importing a better `sleep` from the `Time::HiRes` module takes more chars than abusing [4-arg `select`](http://perldoc.perl.org/functions/select.html#select-RBITS,WBITS,EBITS,TIMEOUT).
[Answer]
## HTML and JavaScript, 436 chars
Prepend it to the input:
```
<body onload="for(a=[],b=[],c=document.body.firstChild,e=c[H='innerHTML'].split(N='\n'),f=e.length-1,g=24,h=g-f;f--;)for(X=80;X--;)b[80*(h+f)+X]='*'==e[f][X];for(setInterval(F='for(y=24;y--;)for(x=80;x--;)if(a[w=80*y+x]){d=1;if(b[w])for(d=0,z=y+1;24>z;++z)b[s=80*z+x]&&!a[s]&&(d=1);d&&(a[w]=0,a[w+80]=1)}for(x=80;x--;).1>Math.random(i=0)&&(a[x]=1);for(t=\'\';1920>i;++i)t+=\'* \'[+!a[i]],79==i%80&&(t+=N);c[H]=t',67);g--;)eval(F)"><pre>
```
See it run for each example: [code golf](http://jsbin.com/atuter), [Stack Overflow logo](http://jsbin.com/unuzax), [Christmas trees](http://jsbin.com/uxolep). Internet Explorer users need to run version 9 and set the "Document Mode" to "IE9 standards" (using the F12 developer tools) for this submission to correctly work.
[Answer]
## Python, 299 chars
This should conform to the rules, assuming the newline is included in the 80 char limit.
```
import random,sys,time
C=1920
v=_,x=' *'
a=['']*C
f=lambda n:[random.choice(e*9+x)for e in _*n]
for e in sys.stdin:a+="%-80s"%e
a=a[-C:]
s=f(C)
while 1:
z=0;t=''
for e in s:
t+=v[x<a[z]or e>_]
if(e>_<a[z])>(x in a[z+80::80]):a[z]='+'
t+=z%80/79*'\n';z+=1
print t;s=f(80)+s[:-80];time.sleep(.1)
```
[Answer]
## Java, 625 chars
```
import java.io.*;import java.util.*;class s extends TimerTask {int _c,_k;char _i[],_o[];boolean _b[];public s(String f) throws IOException {_i=new char[23*80];_o=new char[80];_b=new boolean [23*80];BufferedReader br = new BufferedReader(new FileReader(f));while (br.read(_i,_c++*80,80)!=-1);} public void run(){_k=--_k<0?_c:_k;for(int i=0;i<80;_b[_k*80+i]=Math.random()>0.9?true:false,i++);for(int m=0;m<_c;m++){for(int n=0;n<80;_o[n]=_b[(_k+m)%_c*80+n]?'*':_i[m*80+n],n++);System.out.println(_o);}}public static void main(String[] a) throws IOException{Timer timer=new Timer();timer.scheduleAtFixedRate(new s(a[0]),0,500);}}
```
A simple solution in Java.
] |
[Question]
[
**This question already has answers here**:
[Visualize long addition with ASCII art](/questions/74127/visualize-long-addition-with-ascii-art)
(4 answers)
Closed 7 years ago.
Everyone knows how to add numbers by hand, right?––Well, I hope so, but for anyone who needs a quick reminder:
To add `17282` and `1342`, you proceed as follows:
1. place the larger (value wise, not number of digits) number above the smaller number and match up the digits
```
17282
1342
```
2. draw the plus sign (+) to the left of the equation on the second row. The plus sign must be flush with the left side.
```
17282
+ 1342
```
3. draw a line of dashes (-) with one dash in each column of the digits of the first line
```
17282
+ 1342
-----
```
4. evaluate the expression and write the digits above each column if you need to 'carry' them
```
1
17282
+ 1342
-----
18624
```
Your output is what you get after applying step #4. You may have trailing whitespace, but there may not be any leading zeroes.
You must write a program or a function that prints or returns the output.
The input can be taken as either two separate inputs or an array with two items; the type of the inputs can be either string or integer.
This is code golf so shortest code in bytes wins!
**Edit:**
The largest number you could expect to receive as output/the sum is the largest integer that your system will display without exponents (thanks to Adám).
**More examples:**
```
Input:
1596, 8404
Output:
1111
8404
+1596
----
10000
Input:
1776, 76
Output:
11
1776
+ 76
----
1852
Input:
123, 456
Output:
456
+123
---
579
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 90 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
{⌽↑(⊂⌽s),⍨↓⌽(' + ',⍨' 1'⊃⍨l<⍴s),'-'⍪⍨w⍪⍨' 1'[10|(⍎¨(-l←⍴⍉w)↑s←⍕+/⍵)-(+/0 10⊤⍎)¨⊂[0]w←⍕⍪⍵]}
```
Takes list of two numbers as argument. Needs `⎕IO←0` which is default on many systems.
```
f←{⌽↑(⊂⌽s),⍨↓⌽(' + ',⍨' 1'⊃⍨l<⍴s),'-'⍪⍨w⍪⍨' 1'[10|(⍎¨(-l←≢⍉w)↑s←⍕+/⍵)-(+/0 10⊤⍎)¨⊂[0]w←⍕⍪⍵]}
f¨(17282 1342)(1596 8404)(1776 76)(123 456)
┌──────┬─────┬─────┬────┐
│ 1 │1111 │ 11 │ │
│ 17282│ 1596│ 1776│ 123│
│+ 1342│+8404│+ 76│+456│
│ -----│ ----│ ----│ ---│
│ 18624│10000│ 1852│ 579│
└──────┴─────┴─────┴────┘
```
[TryAPL online!](http://tryapl.org/?a=%u2395IO%u21900%20%u22C4%20e%u2190%7B%7B1%3D%u2374%u2375%3A%u236C%u2374%u2375%u22C4%u2375%7D%u2283%7B%u237A/%u2375%7D/%u2395VFI%20%u2375%7D%20%u22C4%20%7B%u233D%u2191%28%u2282%u233Ds%29%2C%u2368%u2193%u233D%28%27%20+%20%27%2C%u2368%27%201%27%u2283%u2368l%3C%u2262s%29%2C%27-%27%u236A%u2368w%u236A%u2368%27%201%27%5B10%7C%28e%A8%28-l%u2190%u2262%u2349w%29%u2191s%u2190%u2355+/%u2375%29-%28+/0%2010%u22A4e%29%A8%u2282%5B0%5Dw%u2190%u2355%u236A%u2375%5D%7D%A8%2817282%201342%29%281596%208404%29%281776%2076%29%28123%20456%29&run) Note that `⎕IO` has been set and `⍎` has been emulated with `e` as `⍎` is banned from TryAPL for security reasons.
### Ungolfed and explained
>
> `{` An anonymous function
>
>
>
> >
> > `w ← ⍕ ⍪⍵` *w* gets the textified vertical arrangement of the argument
> > (the numbers to be added)
> >
> >
> > `l ← ≢ ⍉w` *s* gets the count of rows in the transposed *w* (i.e. the
> > number of columns in *w*)
> >
> >
> > `s ← ⍕ +/⍵` *s* gets the textified sum of the argument
> >
> >
> > `' 1'[`... index into the string " 1", so zeros give spaces, and ones
> > give character 1s.
> >
> >
> >
> > >
> > > `⊂[0] w` enclose down, gets list of pairs of corresponding digits in
> > > the numbers
> > >
> > >
> > > `(+/ 0 10 ⊤ ⍎)¨` for each pair; make into digit(s), then sum
> > >
> > >
> > > `(⍎¨ (-l) ↑ s)-` chop left-most digit of grand total to the width of
> > > the longest input, then make each character into separate number and
> > > subtract the column sums (if the sum does not add up to the total, the
> > > discrepancies are due to carrys, so this gives us each column's carry)
> > >
> > >
> > > `10|` division remainder when divided by 10
> > >
> > >
> > >
> >
> >
> > `]` [end of indexing]
> >
> >
> > `w⍪⍨` stack the input numbers below
> >
> >
> > `'-'⍪⍨` stack a minus below each column
> >
> >
> > `(' + ',⍨' 1'⊃⍨l<⍴s),` prepend a space to the 2nd line, a
> > plus to the 3nd, a space to the 4rd, and a one
> > or space to the 1st – depending on if the sum is wider than
> > the widest input (meaning we need a carry high over the plus )
> >
> >
> > `⌽` mirror right-left (so left-justification will be to the right)
> >
> >
> > `↓` make table into list of lines (so that differing line lengths are
> > allowed
> >
> >
> > `(⊂⌽s),⍨` append the sum
> >
> >
> > `↑` combine list of lines into table (padding the right with spaces as
> > needed)
> >
> >
> > `⌽` mirror back to normal
> >
> >
> >
>
>
> `}` [end of function]`
>
>
>
[Answer]
# Python 2.7, ~~201~~ ~~192~~ ~~161~~ ~~155~~ ~~167~~ ~~164~~ 182 bytes:
(*Saved 2 bytes (`192->190`) thanks to TheBikingViking*)
```
def Q(T,Y):O,D=sorted([T,Y]);E=len(`D`);print'%s\n %s\n+%*s\n %s\n %d'%(''.join([' ',i[0]][len(i)>1]for i in[`sum(map(int,u))`for u in zip(`D`,'%0*d'%(E,O))]),D,E,O,'-'*E,sum([T,Y]))
```
A named function that takes input in any order while outputting the correct answer in order of magnitude from top to bottom.
[Try it Online! (Ideone)](http://ideone.com/Eh4ouz)
---
Alternatively, if allowed to take input in order of magnitude (i.e. bigger number first, then smallest), then here is a much smaller solution which also uses a named function at **164 bytes**:
```
def Q(T,Y):E=len(`T`);print'%s\n %d\n+%*d\n %s\n %d'%(''.join([' ',i[0]][len(i)>1]for i in[`sum(map(int,u))`for u in zip(`T`,`Y`.zfill(E))]),T,E,Y,'-'*E,sum([T,Y]))
```
[Try this Version Online! (Ideone)](http://ideone.com/u1JG5E)
[Answer]
# Ruby, ~~192~~ 191 bytes
Returns a multiline string. Input is an array with two strings.
[Try it online!](https://repl.it/ChEZ/1)
```
->o{x,y=o.sort_by!(&:to_i).map{|e|e.reverse.chars}
a,b=o.map &:to_i
k=' '
y.zip(x).map{|z|i,j=z.map &:to_i
k=i+j+k.to_i<10?' ':1}.reverse*''+"
%s
+%#{s=y.size}s
%s
%#{s+1}s"%[b,a,?-*s,a+b]}
```
[Answer]
# C (ansi), ~~392~~ 384 Bytes
Saved 8 thanks to Value Ink (392->384)
## Code:
```
char c[9],d[9],p[99]=" %s\n%0s\n+%0s\n %s\n%0i",*t,*b;k,r;main(a,i,m,n)char**i;{m=strlen(i[1]);n=strlen(i[2]);m==n?(strcmp(i[1],i[2])<0?t=i[2],b=i[1]:(t=i[1],b=i[2])):m<n?t=i[2],b=i[1]:(t=i[1],b=i[2]);n>m?:(n^=m,m=n^m,n=n^m);p[18]=p[5]=1+(p[10]=48+n);while(k<n)d[k]=45,a=(n-++k>=0)*(t[n-k]-48)+(m-k>=0)*(b[m-k]-48),r+=a*pow(10,k-1),c[n-k-1]=32+(a+c[n-k]%2>9)*17;printf(p,c,t,b,d,r);}
```
## With Spacing:
```
char c[9],d[9], p[99] = " %s\n%0s\n+%0s\n %s\n%0i", *t,*b;
k,r;
main(a,i,m,n)char**i;{
m=strlen(i[1]); //get length of num 1
n=strlen(i[2]); //get length of num 2
//Set the larger number to the top pointer
m==n?(strcmp(i[1],i[2])<0?t=i[2],b=i[1]:(t=i[1],b=i[2])):m<n?t=i[2],b=i[1]:(t=i[1],b=i[2]);
n>m?:(n^=m,m=n^m,n=n^m); //set n to the longer length
p[18]=p[5]=1+(p[10]=48+n); //set the buffers in the printf string
while(k<n) //for every number
d[k]=45, //add a dash
a=(n-++k>=0)*(t[n-k]-48)+(m-k>=0)*(b[m-k]-48), //do the addition
r+=a*pow(10.,(float)k-1), //add to result
c[n-k-1]=32+(a+c[n-k]%2>9)*17; //set 1 if carry or a space otherwise
printf(p,c,t,b,d,r); //print to stdio
}
```
## Usage:
### Compile Params:
```
gcc -O3 -ansi -lm -o add add.c
```
### Input:
```
./add 2834 97829
```
### Output:
```
11 1
97829
+ 2834
-----
100663
```
## Notes:
Only works on numbers up to 8 in length - formatting is hard or I'm really bad at it
I feel like my approach was suboptimal
] |
[Question]
[
## The task
The [credit rating agencies](https://en.wikipedia.org/wiki/Credit_rating_agency) assign ratings to bonds according to the credit-worthiness of the issuer, and the "Big Three" credit rating agencies use a similar (though not identical) [tiered rating system](https://en.wikipedia.org/wiki/Bond_credit_rating#Rating_tier_definitions). These have a clear, logical order - using the S&P tiers, AAA > AA+ > AA > AA- > A+ > ... > BBB > B > ... > C. Moody's uses a similar system, but names their tiers differently (Aaa > Aa1 > Aa2 > ... > Baa1 > ... > C).
Your task is to design a program which takes as input a list of strings representing bond rating tiers and output the same list, sorted in descending order from the highest tier (AAA/Aaa) to the lowest tier (C).
## Input / Output
You may choose the format of the input (list, one per argument, CSV file). You may assume that every item in the input list is a *valid rating string* and that all rating strings in a list came from the *same rating agency*. Additionally, you may assume that none of the funky NA-style ratings such as "NR" or "WR" will be included - this is strictly from "Aaa/AAA" to "C". There may be duplicate ratings in the input list, and if found they should not be removed.
You may also choose the format of the output as is appropriate for your language, with the only restriction being that it should be outputting some standard text encoding like UTF-8 or ASCII.
## Rules and scoring
This is code golf, so lowest byte count wins, standard loopholes disallowed. Please specify what the input and output format is.
## Example program and test cases
The example Python program below can be used as a standard example of the correct sort order. The lists `Moody` and `SP` are the orderings to use.
```
Moody = ['Aaa', 'Aa1', 'Aa2', 'Aa3', 'A1', 'A2', 'A3',
'Baa1', 'Baa2', 'Baa3', 'Ba1', 'Ba2', 'Ba3',
'B1', 'B2', 'B3', 'Caa', 'Ca', 'C']
SP = ['AAA', 'AA+', 'AA', 'AA-', 'A+', 'A', 'A-',
'BBB+', 'BBB', 'BBB-', 'BB+', 'BB', 'BB-',
'B+', 'B', 'B-', 'CCC', 'CC', 'C']
test_cases = [
(['Aa2', 'Aaa', 'Aa1'], ['Aaa', 'Aa1', 'Aa2']),
(['AA', 'AA-', 'AA+'], ['AA+', 'AA', 'AA-']),
(['Baa1', 'Ba1', 'A1', 'B1', 'Aaa', 'C', 'Caa', 'Aa1'],
['Aaa', 'Aa1', 'A1', 'Baa1', 'Ba1', 'B1', 'Caa', 'C']),
(['BBB+', 'BB+', 'A+', 'B+', 'AAA', 'C', 'CCC', 'AA+'],
['AAA', 'AA+', 'A+', 'BBB+', 'BB+', 'B+', 'CCC', 'C']),
(['B3', 'B1', 'B2'], ['B1', 'B2', 'B3']),
(['B-', 'B+', 'B'], ['B+', 'B', 'B-']),
(['B3', 'Caa', 'Aa1', 'Caa', 'Ca', 'B3'],
['Aa1', 'B3', 'B3', 'Caa', 'Caa', 'Ca']),
(['B-', 'CCC', 'AA+', 'CCC', 'CC', 'B-'],
['AA+', 'B-', 'B-', 'CCC', 'CCC', 'CC'])
]
mdy_sort = lambda x: Moody.index(x)
sp_sort = lambda x: SP.index(x)
for l_in, l_out in test_cases:
sort_key = mdy_sort if set(l_in).issubset(set(Moody)) else sp_sort
assert sorted(l_in, key=sort_key) == l_out
```
### Test cases
In case the python-style test case formatting is inconvenient, I've output it as space-delimited input strings (grouped in two-line pairs input followed by output):
```
Aa2 Aaa Aa1
Aaa Aa1 Aa2
AA AA- AA+
AA+ AA AA-
Baa1 Ba1 A1 B1 Aaa C Caa Aa1
Aaa Aa1 A1 Baa1 Ba1 B1 Caa C
BBB+ BB+ A+ B+ AAA C CCC AA+
AAA AA+ A+ BBB+ BB+ B+ CCC C
B3 B1 B2
B1 B2 B3
B- B+ B
B+ B B-
B3 Caa Aa1 Caa Ca B3
Aa1 B3 B3 Caa Caa Ca
B- CCC AA+ CCC CC B-
AA+ B- B- CCC CCC CC
```
***Note***: I mention the "Big Three" but only specify Moody's and S&P here - the reason is that the third, Fitch, uses the same system as S&P when you don't take into account the NA-style ratings, so including Fitch would be redundant.
[Answer]
## ES6, ~~71~~ 65 bytes
```
a=>a.sort((b,c)=>r(b)>r(c)||-1,r=s=>s.replace(/[^A-z]*$/,"z$&,"))
```
By inserting a `z` after the letters and suffixing a `,` we just have to sort the strings lexically.
Edit: Saved 6 bytes thanks to @user81655.
[Answer]
# Bash + GNU utilities, 45
Credit is due to @Neil for [the approach](https://codegolf.stackexchange.com/a/71725/11259).
```
sed s/$/e/|tr +-3 d-l|sort|tr -d e|tr d-l +-3
```
In my locale sort order, numbers sort before letters and `-` sorts before `+`. So these characters are transliterated into the alphabet range so they sort in the right order.
[Try it online.](https://ideone.com/VPZA1K)
[Answer]
## Pyth, 16 bytes
```
o+Xs}RGrN0N\z\,Q
```
We sort lexicographically by a key using @Neil's approach. Input and output are as lists; this does not mutate the list.
```
o+Xs}RGrN0N\z\,Q Implicit: Q = input list
lambda N (N is a bond rating)
rN0 Convert N to lowercase
}RG Map is-in G, the lowercase alphabet.
s Sum the list of bools; the number of letters in N.
X N\z Insert "z" at that position in N.
+ \, Append "," to the end.
This works because "," is between "+" and "-" lexicographically.
o Q Sort Q, using that lambda as a key.
```
Try it [here](https://pyth.herokuapp.com/?code=o%2BXs%7DRGrN0N%5Cz%5C%2CQ&test_suite=1&test_suite_input=%5B%27Baa2%27%2C+%27B1%27%2C+%27B2%27%2C+%27Baa3%27%2C+%27Ba3%27%2C+%27A1%27%2C+%27Aa3%27%2C+%27Aa1%27%2C+%27Ba1%27%2C+%27A2%27%2C+%27Caa%27%2C+%27Baa1%27%2C+%27Aa2%27%2C+%27Ca%27%2C+%27Aaa%27%2C+%27A3%27%2C+%27Ba2%27%2C+%27C%27%2C+%27B3%27%2C+%27B1%27%5D%0A%5B%27BB%2B%27%2C+%27CC%27%2C+%27C%27%2C+%27AA%27%2C+%27BB%27%2C+%27B%27%2C+%27BBB%2B%27%2C+%27B%2B%27%2C+%27AA-%27%2C+%27B-%27%2C+%27CCC%27%2C+%27A%27%2C+%27BB-%27%2C+%27AAA%27%2C+%27A-%27%2C+%27BBB-%27%2C+%27A%2B%27%2C+%27BBB%27%2C+%27AA%2B%27%2C+%27B%2B%27%5D&debug=0). Test cases are all bond ratings of each rating scheme, with a duplicate thrown in.
] |
[Question]
[
>
> OH GODS NO!! You can't leave us here with Doorknob! It'll be nethack everywhere! - [1d ago](http://chat.stackexchange.com/transcript/message/22533239#22533239) by [Geobits](http://chat.stackexchange.com/users/51024/geobits)
>
>
>
Well, couldn't disappoint...
## Introduction
*(you can skip this section if you don't care about exposition and/or if you have [Tab Explosion Syndrome](https://xkcd.com/609/))*
One of the characteristic mechanics of [Nethack](http://nethackwiki.com/wiki/NetHack) (and Rogue, and similar games in the same roguelike genre) is its [identification system](http://nethackwiki.com/wiki/Identification). At the beginning of the game, only items in your starting inventory are "formally identified." The vast majority of other objects start out unknown; for example, a "shield of reflection" will initially display as a "polished silver shield" before it's identified.
A "polished silver shield" can only be a [shield of reflection](http://nethackwiki.com/wiki/Shield_of_reflection), but this has interesting consequences in two other cases.
1. Some items are different from each other, but have the same "appearance." For example, if you find a "[gray stone](http://nethackwiki.com/wiki/Gray_stone)," it could be one of four things: A [flint stone](http://nethackwiki.com/wiki/Flint_stone) (useless), a [touchstone](http://nethackwiki.com/wiki/Touchstone) (can be useful), a [loadstone](http://nethackwiki.com/wiki/Loadstone) (which will severely encumber you because it weighs a ton and you can't drop it), or a [luckstone](http://nethackwiki.com/wiki/Luckstone) (extremely helpful, almost necessary for winning the game).
2. Many items (scrolls, wands, rings, spellbooks, some armor, etc.) have a randomized appearance. What this means is that there is a set list of possible apperances, say, potions could have; for example, [*golden potion*, *swirly potion*, *fizzy potion*, *purple-red potion*, etc.]. These appearances are then randomly assigned to what they actually are (*[potion of healing](http://nethackwiki.com/wiki/Potion_of_healing)*, *[potion of paralysis](http://nethackwiki.com/wiki/Potion_of_paralysis)*, *[potion of see invisible](http://nethackwiki.com/wiki/Potion_of_see_invisible)*, *[potion of polymorph](http://nethackwiki.com/wiki/Potion_of_polymorph)*, etc.).
Which means that a *hexagonal amulet* could [save your life in one game (amulet of life saving)](http://nethackwiki.com/wiki/Amulet_of_life_saving), and [choke you to death the next (amulet of strangulation)](http://nethackwiki.com/wiki/Amulet_of_strangulation).
Naturally, this makes identifying items a critical part of the game. Items can be "formally identified," meaning that they will unambiguously show up as definitely being a certain item (ex. all the *jeweled wands* you find will show up as *[wands of create monster](http://nethackwiki.com/wiki/Wand_of_create_monster)*); this is done primarily via [scrolls](http://nethackwiki.com/wiki/Scroll_of_identify) or [spellbooks](http://nethackwiki.com/wiki/Spellbook_of_identify) of identify. Typically those are in short supply, though, which brings us to...
Informal identification. This means that you're *pretty sure* (or certain) that a certain unidentified item is of a certain type (or that it can only be one of several types), but you haven't "formally" identified it yet. This can be done via several methods: [engrave-testing](http://nethackwiki.com/wiki/Wand#Engrave-identification) for wands, [sink-testing](http://nethackwiki.com/wiki/Sink#Identifying_rings_with_a_sink) for rings, or, the most common method...
[](http://nethackwiki.com/wiki/Price_identification#Identifying_scrolls)
... [price identification](http://nethackwiki.com/wiki/Price_identification)! Which is what this challenge is about.
In a nutshell, there are [shops](http://nethackwiki.com/wiki/Shop) located throughout the Dungeons of Doom (yes, the [shopkeepers](http://nethackwiki.com/wiki/Shopkeeper) thought it'd be a good idea to set up shop in some underground dungeon; don't ask why). In these shops, you can buy and sell the various items that you come across during your travels. When buying or selling an item, the shopkeeper will first tell you how much he would sell it to you / buy it from you for. Since certain items are guaranteed to have specific [prices](http://nethackwiki.com/wiki/Zorkmid#Use), you can use this to *informally identify* a certain type of item.
Some items, such as the *[scroll of light](http://nethackwiki.com/wiki/Scroll_of_light)*, are the only items to cost a certain amount, which allows you to unambiguously identify them; however, most items share a price group with other items of the same class, which only lets you narrow down the possibilities (which is still useful). However, the buy/sell prices of an item are affected by a number of variables (such as your [Charisma](http://nethackwiki.com/wiki/Charisma) stat). Hence the chart above.
Could you tell I like Nethack?
## Input
Input will be provided as a (vanilla, 3.4.3) Nethack game currently being played:
```
"For you, most gracious sir; only 177 for this scroll labeled VERR YED HORRE."
--More--
------------
| . ---------
| | ---------- | ^ |
| .## ################. +# #. .#
| | # | _|# #---------#
| | ### ##.< |# #### #
| .#########################----------# # #
------------ ### # ############# # # #
# # ----------- # # # ####
### ###| |### # # #----------
# #. |# ### # # #|.???????|
## | |# #--------# #|.??@????|
----.----###############. |# #| |# #-@???????|
|.......+# | |# #. |# ----------
|.......| | .# | |#
|......>| ----------- | +#
--------- --------
Wizard the Evoker St:12 Dx:14 Co:11 In:16 Wi:12 Ch:10 Chaotic
Dlvl:2 $:0 HP:11(11) Pw:0(8) AC:9 Exp:1 T:11
```
This means that it is guaranteed to have several properties:
* It will **always** be 24 lines long.
* Each line will **always** be 80 characters or less in length.
* The second-to-last line will consist of the following "*tokens*": the player's name and title (in the form of "*foo* the *bar*"), the list of attributes (separated by a single space), and the player's alignment (Lawful, Neutral, or Chaotic). Each *token* will be separated by a variable number of spaces.1
* The list of attributes will always be `St:* Dx:* Co:* In:* Wi:* Ch:*`, where a `*` character represents an integer from 3 to 25.2 (The point of interest here is the last stat, Charisma, which you need to calculate prices.)
* The first line will always consist of a shop-related message (specifically, the message that is displayed when you are buying or selling an item). Furthermore, this item is guaranteed to be a single, unidentified, unnamed scroll. For buying an item, this is:
```
"For you, {TITLE}; only {PRICE} for this scroll labeled {LABEL}."--More--
```
and for selling, it is:
```
{SHK} offers {PRICE} gold pieces for your scroll labeled {LABEL}. Sell it? [ynaq] (y)
```
where the "variables" listed in `{curly braces}` are the following:
+ `{TITLE}` is always one of "*good*", "*honored*", "*most gracious*", or "*esteemed*", concatenated with either "*lady*" or "*sir*".
+ `{PRICE}` is always an integer.
+ `{LABEL}` will always be one of the following ([source](http://nethackwiki.com/wiki/Randomized_appearance#Scrolls)):
```
ZELGO MER JUYED AWK YACC NR 9 XIXAXA XOXAXA XUXAXA
PRATYAVAYAH DAIYEN FOOELS LEP GEX VEN ZEA PRIRUTSENIE
ELBIB YLOH VERR YED HORRE VENZAR BORGAVVE THARR
YUM YUM KERNOD WEL ELAM EBOW DUAM XNAHT
ANDOVA BEGARIN KIRJE VE FORBRYDERNE HACKEM MUCHE
VELOX NEB FOOBIE BLETCH TEMOV GARVEN DEH
READ ME
```
+ `{SHK}` will always be one of the following ([source](http://nethackwiki.com/wiki/Shopkeeper#Shopkeeper_names)):
```
Skibbereen Ballingeary Inishbofin Annootok Abitibi
Kanturk Kilgarvan Kesh Upernavik Maganasipi
Rath Luirc Cahersiveen Hebiwerie Angmagssalik Akureyri
Ennistymon Glenbeigh Possogroenoe Aklavik Kopasker
Lahinch Kilmihil Asidonhopo Inuvik Budereyri
Kinnegad Kiltamagh Manlobbi Tuktoyaktuk Akranes
Lugnaquillia Droichead Atha Adjama Chicoutimi Bordeyri
Enniscorthy Inniscrone Pakka Pakka Ouiatchouane Holmavik
Gweebarra Clonegal Kabalebo Chibougamau Lucrezia
Kittamagh Lisnaskea Wonotobo Matagami Dirk
Nenagh Culdaff Akalapi Kipawa
Sneem Dunfanaghy Sipaliwini Kinojevis
```This message may be split onto another line (but it will never take up more than 2 lines).3
* Aside from the first few lines, all bets are off as to what the rest of the screen looks like. Nethack uses [the majority of the ASCII character set](http://nethackwiki.com/wiki/American_Standard_Code_for_Information_Interchange). The only thing that you can safely assume is that the input will be purely ASCII (however this probably won't matter because you can discard lines 3-22 anyway).
If the input is taken as a function argument, it will be given exactly as shown in the example above (newline separated). If you input via STDIN, it will be given as 24 consecutive lines of input (again, as shown above). You may choose whether you want the input to have a trailing newline or not. The input is guaranteed to have no trailing spaces.
## Output
Output should be provided as what I should [`#name`](http://nethackwiki.com/wiki/Name) the scroll that I just price-ID'd. The naming system I use (and that I have seen others use) is:
* If the scroll is unambiguously identified as a certain scroll (identify, light, enchant weapon), `#name` it that. This is the case for scrolls of the following *base prices* (you will see how to calculate base price below): 20 -> identify, 50 -> light, 60 -> enchant weapon.
* Otherwise, take the first three letters of the scroll's appearance, or the first word if it is less than 3 characters. For example, `ZELGO MER` becomes `ZEL`, `VE FORBRYDERNE` becomes `VE`, etc. Concatenate with this (a space, and then) the base price of the scroll. For example, `ELB 300`.
* If the base price can be one of two possibilities, I usually keep trying to buy or sell the item until I get an offered price that unambiguously places it into a certain price slot. However, you can't do that in this challenge, so just separate the two possible base prices with a slash (`/`). For example, `HAC 60/80`.
Here's the formula for converting the base price of an item into the price you are offered to buy it:
* start with the base price of the item
* chance of a possible 33% "unidentified surcharge," calculated via `price += price / 3`
* another chance of a 33% "sucker markup" (this isn't random chance actually, but for the purposes of this challenge it is), calculated the same way
* a charisma modifier, which is applied as follows:
```
Ch 3-5 6-7 8-10 11-15 16-17 18 19-25
Mod +100% +50% +33% +0% -25% -33% -50%
Code p *= 2 p += p/2 p += p/3 --- p -= p/4 p -= p/3 p /= 2
```
And here's the formula for base price -> sell price:
* start with the base price of the item
* divide this by either 2 or 3 ("normal" or "sucker markup" respectively; again, not random, but it is for the purposes of this challenge)
* chance of a further 25% reduction4, calculated via `price -= price / 4`
The division is integer division, which means the result *at each step* is rounded down. (Source: [wiki](http://nethackwiki.com/wiki/Price_identification), and a bit of source code digging. Reversing these formulas is your job.)
Finally, here's a handy-dandy ASCII chart that shows the possible buy prices (grouped by Charisma stat) and sell prices of a scroll with a certain base price:
```
Base Ch<6 6-7 8-10 11-15 16-17 18 19-25 Sell
20 40/52/68 30/39/51 26/34/45 20/26/34 15/20/26 14/18/23 10/13/17 5/6/8/10
50 100/132/176 75/99/132 66/88/117 50/66/88 38/50/66 34/44/59 25/33/44 12/16/19/25
60 120/160/212 90/120/159 80/106/141 60/80/106 45/60/80 40/54/71 30/40/53 15/20/23/30
80 160/212/282 120/159/211 106/141/188 80/106/141 60/80/106 54/71/94 40/53/70 20/26/30/40
100 200/266/354 150/199/265 133/177/236 100/133/177 75/100/133 67/89/118 50/66/88 25/33/38/50
200 400/532/708 300/399/531 266/354/472 200/266/354 150/200/266 134/178/236 100/133/177 50/66/75/100
300 600/800/1066 450/600/799 400/533/710 300/400/533 225/300/400 200/267/356 150/200/266 75/100/113/150
```
(This is identical to the chart on the wiki except that it lists all possible sell prices, while the wiki chart neglects to include two of the four possible sell prices. No, I didn't manually make that chart; generated with [this Ruby script](https://gist.github.com/KeyboardFire/58dfdb2fffaf59d69a6b).)
## Test cases
Input:
```
"For you, honored sir; only 80 for this scroll labeled LEP GEX VEN ZEA."
--More-- # #
---------------- -----
| | ------------####+ |
----- | -##############+ .# | |
| .###########| > |# # | | ##. |
| | #------------.---# ##. | # -----
-+--- ################## ----.-------### #
#### ### # # #
# # # ### ###
### ### # # #
# # # ### -----|--
-----.--- ### ----+---# |...@..|
| | # | |# |???+??|
| < .# ## ##+ | |+?????|
| |# ------.------- | | |??]?@?|
---------### | | | | --------
# # | | --------
###| | #
#+ |
--------------
Wizard the Evoker St:11 Dx:15 Co:9 In:20 Wi:9 Ch:11 Chaotic
Dlvl:7 $:0 HP:11(11) Pw:1(8) AC:9 Exp:1
```
Output: `LEP 60/80`
---
Input:
```
"For you, most gracious sir; only 80 for this scroll labeled DAIYEN FOOELS."
--More-- #
------------ ----- -------
----- | | | | | |
|!)%| | | --------------- | | #- |
|*[@| | .#####| < |#####. | ###| |
|?(?| ---------.-- #+ |# | | # | |
|[!(| ## | |# | +#### #. .#
|.@.| ##################. +# ---.- #| |#
---|- ### ---------------# ## #-------#
## # ###### # # #
# ### # # # #
## # # # # #
------ ##### # # # #
| | -.---- # # # #
| .##### |^ | #### # # #
| | # | | ---- #-----------.---- # #------
| | ###| | | | #. > | # #| |
------ #. | | | | .## #| |
| | ---- | | #. |
------ ---------------- ------
Wizard the Evoker St:11 Dx:14 Co:16 In:15 Wi:10 Ch:9 Chaotic
Dlvl:6 $:0 HP:11(11) Pw:9(9) AC:9 Exp:1
```
Output: `enchant weapon`
---
Input:
```
Aklavik offers 113 gold pieces for your scroll labeled GARVEN DEH. Sell it?
[ynaq] (y)
----- ------ --------- -------
| | | | # ##. | |.?)%/|
| | ##. | ----- # | | |.@!=*|
|< | # | | # ##. .#####+ > |# #-.*?@[|
| .##### | | ------------ # | { |# |^ |# #|.=%)+|
---.- | | | .#### | |# ---------## #-------
## -.---- #. | | |# # ### #
# ######## #| .## | |# ## #
### # #------------ # -----# #### #
# ####### ########################## #
# # # ###----.--#
# ### # # #| |#
--.---- ########################################### #. |#
| | #----------.-# | |#
| | #| |# -------
| | #| .#
| |########| |
------- ------------
# #
Wizard the Evoker St:9 Dx:14 Co:11 In:19 Wi:10 Ch:12 Chaotic
Dlvl:4 $:0 HP:11(11) Pw:5(9) AC:9 Exp:1 Satiated
```
Output: `GAR 300`
---
Input:
```
"For you, good lady; only 67 for this scroll labeled VE FORBRYDERNE."--More--
-------
##| |
------------ # | |
|+[!/!?%[?)| ### | | --------
|[)(!/+]?!@| # # | | ##+ |
|.......@..| -------------- ### | < | ## | |
--------+--- #| | # | | # | > |
# ###| .#### --.---- ### #- |
# ###. | # # ###| |
# #### ---.---------- # ######. |
# #### ## # ### --------
# #### # # #
# #### ######################## ###
### #### ----+---- #
# # #### | .##
----.------#### | ^ |
| +#### | > |
| | | ^ |
----------- ---------
Wizard the Evoker St:18 Dx:18 Co:16 In:20 Wi:20 Ch:18 Chaotic
Dlvl:4 $:150 HP:11(11) Pw:5(7) AC:9 Exp:1
```
Output: `VE 100`
---
Input:
```
Droichead Atha offers 5 gold pieces for your scroll labeled XIXAXA XOXAXA
XUXAXA. Sell it? [ynaq] (y)
------------
----- | .#
| .### ----------- #. { |#
----- | | # | | ###| |#
| .# #. | # | | # ---------+--#
| | ###-|--- | .## ### ## #
| | # # # | | # # # #
| -##### # | | #### ############ #
|> | ## # ---------+- ## -.---------- # ----------
| .#### ### ## #####| | # |.*??/?)*|
----- # # # # | | # |@*)%!)]%|
### ### ###### | | # |.=)!%*!!|
# # # # | | ##+@*[%)(%?|
##################### | | |.]?*?)%%|
-----+---.----##########. | |.%)%!!!%|
| +## ------------ ----------
| < | #
| |
--------------
Wizard the Digger St:11 Dx:9 Co:14 In:6 Wi:6 Ch:9 Lawful
Dlvl:3 $:0 HP:15(15) Pw:0(1) AC:9 Exp:1
```
Output: `identify`
*(I had to manually compile Nethack with all the other shopkeeper names removed because I couldn't find a shopkeeper who had a space in his name...)*
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes will ~~[ascend](http://nethackwiki.com/wiki/Ascension)~~ win.
---
1: this isn't necessarily always true during a Nethack game, but we assume this for the sake of simplicity.
2: again, not always true. Strength can be 18/01 through 18/\*\*, but you don't need to handle that.
3: more gross oversimplifications. For example, it is possible for a shopkeeper to call you "scum" or "most renowned and sacred creature," but you don't have to handle any of that.
4: which a smart player gets around by repeatedly offering to sell the item until given the higher price.
[Answer]
## Javascript (ES6), ~~1610~~ ~~724~~ ~~601~~ ~~612~~ ~~419~~ ~~405~~ 390 bytes
```
a=>(b=a.match(/(\d+) (g|f).+d (\w{0,3})[\s\S]+h:(\d+)/),c=+b[4],d=[20,50,60,80,100,200,300].reduce((d,e)=>(f=e/2,g=~~(e/3),(b[2]=='g'?[g-(g>>2),g,f-(f>>2),f]:[e,e+g,e+g+~~((e+g)/3)].map(h=>c<6?h*2:c<8?h+h>>1:c<11?h+~~(h/3):c<16?h:c<18?h-(h>>2):c<19?h-~~(h/3):h>>1)).includes(+b[1])?[...d,e]:d),[]),i={20:'identify',50:'light',60:'enchant weapon'}[d[0]],j=b[3]+' '+d[0],d[1]?j+'/'+d[1]:i||j)
```
~~**Large wall of text, meet large wall of code.**~~
### Ungolfed
```
inp => (
extraction = inp.match(/(\d+) (g|f).+d (\w{0,3})[\s\S]+h:(\d+)/),
charisma = +extraction[4],
allowed = [20, 50, 60, 80, 100, 200, 300].reduce((allowed, base) => (
tmp1 = base / 2,
tmp2 = ~~(base / 3),
(extraction[2] == 'g' ?
[tmp2 - (tmp2 >> 2), tmp2, tmp1 - (tmp1 >> 2), tmp1]
:
[base, base + tmp2, base + tmp2 + ~~((base + tmp2) / 3)].map(val =>
charisma < 6 ?
val * 2
: charisma < 8 ?
val + val >> 1
: charisma < 11 ?
val + ~~(val / 3)
: charisma < 16 ?
val
: charisma < 18 ?
val - (val >> 2)
: charisma < 19 ?
val - ~~(val / 3)
: val >> 1
)).includes(+extraction[1]) ? [...allowed, base] : allowed
), []),
name_ = {
20: 'identify',
50: 'light',
60: 'enchant weapon'
}[allowed[0]],
tmp3 = extraction[3] + ' ' + allowed[0],
allowed[1] ?
tmp3 + '/' + allowed[1]
:
name_ || tmp3
)
```
### Example
```
document.getElementById('input').value = `Droichead Atha offers 5 gold pieces for your scroll labeled XIXAXA XOXAXA
XUXAXA. Sell it? [ynaq] (y)
------------
----- | .#
| .### ----------- #. { |#
----- | | # | | ###| |#
| .# #. | # | | # ---------+--#
| | ###-|--- | .## ### ## #
| | # # # | | # # # #
| -##### # | | #### ############ #
|> | ## # ---------+- ## -.---------- # ----------
| .#### ### ## #####| | # |.*??/?)*|
----- # # # # | | # |@*)%!)]%|
### ### ###### | | # |.=)!%*!!|
# # # # | | ##+@*[%)(%?|
##################### | | |.]?*?)%%|
-----+---.----##########. | |.%)%!!!%|
| +## ------------ ----------
| < | #
| |
--------------
Wizard the Digger St:11 Dx:9 Co:14 In:6 Wi:6 Ch:9 Lawful
Dlvl:3 $:0 HP:15(15) Pw:0(1) AC:9 Exp:1`;
func=a=>(b=a.match(/(\d+) (g|f).+d (\w{0,3})[\s\S]+h:(\d+)/),c=+b[4],d=[20,50,60,80,100,200,300].reduce((d,e)=>(f=e/2,g=~~(e/3),(b[2]=='g'?[g-(g>>2),g,f-(f>>2),f]:[e,e+g,e+g+~~((e+g)/3)].map(h=>c<6?h*2:c<8?h+h>>1:c<11?h+~~(h/3):c<16?h:c<18?h-(h>>2):c<19?h-~~(h/3):h>>1)).includes(+b[1])?[...d,e]:d),[]),i={20:'identify',50:'light',60:'enchant weapon'}[d[0]],j=b[3]+' '+d[0],d.length-1?j+'/'+d[1]:i||j);
function run() {
try {
document.getElementById('output').value = func(document.getElementById('input').value);
} catch (e) {
document.getElementById('output').value = 'ERROR!';
}
}
```
```
<textarea id="input" placeholder="input" rows="20" cols="70"></textarea>
<br>
<button onclick="run()">Run</button>
<br>
<textarea id="output" placeholder="output" disabled="disabled"></textarea>
```
] |
[Question]
[
I'm a time traveler, and I'm obsessed with the passage of time. I particularly love the moments when the clock hands pass 12, or when I get to flip to the next page of my calendar, or when everyone yells "Happy New Year!"
Please write for me a program to show me how far I am from the last such moment to the next, in the form of a progress bar. For example, if I tell it the time is 09:12, it should print this:
```
09:00 ####---------------- 10:00
```
If I tell it the month is May, 1982, it should print this:
```
1982-01 #######------------- 1983-01
```
Did I mention I'm a time traveler? I travel to anywhere from the first millisecond of 0 A.D. to the last millisecond of 9999 A.D., so the program needs to handle any date and time in that range.
# Input
* Input will be in one of the following formats:
+ `YYYY-MM-DDThh:mm:ss.sss`
+ `YYYY-MM-DDThh:mm:ss`
+ `YYYY-MM-DDThh:mm`
+ `YYYY-MM-DDThh`
+ `YYYY-MM-DD`
+ `YYYY-MM`These are the only formats that need be handled. Each part will have exactly the number of digits shown, which means fractional seconds may have trailing zeroes (e.g. `.120`, never `.12`). The `T` is a literal letter "T" delimiting the date from the time. Hours are on a 24-hour clock.
* Months and days are 1-based (more on this below).
* Invalid and out-of-range inputs need not be handled.
* At the programmer's discretion, input may have a single trailing newline.
# Progress bar math
The program is concerned with the least- and second-least-significant units in the given input. For example, if the input has day-level precision (e.g. `2016-12-14`), the progress bar will indicate what proportion of the days in the input month have elapsed versus what remains.
The progress bar will have 20 units (characters) and the proportion represented will be rounded to the nearest increment of 1⁄20. For example, given `2016-12-14T12:28`, the progress bar will show **Round(28⁄60 × 20) = 9** of 20 units "filled."
### 1-based months and days
Although the day of December 1 (for example) is `01` in `2016-12-01`, for the purpose of calculation it is the 0th day of the month, because the truncated units imply the 0th millisecond of the 0th minute of the 0th hour of the day. In other words, `2016-12-01` is 0⁄31 of the way through December and `2016-12-02` is 1⁄31, and so on.
Likewise, `2016-01` is the 0th millisecond of the 0th day of January, so in calculations it is 0⁄12, which means `2016-12` is 11⁄12.
Yes, that means months and days will never completely fill the progress bar.
### Differing month durations and leap years
Different months have different numbers of days and the output must reflect this—including leap years. The progress bar for February 6, 2017 will be different from the progress bar for February 6, 2016 (or January 6 of both years).
### Miscellaneous
* Time travelers use the [proleptic Gregorian calendar](https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar). TL;DR: No special cases like [missing days in 1752](http://mentalfloss.com/article/51370/why-our-calendars-skipped-11-days-1752). Input will include dates in the year 0 A.D.
* Time travelers ignore daylight savings.
* The program is not required to account for leap seconds, but it may.
# Output
The program (or function) must print (or return as a string) a horizontally-oriented 20-character progress bar that is "filled in" for time that has elapsed and "open" for time that remains. It must "fill in" from left to right.
The progress bar must have a label to its left showing the beginning of the period being counted and another to its right showing the beginning of the next period, in the same format as the input (but showing only two units of precision). For our example `2016-12-14` valid output would be:
```
12-01 #########----------- 01-01
```
Here are the valid label formats for each of the possible periods:
* Months: `YYYY-MM`
* Days: `MM-DD`
* Hours: `DDThh`
* Minutes: `hh:mm`
* Seconds: `mm:ss`
* Milliseconds: `ss.sss`
No additional units may be included in the labels, and none may be omitted.
### Output notes
* The progress bar's "filled in" units will be represented by a `#` character. "Open" units will be represented by `-`.
* There must be exactly one space between the progress bar and each label.
* Leading or trailing spaces and/or a single trailing newline are allowed.
# Winning
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest code in bytes wins. Standard rules apply. Standard loopholes forbidden.
# Examples
```
Input Output
----------------------- -------------------------------------
2016-12-12T12:17 12:00 ######-------------- 13:00
2016-12-12 12-01 #######------------- 01-01
0000-01-01T00:00:00.000 00.000 -------------------- 01.000
0000-01-01T00:00 00:00 -------------------- 01:00
1899-12-31T23 31T00 ###################- 01T00
1899-12-31 12-01 ###################- 01-01
1899-12 1899-01 ##################-- 1900-01
1982-05-15T17:15 17:00 #####--------------- 18:00
1982-05-15T17 15T00 ##############------ 16T00
1982-05 1982-01 #######------------- 1983-01
9999-12-31T23:59:59.999 59.000 #################### 00.000
9999-12 9999-01 ##################-- 10000-01
2000-01-06 01-01 ###----------------- 02-01
2000-02-06 02-01 ###----------------- 03-01
2001-02-06 02-01 ####---------------- 03-01
1742-09-10 09-01 ######-------------- 10-01
```
[Answer]
# JavaScript, 282 bytes
```
(x,v=x.split(/\D/g),l=v.length-2,[a,b,c,d]=("10e5,01,-,12,01,-,"+new Date(v[0],v[1],0).getDate()+",00,T,24,00,:,60,00,:,60,000,.,1000").split`,`.slice(l*3,l*3+4),t=(v[l+1]-b)/d*20+.5|0,n=v[l],o=((n|0)+1)%a,r=l?('0'+o).slice(-2):o)=>n+c+b+' '+'#'.repeat(t)+'-'.repeat(20-t)+' '+r+c+b
```
Passes all the tests
```
(
x,
v=x.split(/\D/g),
l=v.length-2,
[a,b,c,d]=("10e5,01,-,12,01,-,"+new Date(v[0],v[1],0).getDate()+",00,T,24,00,:,60,00,:,60,000,.,1000").split`,`.slice(l*3,l*3+4),
t=(v[l+1]-b)/d*20+.5|0,
n=v[l],
o=((n|0)+1)%a,
r=l?('0'+o).slice(-2):o
) =>n+c+b+' '+'#'.repeat(t)+'-'.repeat(20-t)+' '+r+c+b
```
Test function prints nothing for pass, values for fail.
```
function test(value,expected){
if (f(value)!=expected)
{
console.log(value);
console.log(f(value));
console.log(expected);
}
}
```
The test cases:
```
test('2016-12-12T12:17','12:00 ######-------------- 13:00') ;
test('2016-12-12','12-01 #######------------- 01-01') ;
test('0000-01-01T00:00:00.000','00.000 -------------------- 01.000') ;
test('0000-01-01T00:00','00:00 -------------------- 01:00') ;
test('1899-12-31T23','31T00 ###################- 01T00') ;
test('1899-12-31','12-01 ###################- 01-01') ;
test('1899-12','1899-01 ##################-- 1900-01') ;
test('1982-05-15T17:15','17:00 #####--------------- 18:00') ;
test('1982-05-15T17','15T00 ##############------ 16T00') ;
test('1982-05','1982-01 #######------------- 1983-01') ;
test('9999-12-31T23:59:59.999','59.000 #################### 00.000') ;
test('9999-12','9999-01 ##################-- 10000-01') ;
test('2000-01-06','01-01 ###----------------- 02-01') ;
test('2000-02-06','02-01 ###----------------- 03-01') ;
test('2001-02-06','02-01 ####---------------- 03-01') ;
test('1742-09-10','09-01 ######-------------- 10-01') ;
```
[Answer]
# Pyth, 213 bytes
My first code in pyth! Behold:
```
+%h=N:[d"%.4d"\-=Z"%.2d"\-Z\TZ\:Z\:Z\."%.3d")-*2lKr:w"[-T:.]"d7 3*2lKJ@K_2+@N1+%eN=b<lK4+d+*\#=Gs+*20c-eKb@=H[0^9T12?q2=k@K1+28+q0%=YhK4-q0%Y400q0%Y100+30%+k/k8 2 24 60 60 999)lK.5+*\--20G+d+%hN%+J1@H-lK1+@N1%eNb
```
My pyth code is closely based off of my previous python answer. Here is the ungolfed version with comments:
```
"K is the input, as a list of numbers"
Kr:w"[-T:.]"d7
"Y=year"
=YhK
"k=month"
=k@K1
"H = a list of denominators"
=H[0 ^9T 12 ?q2k+28+q0%Y4-q0%Y400q0%Y100 +30%+k/k8 2 24 60 60 999)
"J is the second-to-last number of the input"
J@K_2
"b is the +1 starting point for months and days"
=b<lK4
"G is the number of hashtags in the statusbar"
=Gs+*[[email protected]](/cdn-cgi/l/email-protection)
"N is the formatted string"
=N:[d"%.4d"\-=Z"%.2d"\-Z\TZ\:Z\:Z\."%.3d")-*2lK3 *2lK
+%hNJ+@N1+%eNb+d+*\#G+*\--20G+d+%hN%+J1@H-lK1+@N1%eNb
```
Testing multiple values is easily accomplished by making the code loop, and adding a newline print to the end:
```
Wp+%h=N:[d"%.4d"\-=Z"%.2d"\-Z\TZ\:Z\:Z\."%.3d")-*2lKr:w"[-T:.]"d7 3*2lKJ@K_2+@N1+%eN=b<lK4+d+*\#=Gs+*20c-eKb@=H[0^9T12?q2=k@K1+28+q0%=YhK4-q0%Y400q0%Y100+30%+k/k8 2 24 60 60 999)lK.5+*\--20G+d+%hN%+J1@H-lK1+@N1+%eNb"\n"
```
Then I ran `cat testinput | pyth code.pyth > output` and `diff output testoutput` Or [try it online](https://pyth.herokuapp.com/).
[Answer]
# Python 2, 371 bytes
This challenge was surprisingly difficult! It seemed like I was going to be just under 300 until I worked out the output string formatting.
The kind of cool part is that my answer does not use any date package:
```
import re
s=raw_input()
S=[int(i)for i in re.sub('[-T:.]',' ',s).split()]
l=len(S)
y,m=S[:2]
d=[0,20<<9,12,28+(y%4==0!=y%100)+(y%400==0)if m==2else 30+(m+m/8)%2,24,60,60,999]
a,n=S[-2:]
b=1-(1if l>3else 0)
h=int(20.*(n-b)/d[l]+.5)
x,y,z='- %.4d - %.2d - %.2d T %.2d : %.2d : %.2d . %.3d'.split()[l*2-3:l*2]
print x%a+y+z%b+' '+'#'*h+'-'*(20-h)+' '+x%((a+1)%d[l-1])+y+z%b
```
] |
[Question]
[
You should write a program or function which receives a block of chars represented as a string and outputs or returns a similar string in which the letters adjacent in the alphabet are connected.
A visual example (in the form of `input => output`):
```
b d b d
|\ /|
| \ / |
=> | X |
| / \ |
e |/ \e
c a c a
```
## Details
* Input will be a string containing spaces, newlines and exactly one of each of the first `N` lowercase letters. `1 <= N <= 26`
* The lines of the input will be padded with spaces creating a full rectangular block.
* Every pair of letters adjacent in the alphabet will be on the same row, column or diagonal line and should be connected with a straight ascii line using `\ / | or -`. (The line might have a length of 0.)
* The following types of two-line overlaps should be handled:
```
/ and \ become X
| and - become +
/ and / become /
\ and \ become \
| and | become |
- and - become -
[letter] and [anything] become [letter]
```
* No other kind of two-line overlap will occur.
* If more than two lines overlap any pair of them will be guaranteed to be one of the valid overlaps. (e.g. `[letter] / |` triplet will never occur)
* Apart from changing spaces into `\ / | - X and +` input and output should be identical.
* Trailing newline is optional but have to be the same for input and output.
* This is code-golf so the shortest entry wins.
## Examples
Input:
```
b d
h gi
e f
c a
```
Output:
```
b d
|\ /|
| \ / |
| X h+--gi
| / \ | |
|/ \e--f
c a
```
Input:
```
dk j
b l
c fg
a m
i h
e
```
Output:
```
dk----j
/|| /
b / |l /
|X | \/
c \ fg/\
\|/\ \
a \ m
/| \
i-+----h
e
```
Input:
```
eti sqjh k p u cfm vb owgzyx rnd la
```
Output:
```
eti--sqjh-k--p--u--cfm-vb-owgzyx-rnd-la
```
Input:
```
a
```
Output:
```
a
```
[Answer]
# JavaScript (ES6) 246 ~~266 280 285 307~~
Quite bulky ...
A function with string param and returning the modified string. A trailing newline is optional unless the input is just 1 row (I need a newline to find the row len)
*Just to make someone happy*
```
F=b=>b.match(/\w/g).sort().map(l=>(q=b.indexOf(l),~p)?[o=b.indexOf('\n'),~o,o+2,1].map((d,i)=>{k=(q-p)/d|0;if(k&&k*d+p==q)for(m='/|\\-'[i];(p+=k>0?d:-d)-q;c==m|c>'`'&c<'{'?0:b[p]=c>' '?c<'/'|c>'z'?'+':'X':m)c=b[p]}):p=q,p=-1,b=[...b])&&b.join('')
```
*More readable*
```
F=b=>
b.match(/\w/g).sort().map(l=>
(q=b.indexOf(l),~p)?
[o=b.indexOf('\n'),~o,o+2,1].map((d,i)=>{
k=(q-p)/d|0;
if(k&&k*d+p==q)
for(m='/|\\-'[i];
(p+=k>0?d:-d)-q;
c==m|c>'`'&c<'{'?0:b[p]=c>' '?c<'/'|c>'z'?'+':'X':m)
c=b[p]
})
:p=q
,p=-1,b=[...b])
&&b.join('')
```
**Test** In Firefox/FireBug console
```
console.log(F('\
b d\n\
\n\
\n\
\n\
\n\
e\n\
c a\n'))
console.log(F('\
dk j\n\
\n\
b l \n\
\n\
c fg \n\
\n\
a m \n\
\n\
i h \n\
e \n'))
console.log(F('\
b d \n\
\n\
\n\
h gi\n\
\n\
e f \n\
c a \n'))
```
*Output*
```
b d
|\ /|
| \ / |
| X |
| / \ |
|/ \e
c a
dk----j
/|| /
b / |l /
|X | \/
c \ fg/\
\|/\ \
a \ m
/| \
i-+----h
e
b d
|\ /|
| \ / |
| X h+--gi
| / \ | |
|/ \e--f
c a
```
[Answer]
# Perl, 219
Some improvements may be still possible.
```
#!perl -p0
/
/;$x="@-";
sub g{map"(?=$_)(.@_)+[".chr(1+ord).chr(~-ord)."]",a..z}
sub f{for$p(g"{$x}"){s/$p/$&&((_."\177"x~-$x)x y!
!!)/se;$_=lc;s![\0\\]!@_!g}$x++}
f"/";y!\17!/!;f"|";f"\\";y/\17/X/;for$p(g){s/$p/$&=~y! |!-+!r/e}
```
Try [me](http://ideone.com/DJt3Wc).
] |
[Question]
[
## Task
You will be given a set of circles in the plane with their centers on the line **y=0**. It is guaranteed that no pair of circles has more than one common point.
Your task is to determine into how many regions into which the circles divide the plane. A region is an inclusion-maximal contiguous set of points not intersecting any of the circles.
You should write a program that computes this answer when given a description of the circles.
---
Here's an example:

On the left side you see the circles drawn in the plane. However, in the right half of the picture, the regions produced by the circles are colored distinctly (one color per region). There are six regions in this example.
---
### Input
The first line of the input contains a number, `N`, the number of circle descriptions to follow. This line is optional, if your solution works without it, it's fine.
The following `N` lines each contain two integers, *xi* and *ri > 0*, representing a circle with center *(xi, 0)* and radius *ri*.
It is guaranteed that no pair of circles has more than one common point. It is further guaranteed that *xi* and *ri* do not exceed `10^9` in absolute value (so they comfortably fit into a 32-bit integer).
---
The input may be:
* read from STDIN
* read from a file named `I` in the current directory
Alternatively, the input could be:
* available as a string (including newlines) in a global variable
* on the stack
---
### Output
This should be a single integer, the number to regions produced. This should be written to STDOUT or a file named `O` in the current directory.
---
### Rules
* Shortest code in bytes wins
* +200 byte penalty if your code does not have a runtime + space complexity polynomial in `n`
* -100 byte bonus for worst-case expected runtime + space complexity `O(n log n)`
* -50 byte bonus for worst-case expected runtime + space complexity `O(n)`
* -100 byte bonus for deterministic runtime + space complexity `O(n)`
While assessing the runtime:
* Assume that hash tables have `O(1)` expected runtime for insert, delete and lookup, regardless of the sequence of operations and the input data. This may or may not be true, depending on whether the implementation uses randomization.
* Assume that the builtin sort of your programming language takes deterministic `O(n log n)` time, where `n` is the size of the input sequence.
* Assume that arithmetic operations on input numbers take only `O(1)` time.
* Do not assume that input numbers are bound by a constant, although, for practical reasons, they are. This means that algorithms like radix sort or counting sort are not linear time. In general, very large constant factors should be avoided.
---
### Examples
Input:
```
2
1 3
5 1
```
Output: `3`
---
Input:
```
3
2 2
1 1
3 1
```
Output: `5`
```
4
7 5
-9 11
11 9
0 20
```
---
Input:
```
9
38 14
-60 40
73 19
0 100
98 2
-15 5
39 15
-38 62
94 2
```
Output: `11`
---
## Hints
We can use the following idea for a very compact solution. Lets intersect the set of circles with the X axis and interpret the intersection points as nodes in a planar graph:

Every circle produces exactly 2 edges in this graph and up to two nodes. We can count the number of nodes by using a hash table to keep track of the total number of distinct left or right borders.
Then we can use the [Euler characteristic formula](http://en.wikipedia.org/wiki/Euler_characteristic#Planar_graphs) to compute the number of faces of a drawing of the graph:
`V - E + F - C = 1`
`F = E - V + C + 1`
To compute `C`, the number of connected components, we can use a [depth-first search](http://en.wikipedia.org/wiki/Depth-first_search).
---
Note: This problem idea is borrowed from a [recent Croatian programming contest](http://hsin.hr/coci/), but please don't cheat by looking at the solution outlines. :)
[Answer]
## Ruby - ~~312~~ ~~306~~ ~~285~~ ~~273~~ ~~269~~ 259 characters
**This answer has been superseded by [my other approach](https://codegolf.stackexchange.com/a/24956/8478) which uses considerably less characters *and* runs in `O(n log n)`.**
Okay, let's go. For starters, I just wanted a working implementation, so this is not algorithmically optimised yet. I sort the circles from largest to smallest, and build a tree (circles included in other circles are children of those larger ones). Both operations take `O(n^2)` at worst and `O(n log n)` at best. Then I iterate through the tree to count areas. If the children of a circle fill up its entire diameter, there are two new areas, otherwise there is just one. This iteration take `O(n)`. So I have overall complexity `O(n^2)` and qualify for neither reward nor penalty.
This code expects the input *without* the number of circles to be stored in a variable `s`:
```
t=[]
s.lines.map{|x|x,r=x.split.map &:to_i;{d:2*r,l:x-r,c:[]}}.sort_by!{|c|-c[:d]}.map{|c|i=-1;n=t
while o=n[i+=1]
if 0>d=c[:l]-o[:l]
break
elsif o[:d]>d
n=o[:c]
i=-1
end
end
n[i,0]=c}
a=1
t.map &(b=->n{d=0
n[:c].each{|c|d+=c[:d]}.map &b
a+=d==n[:d]?2:1})
p a
```
Ungolfed version (expects input in variable `string`):
```
list = []
string.split("\n").map { |x|
m = x.split
x,radius = m.map &:to_i
list<<{x:x, d:2*radius, l:x-radius, r:x+radius, children:[]}
}
list.sort_by! { |circle| -circle[:d] }
tree = []
list.map { |circle|
i = -1
node = tree
while c=node[i+=1]
if circle[:x]<c[:l]
break
elsif circle[:x]<c[:r]
node = c[:children]
i = -1
end
end
node[i,0] = circle
}
areas = 1
tree.map &(count = -> node {
d = 0
i = -1
while c=node[:children][i+=1]
count.call c
d += c[:d]
end
areas += d == node[:d] ? 2 : 1
})
p areas
```
[Answer]
# Mathematica, ~~125~~ 122 - 150 = -28 chars
I don't know the complexity of the built-in function `ConnectedComponents`.
```
1+{-1,2,1}.Length/@{VertexList@#,EdgeList@#,ConnectedComponents@#}&@Graph[(+##)<->(#-#2)&@@@Rest@ImportString[#,"Table"]]&
```
Usage:
```
1+{-1,2,1}.Length/@{VertexList@#,EdgeList@#,ConnectedComponents@#}&@Graph[(+##)<->(#-#2)&@@@Rest@ImportString[#,"Table"]]&[
"9
38 14
-60 40
73 19
0 100
98 2
-15 5
39 15
-38 62
94 2"]
```
>
> 11
>
>
>
[Answer]
## Ruby, ~~203~~ ~~183~~ ~~173~~ 133 - 100 = 33 characters
So here is a different approach. This time, I sort the circles by their left-most point. Circles touching at their left-most point are sorted from largest to smallest. This takes `O(n log n)` (well, Ruby uses quick sort, so actually `O(n^2)` but implementing merge/heap sort is probably beyond the scope of this challenge). Then I iterate over this list, remembering all left-most and right-most positions of the circles I have visited. This allows me to detect if a series of circles connects all the way across an enclosing larger circle. In this case, there are two subareas, otherwise just one. This iteration takes only `O(n)` giving a total complexity of `O(n log n)` which qualifies for the 100 character reward.
This snippet expects the input to be supplied via a file in the command-line arguments *without* the number of circles:
```
l,r={},{}
a=1
$<.map{|x|c,q=x.split.map &:to_r;[c-q,-2*q]}.sort.map{|x,y|a+=r[y=x-y]&&l[x]?2:1
l[y]=1 if l[x]&&!r[y]
l[x]=r[y]=1}
p a
```
Ungolfed version (expects input in a variable `string`):
```
list = []
string.split("\n").map { |x|
m = x.split
x,radius = m.map &:to_r
list<<{x:x, d:2*radius, l:x-radius, r:x+radius}
}
list.sort_by! { |circle| circle[:l] + 1/circle[:d] }
l,r={},{}
areas = 1
list.map { |circle|
x,y=circle[:l],circle[:r]
if l[x] && r[y]
areas += 2
else
areas += 1
l[y]=1 if l[x]
end
r[y]=1
l[x]=1
}
p areas
```
[Answer]
## Julia - 260 -100(bonus?) = 160
>
> Interpreting the circles as figures with vertices (intersections), edges, and faces (areas of the plane) we can relate each other using **Euler characteristic**, so we only need to know the number of "vertices" and "edges" to have the number of "faces" or regions of the plane with the formula written below: 
>
>
>
**UPDATE:** By thinking a while i figured out that the problem with my method was only when circles where not connected, so i came with an idea, why not artificially connect them? So the whole will satisfy the Euler formula.

F = 2+E-V (V=6, E=9)
**[Dont work with nested circles, so its not an answer of the problem for general cases]**
**Code**:
```
s=readlines(open("s"))
n=int(s[1])
c=zeros(n,2)
t=[]
for i=1:n
a=int(split(s[i+1]))
c[i,1]=a[1]-a[2]
c[i,2]=a[1]+a[2]
if i==1 t=[c[1]]end
append!(t,[c[i,1]:.5:c[i,2]])
end
e=0
t=sort(t)
for i in 1:(length(t)-1) e+=t[i+1]-t[i]>=1?1:0end #adds one edge for every gap
2+2n+e-length(unique(c)) # 2+E-V = 2+(2n+e)-#vertices
```
[Answer]
## Spidermonkey JS, 308, 287, 273 - 100 = 173
I think if I rewrote this in Ruby or Python I could save characters.
Code:
```
for(a=[d=readline],e={},u=d(n=1);u--;)[r,q]=d().split(' '),l=r-q,r-=-q,e[l]=e[l]||[0,0],e[r]=e[r]||[0,0],e[r][1]++,e[l][0]++
for(k=Object.keys(e).sort(function(a,b)b-a);i=k.pop();a.length&&a.pop()&a.push(0)){for([l,r]=e[i];r--;)n+=a.pop()
for(n+=l;l--;)a.push(l>0)}print(n)
```
Algorithm:
```
n = 1 // this will be the total
e = {x:[numLeftBounds,numRightBounds]} // imagine this as the x axis with a count of zero-crossings
a = [] // this is the stack of circles around the "cursor".
// values will be 1 if that circle's never had alone time, else 0
k = sort keys of e on x
for each key in k: // this is the "cursor"
n += key[numLeftBounds] // each circle that opens has at least one space.
k[numRightBounds].times {n += a.pop()} // pop the closing circles. if any were never alone, add 1
k[numLeftBounds].times {a.push(alwaysAlone)} // push the opening circles
if !a.empty():
set the innermost circle (top of stack) to false (not never alone)
fi
loop
```
I'm not terribly great at big O notation, but I think that's O(n) since I'm effectively looping through each circle 3 times (create, left, right) and also sorting the map's keys (and I sort for O(n log n) but that disappears). Is this deterministic?
[Answer]
# JavaScript (ES6) - ~~255~~ 254 Characters - ~~100~~ 250 Bonus = ~~155~~ 4
```
R=/(\S+) (\S+)/ym;N=1;i=w=l=0;for(X=[];m=R.exec(S);){X[N++]={w:j=m[2]*1,l:k=m[1]-j,r:k+2*j};l=k<l?k:l;w=j<w?w:j}M=[];X.map(x=>M[(x.l-l+1)*w-x.w]=x);s=[];M.map(x=>{while(i&&s[i-1].r<x.r)N+=s[--i].w?0:1;i&&(s[i-1].w-=x.w);s[i++]=x});while(i)N+=s[--i].w?0:1
```
Assumes that the input string is in the variable `S` and outputs the number of regions to the console.
```
R=/(\S+) (\S+)/ym; // Regular expression to find centre and width.
N=1; // Number of regions
w=l=0; // Maximum width and minimum left boundary.
X=[]; // A 1-indexed array to contain the circles.
// All the above are O(1)
for(;m=R.exec(S);){ // For each circle
X[N++]={w:j=m[2]*1,l:k=m[1]-j,r:k+2*j};
// Create an object with w (width), l (left boundary)
// and r (right boundary) attributes.
l=k<l?k:l; // Update the minimum left boundary.
w=j<w?w:j // Update the maximum width.
} // O(1) per iteration = O(N) total.
M=[]; // An array.
X.map(x=>M[(x.l-l+1)*w-x.w]=x); // Map the 1-indexed array of circles (X) to a
// sparse array indexed so that the elements are
// sorted by ascending left boundary then descending
// width.
// If there are N circles then only N elements are
// created in the array and it can be treated as if it
// is a hashmap (associative array) with a built in
// ordering and as per the rules set in the question
// is O(1) per insert so is O(N) total cost.
// Since the array is sparse then it is still O(N)
// total memory.
s=[]; // An empty stack
i=0; // The number of circles on the stack.
M.map(x=>{ // Loop through each circle
while(i&&s[i-1][1]<x[1]) // Check to see if the current circle is to the right
// of the circles on the stack;
N+=s[--i][0]?0:1; // if so, decrement the length of the stack and if the
// circle that pops off has radius equal to the total
// radii of its children then increment the number of
// regions by 1.
// Since there can be at most N items on the stack then
// there can be at most N items popped off the stack
// over all the iterations; therefore this operation
// has an O(N) total cost.
i&&(s[i-1][0]-=x[0]); // If there is a circle on the stack then this circle
// is its child. Decrement the parent's radius by the
// current child's radius.
// O(1) per iteration
s[i++]=x // Add the current circle to the stack.
});
while(i)N+=s[--i][0]?0:1 // Finally, remove all the remaining circles from the
// stack and if the circle that pops off has radius
// equal to the total radii of its children then
// increment the number of regions by 1.
// Since there will always be at least one circle on the
// stack then this has the added bonus of being the final
// command so the value of N is printed to the console.
// As per the previous comment on the complexity, there
// can be at most N items on the stack so between this
// and the iterations over the circles then there can only
// be N items popped off the stack so the complexity of
// all these tests on the circles on the stack is O(N).
```
The time complexity is now O(N).
**Test Case 1**
```
S='2\n1 3\n5 1';
R=/(\S+) (\S+)/ym;N=1;i=w=l=0;for(X=[];m=R.exec(S);){X[N++]={w:j=m[2]*1,l:k=m[1]-j,r:k+2*j};l=k<l?k:l;w=j<w?w:j}M=[];X.map(x=>M[(x.l-l+1)*w-x.w]=x);s=[];M.map(x=>{while(i&&s[i-1].r<x.r)N+=s[--i].w?0:1;i&&(s[i-1].w-=x.w);s[i++]=x});while(i)N+=s[--i].w?0:1
```
Outputs: `3`
**Test Case 2**
```
S='3\n2 2\n1 1\n3 1';
R=/(\S+) (\S+)/ym;N=1;i=w=l=0;for(X=[];m=R.exec(S);){X[N++]={w:j=m[2]*1,l:k=m[1]-j,r:k+2*j};l=k<l?k:l;w=j<w?w:j}M=[];X.map(x=>M[(x.l-l+1)*w-x.w]=x);s=[];M.map(x=>{while(i&&s[i-1].r<x.r)N+=s[--i].w?0:1;i&&(s[i-1].w-=x.w);s[i++]=x});while(i)N+=s[--i].w?0:1
```
Outputs: `5`
**Test Case 3**
```
S='4\n7 5\n-9 11\n11 9\n0 20';
R=/(\S+) (\S+)/ym;N=1;i=w=l=0;for(X=[];m=R.exec(S);){X[N++]={w:j=m[2]*1,l:k=m[1]-j,r:k+2*j};l=k<l?k:l;w=j<w?w:j}M=[];X.map(x=>M[(x.l-l+1)*w-x.w]=x);s=[];M.map(x=>{while(i&&s[i-1].r<x.r)N+=s[--i].w?0:1;i&&(s[i-1].w-=x.w);s[i++]=x});while(i)N+=s[--i].w?0:1
```
Outputs: `6`
**Test Case 4**
```
S='9\n38 14\n-60 40\n73 19\n0 100\n98 2\n-15 5\n39 15\n-38 62\n94 2';
R=/(\S+) (\S+)/ym;N=1;i=w=l=0;for(X=[];m=R.exec(S);){X[N++]={w:j=m[2]*1,l:k=m[1]-j,r:k+2*j};l=k<l?k:l;w=j<w?w:j}M=[];X.map(x=>M[(x.l-l+1)*w-x.w]=x);s=[];M.map(x=>{while(i&&s[i-1].r<x.r)N+=s[--i].w?0:1;i&&(s[i-1].w-=x.w);s[i++]=x});while(i)N+=s[--i].w?0:1
```
Outputs: `11`
**Test Case 5**
```
S='87\n-730 4\n-836 2\n-889 1\n-913 15\n-883 5\n-908 8\n-507 77\n-922 2\n-786 2\n-782 2\n-762 22\n-776 2\n-781 3\n-913 3\n-830 2\n-756 4\n-970 30\n-755 5\n-494 506\n-854 4\n15 3\n-914 2\n-840 2\n-833 1\n-505 75\n-888 10\n-856 2\n-503 73\n-745 3\n-903 25\n-897 1\n-896 2\n-848 10\n-878 50\n-864 2\n0 1000\n-934 6\n-792 4\n-271 153\n-917 1\n-891 3\n-833 107\n-847 3\n-758 2\n-754 2\n-892 2\n-738 2\n-876 2\n-52 64\n-882 2\n-270 154\n-763 3\n-868 72\n-846 4\n-427 3\n-771 3\n-767 17\n-852 2\n-765 1\n-772 6\n-831 1\n-582 2\n-910 6\n-772 12\n-764 2\n-907 9\n-909 7\n-578 2\n-872 2\n-848 2\n-528 412\n-731 3\n-879 1\n-862 4\n-909 1\n16 4\n-779 1\n-654 68\n510 490\n-921 3\n-773 5\n-653 69\n-926 2\n-737 3\n-919 1\n-841 1\n-863 3';
R=/(\S+) (\S+)/ym;N=1;i=w=l=0;for(X=[];m=R.exec(S);){X[N++]={w:j=m[2]*1,l:k=m[1]-j,r:k+2*j};l=k<l?k:l;w=j<w?w:j}M=[];X.map(x=>M[(x.l-l+1)*w-x.w]=x);s=[];M.map(x=>{while(i&&s[i-1].r<x.r)N+=s[--i].w?0:1;i&&(s[i-1].w-=x.w);s[i++]=x});while(i)N+=s[--i].w?0:1
```
Outputs: `105`
**Previous Version**
```
C=S.split('\n');N=1+C.shift()*1;s=[];C.map(x=>x.split(' ')).map(x=>[w=x[1]*1,x[i=0]*1+w]).sort((a,b)=>(c=a[1]-2*a[0])==(d=b[1]-2*b[0])?b[0]-a[0]:c-d).map(x=>{while(i&&s[i-1][1]<x[1])N+=s[--i][0]?0:1;i&&(s[i-1][0]-=x[0]);s[i++]=x});while(i)N+=s[--i][0]?0:1
```
With comments:
```
C=S.split('\n'); // Split the input into an array on the newlines.
// O(N)
N=1+C.shift()*1; // Remove the head of the array and store the value as
// if there are N disjoint circles then there will be
// N+1 regions.
// At worst O(N) depending on how .shift() works.
s=[]; // Initialise an empty stack.
// O(1)
C .map(x=>x.split(' ')) // Split each line into an array of the two values.
// O(1) per line = O(N) total.
.map(x=>[w=x[1]*1,x[i=0]*1+w]) // Re-map the split values to an array storing the
// radius and the right boundary.
// O(1) per line = O(N) total.
.sort((a,b)=>(c=a[1]-2*a[0])==(d=b[1]-2*b[0])?b[0]-a[0]:c-d)
// Sort the circles on increasing left boundary and
// then descending radius.
// O(1) per comparison = O(N.log(N)) total.
.map(x=>{ // Loop through each circle
while(i&&s[i-1][1]<x[1]) // Check to see if the current circle is to the right
// of the circles on the stack;
N+=s[--i][0]?0:1; // if so, decrement the length of the stack and if the
// circle that pops off has radius equal to the total
// radii of its children then increment the number of
// regions by 1.
// Since there can be at most N items on the stack then
// there can be at most N items popped off the stack
// over all the iterations; therefore this operation
// has an O(N) total cost.
i&&(s[i-1][0]-=x[0]); // If there is a circle on the stack then this circle
// is its child. Decrement the parent's radius by the
// current child's radius.
// O(1) per iteration
s[i++]=x // Add the current circle to the stack.
});
while(i)N+=s[--i][0]?0:1 // Finally, remove all the remaining circles from the
// stack and if the circle that pops off has radius
// equal to the total radii of its children then
// increment the number of regions by 1.
// Since there will always be at least one circle on the
// stack then this has the added bonus of being the final
// command so the value of N is printed to the console.
// As per the previous comment on the complexity, there
// can be at most N items on the stack so between this
// and the iterations over the circles then there can only
// be N items popped off the stack so the complexity of
// all these tests on the circles on the stack is O(N).
```
The total time complexity is O(N) for everything except the sort which is O(N.log(N)) - however replacing this with a bucket sort, this will reduce the total complexity to O(N).
The memory required is O(N).
~~Guess what is next on my todo list... bucket sort in less than 150 characters.~~ Done
] |
[Question]
[
This challenge is brought to you by real (and tragic) inspiration. Recently, the number row on my keyboard has been a bit sporadic. The keys `1-9` work sometimes--but other times they have no result. As an avid programmer, this is horrible! (See that exclamation point? That's how you know they're working right now.) Not only do I often need the numbers themselves, but the symbols `!@#$%^&*(` are completely ineffective half the time as well! As a C programmer, rather than take time off my busy schedule of doodling around with code to fix my laptop, I've been more interested in working around the problem. Over the course of the past few weeks, slowly, all of the number literals in my code have been replaced with hexadecimal so that I don't have to go hunting around for numbers to copy and paste. However, some numbers aren't easy to type without the keys `1-9`. For example, the number `1` cannot be written so simply in hexadecimal, and I've resorted to replacing `1`s in my code with `0xF - 0xE`. The only keys that are affected are `1-9`, so I maintain full use of symbols like `+`, `-`, and `/`. However, I cannot use multiplication or parentheses, as `*` and `(` are often broken. This leads to your challenge.
# Input
An integer, `n` to stdin or your language's equivalent. If you wish, the integer may be preceded or followed by a new line or other whitespace character. Alternatively, you may receive input via a command line argument.
Your program should respond to negative input correctly, and be able to handle at least 32-bit signed integers.
# Output
Your program should output, in some observable form, the shortest (in non-whitespace characters) possible way to write the number `n` as a sum, difference, or division of one or more hexadecimal values. There is more than one way to solve this problem, and there is no requirement that you favor any equal-length output over any other.
The output should be in the form `A % A % A...` where `A` is a hexadecimal value following `0x` containing only digits `A-F a-f`, and `%` is one of of the symbols `-+/`. Let `/` describe integer division, not floating-point.
(Note that your output should result in `n` when evaluating divisions first, left to right, and then additions and subtractions, left to right, as is convention.)
# Test Cases
Input Output
1. `1`
`0xF - 0xE` (or `0xF-0xE` or `0xB-0xA` or `0xd - 0xc` or `0xF/0xF`)
2. `15`
`0xF`
3. `255`
`0xFF`
4. `30`
`0xF + 0xF`
# Scoring and Rules
This is code-golf. Your preliminary score is the number of bytes in your source file.
You may NOT use any of the digits `1-9` in your source.
You MAY use symbols `!@#$%^&*(` in your source, but each comes at a penalty of +20 to your score.
Your program may be replaced by a function that takes `n` as an argument as long as that function produces some form of human-readable output. Your function's return value does NOT count as output.
[Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are not allowed.
Lowest score wins! Good luck!
*Did I goof something up formatting/questioning/clarity-wise? Let me know! This is my first submission to this site!*
[Answer]
# JavaScript 287 (187+20\*5) ~~295 (195 +20\*5) 338 (198 + 20\*7)~~
A function that check every possible combinations of the 6 allowed hex digits (0xA to 0xF) and the 3 allowed operators.
Output via popup and not returning a value, as requested.
I used [] to group comma separated expression but could not avoid 5 ~~7~~ open brackets for loops and function calling.
To avoid digits there are variables A,B,C for 1,2,3 (this makes the code even more obscure)
**Edit** code revised focusing on avoiding '('. Removed `if`s and explicit RegExp creation
Beware: this function is incredibly slow, it will exceed the time limit for a script in FireFox, even for small input like 90.
To enumerate all the possible expression, I use number starting at 3 and going up forever. Digits encoding:
0,1,2 are the operators +,-,/
4 to 9 are the hex digits A..F
3 is not allowed
Each number is checked with a regexp `/3|[0-2]{2}/` to avoid the digit 3 and having 2 consecutive operators (the check also avoid traling and leading operators - see code)
The resulting string is something like `0xA + 0xA - 0xD` that is valid javascript, so I use eval to evaluate it. Unfortunatley the '/' operator is floating point and not integer in JavaScript, so I'm not 100% sure that the result are correct event casting to integer the final result (but I am quite confident, given that a small rounding error can not be amplified by a '\*')
```
F=x=>{
for(A=-~0,B=A+A,i=C=A+B,j=0;j?x-~~eval(L):A;)
{
j=++i+'0',k=0+j;
for(c of~k.search(C+'|[0-'+B+']{'+B+'}',L='',w='0x')?j='':j)
c>C?w+=' ABCDEF'[c-C]:[L+=w,w=' '+'+-/'[c]+' 0x']
}
alert(L)
}
```
*Something else*
Now, something funnier. I used an oversimplified expressione parser to avoid the eval call and, amusingly, that turned out to be a lot faster.
The parser is really simplified, in a real parser V and O should be arrays containing the pending values stack and the pending operators stack. Here V is the single pending value (and also the return value) and O is a string with at most 2 characters. P contains the operators precedence table, for '-+/' => '112'
This scores 275 + 4\*20 => 355
```
F=x=>{
for(A=-~0,B=A+A,i=C=A+B,D=A+C,j=0,P=''+A+A+B;j?x-V:A;)
{
j=++i+'0',k=0+j;
for(c of~k.search(C+'|[0-'+B+']{'+B+'}',v=V=O=L='',w='0x')?j='':j)
c>C?
w+='ABCDEF'[v<<=D,v+=D+A-~c,c-D]
:[
P[O[0]]>=P[c]?[v=O>A?V/v|0:O>0?V+v:V-v,O=c]:O=c+O,
L+=w,w=' '+'-+/'[c]+' 0x',V=v,v=0
]
}
alert(L)
}
```
**Test** In Firefox/FireBug console, change alert with return (a lot more usable)
```
;[0, 1, 15, 255, 30].forEach(x=>console.log(x,F(x)))
```
>
> 0 0xA - 0xA
>
> 1 0xA / 0xA
>
> 15 0xF
>
> 255 0xFF
>
> 30 0xF + 0xF
>
>
>
Just a little less obvious (but be patient)
```
;[16,40, 51, 62, 73, 84, 95].forEach(x=>console.log(x,F(x)))
```
>
> 16 0xBA / 0xB
>
> 40 0xA + 0xF + 0xF
>
> 51 0xDD - 0xAA
>
> 62 0xEA - 0xAC
>
> 73 0xA + 0xEA - 0xAB
>
> 84 0xFE - 0xAA
>
> 95 0xA + 0xFF - 0xAA
>
>
>
[Answer]
# Python 2: 185 byte + 2 \* 20 = 225
Way too long for a serious answer. But since there are no answers yet, I'll post it anyways.
```
from itertools import product as p
n=input()
l=t=0
while~l:
l=-~l
for i in p("0xABCDEF+-/",repeat=l):
j=""
for k in i:j+=k
try:exec"t="+j
except:0
if t==n:print j;l=~0;break
```
`product` creates all different arrangements of the allowed chars. `exec` tries to decode it. This sadly returns an exception, thence the long `try - catch` block. It the result is fine, it prints and exists.
2 times penalty, because of those braces during function calls.
] |
[Question]
[
The [Collatz Sequence](https://en.wikipedia.org/wiki/Collatz_conjecture) (also called the 3x + 1 problem) is where you start with any positive integer, for this example we will use 10, and apply this set of steps to it:
```
if n is even:
Divide it by 2
if n is odd:
Multiply it by 3 and add 1
repeat until n = 1
```
10 is even, so we divide by 2 to get 5. 5 is odd, so we multiply by 3 and add 1 to get 16. 16 is even, so cut it in half to get 8. Half of 8 is 4, half of 4 is 2, and half of 2 is 1. Since this took us 6 steps, we say that 10 has a **stopping distance** of 6.
A Super Collatz number is a number whose stopping distance is greater then the stopping distance of every number smaller than it. For example, 6 is a Super Collatz number since 6 has a stopping distance of 8, 5 has a stopping distance of 5, 4 has 2, 3 has 7, 2 has 1 and 1 has 0. ([A006877](https://oeis.org/A006877) in the OEIS) You must take a number **n** as input, and output out all the Super Collatz numbers up to **n**.
# Rules
* Full Program or function is acceptable.
* You can not precompute or hard-code the Super Collatz sequence.
* You can take input in any reasonable format.
* Output can be returned as a list from the function, or printed to STDOUT or a file. Whichever is most convenient.
* Invalid inputs (non-numbers, decimals, negative numbers, etc.) result in undefined behavior.
# Sample ungolfed python
```
def collatzDist(n):
if n == 1:
return 0
if n % 2 == 0:
return 1 + collatzDist(n / 2)
return 1 + collatzDist((n * 3) + 1)
n = input()
max = -1
superCollatz = []
for i in range(1, n + 1):
dist = collatzDist(i)
if dist > max:
superCollatz.append(i)
max = dist
print superCollatz
```
# Sample IO:
```
#in #out
4 --> 1, 2, 3
50 --> 1, 2, 3, 6, 7, 9, 18, 25, 27
0 --> invalid
10000 --> 1, 2, 3, 6, 7, 9, 18, 25, 27, 54, 73, 97, 129, 171, 231, 313, 327, 649, 703, 871, 1161, 2223, 2463, 2919, 3711, 6171
```
Also here are the first 44 Super Collatz numbers:
```
1, 2, 3, 6, 7, 9, 18, 25, 27, 54, 73, 97, 129, 171, 231, 313, 327, 649, 703, 871, 1161, 2223, 2463, 2919, 3711, 6171, 10971, 13255, 17647, 23529, 26623, 34239, 35655, 52527, 77031, 106239, 142587, 156159, 216367, 230631, 410011, 511935, 626331, 837799
```
[Answer]
## Python 2, 104 bytes
```
c=lambda x:x>1and 1+c([x/2,x*3+1][x%2])
lambda n:[1]+[x for x in range(2,n)if c(x)>max(map(c,range(x)))]
```
`c` is a helper function that calculates the Collatz distance for a given integer. The unnamed lambda is the main function, which computes the super Collatz numbers up to (but not including) the input.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 41 bytes
```
(∪⊢⍳⌈\)≢∘{1=⍵:⍬⋄2|⊃⌽⍵:⍵,∇1+3×⍵⋄⍵,∇⍵÷2}¨∘⍳
```
An unnamed function. Name or parenthesize to apply.
Test cases:
```
((∪⊢⍳⌈\)≢∘{1=⍵:⍬ ⋄ 2|⊃⌽⍵:⍵,∇ 1+3×⍵ ⋄ ⍵,∇ ⍵÷2}¨∘⍳)¨4 50 10000
┌─────┬────────────────────┬───────────────────────────────────────────────────────────────────────────────────────────┐
│1 2 3│1 2 3 6 7 9 18 25 27│1 2 3 6 7 9 18 25 27 54 73 97 129 171 231 313 327 649 703 871 1161 2223 2463 2919 3711 6171│
└─────┴────────────────────┴───────────────────────────────────────────────────────────────────────────────────────────┘
```
0 results in undefined behaviour.
[Answer]
## ES6, ~~86~~ 83 bytes
```
n=>(i=m=0,c=n=>n<3?n:c(n&1?n*3+1:n/2)+1,[for(x of Array(n))if(c(++i)>m&&(m=c(i)))i])
```
Edit: Saved 3 bytes by switching from `filter` to an array comprehension.
[Answer]
# Haskell, 84 bytes
```
c 1=0;c x|odd x=1+c(3*x+1)|0<1=1+c(div x 2)
f x=[n|n<-[1..x],all(c n>)$c<$>[1..n-1]]
```
This is massively slow, of course, but it works!
[Answer]
# Oracle SQL 11.2, 329 bytes
```
WITH q(s,i)AS(SELECT LEVEL s,LEVEL i FROM DUAL CONNECT BY LEVEL<=:1 UNION ALL SELECT s,DECODE(MOD(i,2),0,i/2,i*3+1)i FROM q WHERE i<>1),v AS(SELECT s,COUNT(*)-1 d FROM q GROUP BY s),m AS(SELECT s,d,MAX(d)OVER(ORDER BY s ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING)m FROM v)SELECT s FROM m WHERE(d>m OR s=1)AND:1>0ORDER BY 1;
```
Un-golfed version
```
WITH q(s,i) AS
(
SELECT LEVEL s, LEVEL i
FROM DUAL CONNECT BY LEVEL <= :1
UNION ALL
SELECT q.s, DECODE(MOD(i,2),0,i/2,i*3+1)i FROM q WHERE q.i <> 1
)
, v AS (SELECT s, COUNT(*)-1 d FROM q GROUP BY s)
, m AS (SELECT s, d, MAX(d)OVER(ORDER BY s ROWS BETWEEN UNBOUNDED PRECEDING AND 1 PRECEDING) m FROM v)
SELECT * FROM m WHERE (d>m OR s=1) AND :1>0
ORDER BY 1;
```
The q view is a true recursive view (not a hierarchical query with CONNECT BY) that compute all steps toward 1 for every integer between 1 and :1.
The v view compute the stopping distances.
The m view use the analytical version of MAX to apply it to every rows preceding, excluding the current row. That way for each integer we know it's stopping distance and the current greatest stopping distance.
The final query check if the stopping distance is greater than the greatest stopping distance. And adds a few tricks to handle 1 and the special case of :1 having a value of 0.
[Answer]
# Pyth, 23 bytes
```
q#eol.u@,/N2h*N3NN)STSQ
```
[Demonstration](https://pyth.herokuapp.com/?code=q%23eol.u%40%2C%2FN2h%2aN3NN%29STSQ&input=100&debug=0)
This works by taking the max of the range up to each number by their Collatz stopping distance, and checking whether that max is the number in question.
[Answer]
# ùîºùïäùïÑùïöùïü, 30 chars / 38 bytes
```
⩥ïⓜМȬ⧺$,a=[])⋎⟮aꝈ-1⟯>ɐ⅋(ɐ=Ⅰ,ᵖ$
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter3.html?eval=true&input=20&code=%E2%A9%A5%C3%AF%E2%93%9C%D0%9C%C8%AC%E2%A7%BA%24%2Ca%3D%5B%5D%29%E2%8B%8E%E2%9F%AEa%EA%9D%88-1%E2%9F%AF%3E%C9%90%E2%85%8B%28%C9%90%3D%E2%85%A0%2C%E1%B5%96%24)`
The only reason I didn't post this earlier was because I wasn't clear on the specs. Uses a custom encoding that encodes 10-bit chars.
# Explanation
`⩥ïⓜ` creates a range `[0,input)` to map over. `МȬ⧺$,a=[])` generates Collatz numbers in an empty array, and `⋎⟮aꝈ-1⟯>ɐ` uses the array of Collatz numbers to get the stopping distance and check if that's greater than the previous maximum stopping distance. If so, `⅋(ɐ=Ⅰ,ᵖ$` makes the current stopping distance the maximum stopping distance and pushes the current item in the range to the stack. After, the stack's items are implicitly printed.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
```
×3‘$HḂ?ƬL$€<Ṫ$PµƇ
```
[Try it online!](https://tio.run/##AS4A0f9qZWxsef8Kw4fGrP/DlzPigJgkSOG4gj/GrEwk4oKsPOG5qiRQwrXGh////zUw "Jelly – Try It Online")
I reckon there's still a couple of bytes that can be removed.
## How it works
```
×3‘$HḂ?ƬL$€<Ṫ$PµƇ - Main link. Takes n on the left
µƇ - Generate the list [1, 2, ..., n] and filter each i based on the following:
$€ - Over each j [1, 2, ..., i]:
Ƭ - Do the following until reaching a fixed point:
? - If statement:
Ḃ - Condition: i is odd
$ - If so:
√ó3 - Multiply by 3
‘ - Increment
H - Else: Halve
L - Take the length
Call this list of lengths l
$ - Group the previous two links and run over l
·π™ - Remove the last value of l
< - Is this greater than each value in l?
P - Is this true for all values?
```
] |
[Question]
[
# Roguelike pathfinding
Your task will be, given a two-dimensional array of the elements described below, which represents a dungeon, to output or return a single number representing the amount of gold pieces the rogue can collect without waking up any monsters.
The elements of the array are as follows:
1. Empty spaces are represented by either `.` or a space, your call;
2. Rogue's starting position is represented by, of course, `@`;
3. A gold piece is represented by `$`;
4. Walls are represented by `#`;
5. Monsters are represented by characters from the following regexp: `[a-zA-Z*&]`.
The array shall not contain any characters not listed above, so you can assume that anything that is not a wall, an empty space, the rogue or a gold piece is a monster.
The rules for pathfinding are:
1. The rogue can only walk through empty cells or cells containing gold;
2. It takes a turn to move to a adjacent or diagonally adjacent cell;
3. Picking up the gold is instant;
4. The rogue can't stay adjacent or diagonally adjacent to a monster for more than one turn without waking it up, which is forbidden;
5. The rogue can enter the awareness area of a monster any number of times, the monster will only wake up if the rogue spends two *consecutive* turns near it.
# Input and output rules
You can get the input in any reasonable format, including a two-dimensional array, a flat array, a string or whatever else. If it makes your life easier, you may also take the dimensions of the array as well.
It's guaranteed that the rogue will not be near a monster at the beginning.
A full program or a function is fine.
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the score is the bytes count of your submission with fewer being better.
# Test cases
I use dots for empty spaces here for readability purposes, if you so desire you may use spaces (see above). Also note that this is a pure coincidence that the rogue is always in the upper-left corner, your code should handle any other valid position as well.
```
1)
@..
.$.
... -> 1
```
Just a sanity test.
```
2)
@....
...g$
..... -> 0
```
Again, a sanity test.
```
3)
@....
...$g
..... -> 1
```
The rogue can grab the gold by moving in from the left.
```
4)
@....g..
.......$
........
.....h.. -> 1
```
The rogue can zig-zag between the monsters, never staying for more than one turn near each.
```
5)
@....z..
.......$
.....b.. -> 0
```
The tactics from the previous test case don't work here - the monster sensitivity areas overlap.
```
6)
@$#.
###$
.... -> 1
```
Sanity test.
```
7)
@..#..
$.$g.$
...#.. -> 2
```
Ditto.
```
8)
@#.d#$
$...##
e.....
..$...
##..$b
.#..g$ -> 3
```
Of all the gold here, only three can be reached safely: the gold near the starting position can be got by moving down one and then back to the starting position. To escape from the top left corner the rogue has to move diagonally down-right twice. The gold in the middle poses no challenge. The outer gold guarded by `g` and `b` can be got by moving in diagonally from the place to the right of the middle gold and then back. The rest cannot be got: top-right gold is blocked by walls, and the bottom-right gold requires two turns in monster sensitivity areas.
The following test cases were generously donated by mbomb007.
```
9)
12345678
a @....g.D
b .......$
c ......#.
d .....h.. -> 1
```
This one is tricky. A path is `b4-b5-c6-b7-c8-b8(grab)`.
```
10)
12345678
a @....g.D
b .......$
c .......#
d .....h.. -> 1
```
A path is `[bc]4-c5-b6-c7-b8(grab)`.
```
11)
12345678
a @....g.D
b ......#$
c .......#
d .....h.. -> 1
```
The extra wall doesn't actually change anything, `[bc]4-c5-b6-c7-b8(grab)` is still a solution.
[Answer]
previous solutions (part of them) can be found in the footer container in the tio link (those are probably more readable)
# [JavaScript (Node.js)](https://nodejs.org),883 436 411 360,345 311 bytes
```
g=>g.map((r,y)=>[...r].map((c,x)=>A+=c=="$"&&P(g,x,y)),A=0)|A
P=(g,x,y,m={},p={},I=i=9,M={})=>{if(/[.$]/.test(c=(g[y]||0)[x])){for(;i--;)if(/^[^.@$#]$/.test(C=(g[y+~-(i/3)]||0)[x+i%3-1])){if(m[C])return
M[C]=1}for(;I--;)if(!p[(X=x+~-(I/3))+","+(Y=y+I%3-1)]&&P(g,X,Y,M,{...p,[x+","+y]:1}))return 1}return c=="@"}
```
[Try it online!](https://tio.run/##zVVdb9pAEHzfX3Gx3egOnw8c0kotvSiIvPCAFKUvSS1HEDCOER@WbSII0L9O92yjBAcikgqplmzt3e3M7s1q5EHnqRN3oyBMrPGk5637cu3LC1@MOiGlEZ8zeeEIISI32@nyGe7UTdmVUjO009Nr6vMZpjFelxW2rMO1zHb4SC5WPFSfpgzkd97CELGLoE/LjjDcski8OKFdzHfm7nJZYc7MZWzRn0S0FlhWjanMe@deXBq6a@TpjTTd/GPRoFxlOcwMvlQtW4ERMnIaLou8ZBqNoYWxtFcpZTOnPAkdeitniqKJFMzUuGbSOzk3m4qFudmlbvkdb/EF3j3kWEElzd0f9orl3MRe5YGS4lJbrbuTcTwZemI48Wmfti@FAGHgK0RbxOEwSNrQZlLaDOBtqkgTfUN9C4DKOwDD3wHYV8HPMOoxNkG@83ggxfMbiocDujV0AbquZ4gD6uhYxcC7ZTX0AuZsB0YXPaQ3VLYO3uZiao2FMXgAReMbW0TVvTpdFXXSP6jTDgqhQ498kkR/RbKXolyC6vlXgjTTJJiM4cg@JukD@@zsuJmf4ZWhIXN0x3quW79LpweaGgquJv3OMPY23s66eHE4FCxOyuQfTJ5EUw9WsO10gOq3Cvl1RJ0/oXIqQSCts5ppBj/PMiFupNI1cFl6OshOB5vT3aO4QSEG/6fs57Z9BNkdF2VHIT@idp741IlIC7GfEf9F@4L0y6UmNPyXASFqAiIYd4fTnhfTBtseBSEtEU7jRzyAVwNRTW31stkstnASvnBTrJyPC3tmLJfMHHBc4rCcdFibWb07KFxDqQzrvw "JavaScript (Node.js) – Try It Online")
# Explantion -
instead of going from the player to the cash i went from the case to the @. i think i should be faster because i know when to stop looking (reach the @) , and when you look for cash you need to always keep moving until you covered all of the spots (and the ways to get to them). so the algo is pretty simple that way - the main function
`g.map((r,y)=>[...r].map((c,x)=>A+=c=="$"&&P(g,x,y)),A=0)|A`:
find cash -> if you found it -> start looking for the player -> if you found him -> increment A
now lets got to the path finder aka P
`if(/[.$]/.test(c=(g[y]||[])[x]))` just check if the current cell is "special" -> if so we want to return if its a player. special cases : @#(monster)
`for(;i--;)
if(/^[a-zA-Z*&]$/.test(C=(g[y+~-(i/3)]||0)[x+i%3-1])) -> if my neighbor is a monster
{if(m[C])return false -> and it already was in the previous turn - this path is not value
M[C]=1} -> if not just add it to the neighbors monsters`
`for(;I--;)
if(!p[(X=x+~-(I / 3))+","+(Y=y+I%3-1)]&&P(g,X,Y,M,{...p,[x+","+y]:1}))return true` iterate neighbors again - if i wasn't already there (p is the path taken)
continue path (call P)
[Answer]
# Python3, 710 bytes
```
E=enumerate
def F(s,c,C,O,e,M,x,y,U):
r=[]
for X,Y in s:e[(x,y)]=e.get((x,y),[])+[((X,Y),c)];r+=[(O+[(x,y)],X,Y,c+C*((X,Y)not in U),M,U+[(X,Y)]*C)]
return r
def f(b):
d,D={4:[]},[]
for x,r in E(b):
for y,v in E(r):d[K]=d.get(K:=[[[[4,3][v=='$'],2][v=='#'],1][v=='.'],0]['@'==v],[])+[(x,y)];D+=[(x,y)]
C,e=[],{}
q=[([],*d[0][0],0,set(),[])]
while q:
O,x,y,c,M,U=q.pop(0)
if c==len(d[3]):return c
o={a:[(x+X,y+Y)for X,Y in[(0,1),(0,-1),(1,0),(-1,0),(1,1),(1,-1),(-1,1),(-1,-1)]if(P:=(x+X,y+Y))in b and[]==[1 for(J,K),w in e.get((x,y),[])if(J,K)==P and w>=c]]for a,b in d.items()}
if not M&{*o[4]}:C+=[c];q=F(o[3],c,1,*(P:=[O,e,{*o[4]},x,y,U]))+q+F(o[1],c,0,*P)+F(o[0],c,0,*P)
return max(C+[0])
```
[Try it online!](https://tio.run/##lVRtT9swEP68/AqLRKvdHFbSFihBnpBa@DDE4AsSyLOmNnFLpZK0SXjpqv727pyXwiCbtki1757nufPdxelild8ncbe/SLfbM6HjxwedjnJtRXpCzmkGIQzgCjRcwgus4IYFFkmFVBaZJCm5hTsyi0kWaEmRZkpoPtU5LRyQirmSUhQxCJk6SV0h6ZVbSQFxCN1Bu1TESW5S3TA86QY1BlPtAcOTUp0/pjFJi5omdGxqiGAo1r1Aqg3UxbxAajKclYICWsFTCaUsiOSFElFR3kUgJD496Cr5JETLaSnolKaNpl@aHE1PydZpS4gnVXVTlH4yNJ0UpkUGoHEesN5YZIkomu1IYpyH0ZDhacUgUPh8P5trsjS1XRXDDE2rYskXyYJ6DOHZhIRCzHVMI9lVLKgaD5FKxHoU4JnuLazcO/Y6fEk98Bngum82Hzxc98vNhxIqmP3S2y9cNZvQ60Ds8jGc0piM4kgqIaRvhke/wgWDZzO/dy8VYw0nxLWJIM9fRKiUqWgEYyOP@CzXDxllm7In82ovP6/bieypTTDA2YXqZCnOaYJd4hR8aJtipLlmlaq8bIoxd@kanW90HrSvWeF6O3d3Ox5GL3TgIsO2mU8E2dvbs045t7iDP9yNn3VeCV7AU8esNd19TzvTt3TvLT0tFeZxaqNC7uuAg7cBPz8EjGvdYa1zbG7Ztl3yJXf0msNGzMGayni7VvRrhc0jDHUMZ1u6Lsj4mBSNsWWCsOUi7LgK49zvdHsHh0d9a8Sr1obWmO9qDSsLa4v47w363v8m4fbHJP4/JbH/lsT8M@TJj3EySiM6xO//U3UtZHsym@c6pd@SWAMZ8mwxn@W09T1uMfwoF@kszumE7mIznzHWAHea4W4z3GuGD5rhw2b4qBnuN8PHzbDv/QE3fW5/AQ)
] |
[Question]
[
## Introduction
Every rational number between 0 and 1 can be represented as an eventually periodic sequence of bits.
For example, the binary representation of 11/40 is
```
0.010 0011 0011 0011 ...
```
where the `0011` part repeats indefinitely.
One way of finding this representation is the following.
Start with **r = 11/40**, then repeatedly double it and take the fractional part, recording when it goes above 1.
When the value of **r** repeats, you know you have entered a loop.
```
1. r = 11/40
2. 2*r = 11/20 < 1 -> next bit is 0, r = 11/20
3. 2*r = 11/10 >= 1 -> next bit is 1, r = 2*r - 1 = 1/10
4. 2*r = 1/5 < 1 -> next bit is 0, r = 1/5
5. 2*r = 2/5 < 1 -> next bit is 0, r = 2/5
6. 2*r = 4/5 < 1 -> next bit is 0, r = 4/5
7. 2*r = 8/5 >= 1 -> next bit is 1, r = 2*r - 1 = 3/5
8. 2*r = 6/5 >= 1 -> next bit is 1, r = 2*r - 1 = 1/5, same as in 4.
The loop 5. -> 6. -> 7. -> 8. now repeats.
```
To get from the binary string back to 11/40, you can use the formula
```
(int(prefix) + int(suffix)/(2^len(suffix) - 1)) / 2^len(prefix)
```
where `prefix` is the initial part `010`, `suffix` is the repeating part `0011`, and `int` converts a binary string to integer.
Given two such representations, we can perform the bitwise XOR operation on them.
The resulting sequence will also be periodic, so it represents a rational number.
For some rational numbers, there are two binary representations.
```
1/4 = 0.010000000...
= 0.001111111...
```
The choice between them can affect the result of the bitwise XOR.
In these cases, we use the former representation, which has infinitely many 0s.
## The task
Your inputs are two rational numbers in the half-open interval [0,1).
Your output shall be the result of the bitwise XOR operation applied to the inputs, expressed as a rational number.
Note that the output can be 1, even though neither of the inputs are.
The exact formats of input and output are flexible, but each rational number should be represented by two integers, the numerator and denominator (with the exception of 0 and 1, which can be represented as `0` and `1` if desired).
You can assume that the inputs are expressed in lowest terms.
The output **must** be expressed in lowest terms.
A built-in rational number type is an acceptable format, as long as it satisfies these restrictions.
You can ignore any bounds on integers imposed by your language, but your algorithm should theoretically work for all rational numbers.
The lowest byte count wins.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Example
Consider the inputs 11/40 and 3/7.
We write their representations one above the other, delimiting the repeating parts by pipes `|`.
Then we extract repeating parts of equal lengths, and apply bitwise XOR to them and the parts before them.
```
11/40 = 0. 0 1 0|0 0 1 1|0 0 1 1|0 0 1 1|0 0 1 1|0 0 1 1|0 0 1 1|0 0 1 ...
3/7 = 0.|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|0 1 1|...
-> 0. 0 0 1|0 1 0 1 1 1 1 0 1 0 0 0|0 1 0 1 1 1 1 0 1 0 0 0|0 1 0 ...
```
The resulting rational number is 89/520.
## Test cases
```
0 0 -> 0
1/2 1/2 -> 0
1/2 1/4 -> 3/4
1/3 2/3 -> 1
1/2 3/4 -> 1/4
5/8 1/3 -> 23/24
1/3 1/5 -> 2/5
15/16 3/19 -> 257/304
15/16 257/304 -> 3/19
3/7 11/40 -> 89/520
5/32 17/24 -> 59/96
16/29 16/39 -> 621001733121535520/696556744961512799
```
[Answer]
# Python 3, 193 164 bytes
```
def x(a,b,z=0):
l=[]
while(a,b)not in l:l+=[(a,b)];z=2*z|(a<.5)^(b<.5);a=a*2%1;b=b*2%1
p=l.index((a,b));P=len(l)-p
return((z>>P)+z%2**P*a**0/~-2**(P or 1))/2**p
```
Takes input as Python 3's `fractions.Fraction` type, and outputs it as well.
Fun fact (you can easily show this using generating functions), if you change `(a<.5)^(b<.5)` to `((a>=.5)and(b>=.5))` above you get the binary AND between two rational numbers. Call this `nd(a, b)`. Then we have `a + b - 2*nd(a, b) = x(a, b)`!
[Answer]
# JavaScript, 141 bytes
```
(p,q,r,s)=>(h=(v,u)=>v%u?h(u,v%u):[a/u,b/u])(b=(g=x=>x%q||x%s?g((x|x/2)+x%2):x)(1),a=(o=b/(b-(b&~-b)),x=p*b/q,y=r*b/s,(x%o^y%o)+(x/o^y/o)*o))
```
Wont work for last test case (integer overflow). Input 4 numbers for `p/q xor r/s`, output an array with two numbers. For testcase `0, 0`, you should input `0, 1, 0, 1`.
**How:**
(All numbers described here is in binary form.)
1. find the smallest number `b`, which `b = 10 ^ p - 10 ^ q (p, q are integers, p > q); and b = 0 (mod q); and b = 0 (mod s)`;
2. Let `x = p * b / q`, `y = r * b / q`; Convert `p / q`, `r / s` to `x / b` and `y / b`;
3. Let `o = 10 ^ (p - q) - 1`; split `x`, `y` to `[x % o, x / o]`, `[y % o, y / o]`; get xor for each part `[x % o xor y % o, x / o xor y / o]`, and join back to `(x % o xor y % o) + (x / o xor y / o) * o`; Donate it as `a`;
4. If `a = 0`, the answer is `0` (or `0 / 1`); Otherwise let `u = gcd(a, b)`; the answer is `(a/u)` and `(b/u)`.
```
f=
(p,q,r,s)=>(h=(v,u)=>u%v?h(u%v,v):[a/v,b/v])(b=(g=x=>x%q||x%s?g((x|x/2)+x%2):x)(1),a=(o=b/(b-(b&~-b)),x=p*b/q,y=r*b/s,(x%o^y%o)+(x/o^y/o)*o))
```
```
<div oninput="[v5.value,v6.value]=['?','?'];[v5.value,v6.value]=f(+v1.value,+v2.value,+v3.value,+v4.value)">
<input id=v1 />/<input id=v2 /> xor <input id=v3 />/<input id=v4 /> = <output id=v5></output> / <output id=v6></output>
<style>input{width:40px}</style>
</div>
```
] |
[Question]
[
Write a program or function that takes in three integers, a width `w`, a height `h`, and a step count `s`. You will be drawing a non-self-intersecting [random walk](https://en.wikipedia.org/wiki/Random_walk) `s` steps long on a `5*w` by `5*h` pixel image where every 5 by 5 pixel cell is either empty (pure beige) or one of these twelve simple "pipes":
[](https://i.stack.imgur.com/gLgZX.png)
The image above is enlarged to show detail. Here are the pipes at actual size:
[](https://i.stack.imgur.com/19XPg.png)
(The gray lines are just to separate the pipe types.)
The random walk will be a single continuous pipe path that starts at one pipe endpoint (one of the bottom four pipe types) and ends at another pipe endpoint.
Start with an empty `w` by `h` grid and randomly choose one cell to be the starting point. Then randomly choose one of the four directions to start in and draw the corresponding pipe endpoint. This starting cell marks the first step in your walk and every time you draw a new cell or overwrite an existing one it counts as another step taken.
Now, repeatedly, randomly choose to go right, left, or straight, drawing the appropriate pipe cell if the direction chosen is valid. Backtrack and re-choose if a direction is not valid until the complete `s` step path is formed. The path should end with a pipe endpoint, which might be anywhere on the grid, depending on the course the path took.
It is very important to note that only the two straight pipe cells can be overwritten, and only by the straight pipe cell of the opposite orientation, the result being an intersection cell. **Otherwise, all pipes must be placed in empty cells.**
When an intersection is drawn, the part of the path that is further along from the starting cell should be drawn on top.
It is up to you whether or not the grid has [periodic boundary conditions](https://en.wikipedia.org/wiki/Periodic_boundary_conditions) (PBC), i.e. whether a pipe exiting one side of the grid will come out on the other side. Without PBC the grid boundary counts as a barrier that you can run into just like other pipes.
### Special Cases
* When `s` is 0 no pipes should be drawn and the output should be a blank `5*w` by `5*h` image (i.e. all beige).
* When `s` is 1 a single pipe stub
[](https://i.stack.imgur.com/J6uSv.png) (Actual size: [](https://i.stack.imgur.com/DmCX6.png))
should be drawn at the randomly chosen starting cell.
### Other Details
* You may assume that `s` is at most `w*h` so a path will always be possible. (Though longer paths are possible due to intersections.)
* `w` and `h` will always be positive.
* All random choices must be *uniformly* random. e.g. you shouldn't avoid making intersections when they are possible even if it makes the problem easier. Pseudo-random number generators are allowed.
* Any three visually distinct colors may be used in place of the black, blue, and beige.
* Your output images may be enlarged so that they are really `5*w*k` by `5*h*k` pixels where `k` is a positive integer. (Enlarging any examples you post is advised even if your `k` is 1.)
* Any common lossless image file format may be used and the image may be saved to a file, displayed, or spewed raw to stdout.
**The shortest code in bytes wins.**
# Examples
(All enlarged by 500%.)
If the input is `w=2, h=1, s=0` then the output will always be:
[](https://i.stack.imgur.com/V3Rf2.png)
If the input is `w=2, h=1, s=1` then the output will be one of these images with equal chance:
[](https://i.stack.imgur.com/F5KaU.png) [](https://i.stack.imgur.com/LfBGr.png)
If the input is `w=2, h=1, s=2` then the output will be
[](https://i.stack.imgur.com/tzjUW.png)
or possibly
[](https://i.stack.imgur.com/fnd8j.png)
if the grid is assumed to have PBC.
(Note that starting the path like [](https://i.stack.imgur.com/uxlJk.png) would make a second step impossible.)
---
Here are some possible outputs for `w=3, h=2, s=6`, assuming PBC:
[](https://i.stack.imgur.com/uCX1Z.png) [](https://i.stack.imgur.com/7rS6B.png) [](https://i.stack.imgur.com/amCUs.png)
---
Here is a possible output for `w=3, h=3, s=9`, assuming PBC:
[](https://i.stack.imgur.com/ZRzDX.png)
Notice that the path didn't need to cover all the cells due to the intersection counting as two steps. Also, we can deduce that the corner endpoint was the starting cell since the intersection overpass must have been drawn afterwards. Thus we can infer the sequence of random choices that were made:
```
start at top left, facing east
go straight
go right
go right
go right
go straight
go left
go right
end
```
---
Finally, here are examples of `w=4, h=5, s=20` and `w=4, h=5, s=16`:
[](https://i.stack.imgur.com/8154U.png) [](https://i.stack.imgur.com/wV4IT.png)
[Answer]
# CJam, 274
```
q~:K;:B;:A;{0aA*aB*:M5*5f*:I;K{[Bmr:QAmr:P]5f*:R;3Ym*{R.+:)2{1$0=I=2$W=@tI@0=@t:I;}:F~}/R2f+1FK({MQ=P=:EY4mr:D#&1{{MQMQ=PE2D#+tt:M;}:G~7,1>[W0_1_0_W]2/D=:Off*{[QP]5f*2f+.+_:H1F_OW%.+2FOW%.m2F}/H2FO~P+:P;Q+:Q;MQ=P=:E_5YD2%-*=!JK2-=+*1{D2+4%:D;G}?}?}fJ]}0?}g'P2NA5*SI,N2NI:+N*
```
[Try it online](http://cjam.aditsu.net/#code=q~%3AK%3B%3AB%3B%3AA%3B%7B0aA*aB*%3AM5*5f*%3AI%3BK%7B%5BBmr%3AQAmr%3AP%5D5f*%3AR%3B3Ym*%7BR.%2B%3A)2%7B1%240%3DI%3D2%24W%3D%40tI%400%3D%40t%3AI%3B%7D%3AF~%7D%2FR2f%2B1FK(%7BMQ%3DP%3D%3AEY4mr%3AD%23%261%7B%7BMQMQ%3DPE2D%23%2Btt%3AM%3B%7D%3AG~7%2C1%3E%5BW0_1_0_W%5D2%2FD%3D%3AOff*%7B%5BQP%5D5f*2f%2B.%2B_%3AH1F_OW%25.%2B2FOW%25.m2F%7D%2FH2FO~P%2B%3AP%3BQ%2B%3AQ%3BMQ%3DP%3D%3AE_5YD2%25-*%3D!JK2-%3D%2B*1%7BD2%2B4%25%3AD%3BG%7D%3F%7D%3F%7DfJ%5D%7D0%3F%7Dg'P2NA5*SI%2CN2NI%3A%2BN*&input=4%203%2010)
Uses PBC, outputs in PGM format. You can remove the `:+` near the end to get a nicer visual output in the browser.
It's very slow for larger input, especially if the step count is close to the area.
Example result for input `4 3 10` (scaled 500%):
[](https://i.stack.imgur.com/9lVCD.png)
**Brief explanation:**
The general approach is:
* repeat all the following steps until successful:
* initialize 2 matrices: one recording which sides are being used in each cell, and one for the image
* if s=0, we're done, else:
* pick a random cell and draw a square, then do the following s-1 times:
* pick a random direction; if that side is already used, fail and start over
* mark the side as used and draw the actual pipe in the image (drawing 3 adjacent lines of length 6, starting right "after" the center pixel of the current cell, then adding a dot to cap the end of the pipe)
* update the current position (moving to the next cell)
* check if the cell is empty or it's a valid crossing; if not, fail and start over
* mark the side in the opposite direction as used in this cell, then continue the loop
[Answer]
# QBasic, ~~517~~ 516 bytes
```
RANDOMIZE TIMER
SCREEN 9
INPUT w,h,s
1CLS
IF s=0GOTO 9
x=5*INT(RND*w)
y=5*INT(RND*h)
GOSUB 7
FOR k=1TO s-1
r=INT(RND*4)+1
a=x+5*((r=2)-(r=4))
b=y+5*((r=1)-(r=3))
c=(POINT(a,b+2)*POINT(a+4,b+2)+POINT(a+2,b)*POINT(a+2,b+4))*(0=POINT((a+x)\2+2,(b+y)\2+2))
IF((0=POINT(a+2,b+2))+c)*(a>=0)*(b>=0)*(a<5*w)*(b<5*h)=0GOTO 1
x=a
y=b
GOSUB 7
o=1AND r
p=x-2+3*o-5*(r=2)
q=y+1-3*o-5*(r=1)
u=p+3-o
v=q+2+o
LINE(p,q)-(u,v),7,B
LINE(p+o,q+1-o)-(u-o,v-1+o),1
NEXT
9IF c GOTO 1
END
7LINE(x+1,y+1)-(x+3,y+3),7,B
PSET(x+2,y+2),1
RETURN
```
* Takes `w`, `h`, and `s` from user input, comma-separated.
* Output is drawn on the screen. While the program is searching for a solution, you may see partial solutions flickering past.
* Does not use periodic boundary conditions. I found it easier to draw and test for connecting pipes without having to worry about half of the pipe being on one side of the grid and half on the other.
The approach here is to try a random direction at each step and start over from the beginning if it results in an invalid move. We draw the pipes as the directions are decided, and use `POINT` to test points on the screen for our validity conditions. A move is valid if it doesn't go outside the boundaries of the grid and:
1. The moved-to cell is empty; or
2. Both
1. The moved-to cell contains a pipe going straight through, either horizontally or vertically, and
2. The new pipe section does not double up an existing pipe section
Like [aditsu's CJam answer](https://codegolf.stackexchange.com/a/76230/16766), this code is very slow, and can be mind-numbingly slow if `s` is a significant fraction of `w*h`. On my QB64 setup, it comes up with an answer for `5,5,19` fairly promptly, but takes longer than I was willing to wait on `5,5,20`.
If you want to run larger/more densely packed examples, here's my original approach using a [depth-first search](https://en.wikipedia.org/wiki/Depth-first_search). It's much more efficient, at the cost of a whopping 300 extra bytes.
```
RANDOMIZE TIMER
SCREEN 9
INPUT w,h,s
DIM t(s),m(s)
0
FOR z=1TO s
t(z)=-1
NEXT
i=5*INT(RND*w)
j=5*INT(RND*h)
k=1
1CLS
IF s=0GOTO 9
x=i
y=j
GOSUB 7
FOR z=1TO k-1
r=m(z)
GOSUB 6
x=a
y=b
GOSUB 7
o=1AND r
p=x-2+3*o-5*(r=2)
q=y+1-3*o-5*(r=1)
u=p+3-o
v=q+2+o
LINE(p,q)-(u,v),7,B
LINE(p+o,q+1-o)-(u-o,v-1+o),1
NEXT
IF c*(k=s)THEN k=k-1:GOTO 1 ELSE IF k=s GOTO 9
IF k<1GOTO 0
IF t(k)>=0GOTO 4
t(k)=0
f=30
WHILE f
r=INT(RND*4)+1
IF f AND 2^r THEN t(k)=t(k)*5+r:f=f-2^r
WEND
4r=t(k)MOD 5
m(k)=r
t(k)=t(k)\5
GOSUB 6
c=(POINT(a,b+2)*POINT(a+4,b+2)+POINT(a+2,b)*POINT(a+2,b+4))*(0=POINT((a+x)\2+2,(b+y)\2+2))
IF((0=POINT(a+2,b+2))+c)*(a>=0)*(b>=0)*(a<5*w)*(b<5*h)THEN k=k+1 ELSE IF t(k)>0GOTO 4 ELSE t(k)=-1:k=k-1
GOTO 1
6a=x+5*((r=2)-(r=4))
b=y+5*((r=1)-(r=3))
RETURN
7LINE(x+1,y+1)-(x+3,y+3),7,B
PSET(x+2,y+2),1
RETURN
9
```
Example output for inputs `10, 10, 100`, actual size: [](https://i.stack.imgur.com/tsMfV.png)
A still fancier version can be found in [this gist](https://gist.github.com/dloscutoff/a16253d67c0295336228e8b33db6b6be). Besides being ungolfed and thoroughly commented, it scales up the output by a constant factor and allows for a set delay between steps, enabling you to watch the DFS algorithm at work. Here's an example run:
[](https://i.stack.imgur.com/ccO7A.gif)
] |
[Question]
[
The goal of this challenge is to write a **program** that visualizes a dependency graph in the form of a tree.
While "dependency graph" in this context means nothing more than a directed graph, the visualization method described here works best for graphs describing some dependency relation (as an exercise, after you've read the challenge, try to reverse the direction of one of the sample graphs, and see if the result is as useful.)
The **input** to the program consists of one or more **target definitions**, which are lines of the form
```
Target DirectDependency1 DirectDependency2 ...
```
, defining a **target**, and its associated **direct dependencies**, if any.
Targets and their dependencies are collectively called **objects**.
If an object appears only as a dependency, and not as a target, it has no dependencies.
The set of all objects that appear in the input is called **Γ**.
(See the Input and Output section for more details about the input format.)
For any pair of objects, *A* and *B*, we say that:
* ***A* depends on *B*** (equivalently, ***B* is required by *A***), if *A* directly depends on *B*, or if *A* directly depends on *B'*, and *B'* depends on *B*, for some object *B'*;
* ***A* properly depends on *B*** (equivalently, ***B* is properly required by *A***), if *A* depends on *B*, and *B* does not depend on *A*.
We define a contrived object, **ʀooᴛ**, not in Γ, such that ʀooᴛ is not directly required by any object, and such that, for all objects *A*, ʀooᴛ directly depends on *A* if and only if *A* is in Γ, and *A* is not properly required by any object in Γ (in other words, ʀooᴛ directly depends on *A* if no other object depends on *A*, or if all objects that depend on *A* are also required by *A*.)
**Output Tree**
We construct a **tree**, whose root node is ʀooᴛ, and such that the children of each node are its direct dependencies.
For example, given the input
```
Bread Dough Yeast
Dough Flour Water
Butter Milk
```
, the resulting tree is

, or, in ASCII form,
```
ʀooᴛ
+-Bread
| +-Dough
| | +-Flour
| | +-Water
| +-Yeast
+-Butter
+-Milk
```
.
The program's **output** is the above-defined tree, printed *without* the ʀooᴛ node.
So, for example, the corresponding output for the above input is
```
Bread
+-Dough
| +-Flour
| +-Water
+-Yeast
Butter
+-Milk
```
.
A detailed description of the layout of the output tree is given later.
**Node Order**
The child nodes of a given parent node, *P*, should be **sorted**, such that, for all child nodes *A* and *B* of *P*, *A* appears before *B* if and only if
* there exists a child node *C* of *P*, such that *A* is properly required by *C*, and *C* precedes, or equals to, *B*, according to the same order; **or**,
* *A* alphabetically precedes *B* (more preceisely, *A* precedes *B* using ASCII collation,) **and** there exists **no** child node *C* of *P*, such that *B* is properly required by *C*, and *C* precedes, or equals to, *A*, according to the same order.
(People looking for a mathematical challenge might want to show that this relation is well defined, and that it's, in fact, a strict total order. Don't forget that Γ is finite!)
For example, given the input
```
X D C B A
B D
C A
```
, the output should be
```
X
+-A
+-D
+-B
| +-D
+-C
+-A
```
.
`A` appears before `B`, and `B` appears before `C`, due to their alphabetical order;
`D` appears before `B`, since it is properly required by it, and after `A`, since it alphabetically follows it;
`B` and `C` do not appear before `D`, even though they precede it alphabetically, since there exists a node, namely, `B`, that properly requires `D`, and that equals to `B` (i.e., itself), and preceeds `C`, according to the same rules.
**Repetitions**
The same object, *A*, may appear more than once in the output, if, for example, it is required by more than one object.
If *A* has no dependencies of its own, no special handling is required in this case.
Otherwise, in order to minimize the verbosity of the output, and to avoid infinite recursion due to circular dependencies, the dependencies of *A* are listed only on its **first occurrence** for which none of the ancestors are siblings of another *A* node;
any other occurrence of *A* should have no children, and should appear followed by a space and an ellipsis, as in *`A`*`...`.
For example, given the input
```
IP Ethernet
TCP IP
UDP IP
WebRTC TCP UDP
```
, the output should be
```
WebRTC
+-TCP
| +-IP
| +-Ethernet
+-UDP
+-IP ...
```
.
As another example, featuring both circular dependency and ancestry considerations,
```
Rock Scissors
Paper Rock
Scissors Paper
```
, should result in
```
Paper
+-Rock ...
Rock
+-Scissors ...
Scissors
+-Paper ...
```
.
Note that, for example, the first occurrence of `Rock` does not list its dependencies, since its parent, `Paper`, is a sibling of another `Rock` node.
The parent of the second `Rock` node, ʀooᴛ (which doesn't appear in the output), doesn't have `Rock` as a sibling, so the dependencies of `Rock` are listed on this node.
**Output Tree Layout**
I'm sure you got the hang of how the tree should be represented as ASCII art (and feel free to skip this section if you have,) but for the sake of completeness...
The child nodes of ʀooᴛ are printed on separate lines, without any indentation, in order.
Each node is immediately followed by its children, if any, printed in the same fashion, recursively, indented by two characters to the right.
For each node that has children, a vertical line, consisting of `|` (pipe) characters, extends down from the character directly below the first character of the node, until the row of its last child node, not including the last child node's children.
If the indentation of a node is nonzero, it is preceded by `+-` (on the same indentation level as its parent), overwriting the vertical line described above.
## Input and Output
You may read the input through **STDIN**, or using an **equivalent method**.
You may assume that there are **no empty lines**, and you may require that the last line ends, or doesn't end, in a newline character.
You may assume that object names consists of **printable ASCII characters** (not including space).
You may assume that objects in a target definition are **separated by a single space** character, and that there are **no leading or trailing spaces**.
You may assume that each target is **defined at most once**, and that there are **no repetitions** in its dependency list.
You may write the output to **STDOUT**, or use an **equivalent method**.
All output lines, except for the longest, may include trailing spaces.
The last output line may, or may not, end in a newline character.
## Score
This is **code-golf**.
The **shortest answer**, in bytes, wins.
## Test Cases
Your program should process each of the following test cases in a reasonable amount of time.
---
*Input*
```
Depender Dependee
Independent
```
*Output*
```
Depender
+-Dependee
Independent
```
---
*Input*
```
Earth Turtle
Turtle Turtle
```
*Output*
```
Earth
+-Turtle
+-Turtle ...
```
---
*Input*
```
F A C B D I
A B
B A C
D E H
C
G F
J H G C E I
E D
H D
I G
```
*Output*
```
J
+-C
+-E
| +-D
| +-E ...
| +-H ...
+-H
| +-D ...
+-G
| +-F
| +-C
| +-A
| | +-B ...
| +-B
| | +-C
| | +-A ...
| +-D ...
| +-I ...
+-I
+-G ...
```
---
**Civilization V Technology Tree**
*Input*
```
Pottery Agriculture
AnimalHusbandry Agriculture
Archery Agriculture
Mining Agriculture
Sailing Pottery
Calendar Pottery
Writing Pottery
Trapping AnimalHusbandry
TheWheel AnimalHusbandry
Masonry Mining
BronzeWorking Mining
Optics Sailing
Philosophy Writing
HorsebackRiding TheWheel
Mathematics TheWheel Archery
Construction Masonry
IronWorking BronzeWorking
Theology Calendar Philosophy
CivilService Philosophy Trapping
Currency Mathematics
Engineering Mathematics Construction
MetalCasting Construction IronWorking
Compass Optics
Education Theology CivilService
Chivalry CivilService HorsebackRiding Currency
Machinery Engineering
Physics Engineering MetalCasting
Steel MetalCasting
Astronomy Compass Education
Acoustics Education Chivalry
Banking Chivalry
PrintingPress Machinery Phyisics
Gunpowder Physics Steel
Navigation Astronomy
Economics Banking PrintingPress
Chemistry Gunpowder
Metallurgy Gunpowder
Archaeology Navigation
ScientificTheory Navigation Acoustics Economics
MilitaryScience Economics Chemistry
Fertilizer Chemistry
Rifling Metallurgy
Biology Archaeology ScientificTheory
SteamPower ScientificTheory MilitaryScience
Dynamite MilitaryScience Fertilizer Rifling
Electricity Biology SteamPower
ReplaceableParts SteamPower
Railroad SteamPower Dynamite
Refrigeration Electricity
Telegraph Electricity
Radio Electricity
Flight ReplaceableParts
Combustion ReplaceableParts Railroad
Penicillin Refrigeration
Plastics Refrigeration
Electronics Telegraph
MassMedia Radio
Radar Radio Flight Combustion
AtomicTheory Combustion
Ecology Penicillin Plastics
Computers Electronics MassMedia Radar
Rocketry Radar
Lasers Radar
NuclearFission AtomicTheory
Globalization Ecology Computers
Robotics Computers
Satellites Rocketry
Stealth Lasers
AdvancedBallistics Lasers NuclearFission
ParticlePhysics Robotics Satellites
NuclearFusion Satellites Stealth AdvancedBallistics
Nanotechnology ParticlePhysics
FutureTech Globalization Nanotechnology NuclearFusion
```
*Output*
```
FutureTech
+-Globalization
| +-Computers
| | +-Electronics
| | | +-Telegraph
| | | +-Electricity
| | | +-Biology
| | | | +-Archaeology
| | | | | +-Navigation
| | | | | +-Astronomy
| | | | | +-Compass
| | | | | | +-Optics
| | | | | | +-Sailing
| | | | | | +-Pottery
| | | | | | +-Agriculture
| | | | | +-Education
| | | | | +-CivilService
| | | | | | +-Philosophy
| | | | | | | +-Writing
| | | | | | | +-Pottery ...
| | | | | | +-Trapping
| | | | | | +-AnimalHusbandry
| | | | | | +-Agriculture
| | | | | +-Theology
| | | | | +-Calendar
| | | | | | +-Pottery ...
| | | | | +-Philosophy ...
| | | | +-ScientificTheory
| | | | +-Acoustics
| | | | | +-Chivalry
| | | | | | +-CivilService ...
| | | | | | +-Currency
| | | | | | | +-Mathematics
| | | | | | | +-Archery
| | | | | | | | +-Agriculture
| | | | | | | +-TheWheel
| | | | | | | +-AnimalHusbandry ...
| | | | | | +-HorsebackRiding
| | | | | | +-TheWheel ...
| | | | | +-Education ...
| | | | +-Economics
| | | | | +-Banking
| | | | | | +-Chivalry ...
| | | | | +-PrintingPress
| | | | | +-Machinery
| | | | | | +-Engineering
| | | | | | +-Construction
| | | | | | | +-Masonry
| | | | | | | +-Mining
| | | | | | | +-Agriculture
| | | | | | +-Mathematics ...
| | | | | +-Phyisics
| | | | +-Navigation ...
| | | +-SteamPower
| | | +-MilitaryScience
| | | | +-Chemistry
| | | | | +-Gunpowder
| | | | | +-Physics
| | | | | | +-Engineering ...
| | | | | | +-MetalCasting
| | | | | | +-Construction ...
| | | | | | +-IronWorking
| | | | | | +-BronzeWorking
| | | | | | +-Mining ...
| | | | | +-Steel
| | | | | +-MetalCasting ...
| | | | +-Economics ...
| | | +-ScientificTheory ...
| | +-MassMedia
| | | +-Radio
| | | +-Electricity ...
| | +-Radar
| | +-Combustion
| | | +-Railroad
| | | | +-Dynamite
| | | | | +-Fertilizer
| | | | | | +-Chemistry ...
| | | | | +-MilitaryScience ...
| | | | | +-Rifling
| | | | | +-Metallurgy
| | | | | +-Gunpowder ...
| | | | +-SteamPower ...
| | | +-ReplaceableParts
| | | +-SteamPower ...
| | +-Flight
| | | +-ReplaceableParts ...
| | +-Radio ...
| +-Ecology
| +-Penicillin
| | +-Refrigeration
| | +-Electricity ...
| +-Plastics
| +-Refrigeration ...
+-Nanotechnology
| +-ParticlePhysics
| +-Robotics
| | +-Computers ...
| +-Satellites
| +-Rocketry
| +-Radar ...
+-NuclearFusion
+-AdvancedBallistics
| +-Lasers
| | +-Radar ...
| +-NuclearFission
| +-AtomicTheory
| +-Combustion ...
+-Satellites ...
+-Stealth
+-Lasers ...
```
---
**Cygwin syslog-ng Package Dependency Graph**
*Input*
```
p11-kit-trust cygwin libtasn1_6
libtasn1_6 cygwin
libp11-kit0 cygwin libffi6 libintl8
libopenssl100 cygwin libgcc1 zlib0 ca-certificates
gsettings-desktop-schemas libglib2.0_0
p11-kit cygwin libp11-kit0 libtasn1_6
zlib0 libgcc1
libpcre1 cygwin
libfam0 gamin
shared-mime-info cygwin libglib2.0_0 libxml2
coreutils cygwin libattr1 libgcc1 libgmp10 libiconv2 libintl8 tzcode _update-info-dir
syslog-ng bash gawk libevtlog0 libgcc1 libglib2.0_0 libopenssl100 libpcre1 libwrap0 tzcode
libxml2 libiconv2 libreadline7 zlib0
cygwin base-cygwin
ca-certificates bash p11-kit p11-kit-trust cygwin
libintl8 cygwin libiconv2
libncursesw10 cygwin libgcc1 libstdc++6 terminfo
libstdc++6 libgcc1
bash coreutils cygwin libgcc1 libiconv2 libintl8 libncursesw10 libreadline7 _update-info-dir
libmpfr4 libgcc1 libgmp10
tzcode bash cygwin libgcc1
_update-info-dir cygwin
libreadline7 libncursesw10
gawk bash cygwin libgcc1 libgmp10 libintl8 libmpfr4 libreadline7
gamin libglib2.0_0
libglib2.0_0 libfam0 libffi6 libgcc1 libiconv2 libintl8 libpcre1 zlib0 gsettings-desktop-schemas shared-mime-info tzcode
```
*Output*
```
syslog-ng
+-libgcc1
+-bash
| +-cygwin
| | +-base-cygwin
| +-_update-info-dir
| | +-cygwin ...
| +-libgcc1
| +-libiconv2
| +-libintl8
| | +-cygwin ...
| | +-libiconv2
| +-libncursesw10
| | +-cygwin ...
| | +-libgcc1
| | +-libstdc++6
| | | +-libgcc1
| | +-terminfo
| +-libreadline7
| | +-libncursesw10 ...
| +-coreutils
| +-cygwin ...
| +-_update-info-dir ...
| +-libattr1
| +-libgcc1
| +-libgmp10
| +-libiconv2
| +-libintl8 ...
| +-tzcode ...
+-tzcode
| +-cygwin ...
| +-libgcc1
| +-bash ...
+-gawk
| +-cygwin ...
| +-libgcc1
| +-libgmp10
| +-libintl8 ...
| +-libreadline7 ...
| +-bash ...
| +-libmpfr4
| +-libgcc1
| +-libgmp10
+-libevtlog0
+-libpcre1
| +-cygwin ...
+-libglib2.0_0
| +-libffi6
| +-libgcc1
| +-libiconv2
| +-libintl8 ...
| +-libpcre1 ...
| +-tzcode ...
| +-zlib0
| | +-libgcc1
| +-gsettings-desktop-schemas
| | +-libglib2.0_0 ...
| +-libfam0
| | +-gamin
| | +-libglib2.0_0 ...
| +-shared-mime-info
| +-cygwin ...
| +-libxml2
| | +-libiconv2
| | +-libreadline7 ...
| | +-zlib0 ...
| +-libglib2.0_0 ...
+-libopenssl100
| +-cygwin ...
| +-libgcc1
| +-ca-certificates
| | +-cygwin ...
| | +-bash ...
| | +-p11-kit
| | | +-cygwin ...
| | | +-libp11-kit0
| | | | +-cygwin ...
| | | | +-libffi6
| | | | +-libintl8 ...
| | | +-libtasn1_6
| | | +-cygwin ...
| | +-p11-kit-trust
| | +-cygwin ...
| | +-libtasn1_6 ...
| +-zlib0 ...
+-libwrap0
```
---
**GNU grep `regex.c` Call Graph**
*Input*
```
check_dst_limits_calc_pos_1 check_dst_limits_calc_pos_1
re_string_destruct
match_ctx_add_sublast
build_charclass bitset_set
match_ctx_init
rpl_re_set_syntax
link_nfa_nodes re_node_set_init_1 re_node_set_init_2
re_node_set_init_union re_node_set_init_copy
register_state re_node_set_insert_last re_node_set_alloc
rpl_re_search re_search_stub
re_node_set_init_2
re_search_2_stub re_search_stub
merge_state_array re_acquire_state re_node_set_init_union
calc_eclosure calc_eclosure_iter
create_token_tree
create_tree create_token_tree
pop_fail_stack
re_compile_fastmap_iter
rpl_regcomp rpl_re_compile_fastmap re_compile_internal
check_arrival_expand_ecl find_subexp_node check_arrival_expand_ecl_sub re_node_set_merge re_node_set_alloc
clean_state_log_if_needed extend_buffers
lower_subexps lower_subexp
duplicate_node re_dfa_add_node
re_node_set_merge
build_equiv_class bitset_set
create_initial_state re_acquire_state_context re_node_set_merge re_node_set_init_copy re_node_set_contains
rpl_regfree free_dfa_content
check_halt_state_context check_halt_node_context re_string_context_at
check_dst_limits search_cur_bkref_entry check_dst_limits_calc_pos
re_node_set_insert re_node_set_init_1
transit_state_bkref transit_state_bkref check_subexp_matching_top get_subexp re_string_context_at re_node_set_init_union re_acquire_state_context
get_subexp_sub match_ctx_add_entry clean_state_log_if_needed check_arrival
free_tree free_token
parse_reg_exp free_tree parse_branch fetch_token postorder create_tree
re_string_skip_chars
match_ctx_clean
re_copy_regs
parse_expression parse_dup_op parse_sub_exp build_charclass_op parse_expression init_word_char create_tree free_tree create_token_tree fetch_token parse_bracket_exp postorder
init_dfa
re_acquire_state_context calc_state_hash re_node_set_compare create_cd_newstate
re_node_set_add_intersect
merge_state_with_log transit_state_bkref check_subexp_matching_top re_acquire_state_context re_string_context_at re_node_set_init_union
free_fail_stack_return
check_subexp_limits sub_epsilon_src_nodes re_node_set_contains
build_charclass_op create_tree bitset_not bitset_set build_charclass create_token_tree bitset_mask free_charset
re_node_set_alloc
check_arrival_add_next_nodes check_node_accept_bytes re_acquire_state re_node_set_merge check_node_accept re_node_set_insert
check_node_accept_bytes re_string_char_size_at re_string_wchar_at re_string_elem_size_at
re_string_allocate re_string_construct_common re_string_realloc_buffers
lower_subexp create_tree
parse_branch parse_expression create_tree postorder free_tree
rpl_regexec re_search_internal
free_state
expand_bkref_cache re_node_set_init_1 re_node_set_insert search_cur_bkref_entry re_node_set_merge re_node_set_init_copy check_arrival_expand_ecl re_node_set_contains re_acquire_state
peek_token re_string_peek_byte_case re_string_wchar_at peek_token
re_string_construct build_wcs_upper_buffer re_string_construct_common build_upper_buffer re_string_translate_buffer re_string_realloc_buffers build_wcs_buffer
re_string_realloc_buffers
calc_inveclosure re_node_set_insert_last
sub_epsilon_src_nodes re_node_set_add_intersect re_node_set_contains re_node_set_remove_at
sift_ctx_init
re_string_fetch_byte_case re_string_char_size_at
find_recover_state merge_state_with_log
sift_states_iter_mb check_node_accept_bytes re_node_set_contains
group_nodes_into_DFAstates bitset_set_all bitset_copy bitset_set re_node_set_init_1 re_node_set_insert re_node_set_init_copy bitset_merge bitset_clear bitset_contain bitset_empty
push_fail_stack re_node_set_init_copy
check_node_accept bitset_contain re_string_context_at
match_ctx_free match_ctx_clean
build_wcs_upper_buffer
rpl_regerror
sift_states_backward re_node_set_init_1 update_cur_sifted_state build_sifted_states
build_sifted_states re_node_set_insert sift_states_iter_mb check_dst_limits check_node_accept re_node_set_contains
transit_state_mb check_node_accept_bytes re_acquire_state_context re_string_context_at re_node_set_init_union clean_state_log_if_needed
optimize_utf8
build_collating_symbol bitset_set
re_search_stub rpl_re_compile_fastmap re_search_internal re_copy_regs
check_matching merge_state_with_log find_recover_state re_acquire_state_context transit_state check_subexp_matching_top transit_state_bkref extend_buffers check_halt_state_context re_string_context_at
extend_buffers build_wcs_upper_buffer re_string_translate_buffer re_string_realloc_buffers build_wcs_buffer build_upper_buffer
check_arrival re_node_set_init_1 re_string_context_at expand_bkref_cache re_node_set_merge re_node_set_init_copy re_node_set_contains check_arrival_expand_ecl check_arrival_add_next_nodes re_acquire_state_context
free_workarea_compile
match_ctx_add_entry
parse_bracket_symbol re_string_fetch_byte_case
free_charset
build_trtable re_node_set_merge re_node_set_alloc group_nodes_into_DFAstates re_acquire_state_context bitset_merge bitset_contain bitset_empty
re_node_set_init_copy
duplicate_node_closure duplicate_node_closure re_node_set_insert duplicate_node search_duplicated_node
parse_bracket_exp build_equiv_class bitset_not bitset_set parse_bracket_element build_range_exp free_charset peek_token_bracket bitset_mask build_charclass create_tree build_collating_symbol create_token_tree
parse_bracket_element peek_token_bracket re_string_wchar_at parse_bracket_symbol re_string_char_size_at
re_search_internal re_string_destruct re_string_allocate match_ctx_init match_ctx_free check_matching check_halt_state_context re_string_reconstruct match_ctx_clean set_regs prune_impossible_nodes
set_regs free_fail_stack_return update_regs pop_fail_stack proceed_next_node
prune_impossible_nodes sift_ctx_init check_halt_state_context sift_states_backward merge_state_array
check_arrival_expand_ecl_sub re_node_set_insert re_node_set_contains check_arrival_expand_ecl_sub
re_acquire_state re_node_set_compare create_ci_newstate calc_state_hash
build_wcs_buffer
rpl_re_compile_pattern re_compile_internal
free_dfa_content free_token free_state
get_subexp match_ctx_add_sublast get_subexp_sub clean_state_log_if_needed extend_buffers search_cur_bkref_entry find_subexp_node check_arrival
analyze calc_first optimize_subexps postorder lower_subexps calc_eclosure preorder link_nfa_nodes calc_inveclosure calc_next
re_node_set_init_1
duplicate_tree create_token_tree
calc_eclosure_iter duplicate_node_closure calc_eclosure_iter re_node_set_alloc re_node_set_insert re_node_set_merge
bitset_empty
free_token free_charset
bitset_copy
parse_dup_op fetch_token mark_opt_subexp fetch_number create_tree postorder duplicate_tree free_tree
rpl_re_compile_fastmap re_compile_fastmap_iter
re_dfa_add_node
re_node_set_insert_last
sift_states_bkref re_node_set_remove_at sift_states_backward search_cur_bkref_entry re_node_set_insert check_dst_limits merge_state_array re_node_set_init_copy re_node_set_contains
fetch_number fetch_token
match_ctx_add_subtop
fetch_token peek_token
bitset_set_all
re_string_reconstruct build_wcs_buffer re_string_translate_buffer re_string_skip_chars bitset_contain build_upper_buffer build_wcs_upper_buffer re_string_context_at
rpl_re_match_2 re_search_2_stub
create_cd_newstate re_node_set_init_copy re_node_set_remove_at free_state register_state
check_subexp_matching_top match_ctx_add_subtop
proceed_next_node check_node_accept re_node_set_contains push_fail_stack check_node_accept_bytes re_node_set_insert
rpl_re_match re_search_stub
build_range_exp bitset_set
add_epsilon_src_nodes re_node_set_add_intersect re_node_set_merge re_acquire_state re_node_set_alloc
update_regs
rpl_re_search_2 re_search_2_stub
transit_state re_string_context_at build_trtable transit_state_mb
check_dst_limits_calc_pos check_dst_limits_calc_pos_1
build_upper_buffer
calc_first re_dfa_add_node
re_compile_internal optimize_utf8 re_string_destruct init_dfa free_workarea_compile parse create_initial_state analyze free_dfa_content re_string_construct
parse_sub_exp postorder create_tree fetch_token free_tree parse_reg_exp
re_string_context_at bitset_contain
init_word_char
create_ci_newstate register_state free_state re_node_set_init_copy
update_cur_sifted_state check_subexp_limits re_acquire_state sift_states_bkref add_epsilon_src_nodes
parse fetch_token create_tree parse_reg_exp
rpl_re_set_syntax
rpl_re_set_registers
rpl_regerror
```
[*Output*](https://gist.githubusercontent.com/anonymous/b91081cd434d6b97499d/raw/a515ade2c7f7d6ecc3b922be62e9551a0bac71ee) (Whoops! Too long for SE to handle.)
[Answer]
# Haskell, 512 bytes
```
import Data.List
r=reverse
n j|let(w,s)#p|let a?b=or[q!b<GT|(q,r)<-i,a==r,elem q(h p)>elem(a,q)i];a!b|a==b=EQ|a?b||(a<b)>b?a=LT;_!_=GT;l=nub.sortBy(!)$h p;m(v,s)q|h q==[]=(v,[q]:s)|elem q w=(v,[q++" ..."]:s)|(w,x:y)<-(v,[])#q=(w,(q:(u"| "=<<r y)++u" "x):s)=foldl m(l++w,[])l;c(p,q)=z$p:q:h q;y=z=<<j;i=iterate(nub.sort.(c=<<))y!!length j;h""=[p|p<-id=<<j,and[elem(p,r)i|(r,q)<-i,p==q]];h p=[r|(q,r)<-y,p==q]=unlines=<<r(snd$mempty#"")
u s(x:y)=("+-"++x):map(s++)y
z(x:y)=(,)x<$>y
main=interact$n.map words.lines
```
[Run online at Ideone](http://ideone.com/WWzBhl)
] |
[Question]
[
# The Challenge:
Given any input that can be typed on a keyboard, move the text along by N chars.
Here is the QWERTY keyboard to be used. You can ignore the modifier keys (Shift, Caps, Enter, Delete and Tab). Once you reach one side (for example `|`) loop back round, so `|` goes to `Q` if `N = 1`.

Spaces do not have to be moved along (they go back round to space as you skip modifiers). If shift was used to type the character (e.g. `!` and `@`) the changed character should also be typed using shift (i.e. `!` goes to `@` not `2` if `N = 1`).
UK keyboards are different to this, but please use this so that we can compare.
# Input:
Any sentence that can be typed on the above keyboard followed by a positive integer. There is no maximum to the size of this integer.
# Output:
The same sentence, shifted along by N.
# Examples:
```
My name is Tim 3
?o .f/y [g I[/
```
```
Hello World 7
Spgge Oe[g;
```
```
I Wi5h I h4d b3773r C@d3ing ski{{s 3
{ T[8l { l7h ,6006u N%h6[.k g'[QQg
```
This is code golf, so shortest code wins.
[Answer]
## C, 217 bytes
```
char*t=" @A$%^*a)_(~.=/z-234567890\"'>`?Z#SNVFRGHJOKL:<MP{WTDYIBECUX]q\\&=1snvfrghjokl;,mp[wtdyibecux}Q|!";l,d,k;f(char*s){for(l=strlen(s);s[--l]-32;);d=atoi(s+l);for(s[l]=0;d--;)for(k=l;k--;s[k]=t[s[k]-32]);puts(s);}
```
Readable version with whitespace, includes, etc:
```
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
char* t = " @A$%^*a)_(~.=/z-234567890\"'>`?Z#SNVFRGHJOKL:<MP{WTDYIBECUX]q\\&=1snvfrghjokl;,mp[wtdyibecux}Q|!";
int l, d, k;
void f(char* s) {
l = strlen(s);
for( ; s[--l] - 32; );
d = atoi(s + l);
s[l] = 0;
for ( ; d--; ) {
for (k = l; k--; s[k] = t[s[k] - 32]);
}
puts(s);
}
```
The code pretty much speaks for itself. Just a lookup table that maps from each character to the next character, which is applied the given number of times. Much of the code is actually for parsing the number out of the input.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 61 bytes
*-1 byte thanks to Kevin Cruijssen*
```
žVDu«1ú`žhÀ“~!@#$%^&*()_+ `ÿ-=ÿ<>?ÿ:"ÿ{}|ÿ,./ÿ;'ÿ[]\“#vyy¹._‡
```
[Try it online!](https://tio.run/##AX4Agf9vc2FiaWX//8W@VkR1wqsxw7pgxb5ow4DigJx@IUAjJCVeJiooKV8rIGDDvy09w788Pj/Dvzoiw797fXzDvywuL8O/OyfDv1tdXOKAnCN2eXnCuS5f4oCh//8zCkkgV2k1aCBJIGg0ZCBiMzc3M3IgQ0BkM2luZyBza2l7e3M "05AB1E – Try It Online")
[Answer]
# Pyth, 126 bytes
```
XjdPczdsJc"~!@#$%^&*()_+ `1234567890-= qwertyuiop[]\ QWERTYUIOP{}| asdfghjkl;, ASDFGHJKL:\" zxcvbnm,./ ZXCVBNM<>?")sm.<dvecz)J
```
Try it online: [Demonstration](https://pyth.herokuapp.com/?code=XjdPczdsJc%22~!%40%23%24%25%5E%26*()_%2B%20%601234567890-%3D%20qwertyuiop%5B%5D%5C%20QWERTYUIOP%7B%7D%7C%20asdfghjkl%3B%2C%20ASDFGHJKL%3A%5C%22%20zxcvbnm%2C.%2F%20ZXCVBNM%3C%3E%3F%22)sm.%3Cdvecz)J&input=I%20Wi5h%20I%20h4d%20b3773r%20C%40d3ing%20ski%7B%7Bs%203&debug=0) or [Test Suite](https://pyth.herokuapp.com/?code=zFz.zp%22%20%3D%3E%20%22zXjdPczdsJc%22~!%40%23%24%25%5E%26*()_%2B%20%601234567890-%3D%20qwertyuiop%5B%5D%5C%20QWERTYUIOP%7B%7D%7C%20asdfghjkl%3B%2C%20ASDFGHJKL%3A%5C%22%20zxcvbnm%2C.%2F%20ZXCVBNM%3C%3E%3F%22)sm.%3Cdvecz)J&input=Test%20Cases%3A%0AMy%20name%20is%20Tim%203%0AHello%20World%207%0AI%20Wi5h%20I%20h4d%20b3773r%20C%40d3ing%20ski%7B%7Bs%203&debug=0)
### Explanation:
```
czd split input by spaces
P remove the last element
jd join by spaces (=#1)
"..." string with the chars of each row
c ) split by spaces
J assign to J
sJ sum of J (=#2)
cz) split input by spaces
e take the last element
v and evaluate it
m J map each row d of J to:
.<d rotate the row d by value
s sum (=#3)
X Take #1, and replace the chars in #2 by the chars in #3
```
[Answer]
## Python 3, 311 bytes
```
*i,s=input().split()
r=["`1234567890-=","qwertyuiop[]\\","asdfghjkl;'","zxcvbnm,./","~!@#$%^&*()_+","QWERTYUIOP{}|",'ASDFGHJKL:"',"ZXCVBNM<>?"]
print("".join([[x[int(s):]+x[:int(s)]for x in r][r.index([x for x in r if c in x][0])][([x for x in r if c in x][0]).index(c)]if c!=" "else " " for c in " ".join(i)]))
```
[Answer]
# Python 3, ~~271~~ 255 bytes
Baseline, almost ungolfed, used to create the shifted words in the question.
```
x=input().split()
n=int(x[-1])
x=' '.join(x[:-1])
l=['`1234567890-=','qwertyuiop[]\\',"asdfghjkl;'",'zxcvbnm,./', '~!@#$%^&*()_+','QWERTYUIOP{}|','ASDFGHJKL:"','ZXCVBNM<>?',' ']
y=''
for i in x:
for q in l:
if i in q:y+=q[(q.index(i)+n)%len(q)]
print(y)
```
Explanation:
```
x=input().split() # Get input
n=int(x[-1]) # Get N from input
x=' '.join(x[:-1]) # Get the words from input
# Create list of letters
l=['`1234567890-=', 'qwertyuiop[]\\',
"asdfghjkl;'", 'zxcvbnm,./',
'~!@#$%^&*()_+', 'QWERTYUIOP{}|',
'ASDFGHJKL:"', 'ZXCVBNM<>?',
' ']
y='' # Blank string
for i in x: # Loop through letters in input
for q in l: # Loop through items in list
if i in q: # Is letter of input in item of list?
y+=q[ # Append letter to y
(q.index(i)+n) # locate the letter in item, and add N
%len(q)] # % is modulus, loop to beginning if big
print(y) # Print out the offset word.
```
[Answer]
# JavaScript (ES6), 200 ~~216~~
Using template strings, the newlines are significant and counted.
Note about `replace`: the two snippets
`string.split('x').map(w=>...)` and
`string.replace(/[^x]+/g,w=>...)` are equally valid ways to execute a function for each part in a string, using a separator. Using a newline as a separator is handy as the replace regexp becomes `/.+/g`, because the dot match any non-newline. And using templated strings the newlines have no extra cost.
```
f=(t,d)=>[for(c of t)`~!@#$%^&*()_+
1234567890-=
QWERTYUIOP{}|
qwertyuiop[]\\
ASDFGHJKL:"
asdfghjkl;'
ZXCVBNM<>?
zxcvbnm,./`.replace(/.+/g,r=>(p=r.indexOf(c))<0?0:q=r[(p+d)%r.length],q=c)&&q].join('')
// less golfed
x=(t,d)=>
[for(c of t)
'~!@#$%^&*()_+ 1234567890-= QWERTYUIOP{}| qwertyuiop[]\\ ASDFGHJKL:" asdfghjkl;\' ZXCVBNM<>? zxcvbnm,./'
.split(' ')
.map(r=>(p=r.indexOf(c))<0?0:q=r[(p+d)%r.length],q=c)&&q
].join('')
// TEST
out=x=>O.innerHTML+=x+'\n'
;[['Hello World',7,],['My name is Tim',3],['I Wi5h I h4d b3773r C@d3ing ski{{s', 3]]
.forEach(p=>out(p+' -> '+f(p[0],p[1])))
```
```
<pre id=O></pre>
```
[Answer]
# CJam, 107 bytes
```
lS/)~\S*\",./ ;' <>? :\" _+~!@#$%^&*() -=`"A,s(++S/"zxcvbnm
asdfghjkl
[]\qwertyuiop"N/_32ff^+.+_@fm>s\ser
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=lS%2F)~%5CS*%5C%22%2C.%2F%20%3B'%20%20%3C%3E%3F%20%3A%5C%22%20%20_%2B~!%40%23%24%25%5E%26*()%20-%3D%60%22A%2Cs(%2B%2BS%2F%22zxcvbnm%0Aasdfghjkl%0A%5B%5D%5Cqwertyuiop%22N%2F_32ff%5E%2B.%2B_%40fm%3Es%5Cser&input=I%20Wi5h%20I%20h4d%20b3773r%20C%40d3ing%20ski%7B%7Bs%203).
### How it works
```
lS/) e# Read one line from STDIN, split at spaces and pop the last chunk.
~\S*\ e# Evaluate the popped chunk and join the remaining ones back together.
",./ ;' <>? :\" _+~!@#$%^&*() -=`"
e# Push that string.
A,s(++ e# Concatenate it with "1234567890".
S/ e# Split at spaces.
"zxcvbnm asdfghjkl []\qwertyuiop"
e# Push that string.
S/ e# Split at spaces. (`N/' would split at linefeeds.)
_32ff^ e# XOR each character of a copy with 32.
+ e# Concatenate the copies.
.+ e# Perform vectorized concatenation. This pushes the following array:
[ ",./zxcvbnm" ";'asdfghjkl" "[]\qwertyuiop" "<>?ZXCVBNM"
":\"ASDFGHJKL" "{}|QWERTYUIOP" "_+~!@#$%^&*()" "-=`1234567890" ]
_@fm> e# Rotate each chunk by the number of character specified in the input.
s\s e# Flatten this array and the original.
er e# Perform transliteration.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 67 bytes
```
ØDṙ1ṭØQ;Øq;"“{}|“:"“<>?“-=`“[]\“;'“,./“~!@#$%^&*()_+“ ”
¢œiⱮ+2¦€œị¢
```
[Try it online!](https://tio.run/##y0rNyan8///wDJeHO2caPty59vCMQOvDMwqtlR41zKmurQGSViCmjZ09kNS1TQCS0bExQNJaHUjo6OkDyTpFB2UV1Tg1LQ3NeG0gX@FRw1yuQ4uOTs58tHGdttGhZY@a1hyd/HB396FF////91QIzzTNUPBUyDBJUUgyNjc3LlJwdkgxzsxLVyjOzqyuLv5vDAA "Jelly – Try It Online")
A dyadic link taking the string as its left argument and the number of places to shift as its right argument.
[Answer]
# [Python 2](https://docs.python.org/2/), 194 bytes
```
f=lambda s,n:n and f(''.join(B[B.find(c)+1]for c in s),n-1)or s
A='qwertyuiop%sqasdfghjkl%sazxcvbnm%sz'
B='`1234567890-=`~!@#$%^&*()_+~'+A%('[]\\',";'",',./')+(A%('{}|',':"','<>?')).upper()+' '
```
[Try it online!](https://tio.run/##FY9NW4JAFEb3/IobRXcmRgrRKAtTWrVr10IsgREZPwacQUsx/zrR5j3PObu3PFR5IbtNkwXreJPwGDSTAwmx5JARRGdZCEnCSehkQnKSUtudZoWCFIQETZnsuLRVbYwD3H7PVXXYiaK09DbWPFvky9Xa0vHxJ90ncmPpIxphgDO36/X69/7D410nmJ0vRpdX1uf1DaFf9hntsUVwMo0iZOYTmgyZc4vUJv@5/j0hw4HZzvPwBSl1dmU5V4TaCICNDvC9hDf4EP28Rd7jkHi@7yk4RfA64p6QC9ArUdcaPFDZHo1SCVm1RzVzPdoYfw "Python 2 – Try It Online")
] |
[Question]
[
I have bunch of hexagonal rods glued together into an odd sculpture. The rods
are 1 to 99 centimetres (cm) long and 1 square cm in cross-section area. All
rods are glued on a hexagonal face to at least one other rod. The rods are all
aligned at their bottom edge.
After some heavy rain, the sculpture is full of water. How much water does it
hold?
## Input
Your program should read in (via stdin or a file) a number of lines consisting of
pairs of spaces and pairs of digits specifying the length of the rods in this format:
```
aa bb
cc dd ee
ff gg
```
Each rod (like dd here) is glued to a maximum of 6 surrounding rods as shown in the examples. Missing rods are holes and do not gather water. For example, the input
```
04 04
04 01 03
04 04
```
would represent the following sculpture:

The centre rod is height `1` (I didn't find a good angle where that rod is also visible). Now the column above that rod could hold 2 cm of water, before it would overflow over the `3` rod on the right. Since none of the other rods can hold any water above them, the answer would be `2`. Here are two more complex examples:
```
Example 2:
55 34 45 66
33 21 27
23 12 01 77
36 31 74
answer = 35 ( 2 on top of 21
+11 on top of 12
+22 on top of 01, before everything overflows over 23)
Example 3:
35 36 77 22 23 32 54 24
33 07 02 04 21 54 07 07 07 76
20 04 07 07 01 20 54 11 81 81 07 76
20 67 67 22 07 01 78 54 07 81 07 81 09 76
20 67 07 67 22 22 07 44 55 54 07 81 07 07 61 07 20
67 57 50 50 07 07 14 03 02 15 81 99 91 07 81 04
67 07 50 50 87 39 45 41 34 81 07 07 89 07 81 79
67 07 50 50 07 07 07 27 07 27 81 07 07 79 81 78
20 67 67 07 07 07 07 99 33 46 02 81 07 07 81 01 20
33 07 07 01 05 01 92 20 02 81 07 81 15 32
22 07 20 20 07 20 63 02 80 81 15 32
45 20 01 20 39 20 15 07 15 32
23 20 20 29 43 21 18 41 20 66 66 43 21
90 99 47 07 20
50 20 02 48
70 56 20
90
answer = 1432
```
## Output
Your program should output a single integer giving the volume of water in cubic
centimetres.
## Score
Your score is the byte count of your source code. Lowest wins.
The standard loopholes are prohibited as usual.
This puzzle was inspired by a
[SPOJ Question](http://www.spoj.com/problems/WATER/).
[Answer]
# Python 2, 222 bytes
```
import sys
y=h=v=0;B={}
for l in sys.stdin:
z=y;y+=2j
while l:
if"0"<l:B[z]=int(l[:2])
l=l[2:];z+=1
while B:C=B;B={b:B[b]for b in B if(h<B[b])+sum(3>abs(c-b)for c in B)/7};a=C==B;h+=a;v+=a*sum(h>B[b]for b in B)
print v
```
Reads input through STDIN and writes the result to STDOUT.
## Explanation
We start at zero and incrementally increase the water level as follows:
Suppose that the water level is *h*, and we want to add 1 centimeter of water.
We'll call hexagons of height *h* or less, ones that are about to go (or already are) underwater, "*submerged*."
The water will spill through any submerged hexagon that isn't surrounded by six neighbors.
We eliminate all such hexagons; of course, now some other submerged hexagons might have less than six neighbors, and they need to be eliminated as well.
We continue in this fashion until convergence, i.e., until all remaining submerged hexagons have exactly six neighbors.
At this point we add the number of submerged hexagons (the gained water volume) to the total count, and increment the water level.
Eventually, all the hexagons will have been eliminated and we halt.
[Answer]
# Ruby 299
```
f=->i{s={}
l=i.lines
y=0
l.map{|r|x=0
r.scan(/../){s[[x,y]]=[v=$&.to_i,v<1?0:99];x+=1}
y+=1}
loop{break if s.map{|c,r|x,y=c
m = [[-1,-1],[1,-1],[-2,0],[2,0],[1,-1],[1,1]].map{|w,z|s[[x+w,y+z]]}.map{|n|n ?n[0]+n[1]:0}.min
r[1]=[0,m-r[0]].max if r[0]+r[1]>m&&r[1]>0}.none?}
s.map{|c,r|r[1]}.reduce :+}
```
Brief description of the algorithm:
* parses the input, and for each rod saves a two-element array of the form [rod\_height, water\_height]
* rods are placed in a hash and indexed by their x,y coordinates
* the water leaking part takes into account the rod/water heights of the immediate neighbors
A slightly more readable version is available here: <http://ideone.com/cWkamV>
Run the golfed version online with tests: <http://ideone.com/3SFjPN>
] |
[Question]
[
Your boss has recently learned of this interesting programming language called [English](http://esolangs.org/wiki/English). He has had this "revolutionary" idea, he wants to code with you to double code production rates! Since he is not a tech savvy, he wants you to write a compiler for it so that he can code too!
Now, you are an evil lazy programmer and obviously will not write a program to compile this ridiculously complex language. Instead, you are going to make sure there is always an error in your boss's code, so that he never gets to the actual compilation and is stuck fixing grammar errors instead of coding.
The challenge is to write a program that can be run from the terminal, and accepts a file path as an argument. The program has to:
1. modify the file input by introducing a typo.
2. Pretend to fail compilation due to encountering the typo you introduced.
3. Running the program on copies of the same file should not introduce the same typo twice in a row.
To illustrate the challenge, running your program on this file:
```
Take an array as input.
Sort the array.
Output the array.
```
should output something along the lines of
```
Error on line 1:
'Take an arqay as input.'
^
arqay is not a valid identifier.
```
and the file that you told the program to compile should now look like:
```
Take an arqay as input.
Sort the array.
Output the array.
```
Here are some more details on the specs of the program:
Your program is allowed to assume that swapping any character in the program your boss inputs for a different random character will cause a grammar error.
Your program should not use non alphabetical characters to create errors in your bosses code. Your boss would never use a number or symbol, and he would find out that something is afoot.
Your program should only introduce errors to the words in your boss's program. Do not change the spaces in the sentences, or the punctuation.
Your program should not alter the case of the program your boss tries to compile, meaning errors like `arQay` are invalid. This prevents errors like `take` instead of `Take` happening, or `Array` instead of `array`.
Your program should output the error by first stating what line the error is at:
```
Error on line <insert line number here>:
```
It should then print out the line with the error inside `'` symbols. On the next line it should place a `^` symbol under the *word* with the error, and finally it should have some text describing the error (this part is up to you, you can say whatever you want there as long as it describes an error).
You can assume that the input file exists and it is not empty.
You can also assume the input file has no grammatical errors before you add one.
Bonuses:
-60 bytes if the errors your code introduces are not completely random, but typo-based as in [this](https://codegolf.stackexchange.com/questions/20450/insert-typos-into-text) question.
-60 bytes for at least 5 different error messages, randomly alternating.
-60 bytes if your program has a 1 in 100 chance or less to output some demotivational message to your boss.
**EDIT: The byte count of the messages do not count towards your score.**
(Thanks to Martin Büttner for this good idea)
This is code-golf, shortest byte count wins. Please do not golf the error message content, your boss wont be happy if he can't understand the error messages, and will ask you to fix them for him.
[Answer]
# TI-BASIC, 77 - 34 (error text) = 43
*In case he wants to do in on his TI-83/84 calculator ;)*
As standard for functions, file string should be in `Ans` so it can return and display the output.
```
Ans->Str1:If 1=inString(Ans,"A
Then:"B
Else:"A
End:Disp "ERROR ON LINE 1","'"+Ans+sub(Str1,2,-1+length(Str1))+"'"," ^ INVALID
```
Note that many tokens are one byte.
[Answer]
# JavaScript, ~~484~~ 458 bytes
```
F=process.argv[2]
C=console.log
r=require('fs')
l=r.readFileSync(F,'utf-8').replace(/\r/g,'').split`
`
S=b=>b[H=Math.random()*b.length|0]
L=S(l)
y=H
C(`Error on line ${y+1}:`);
while(/[^a-z]/.test(S(R=L.split` `)));
Y=H
R[Y]=R[Y].replace(t=S(R[Y]),(J=_=>(Z=S('abcdefghijklmnopqrstuvwxyz'))==t?J():Z)(t))
j=R.join` `
C(`'${j}'`)
C(' '.repeat(1+R.reduce((a,e,i)=>a+=i<Y&&e.length,Y))+'^')
C('Unexpected '+R[Y])
r.writeFileSync(F,l.map((e,i)=>i==y?j:e).join`
`)
```
No TIO link, but it takes in a path like `./test.txt` as input via command line arguments and outputs the error like so:
```
Error on line 1:
'Take an mrray as input.'
^
Unexpected mrray
```
I'm a little unsure about how to count the error message length. Is it the length of `Unexpected` (with the space)?
Anyway, this took a while. Basically selects a line at random, then a word at random, replaces a random letter of that word with another random letter that is not the same, then outputs line number, modified line, then the caret after a number of spaces. Then outputs `Unexpected <word>` where is the aforementioned word.
Then uses `writeFileSync` to replace the content.
[Answer]
# Python 3, ~~245~~ 239 bytes
```
import sys,time
t=time.time
p=sys.argv[1]
f=open(p).read()
a=f[0]
f=chr(ord(a)+int(-t()if a in"yzYZ"else t())%2+1)+f[1:]
open(p,"w").write(f)
n="\n"
s=f.split
print(f"Error on line 1:\n'{s(n)[0]}'\n ^\n{s()[0]} is not a valid identifier.")
```
Slightly bending the rules in a few ways:
* It always makes the error on the first character, which it assumes to be a valid character, since otherwise it would be an English syntax error
* It only ever outputs two different typos for any given input: for A-X it shifts either +1 or +2, for Y-Z it shifts either -1 or -2.
* It uses `int(time.time())` as its PRNG, so running the program several times within a second will output the same typo.
Output on the sample input:
```
Error on line 1:
'Uake an array as input.'
^
Uake is not a valid identifier.
```
I'm unsure about how long the error message is, anyone have any ideas?
] |
[Question]
[
When you hammer a set of nails into a wooden board and wrap a rubber band around them, you get a [Convex Hull](http://en.wikipedia.org/wiki/Convex_hull).

Your mission, should you decide to accept it, is to find the [Convex Hull](http://en.wikipedia.org/wiki/Convex_hull) of a given set of 2D points.
---
Some rules:
* Write it as a function, the point's list coordinates (in any format you want) is
the argument
* The output must be the list of points in the convex hull listed
clockwise or anticlockwise, starting at any of them
* The output list can be in any reasonable format where each point's coordinates are clearly distinguishable. (For example NOT a one dim list { 0.1, 1.3, 4, ...})
* If three or more points in a segment of the convex hull are
aligned, only the two extremes should be kept on the output
Sample data:
### Sample 0
Input:
```
{{1, 1}, {2, 2}, {3, 3}, {1, 3}}
```
Output:
```
{{3, 3}, {1, 3}, {1, 1}}
```

(The figures are just illustrative)
### Sample 1
Input:
```
{{4.4, 14}, {6.7, 15.25}, {6.9, 12.8}, {2.1, 11.1}, {9.5, 14.9},
{13.2, 11.9}, {10.3, 12.3}, {6.8, 9.5}, {3.3, 7.7}, {0.6, 5.1}, {5.3, 2.4},
{8.45, 4.7}, {11.5, 9.6}, {13.8, 7.3}, {12.9, 3.1}, {11, 1.1}}
```
Output:
```
{{13.8, 7.3}, {13.2, 11.9}, {9.5, 14.9}, {6.7, 15.25}, {4.4, 14},
{2.1, 11.1}, {0.6, 5.1}, {5.3, 2.4}, {11, 1.1}, {12.9, 3.1}}
```

### Sample 2
Input:
```
{{1, 0}, {1, 1}, {1, -1}, {0.68957, 0.283647}, {0.909487, 0.644276},
{0.0361877, 0.803816}, {0.583004, 0.91555}, {-0.748169, 0.210483},
{-0.553528, -0.967036}, {0.316709, -0.153861}, {-0.79267, 0.585945},
{-0.700164, -0.750994}, {0.452273, -0.604434}, {-0.79134, -0.249902},
{-0.594918, -0.397574}, {-0.547371, -0.434041}, {0.958132, -0.499614},
{0.039941, 0.0990732}, {-0.891471, -0.464943}, {0.513187, -0.457062},
{-0.930053, 0.60341}, {0.656995, 0.854205}}
```
Output:
```
{{1, -1}, {1, 1}, {0.583004, 0.91555}, {0.0361877, 0.803816},
{-0.930053, 0.60341}, {-0.891471, -0.464943}, {-0.700164, -0.750994},
{-0.553528, -0.967036}}
```

Standard code-golf rules apply. No ad-hoc geometry libraries. Shorter code wins.
**Edit 1**
We are looking for an algorithmic answer here, not a convex hull finder pre-programmed routine like [this one in MatLab](http://www.mathworks.com/help/matlab/ref/convhull.html) or [this one in Mathematica](http://reference.wolfram.com/mathematica/ComputationalGeometry/tutorial/ComputationalGeometry.html)
**Edit 2**
Answering comments and additional info:
1. You can assume the input list contains the minimum number of points
that suits you. But you must ensure proper treatment of aligned (sub)sets.
2. You may find repeated points in the input list
3. The maximum number of points should be limited only by the available memory
4. Re "floating point": You need to be able to process input lists with
decimal coordinates as those given in the samples. You *could* do that by using a floating point representation
.
[Answer]
### Ruby, 168 characters
```
C=->q{r=[]
f=m=q.sort[0]
t=-0.5
(_,_,t,*f=q.map{|x,y|a=x-f[0]
b=y-f[1]
[0==(d=a*a+b*b)?9:(-t+e=Math.atan2(b,a)/Math::PI)%2,-d,e,x,y]}.sort[0]
r<<=f)while
!r[1]||f!=m
r}
```
This ruby code also uses the gift wrapping algorithm. The function `C` accepts an array of points and returns the convex hull as array.
Example:
```
>p C[[[4.4, 14], [6.7, 15.25], [6.9, 12.8], [2.1, 11.1], [9.5, 14.9],
[13.2, 11.9], [10.3, 12.3], [6.8, 9.5], [3.3, 7.7], [0.6, 5.1], [5.3, 2.4],
[8.45, 4.7], [11.5, 9.6], [13.8, 7.3], [12.9, 3.1], [11, 1.1]]]
[[5.3, 2.4], [11, 1.1], [12.9, 3.1], [13.8, 7.3], [13.2, 11.9], [9.5, 14.9], [6.7, 15.25], [4.4, 14], [2.1, 11.1], [0.6, 5.1]]
```
[Answer]
## Mathematica 151
still work in progress
```
f = For[t = Sort@#; n = 1; l = Pi; a = ArcTan; c@1 = t[[1]],
n < 2 || c@n != c@1,
n++,
(l = a @@ (# - c@n); c[n + 1] = #) & @@
t[[Ordering[Mod[a@## - l, 2 Pi] & @@ (#2 - #1) & @@@ Tuples@{{c@n}, t}, 1]]]] &
```
testing:
```
ClearAll[a, c, t];
s = {{1, 0}, {0.68957, 0.283647}, {0.909487, 0.644276}, {0.0361877, 0.803816},
{0.583004, 0.91555}, {-0.748169, 0.210483}, {-0.553528, -0.967036},
{0.316709, -0.153861}, {-0.79267, 0.585945}, {-0.700164, -0.750994},
{0.452273, -0.604434}, {-0.79134, -0.249902}, {-0.594918, -0.397574},
{-0.547371, -0.434041}, {0.958132, -0.499614}, {0.039941, 0.0990732},
{-0.891471, -0.464943}, {0.513187, -0.457062}, {-0.930053, 0.60341},
{0.656995, 0.854205}};
f@s
Show[Graphics@Line@Table[c@i, {i, n}],
ListPlot[{t, Table[c@i, {i, n}]},
PlotStyle -> {PointSize[Medium], PointSize[Large]},
PlotRange -> All]]
```

[Answer]
# CoffeeScript, 276:
```
f=($)->z=$[0];e.r=Math.atan2(e.x-z.x,e.y-z.y)for e in $;$.sort((x,y)->(x.r>y.r)-(x.r<y.r));(loop(a=$[i-1]||$[$.length-1];b=$[i];c=$[i+1]||$[0];break if!b;s=(b.x-a.x)*(c.y-b.y)-(b.y-a.y)*(c.x-b.x);break if s<0||!s&&(a.x-b.x)*(b.x-c.x)<0;$.splice i,1))for i in [$.length-1..0];$
```
If the function needs not be accessible, remove `f=` to shave off two more characters.
Input/output is a single array of points, with each point being defined by the `x,y` properties. The input array is modified, as well as returned (if the latter not required, remove the last two characters).
Explanation may be added later.
Test suite (won't work in oldIE):
```
alert JSON.stringify f({x:e[0], y:e[1]} for e in JSON.parse "
{{1, 1}, {2, 2}, ...}
".replace(/{/g,"[").replace(/}/g,"]"))
```
suggested test environment: <http://coffeescript.org/>
[Answer]
# Python, 209 205 195
```
from math import*
s=lambda(a,b),(c,d):atan2(d-b,c-a)
def h(l):
r,t,p=[],pi/2,min(l)
while 1:
q=min(set(l)-{p},key=lambda q:(s(p,q)-t)%(2*pi));m=s(p,q);r+=[p]*(m!=t);p=q;t=m
if p in r:return r
```
Uses a gift wrapping algorithm. The result starts with the leftmost point and wraps counter-clockwise.
Example: `h([(1, 1), (2, 2), (3, 3), (1, 3)])` returns `[(1, 3), (1, 1), (3, 3)]`
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~327~~ 301 bytes
```
#import<bits/stdc++.h>
using V=std::complex<double>;using W=std::deque<V>;W f(W x){V m=x[0],r,c;double v=imag(m),t,g,s=1;for(V a:x)c=m=imag(a-m)>0?a:m,v=fmin(imag(a),v);W p;do{p.push_back(r=c);g=4;for(V a:x)m=c=a!=r?t=std::arg(s*(a-r)),t<g|t==M_PI?g=t,a:c:c;s=imag(m)-v?s:-1;}while(m!=p[0]);return p;}
```
[Try it online!](https://tio.run/##pVJNc9MwEL3nV6jDoTF1hL5l2VZ65sAMp/QATMd1XddDnRjbCZkJ@e1hJTkt0GE4cPLu2923b59Vdt2iLsvT6U3Tdpt@zO@acXg3jPfl1RV@XM62Q7Ou0coCkqblpu2eqn1@v9nePVXLLBRvQvG@@rat8tUyu0EP8xu0jw4r1Nr9J/Il7uMyCzNoZ5u2qOdtFI9xHQ@WZg@bfr5CRbqPStuGarFooyW5LtI23tmHtlnPAxzFuwjoOyA7dLjbDo@3d0X5dd7bMspqK37ham1piwvbX49BXdHX8@EtMPcRrM7rH6O1H24/vr@u7RgXaZmW2XCWtthdD@mCZsfvj81TNW8vbAdXRFlfjdt@DeuPp3D5umiroSvKCsGObNasR9QWoDY6zFCw4w/Hls2a2sOB4hhRfIzRgUHEfMQh4j6iITpmM1Rsxw3abEeKLJgKwxGA7khf2Keu5JahEqI83@f5ZXwJLceQX35eQ/Z3LQy0CCxAjPCbFdYQS8xkyAxkDCdBKIWEYuoSg6WfMZDMQDDHzBeNl08w93M8kCQxgv5wIhQ01i4mWMVIBjrpcIZFYEuwAHYR2oBUunnlE@7IdCCGBcb5RKc25yj9zTQ2mcZem8b@wzTufmCMiN8LW6fvgk5nJUaCiwSzhCsx3WqIEYlHlRBMq3ApwYQrmmhfSAhPqArtMuGECIcaKqX3bkGwFtBgPDUlIuGBBApScsnAGQiN0sAZWDiFxHiYSp4oeuYxTPmVMpFGAHtg0YRQJXy7lsQYEViEZExzDysiBBfPLJSHbiaMIexFjRGGBjXcaKnPA1JorqnHgYWIyS8jE8pZgI1RVLx4Axqc0RjEEM3ZxJMYKs48ShjBJ88op85iB0tN1IsgA2ZK7s0n/LxWSWWM9MZLwYj0L@f56XDrHg5//XD4Px/O8fQT "C++ (gcc) – Try It Online")
Another implementation of the gift wrapping algorithm. Slightly golfed less:
```
#import<bits/stdc++.h>
using V=std::complex<double>;
using W=std::deque<V>;
W f(W x){
V m=x[0],r,c;
double v=imag(m),t,g,s=1;
// find topmost point
for(V a:x)
c=m=imag(a-m)>0?a:m,
v=fmin(imag(a),v);
W p;
do{
p.push_back(r=c);
g=4;
// loop to find the smallest angle t
for(V a:x)
m=c=a!=r?
t=std::arg(s*(a-r)),t<g|t==M_PI?
g=t,a
:
c
:
c;
// are we wrapping over or under?
s=imag(m)-v?s:-1;
// loop until we've gone all the way around
}while(m!=p[0]);
return p;
}
```
] |
[Question]
[
Sometimes authors will write `(s)he` as a stand in for `she` or `he` and for some reason they don't want to use singular they. This is ok for the nominative but doesn't work so well when you want to write "her or him". You can write `h(er)(im)` which covers both cases but gives two extra "pronouns"
```
h
her
him
herim
```
In formalizing these patterns we will strings with no parentheses match the exact same string. So `she` matches only `she` etc. Additionally a pattern \$A\left(B\right)C\$, where \$A, B, C\$ are all patterns, matches everything that \$AC\$ and \$ABC\$ match and nothing else.
This lets us nest brackets so for the words so the pattern `(they)((s)he)` matches
```
they
she
he
theyshe
theyhe
```
We will measure the effectiveness of a pattern as the number of incorrect words it generates. So from above `(s)he` has the best possible effectiveness with 0, while `h(er)(im)` and `h(er)(is)` both have effectiveness of 2. If `(they)((s)he)` is trying to generate `they`, `she`, and `he` then it has effectiveness 3.
Your program or function will take a non-empty set of words as input.
Your program should figure out the smallest possible effectiveness any pattern can have that matches all the inputs. For example in for `her` and `him` we have shown a pattern with effectiveness 2, and it is impossible to get a pattern with effectiveness less than 2, so you should output 2.
You don't need to output the solution just its effectiveness score. You may take input and output with the usual rules and you may assume the strings will be strictly alphabetic.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so answers will be scored in bytes with fewer bytes being better.
## Test cases
Each case has a potential pattern below it, there may be more than one.
```
she -> 0
she
she, he -> 0
(s)he
her, him -> 2
h(er)(im)
her, his -> 2
h(er)(is)
they, she, he -> 3
(they)((s)he)
them, her, him -> 5
(them)(her)(him)
their, her, his -> 5
(their)(her)(his)
their, her -> 2
(thei)(he)r
goca, oc, oca -> 1
(g)oc(a)
goca, soca, oc, goce, soce -> 11
(g)(s)oc(a)(e)
goca, soca, gsocae, goce, soce -> 11
(g)(s)oc(a)(e)
goca, soca, gsxocae, goce, soce, xoce -> 26
(g)(s)(x)oc(a)(e)
```
[Answer]
# Python3, 1356 bytes
```
import itertools as i
def w(s,q=[]):
if s:
if not q:yield from w(s[1:],q+[(0,[s[0]])]);yield from w(s[1:],q+[(1,[s[0]])])
else:
if q[-1][0]:yield from w(s[1:],q[:-1]+[(q[-1][0],q[-1][1]+[s[0]])])
yield from w(s[1:],q+[(not q[-1][0],[s[0]])])
else:yield tuple((a,tuple(set(b)))for a, b in q)
def p(s,l=0):
if len(s)==1:yield tuple(s);return
n=min(s,key=len)
if m:=[n[x:y+1]for x in range(len(n))for y in range(x,len(n))if all(n[x:y+1]in a for a in s)]:
for q in m:
a,b=[[*filter(None,x)]for x in zip(*[j.split(q,1)for j in s])];x,y=[p(a,1)]if a else [],[p(b,1)]if b else []
yield from i.product(*(x+[(q,)]+y))
if not l:yield (*[(u,)for u in dict.fromkeys(a)],q,*[(u,)for u in dict.fromkeys(b)])
if not l:
for j in w(s):
if any(not x[0]for x in j):yield from i.product(*[p(b,1)if a else[b]for a,b in j])
else:
s=[x for y in s for x in(y if any(any(j in v for v in s if v!=y)for j in y)else[y])];yield tuple([(u,)for u in sorted(set(s),key=s.index)])
def e(s):
yield from map(''.join,i.product(*[[k]if isinstance(k,str)else[*e(k),'']for k in s]))
def t(s):
for i in s:
if isinstance(i,str):yield i
elif any(isinstance(j,str)for j in i):yield tuple(t(i))
else:yield from t(i)
def f(s):
s=s.split(', ')
return min([((v:=tuple(t(i))),sum(j not in s for j in e(v)))for i in set(p(s))],key=lambda x:x[1])
```
The central strategy is to build possible paths starting with matching substrings from the input passed to `p` at each call, then surrounding the matching substrings with other possible valid patterns derived from the non-matching remainders.
[Try it online!](https://tio.run/##jVTBkpswDL3nK9zpATvrZjbTS4cdfqE/4OFggtk4AUOwk0J/PpVkQsh20@mBAUtPT9KTTDeGfeu@/@j669U2XdsHZoPpQ9vWnmnP7Ko0FfvFvTxlKhfpitmKeXjh27WBndLRmrpkVd82iFPbNJenF8VfpfLqNc9FLt6eQLZ3CBCa2hskRuaT@rbNwfUpuUrBCeE3kIwfaFvQsSdJqehb5CKA0seYcO5qw7mW8cObwAshRNX2TEtWMOvYSZAwHQhTZ6@TLrVx3Iss2z7wePHWm3Du3Yq5rLEAkUczZgAWFNWkmXJqSMeXbY4pBuTvtXs3HAldTDzerYOc7BCs65rfggGgGRWJWC9yVBPPJzw3pK2WRabUurI1TJn/bJ2Rg7in/W07vlaHje9qG/hJbin3gfhAprdBjpnqQJmtyDE7qcYUCNnxYjIWN@OHIdhN17fleRf4mg84Pinyl1GIaeQ4l3oSDmrgZ0m5z5i7tLuwQRIQznMtYJLyn5Ai7sBMiznmTmAbBFnQr91IKzHAIswyHET6eeFTm3PrqsjjVtBSHOY9AnafqYHNk/PsRs7HW1p8qKALOS8RB87Ll2y8Cz8KyjSi/su9euzfw9U1Je2qF7RgfmNdaQZUAlfVTF0vGmt0x5Nkc2itk8sm1RHnaL11Pmi3M/wofehjGWs4CZkk1PdxWoyYIcQM6LDkmH4TCyJLRJO4li79JMYCdCDQ3L8VD9cpcCvm38WiGbRTGVUsw4MAcY0TyRKIiJeQ4Q1UnF/SbMEnpD83MAzchHlalN3wy3T1Y0@gL1x6AStIl1g3RanZkA7w@xHXr40GTDA@sJ32xq@63rrAK56EvbF9AoU/WiTbm0cznMFomwej3xtEfowfJXviaYj4b6L3dgd/sHaHj/7E42c/nA2dzVPYO77Mf0KHj1jJhhhx/QM)
] |
[Question]
[
## Information
Create a diagonal line given its length (let’s call the variable, say, \$n\$ where \$n > 0\$)
* The diagonal line starts from the top left and goes to the bottom right.
* You **must** use the ASCII character `\` for the line.
* The input number can be given from STDIN or if your program doesn’t support that, use a hardcoded value in your code or pass it as an argument while running the program.
* For padding, **only use** the **space character** `0x20`
* *Trailing spaces* and/or *newlines* are **allowed**.
* The **length** of the line is the **non whitespace** characters
Here is an example program (59 bytes):
```
n = int(input())
for i in range(n):
print(' ' * i + '\\')
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P0/BViEzr0QjM6@gtERDU5MrLb9IIRMopFCUmJeeqpGnacWloFBQBFKjrqCuoAWU1FZQj4lR1/z/3wQA "Python 3.8 (pre-release) – Try It Online")
Example:
```
Input: 4
Output
\
\
\
\
```
### Rules
* Use *standard* I/O when possible.
* Standard *loopholes* are forbidden.
* This is code golf, so the shortest answer in bytes wins.
* Please explain the code that you wrote.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 1 [byte](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
Better tool for the job ;)
```
\
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjND,i=NA__,v=8)
Given an integer, this draws a diagonal of that string. If you pass a string instead, this prints the string along the diagonal. There is matching anti-diagonal builtin `/` as well.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 2 bytes
```
↖N
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R27T3e9b9/28CAA "Charcoal – Try It Online")
right tool for the job
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 9 bytes ([SBCS](https://github.com/abrudz/SBCS))
Anonymous tacit prefix function. Returns a list of string, as per [meta consensus](https://codegolf.meta.stackexchange.com/a/17095/43319).
```
'\'↑⍨¨-∘⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///Xz1G/VHbxEe9Kw6t0H3UMeNR7@b/aY/aJjzq7XvU1fyod82j3i2H1huDlPRNDQ5yBpIhHp7B/4G0V7C/n0KaggkA "APL (Dyalog Unicode) – Try It Online")
`∘⍳` indices one through \$n\$, then:
`-` negate those
`¨` for each:
`↑⍨` take (when negative: from the rear) that many characters (padding with spaces) from:
`'\'` the backslash character
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
=þị⁾\ Y
```
[Try it online!](https://tio.run/##y0rNyan8/9/28L6Hu7sfNe6LUYj8//@/CQA "Jelly – Try It Online")
```
Ḷ⁶ẋp”\Y
```
[Try it online!](https://tio.run/##y0rNyan8///hjm2PGrc93NVd8Khhbkzk////TQA "Jelly – Try It Online")
## How they work
```
=þị⁾\ Y - Main link. Takes N on the left
=þ - Yield the identity matrix of size N
ị⁾\ - Index into "\ ", replacing 1 with "\" and 0 with " "
Y - Join by newlines
```
```
Ḷ⁶ẋp”\Y - Main link. Takes N on the left
Ḷ - Range [0, ..., N-1]
⁶ẋ - Repeat that many spaces for each
p”\ - Append "\" to each
Y - Join by newlines
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-R`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
õ!ù'\
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LVI&code=9SH5J1w&input=OA)
```
õ!ù'\ :Implicit input of integer
õ :Range [1,input]
!ù'\ :For each, left pad "\" to that length with spaces
:Implicit output joined with newlines
```
# [Japt](https://github.com/ETHproductions/japt) [`-mR`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
'\iUç
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW1S&code=J1xpVec&input=OA)
```
'\iUç :Implicit map of each U in the range [0,input)
'\i :Prepend to "\"
Uç : Space repeated U times
:Implicit output joined with newlines
```
[Answer]
# [51AC8](https://github.com/PyGamer0/51AC8), 10 bytes
```
R[\ ×\\+t]
```
[Try it Online!](https://pygamer0.pythonanywhere.com/?flags=&header=&code=R%5B%5C%20%C3%97%5C%5C%2Bt%5D&footer=&stdin=4)
*-2 bytes* due to an update.
*-7 bytes* due to an update introducing for\_each loops and range.
*-1 byte* online interpreter and implicit input.
## Explanation
```
# Implicit Input (STDIN) and push to stack
R # Range from 0 to input (exclusive)
[ # Start for each
\ # Push ' ' to the stack
× # Multiply the top 2 elements on the stack
\\ # Push '\'
+ # Add top 2 elements
t # Pop and print top of stack
] # End of while loop
```
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes
```
x='\\'
exec'print x;x=" "+x;'*input()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v8JWPSZGnSu1IjVZvaAoM69EocK6wlZJQUm7wlpdKzOvoLREQ/P/fxMA "Python 2 – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), 37 bytes
```
f(n){printf("%*c\n",n--,92,n&&f(n));}
```
[Try it online!](https://tio.run/##S9ZNzknMS///P00jT7O6oCgzryRNQ0lVKzkmT0knT1dXx9JIJ09NDSSraV37PzcxM09DU6GaS0EhTcNQ0xpMG0FpYyhtAqRr/wMA "C (clang) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 39 bytes
A recursive version suggested by [@att](https://codegolf.stackexchange.com/users/81203/att).
```
f(n){--n&&f(n);printf("%*c\n",n+1,92);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NI0@zWlc3T00NxLIuKMrMK0nTUFLVSo7JU9LJ0zbUsTTStK79n5uYmaehqVDNpaCQpmGoaQ2mjaC0MZQ2AdK1/wE "C (gcc) – Try It Online")
---
# [C (gcc)](https://gcc.gnu.org/), 44 bytes
```
i;f(n){for(i=0;i++<n;)printf("%*c\n",i,92);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/TOk0jT7M6Lb9II9PWwDpTW9smz1qzoCgzryRNQ0lVKzkmT0knU8fSSNO69n9uYmaehqZCNZeCQpqGoaY1mDaC0sZQ2gRI1/4HAA "C (gcc) – Try It Online")
[Answer]
# Dyalog APL, ~~16~~ 14 bytes
Solution - Takes in number of lines as input from user, and returns a
string of diagonal line.
`' \'[1+∘.=⍨⍳⎕]`
### Explanation
```
⎕ ⍝ ⎕ takes input from the user (number of lines)
⍝ In the below explanation, I have assumed ⎕ = 9 as input
⍳⎕ ⍝ 1 to 9 : [1,2,3,4,5,6,7,8,9]
∘.= ⍝ Outer Product with Equality
⍨ ⍝ Apply a function with same argument on both sides
∘.=⍨⍳⎕ ⍝ ∘.=⍨ function applied to array ⍳⎕ = [1,2..9]
⍝ This is same as (⍳9) ∘.= (⍳9), which produces Identity Matrix of size 9
1+∘.=⍨⍳⎕ ⍝ Add 1 to each element of previous matrix (since APL uses 1-based index)
' \'[1+∘.=⍨⍳⎕] ⍝ From the string ' \', select characters specified by indices in 1+∘.=⍨⍳⎕
```
[Answer]
# brainfuck, 113 bytes
```
,>>+++++++[<+++++++++++++>-]<+>++++++++++>>++++[<++++++++>-]<<<<[>>>>[->+>+<<]>[-<+>]>[<<<.>>>-]<<<<<.>.>>+<<<<-]
```
[Try it online.](https://tio.run/##SypKzMxLK03O/v9fx85OGwKibbSRgZ1urI22HRLfDlURSB4Iou2AIFrXDqjUxiYWyAJqAlJAGT2gBEQNkAnkaINYurH//ysCAA)
First time poster. This was a fun exercise! Please provide criticism, I pretty much went in cold when writing this.
```
, how long the line should be via char code
>
initialize cell 1 with "\"
>+++++++[<+++++++++++++>-]<+
>
initialize cell 2 with "\n"
++++++++++
>
initialize cell 3 with " "; go back to beginning
>++++[<+++++>-]<
<<<
start loop at cell 0
[
>>>> go to cell 4
[
->+>+<< copy the pad value to cells 5 and 6
]
> now we move cell 5 to cell 4
[
-<+> cell 4 keeps track how much padding we'll need for our next iteration
]
>
cell 6 keeps track of how many spaces we need to print currently
[
<<< go to space char
. print it
>>>- decrease counter
]
<<<<< move to line char
.>. print line and newline
>>+ move to cell 4 and increase our padding by 1
<<<<- back to cell 0; subtract line counter
]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
Ṭ€ị⁾\ Y
```
[Try it online!](https://tio.run/##y0rNyan8///hzjWPmtY83N39qHFfjELk////TQA "Jelly – Try It Online")
~~Working on golfing. This is longer than I remember it being possible.~~ The JHT exercise allows other characters so I can't get this to 5 bytes because of that :/
```
Ṭ€ị⁾\ Y Main Link
€ For each (implicit range)
Ṭ Generate a boolean list with 1s at the indices
ị Index that into
⁾\ "\ "
Y and join on newlines
```
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
' \'{~=@i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1RVi1KvrbB0y9f5rcqUmZ@QraFinaSoYIbFNkNhm/wE "J – Try It Online")
[Answer]
# [C (clang)](http://clang.llvm.org/), ~~90~~ ~~77~~ 60 bytes
```
i;main(n){for(scanf("%i",&n);i<n;printf("%*s\\\n",i++,""));}
```
[Try it online!](https://tio.run/##FchLCoAgFAXQrcSLQsuaNVJaiROx34O6RtooWrvRGR7f@d1hzSXD7/c0FyamiUO/jZn14RgC8lnCJaJ3WARVTKqG1Gygz4uR/muitRakuG0VkZT6zXn4AA "C (clang) – Try It Online")
My first work without `int` in it while still using it. I'm doing better now, aren't I?
Thanks to att for golfing 13 bytes. Thanks to ceilingcat for golfing 17 bytes.
[Answer]
# [convey](http://xn--wxa.land/convey/), 46 bytes
```
[0>>,+1
v"^
{,"=@#]}
>^}"~v#'\\'
' '!""~/}
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoiWzA+PiwrMVxuICAgdlwiXlxueyxcIj1AI119XG4gPl59XCJ+diMnXFxcXCdcbicgJyFcIlwifi99IiwidiI6MSwiaSI6IjIwIn0=)
Visualization (i use '\_' instead of space because the gif doesnt show the space char if i use it, but in the official page the output works whit spaces):
[](https://i.stack.imgur.com/S12iw.gif)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `M`, 7 bytes
```
(nI\\+,
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJNIiwiIiwiKG5JXFxcXCssIiwiIiwiNSJd)
Explanation:
```
( # range from 0 to implict input
n # loop variable
I # push that many spaces
\\ # backslash literal
+ # concatenate the spaces with the backslash
, # print
```
[Answer]
# JavaScript (ES6), 33 bytes
```
f=(n,s=`\\
`)=>--n?s+f(n,' '+s):s
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjT6fYNiEmhitB09ZOVzfPvlg7DSimrqCuXaxpVfw/OT@vOD8nVS8nP10jTcNQU5MLVcQIQ8QYQ8REU/M/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# MATLAB/Octave, ~~32~~ 31 bytes
*-1 byte thanks to [Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)*
```
disp([60*eye(input(''))+32,''])
```
[Try it online!](https://tio.run/##y08uSSxL/Z@SWVygoe6ZV1BaYmWorgnhR5sZaKVWpmpkgoQ11NU1NbWNjXTU1WM1UdSbqGtygfnJGYlFGtj0aEIVQDWYk6rB0IwIHf8NuUy4zLkMzQA "Octave – Try It Online")
Reads the length from standard input, writes to standard output.
---
Alternatively, using function input/output, **~~22~~ 21 bytes**:
```
@(x)[60*eye(x)+32,'']
```
[Try it online!](https://tio.run/##y08uSSxL/f/fQaNCM9rMQCu1MhXI0jY20lFXj/2fZpuYV2zNlZJZXKCh7plXUFpiZaiuCeGnaRhqaqJIGSOkjNGkTBBSJmhS5ggpczQpQyMky4zQJI0MEJJGBpqa/wE "Octave – Try It Online")
Anonymous function, outputs character array.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 3 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
■♦9
```
[Run and debug it](https://staxlang.xyz/#p=fe0439&i=5)
## Explanation
```
m'\)
m map 1..n and print with newlines
'\) pad \ on the left with spaces to given length
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
'\3Λ
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fPcb43Oz//00A "05AB1E – Try It Online")
Using the input as length, draw `\` in direction `3` (down-right) with the canvas builtin `Λ`. See [Kevin's tip](https://codegolf.stackexchange.com/a/175520/64121) for details on how the canvas works
---
6 bytes without the canvas builtin:
```
'\ILj»
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fPcbTJ@vQ7v//TQA "05AB1E – Try It Online")
For each number in the range `IL == [1..input]`, pad the string `"\"` with leading spaces to this length (`j`). `»` joins the results by newlines.
Another 6 bytes solution suggested by [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen):
```
L<'\ú»
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fx0Y95vCuQ7v//zcBAA "05AB1E – Try It Online")
For each number in the range `L< == [0..input-1]`, pad the string `"\"` with that many leading spaces.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 46 bytes
```
for i in range(int(input())):print(' '*i+'\\')
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/Py2/SCFTITNPoSgxLz1VIzOvBIgLSks0NDU1rQqKQHx1BXWtTG31mBh1zf//TQA "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `jṀ`, 4 bytes
```
ƛ\\꘍
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j%E1%B9%80&code=%C6%9B%5C%5C%EA%98%8D&inputs=4&header=&footer=)
Flags go brrr
```
ƛ\\꘍ Full Program
ƛ For each (implicity loops from 0 to n - 1)
\\ push '\'
꘍ prepend x spaces to '\'
```
`Ṁ` is equivalent to `mM`, which makes implicit range start at `0` instead of `1` and end at `n - 1` instead of `n`.
`j` joins the top of the stack on newlines at the end.
[Answer]
# [Red](http://www.red-lang.org), 30 bytes
```
repeat i n[print pad/left"\"i]
```
[Try it online!](https://tio.run/##K0pN@R@UmqIQHauQZ6VgaPC/KLUgNbFEIVMhL7qgKDOvRKEgMUU/JzWtRClGKTP2/38A "Red – Try It Online")
[Answer]
# Java, 56 bytes
```
n->{for(var s="\\";n-->0;s=" "+s)System.out.println(s);}
```
[Try it online!](https://tio.run/##LU6xDoIwFJzhKxomGkPj4FZlcXJwYhSHWgopwivpeyUxhG@vjfGWy90ldzeqVVVj945LeE1WMz0pRHZXFtiWs4S/j6Qo0epsx@aUlg15C8PjyZQfkG95NqYmEchOog@gyToQVwcYZuPPNyAzGF/3lwhVvfXOl6vyDC9F2xYSqqo@yiRYcUDefJDMLFwgsaQJmqBELvco86wXSmuzUHni8nduz/f4BQ)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 10 bytes
```
ri{S*'\N}%
```
[Try it online!](https://tio.run/##S85KzP3/vyizOlhLPcavVvX/f1MA "CJam – Try It Online")
### Explanation
```
r e# Read input
i e# Evaluate as an integer, n
{ }% e# Do the following for each k in [0 1 ... n-1]
e# Push k (implicit)
S e# Push space
* e# Repeat. Gives a string with k spaces
'\ e# Push character "\"
N e# Push newline
e# Output the stack (implicit)
```
[Answer]
# [R](https://www.r-project.org/), 35 bytes
```
cat(sep="\\
",strrep(" ",0:scan()))
```
[Try it online!](https://tio.run/##K/r/PzmxRKM4tcBWKSaGS0mnuKSoKLVAQ0lBScfAqjg5MU9DU1Pzv/l/AA "R – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~42~~, 39 bytes
* -3 bytes thanks to @Dominic van Essen
```
write(strrep("\\",diag(x<-scan())),1,x)
```
[Try it online!](https://tio.run/##K/r/v7wosyRVo7ikqCi1QEMpJkZJJyUzMV2jwka3ODkxT0NTU1PHUKdC87/5fwA "R – Try It Online")
**Explanation:**
* take x from standard input,
* create a diagonal matrix of size x
* repeat the character `'\'` one time for each 1 of the matrix and 0-times for each 0 (= empty string)
* print the matrix separating each character with a space
[Answer]
# [PHP](https://www.php.net/), 58 57 bytes
```
for($i=0;$i<$argv[1];$i++)echo str_repeat(' ',$i)."\\\n";
```
[Try it here!](https://tio.run/##K8go@G9jXwAk0/KLNFQybQ2sVTJtVBKL0suiDWOBbG1tzdTkjHyF4pKi@KLUgtTEEg11BXUdlUxNPaWYmJg8Jev///@bAAA)
This is my first golf, so feel free to mention anything I can do to improve this!
[Answer]
# [Factor](https://factorcode.org/), 40 bytes
```
[ iota [ [ bl ] times "\\"print ] each ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqVQnFpYmpqXnFqskJmvkJtYkqGQnVqUl5qjYM3FZfI/GihakqgQDYRJOQqxCiWZuUCVSjExSgVFmXklQJHUxOQMhdj/yYk5Of8B "Factor – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 34 bytes
```
s//\\/;$==<>;s// / while(say,$=--)
```
[Try it online!](https://tio.run/##K0gtyjH9X1qcqlBmqmdoYP2/WF8/JkbfWsXW1sbOGshR0Fcoz8jMSdUoTqzUUbHV1dX8/98UAA "Perl 5 – Try It Online")
This should be run from the command line like `perl -E 's//\\/;$==<>;s// / while(say,$=--)'` to activate the `say` feature without adding any bytes.
Ungolfed:
```
$_='\\'; #Set the default variable $_ to a single backslash
$==<>; #Take input into $=. This variable converts the input to an integer
while($=--){ #Decrement $= and loop
say; #Prints $_ and a newline
$_=" $_"; #Adds a space to the start of $_
}
```
Uses `s// /` as shorthand for `$_=" $_"` (i.e. to prepend a space to `$_`). Putting `say` into the while loop lets us drop the brackets from the loop body.
[Answer]
# [Ruby](https://www.ruby-lang.org/en/), 41 bytes
```
puts Array.new(gets.to_i){|i|(' '*i+'\\')}
```
[Try it online!](https://tio.run/##KypNqvz/v6C0pFjBsagosVIvL7VcIz21pFivJD8@U7O6JrNGQ11BXStTWz0mRl2z9v9/QyMA)
] |
[Question]
[
It's time for CGCC to demonstrate our musical talent! In this challenge, you're going to compose songs while keeping your byte count as small as possible.
On Day 0, multiple answerers will post a function or program that outputs nothing/an empty string. They will also give a single line that next day's answers must output. More lines will be added to that line later, gradually building up a song. I'm not starting off Day 0 myself because letting multiple people answer will allow for more variety later.
On Day 1, answerers will choose an answer from Day 0. They will post a function or program that outputs the line from the Day 0 answer. This will be the song for the next answer. Like on Day 0, Day 1 answerers will also give a single line that next day's answers must add anywhere to their song.
On Day `i`, answerers will choose an answer from Day `i-1` with partial song `s` and line `l`. They can now insert `l` between any two lines in `s` or put it at the start or end of `s`. This will now yield a new partial song that each must write a function or program to output. Again, answerers will also give a line for next day's answers to add to their partial song.
# Rules
**The rules have been changed, please see the bolded parts below.** Sorry for the inconvenience.
* New lines can be put between other lines, at the start of the song, or at the end of the song.
* Lines may be repeated.
* Lines must be at least 20 characters and at most 100 characters.
* You may have trailing spaces at the end of each line when printing the song.
* **You may have multiple answers on a single day and you may answer on consecutive days, but you cannot continue from your answer on a consecutive day.**
* This isn't a hard rule, but if you take your line from a song, please link to it.
* The day changes at midnight UTC+0.
* Your score is the average length, in bytes, of all your answers (not including answers on Day 0), **divided by the number of answers you have posted** (this is a change from before, but the objective is still the same - make your answer as short as possible).
## It is currently Day 19.
# Examples
Note: These examples are just to show the format of each answer; they are not good examples of the kinds of songs you should write, as they lack creativity.
### Day 0. Python, 0 bytes
[Try it online!](https://www.google.com)
Line for next day: `Superman got nothing on me` (from [One Call Away](https://en.wikipedia.org/wiki/One_Call_Away_(Charlie_Puth_song)))
Song:
### Day 1. Foobarbaz, 7 bytes
```
DOSTUFF
```
[Try it online!](https://www.google.com)
**[Previous answer](https://linktopreviousanswer)**
Line for next day: `I can eat more bananas than him`
Song:
```
Superman got nothing on me
```
### Day 2. Foobarbaz, 11 bytes
```
DOMORESTUFF
```
[Try it online!](https://www.google.com)
**[Previous answer](https://linktopreviousanswer)**
Line for next day: `And I'm never gonna give you up` (modified from [here](https://www.youtube.com/watch?v=dQw4w9WgXcQ))
Song:
```
Superman got nothing on me
I can eat more bananas than him
```
### Day 3. somelanguage, 3 bytes
```
foo
```
[Try it online!](https://www.google.com)
**[Previous answer](https://linktopreviousanswer)**
Line for next day: `That's the only thing that matters`
Song:
```
Superman got nothing on me
I can eat more bananas than him
And I'm never gonna give you up
```
A possible song for day 4 (note that the new line was inserted this time instead of being appended):
```
Superman got nothing on me
I can eat more bananas than him
That's the only thing that matters
And I'm never gonna give you up
```
[Answer]
# Day 0. [Java (OpenJDK 8)](http://openjdk.java.net/), 5 bytes
```
a->""
```
[Try it online!](https://tio.run/##NYyxCoMwFEX3fsXDSaGG7mkdCx06OZYOrxrl2ZiE5EWQ4rengdrpXu453AkXrK1TZurfiWZnPcOUNxGZtBii6ZisEde9yIOLL00ddBpDgDuSgQ/sW2DkHIulHuZMypY9mfHxBPRjqLL4vznfDKtR@SP8lAYGuEDCuimKJKFdA6tZ2MjCZczlINA5vZanqpKwwZa@ "Java (OpenJDK 8) – Try It Online")
The line for tomorrow is `Baka mitai kodomo na no ne`.
thanks to caird for reminding me i don't need to submit a full program lol
[Answer]
# Day 0. [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
⁸
```
[Try it on](https://www.youtube.com/watch?v=dQw4w9WgXcQ)[l](https://tio.run/##y0rNyan8//9R447//wE "Jelly – Try It Online")[ine!](https://www.youtube.com/watch?v=dQw4w9WgXcQ)
The line for tomorrow is `We're no strangers to love`
## How it works
`⁸` is a builtin for `[]` (the empty array), assuming no arguments are passed. Due to Jelly's printing, this displays nothing
[Answer]
# Day 0. [QBasic](https://en.wikipedia.org/wiki/QBasic), 0 bytes
Nothing to it.
The line for tomorrow is `Baby shark doo doo doo-doo doo-doo`
[Answer]
# Day 0, [Nim](http://nim-lang.org/), 0 bytes
[Try it online!](https://tio.run/##y8vM/Q8EAA "Nim – Try It Online")
Line for next day: `side to side, side, side to side`
Taken from [Revenge](https://www.youtube.com/watch?v=cPJUBQd-PNM) by CaptainSparklez. Instead of the first line, I chose one that can be compressed well.
[Answer]
# Python 3, 35 bytes
```
print("We're no strangers to love")
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQyk8Vb0oVSEvX6G4pCgxLz21qFihJF8hJ78sVUnz/38A "Python 3 – Try It Online")
Line for next day: `You know the rules, and so do I`.
It begins.
[Answer]
# Day 0, [Hexagony](https://github.com/m-ender/hexagony), 0 bytes
[Try it online!](https://tio.run/##y0itSEzPz6v8DwQA "Hexagony – Try It Online")
Tomorrow's line is: `A B C Ch D E F G H I J K Ll L M N Ñ O P Q R Rr S T U V W X Y Z`
from [the Spanish alphabet song](https://www.dailymotion.com/video/x5ec3dg)
[Answer]
# Day 0. [nameless language](https://github.com/bforte/nameless-lang), 0 bytes
[Try it online!](https://tio.run/##y0vMTc1JLS7@DwQA "nameless language – Try It Online")
Line for next day: `Juno was mad, He knew he'd been had, So he shot at the sun with a gun`, [Link](https://www.youtube.com/watch?v=I8sUC-dsW8A)
[Answer]
# Day 0. [Vyxal](https://github.com/Lyxal/Vyxal) 1 byte
```
¤
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%C2%A4&inputs=&header=&footer=)
Tomorrow's line is: `How ba-a-a-ad can I be? I'm just doing what comes naturally--` taken from [How Bad Can I be](https://genius.com/Ed-helms-how-bad-can-i-be-lyrics) from the Lorax.
Consequently, I now would like to be referred to as `The Lyx-ler` (a play on the name "the once-ler").
[Answer]
# Day 0. [unsure](https://github.com/Radvylf/unsure), 0 bytes
```
```
Line for next day: `1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19`
[Answer]
# Day 1. [Pyth](https://github.com/isaacg1/pyth), 25 bytes
```
j", "[Kj" to ",J"side"JJK
```
[Try it here](http://pythtemp.herokuapp.com/?code=j%22%2C+%22%5BKj%22+to+%22%2CJ%22side%22JJK&debug=0)
**[Previous answer](https://codegolf.stackexchange.com/a/224578/78186)**
Line for next day: `do you like my sword, sword, sword my diamond sword, sword`
The song so far:
```
side to side, side, side to side
```
[Answer]
# Day 1. [Vyxal](https://github.com/Lyxal/Vyxal) `S`, 19 bytes
```
`⟇ɽ to``⟇ɽ,`ȮȮ$Ȯṫ_W
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=S&code=%60%E2%9F%87%C9%BD%20to%60%60%E2%9F%87%C9%BD%2C%60%C8%AE%C8%AE%24%C8%AE%E1%B9%AB_W&inputs=&header=&footer=)
[Previous answer](https://codegolf.stackexchange.com/a/224578/77516)
Song:
`side to side, side, side to side`
Line for next day: `Tell me, tell me if you love me or not, love me or not, love me or not?` from [Maroon 5 - What Lovers Do](https://www.youtube.com/watch?v=5Wiio4KoGe8)
[Answer]
# Day 0. [C (gcc)](https://gcc.gnu.org/), 5 bytes
```
f(){}
```
[Try it online!](https://tio.run/##S9ZNT07@/z9NQ7O69n9mXolCbmJmnoYmVzWXAhAAha25av//S07LSUwv/q9bDgA "C (gcc) – Try It Online")
Next line: `YOU ARE LIKELY TO BE EATEN BY A GRUE` [(MC Frontalot "It Is Pitch Dark")](https://www.youtube.com/watch?v=4nigRT2KmCE&ab_channel=MCFrontalot)
[Answer]
# Day 0, [Charcoal](https://github.com/somebody1234/Charcoal), 0 bytes
[Try it online!](https://tio.run/##S85ILErOT8z5DwQA "Charcoal – Try It Online") ~~Link is to verbose version of code.~~
Next: line: `Deck the halls with boughs of holly, Fa la la la la la la la la!` Optional comma between the fourth and fifth `la`.
[Answer]
# Day 0. [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 1 byte
```
@
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//93@P8fAA "Befunge-98 (PyFunge) – Try It Online")
Line for next day: `I'm only human after all` (from [Human](https://en.wikipedia.org/wiki/Human_(Rag%27n%27Bone_Man_song)))
[Answer]
# Day 1, Deadfish~, 323 bytes
```
{{i}ddd}iiic{ddd}ddddc{iiiiii}ic{{d}iii}iic{{i}ddd}iiiiiicdddciicddddddc{{d}iii}ic{{i}dd}iiiicdddddc{{d}ii}ic{{i}ddd}ciiiciiiiic{d}c{{d}iii}iic{{i}dd}dciiiiiicdc{{d}ii}ddddc{{i}d}dddc{d}dddddc{d}iiic{ii}dc{{d}ii}ddddc{{i}dd}iic{d}dddcddddc{i}icdddc{i}iciiiiic{{d}i}ic{iiii}ic{ddd}ddddc{{i}ddd}c{{d}ii}iiic{{i}ddd}iiiciiiiic
```
[Try it online!](https://tio.run/##ZVBJCsAwCHxRH1ViSz33KPN269oQEggZnEUNXSfd/D6HqgiDiMDMQxzYpSEcB1aT4OD0lLradfmEo3UlQ2t@DjNhOJcpRu09QKObtLmCDCBQDhogYlyyawnZwgu1GHLyADWCu8C5NJZv6Hl7g/UXyq/6AQ "Deadfish~ – Try It Online")
Song so far:
`I'd like to find out what reality I'm in`
Next line:
`We wish you a Merry Christmas and a happy New Year!`
[Previous answer](https://codegolf.stackexchange.com/questions/224562/compose-a-song-line-by-line/224584#224584)
[Answer]
# Day 0, [PHP](https://php.net/), 0 bytes
[Try it online!](https://tio.run/##K8go@G9jXwAk//8HAA "PHP – Try It Online")
Next line: `I'd like to find out what reality I'm in` ([Night Verses "Phoenix IV: Levitation"](https://www.youtube.com/watch?v=b1js-01XnQY))
Nothing planned to reduce byte counts, just currently listening to this amazing album, it kinda have lyrics (voice samples), and I like that line
[Answer]
# Day 1, Javascript, 67 / 131
## Printing it, 67
```
_=>`A B C Ch D E F G H I J K Ll L M N Ñ O P Q R Rr S T U V W X Y Z`
```
## More interesting but longer, 131
```
_=>[...Array(30).keys()].map(i=>i^3?i^12?i^16?i^21?String.fromCharCode(65+i-(i>3)-(i>12)-(i>16)-(i>21)):'Rr':'Ñ':'Ll':'Ch').join` `
```
[Previous](https://codegolf.stackexchange.com/questions/224562/compose-a-song-line-by-line/224568#224568)
Next line: `Money money money, it must be funny, in a rich man's world` ([from here](https://www.youtube.com/watch?v=ETxmCCsMoD0))
[Answer]
# Day 1. Picolisp, ~~47~~ 42 bytes
```
(prin"Baby Shark doo doo doo-doo doo-doo")
```
---
### Much more interesting, 47 byte version
```
(prin(text"Baby Shark @1@1@2@1@2@1""doo "'doo-]
```
---
Next lyric: `you're not JoKing, you're`
[Previous lyrics](https://codegolf.stackexchange.com/a/224567/90614)
I'd also post the full song so far, but I don't want to accidentally read it myself.
[Answer]
# Day 1, [Zsh](https://www.zsh.org/), 28 bytes
```
<<Z
I'm only human after all
```
[Try it online!](https://tio.run/##qyrO@P/fxiaKy1M9VyE/L6dSIaM0NzFPITGtJLVIITEn5/9/AA "Zsh – Try It Online")
Song so far:
```
I'm only human after all
```
Next line: `I'm only human after all` (yes, that's the same line repeated again - that's how the song goes...)
[Answer]
# Day 1. [Vyxal](https://github.com/Lyxal/Vyxal), 43 bytes
```
`λ… ba-a-a-ad λ‹ I be? I'm λ¾ °Ḋ λ⟨ †↲ ₀⅛--
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60%CE%BB%E2%80%A6%20ba-a-a-ad%20%CE%BB%E2%80%B9%20I%20be%3F%20I%27m%20%CE%BB%C2%BE%20%C2%B0%E1%B8%8A%20%CE%BB%E2%9F%A8%20%E2%80%A0%E2%86%B2%20%E2%82%80%E2%85%9B--&inputs=&header=&footer=)
**[Previous Answer](https://codegolf.stackexchange.com/a/224566/101522)**
Line for tomorrow: `If it's all right, then you're all wrong.` From [*I Know, You Know*](https://genius.com/The-friendly-indians-i-know-you-know-lyrics), a.k.a. the [*Psych*](https://en.wikipedia.org/wiki/Psych) theme song, by The Friendly Indians
---
Song so far:
```
How ba-a-a-ad can I be? I'm just doing what comes naturally--
```
[Answer]
# Day 1, [brainfuck](https://github.com/TryItOnline/brainfuck), 677 bytes
```
++++++++++[>++++++++++>+++++++++++>+++++>++++++>++++<<<<<-]>+.>+.+++.>>-.<<----.>>---.<++.<++.<.+++++.>>>.<<<--------.>++++.----.>>+++.---.<<<.>-.<+++.++++.>++++++.<-.>-.-----.+.+++++++.<-------.>>>.<<<+++++++.>>+.<-------.-.+++.>.>.<<<.>---.<------.>>>.<<<++++++.>>.<+.>---.>+.<<<.>>+++.<<-----------.>>--------.>.<+++++.+++.--------.<------.<.>+++++++++++++.<++++++++++.++.+++++++.>>>-----.<<<-.--------------------.>>>-.++.<<<++++++++++++++.>.<++++++.>--.<----------.>------.++++++.>>++++.<<<----------.>>.+++.<<++++++++++.>-.<-.>-----.-----.<++.>+++++++++++.------.+++++.----.-.<+.>>>++.<<<++++.--------.>-----.++.---.++++++++++++.+++.<++++++.++++++.----.-.------.++++++++.
```
[Try it online!](https://tio.run/##bVFLCkIxDDxQyJwg5CLiQgVBBBeC56/59TUVw/uk02Q6mV7fl8fr/rk9x6AjTrryllaubSEefFaCPbaGKsMQC0/tKwbGi@gyVCFZkVWBVkOlXgCN3mAl1JkQdjw7cyvRSZbkEzfCtcepD1rsfsy/NviCssD7vTiELdHHdJUiWzEn4U4u6BamG0dOawgtxnAH/CeiBKFEaOecEkI3pPfUf1mSs2w1igQ7I6fZ6R3Pq@yzoFOjTJaYZInEjxLUFW/ymy2gjW5Tb/AYXw "brainfuck – Try It Online")
[Previous answer](https://codegolf.stackexchange.com/questions/224562/compose-a-song-line-by-line/224570#224570)
Song so far:
```
eor;n84pej8btp;8boeiuhtopwa8h5por58hob8h5p29h5]-925-j]wgip4o[35iwoueou9[-0etdojfuotpog;kcjliuxiokjdl
```
Next line:
```
You are my SyntaxError, my only SyntaxError.
```
Makonede, maybe get some singing lessons?
*I learned brainfuck for this.*
[Answer]
# Day 2, PHP, follows [this](https://codegolf.stackexchange.com/questions/224562/compose-a-song-line-by-line/224676#224676), 75 bytes
```
<?=$a=side," to $a, $a, $a to $a
",$i='Oh-u',"-$i-$i $i-$i-Oh I'm falling";
```
Song so far:
```
side to side, side, side to side
Oh-u-Oh-u-Oh-u Oh-u-Oh-u-Oh I'm falling
```
Next line:
```
Na, na, na-na-na-na, na-na-na-na, hey Jude
```
From [Hey Jude](https://www.youtube.com/watch?v=A_MjCqQoLLA)
[Answer]
# Day 14, [Charcoal](https://github.com/somebody1234/Charcoal), 450 bytes
```
⟦⪫E313…side to ×Iι⁴, ⟧F²⁺…Oh-u-⊗⁺ι⁶ “P➙⭆BX5↶÷ρ⦄⟧⁸A>ιZ›➙πα⊗σ*7¹´$⁹“BzI⊞³⌈”× la⁸“[¶²/;pv﹪HD⦃»ⅉδE4pPf·⁹E”⪫E³… round and¹⁶,¦⸿It won't be long⪫E³ yeah (yeah)¦,⪫⪪“Z⧴aC¿Jy⌈←*üYlΦθd;hA⊗U±”¶¦ catchy⪫⟦⸿Please ¦ (¦)⸿A⟧don't be long×a³⁵⪫⪪“T⊞8⁻‖⟧e2ü"↑«℅γ“=βk²↨r⊟h‹⬤BY=⁰”¶¦Galileo…o-⁹⸿F²⁺× on the wall, ι”- ⊟d⌈Pï⌊;∕1/↖⍘”⸿⪫E..,!⁺⁺×No, you can't. ‹!ιYes, I canι ¦⸿N…o n¹⁹!× Mama mia³⪫⪪“\`↖⮌3&℅⮌ü⎇Y,L¦⊞⊟η*"Dμ◧À⬤×(»q#⌕´⁸.₂O3K”¶”↶↥%q7*J↑º⌕+”F⪪, my only¶.¦¶⁺ SyntaxErrorι
```
[Try it online!](https://tio.run/##bZNRb9owEMff9ykOv5BIAaljq4b6NNG1YhodEn2pmj6Y5EgsOT7kOLB8enZ2Cg0UCUWOufvd3f9/yUppM5L6cFhaZVz0@puUiRZyG4nJzUQkMGszjbOS@KJWOYIj4NtnVWEdzWTtIhUn8C2O@cn3In6L775syEL0NYYOudQNh35g/pajZsSx99SsNebd/yqB2w7CDEZ0qWI@rGAjtVamSO09GdgjGNoDNRYK2YLcbqVFncCDFKesrjkBWnKVHz1aap9LhH2JqGtgmOO3dVNDQR/Jp/knZ7ODpcbkIE3OzJvbblxxxp472JMZOlgjaDLFdaaAFmUJkX/G4hITIldbrQJxRalJ@AfKDWuom6wEmRqoPZwTUxPyIZMuK9tLyisDlhpljcEYiII9qf0p3viQn3d6qZ1XbvL9el/lILVRamLwnZ0O3NeDKqQlWMjCqI3Kei0@Sq00Uq9OT1ryyzA9k1JcX6Kjse/W7Xkxwtb5FRTTKazJOY1s7YYnQys@MS/sEONxMuD8AO9XeKIEWmpYWVZp7Ev8wZrvB6GYr/aCdQJzH@AHVMfN7dV7EleHBeMXqD/u4PPmLmQloVLBhesmgEYHFfLqciWvv2EDoke1w9B4s2WnX/jAXwdUbc8K3CF/OmSMhIKjg0ZB6ndwwuEssG5TMz6m9T0QsGqNk/9@WUu2k@PucDiMdvo/ "Charcoal – Try It Online") Link is to verbose version of code. Song so far:
```
side to side, side, side to side
Oh-u-Oh-u-Oh Oh-u-Oh-u-Oh-u I'm falling
Don we now our gay apparel, Fa la la la la la la la la
The wheels on the bus go round and round, round and round, round and round
It won't be long yeah (yeah), yeah (yeah), yeah (yeah)
So catchy, catchy, it's such a catchy song
Please don't be long (don't be long)
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah!
(Galileo) Galileo, (Galileo) Galileo, Galileo Figaro Magnifico-o-o-o-o
99 bottles of beer on the wall, 99 bottles of beer
No, you can't. Yes, I can. No, you can't. Yes, I can. No, you can't. Yes, I can, Yes, I can!
No no no no no no no! Mama mia Mama mia Mama mia let me go
Never gonna give, never gonna give (Give you up)
You are my SyntaxError, my only SyntaxError.
```
Next line:
```
No juggernaut can stop us, no 4000
```
[Answer]
# Day 16. [Jelly](https://github.com/DennisMitchell/jelly), 487 bytes
```
Wẋ3j⁾,
““ to “, ”m0j“¡⁶G»”
“Oh“u”ŒḄ⁺j”-¤ɼ⁶®⁾-u⁶“µçṃtẉṛ»”
“œɗ:eĖḤQO⁴ẹḂÐMẠ⁷¦ŒŒ%»“ la”ẋ8¤”
“ɗ%'ƇạẉṗߥTÄḍ^qĖ»⁶“ØQ¤[ṛŻċ¤»Ç”
“;Ȯṗạḥ!ƭ⁽5⁾Ỵ»⁶“¡Ḷqɓ®rʋʠ»Ç”
“¢wðÇ8ṗȤḃȯ}Ėdẇ³ʂƙḷĖẈß5ʋu⁴»”
“)ọa»“ “ (“)”j“⁸v°Ȧ¢eṠCÄ»$”
”A”aẋ31¤⁾h!”
“(“) “, (“) “, “ ”j“©V°»$“ÆƥṠ=_eiȯẸʂIḄɱƇ»”
99“×&ṛƲȯ8+c6»ɼ“¬!}Ẇ?ɠ'Ạ01nṄ»®”
“¡ñeḣCṀƝṃṘ¡mLṁĠ"61ṁḂ"Ẉ»;⁶¤ẋ3$ṖṖ“ṃƇṆḶẆ ßḲP!»”
“Ẉ¿Jl»“ịPẠ»⁺⁺“¡µƈ`ȯ»“ḅiṢ»⁺⁺Ṗ⁶99®⁾!
“©ƒḣȦdḋL»,Œl$j⁾, “£ZAɦŻ/ıṙċṫ»”
“€¦ẒtFḷœ»“f#İ⁽s»ɼ“¢ẈĊⱮĖu»®⁾.
“çḥƭ~l?JⱮŻṁ^ƊƊg|ʂ»⁶4ȷ”
“Na, na, ”⁾naWẋ4¤j”-¤;⁾, ¤⁺“¡ẠȥỤC»
```
[Try it online!](https://tio.run/##TVNtSxRRFP7er9g1zaK1lFTcJESEIrFUiIICa8ktldUwtQgynNVccxFihV0lF3fX2Q1J98V8uTO3DM68MLP/4swf2c6dWRfhztw7c85zXp7n3KlwJPKpVnuGavzOlCOdB3xXnKUdWr75dz7aAvRKT7dP0RGyjnT6ADj9ED7DE/RaoA8jgWzFkVTySbeBbP8hNyhSrLYFOgngifYTleV5VL@h8qMRwNi0U3fDehKZPDrsSMeoKsii2vdHqGYc6QwKRsJItAj3HV8kRCCqsQfkOtpOtbSaMVSzbtSUtgv5J9oKso2xWT1JIDeztjUK8gtKanA9DjJwLVaH91pFQgk4y/vNQ0f620UVIz@@gAJZTmftTSi@r8armUtQyH3Uylqsh/CWjGzZKi3qyXFUY/C7GjW3kZ1RT@qatttVjRMDx42GbyDfCHn9iOe6@EUmwa0jsQ9QtgqQC6OSGdBWgDd7qHQ/PSEhTwf1Lp1P@OvRXLgn0aWjF9yNCftPoezG2dFWzTzFvfcyPGmVUGXV6EPSzK6YMa@4YFA4pa4RU@aRVeq5@bobOAlJQQ78i6iu9tmZVpKlvWMGFaqN5K1zkdUqYWR7A6gsmWkSGZUtyE4PoSLpmabuDtpJ0yaiA3ivmAtZdNKMSpIW4QlBIiqrxDVl8Wm7yI5G/A3GBO7fYMTlDHl8hEoQ@qhiieRwYq69skqenX2dRCV3YRfxpdNg0J1Ev1vrvkmTumcVxpHFh4AHjESk2Zt5Yd173m8XDH5br6CyrcdR@dUow4keQAHVxPx9EtfYdNO9uaqXaWrmLnjKUa36ulMp6skFlyDp/JbA0uizvHn4JdI3SEaDEyNj5rq5/vZzNerOWqd1Vk/zOBTwzYTcG0fomZC4lJ0g1@9Vr1upmAGvd@LCyiOXB4DXav8B "Jelly – Try It Online")
## Output
```
side to side, side, side to side
Oh-u-Oh-u-Oh Oh-u-Oh-u-Oh-u I'm falling
Don we now our gay apparel, Fa la la la la la la la la
The wheels on the bus go round and round, round and round, round and round
It won't be long yeah (yeah), yeah (yeah), yeah (yeah)
So catchy, catchy, it's such a catchy song
Please don't be long (don't be long)
Aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaah!
(Galileo) Galileo, (Galileo) Galileo, Galileo Figaro Magnifico-o-o-o-o
99 bottles of beer on the wall, 99 bottles of beer
No, you can't. Yes, I can. No, you can't. Yes, I can. No, you can't. Yes, I can, Yes, I can!
If I try, try, try, I can drink, drink, drink 99 bottles of beer!
Never gonna give, never gonna give (Give you up)
You are my SyntaxError, my only SyntaxError.
No juggernaut can stop us, no 4000
Na, na, na-na-na-na, na-na-na-na, hey Jude
```
[Previous Answer](https://codegolf.stackexchange.com/a/225583)
Next line: `I used to rule the world, chunks would load when I gave the word`
From CaptainSparklez's Fallen Kingdom (a Minecraft parody of Viva la Vida).
<https://www.youtube.com/watch?v=I-sH53vXP2A>
[Answer]
# JavaScript, 39 bytes (boring)
```
_=>'Baby shark doo doo doo-doo doo-doo'
```
[Try it online](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/e1k7dKTGpUqE4I7EoWyElPx@GdZFo9f/J@XnF@Tmpejn56RppGpqa/wE)
# JavaScript, 53 bytes (more interesting)
```
_=>'Baby shark'+' doo-doo'.repeat(3).replace('-',' ')
```
[Try it online](https://tio.run/##FcY7DoAgDADQq7AVorA44@BFTIXij1ACxsTTow4veQfeWF3Z86UTe2rBttmOMOHyiLphOaED4Zn1B0yhTHjJQf2L6EiChh4EqOY4VY5kIq8ySKXaCw)
The song so far is `Baby shark doo doo doo-doo doo-doo` and the next line is `I'm gonna get ya get ya get ya get ya` from Blondie's "One Way Or Another". Yes, 70s stuff.
[Answer]
# Day 1, [PHP](https://php.net/), 34 bytes
```
<?=$a=side," to $a, $a, $a to $a";
```
[Try it online!](https://tio.run/##K8go@P/fxt5WJdG2ODMlVUdJoSRfQSVRB4ohPCXr//8B "PHP – Try It Online")
[Previous answer](https://codegolf.stackexchange.com/a/224578/90841)
Song so far:
```
side to side, side, side to side
```
Next line: `Oh-u-Oh-u-Oh-u Oh-u-Oh-u-Oh I'm falling` ([Twenty One Pilots "Ride"](https://www.youtube.com/watch?v=Pw-0pbY9JeU))
[Answer]
# Day 0. [05AB1E](https://github.com/Adriandmen/05AB1E), 0 bytes
[Try it online!](https://tio.run/##yy9OTMpM/Q8EAA "05AB1E – Try It Online")
Line for next day: `eor;n84pej8btp;8boeiuhtopwa8h5por58hob8h5p29h5]-925-j]wgip4o[35iwoueou9[-0etdojfuotpog;kcjliuxiokjdl`
Song:
---
```
# full program
# implicit output
```
[Answer]
# Day 2, [Python 3](https://docs.python.org/3/), ~~103~~ 101 bytes
```
a=' sword'
b=a+','+a
c='side'
d=c+' to '+c
print(d+f", {c}, {d}\ndo you like my{b},{a} my diamond"+b)
```
[Try it online!](https://tio.run/##DcaxDoQgDADQna9oXHqXsjnzJ7cUqpF4UqMYQwjfji4vby950TT2zg7hvPUQNN4xoUViExyeUSY04gIhZAWkYPYjpvwRmgcLNbQXab8kCkUv@Md1gq1U32zl9g4k8qZJBvLf3h8 "Python 3 – Try It Online")
[Previous answer](https://codegolf.stackexchange.com/questions/224562/compose-a-song-line-by-line/224623#224623)
Song so far:
```
side to side, side, side to side
do you like my sword, sword, sword my diamond sword, sword
```
Next line: `Wo-o-o-o-o-o-oah, wo-o-o-o-o-o-oah` from [here](https://www.youtube.com/watch?v=0fTUj9mfnUk)
[Answer]
# Day 3. [05AB1E](https://github.com/Adriandmen/05AB1E), 51 bytes. My score: \$8\frac{2}9\$
```
“We're€¸æÊs€„„Î
Youƒ€€€‰ï€ƒ€Ê€· I
A‚è©—'s€À I'm™Ð€‚
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcOc8FT1otRHTWsO7Ti87HBXMZD1qGEeEB3u44rMLz02CSQAQQ0bDq8H0mChw10gLdsVPLkcHzXMOrzi0MpHDVPUQboPNyh4quc@all0eAJY06z//wE "05AB1E – Try It Online")
[**Previous answer**](https://codegolf.stackexchange.com/a/224709/94066)
Line for next day: `You wouldn't get this from any other guy`
Song:
```
We're no strangers to love
You know the rules and so do I
A full commitment's what I'm thinking of
```
---
```
“... # trimmed program
“... # push "We're no strangers to love\nYou know the rules and so do I\nA full commitment's what I'm thinking of"
# (implicit) end compressed string
# implicit output
```
[Answer]
# Day 3, [Splinter](https://esolangs.org/wiki/Splinter), 160 bytes
```
A{B{\s\i\d\e}BZ{\ }Z\t\oZB}C{\,Z}ACBCA\
D{E{F{\O\h}F\-\u}E\-}DDFZDDEZ\I\'\mZ\f\a\l\l\i\n\g\
\D\o\nZ\w\eZ\n\o\wZ\o\u\rZ\g\a\yZ\a\p\p\a\r\e\lC\F\aG{Z\l\a}GGGGGGGG
```
[Try it online!](https://tio.run/##tVVNj9owEL3nV4xyKbQbRJC60qKlEp@rnno3w8ElhlgNTuQYKIry2@kEAiRASD@2EymS7fHMvJc3k2hn/FB19pEOl9ADbdv2vp8MEoxRoociHbAEIWVoMGSDdJjgE0v7w8Gwj9YoGSeTBL@hn07QwXU6RicdjSZsNBoz/IofcMVwgRwDeiQqXKKFIwxRMdyiYLQT4pbRa42a0SnHHaNXRA9HjQKDIU6QvyWMAvD07WR7qtKy5CoKtYF4F1tkK7Gi@qe2PYOP0Hm2rK0vAwGBUI0MWxO@QLtrAZlcQKi9w@60PaODHjx/Bq688vZrD17yG5ltKHrbOi8lLTvnlUcr97xStMoKPPsuSmW4l6D56SGnO4Me3Uvs8nFmRyjeBcK1UQwJr5cs971OtSn4dEwpZ1al46kseSwL0a4OeiJEUmD3sddvF1pV8CNfEcSiPmKkpTJgj7UO9ROs1YqbuS/VEr5rPv8hTAxSgfHFIaXmq5ZdG5I02BI/pWk0rerarhhN6ggtyFSCA@59qZ6OruRaZZlSvdrP9DdEntnbShopawMc4iggD6GJUE/OuQn1f@IyreHyiNqpQP0Y7TvKpQZadQvRcJuWhpNDOphlnTHtOu5tU2xK86hMmVtN2TtAvQOREm@ylFfqzP84FdDyhne7F3C3nykPcVRC7nkB2r4zuR6P4qz42Hgk3tZWSyMaOWHNhzUUOeMK6HZE6pcqNno9NzJUhY6Y@5yozFrChLnnFYl3CCzC7FTBLI6Tf2vMqwpuMqWVmf5IMTdpiswWIWca2P8C "Python 2 – Try It Online")
[Previous answer](https://codegolf.stackexchange.com/a/224764/100664)
Song so far:
```
side to side, side, side to side
Oh-u-Oh-u-Oh Oh-u-Oh-u-Oh-u I'm falling
Don we now our gay apparel, Fa la la la la la la la la la
```
Next line: `The wheels on the bus go round and round, round and round, round and round`
] |
[Question]
[
Your task is to write a program which given an array and a number, you need to split the array into chunks with size is number.
## Rules
Your program will receive an array `A` , as well as a positive integer `n`. The array should then be split into chunks of length `n`, if the length of the string isn't divisible by `n` any leftover at the end should be considered its own chunk.
* If `n` is greater than length of array `A`, you will need to return array `A`, for example: if `n = 4` and `array A = [1,2,3]`, you should return `[1,2,3]`
* The array can contain any type rather than number.
* You should not change order (or direction) of any item from left to right. For example `if n = 2` and `A= [1,2,3]`. Any result rather than `[[1,2],[3]]` will be invalid.
## Test Cases
```
n A Output
2 [1,2,3,4,5,6] [[1,2],[3,4],[5,6]]
3 [1,2,3,4,5,6] [[1,2,3],[4,5,6]]
4 [1,2,3,4,5,6] [[1,2,3,4],[5,6]]
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so you the shortest bytes of each language will be the winner.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ô
```
[Try it online](https://tio.run/##yy9OTMpM/f//8Jb//024og11jHSMdUx0THXMYgE) or [verify all test cases](https://tio.run/##yy9OTMpM/W/mU1Zpr6TwqG2SgpK9Z@X/w1v@6/yPNtQx0jHWMdEx1TGLBQA).
Builtins ftw. :)
[Answer]
# JavaScript (ES6), 36 bytes
Takes input as `(n)(array)`.
```
n=>g=a=>a+a&&[a.splice(0,n),...g(a)]
```
[Try it online!](https://tio.run/##Fcq7CsIwFADQvV9xBykJicH6QqzpBzjo4FgKvcQmRMpNaYogpd8edTrLeeEboxn9MK0pPLtkdSJdOY26QoF5XqOKQ@9NxzaSuFRKOYa8STaMjEBDUQLBBU4/hOAwZwAmUAx9p/rgWPs/q5mWM7Qg4Pq431ScRk/O2w@zjDirC7mVO7mXB3lsOOdltqQv "JavaScript (Node.js) – Try It Online")
### Commented
```
n => // n = chunk size
g = a => // g = recursive function taking the array a[]
a + a // if a[] is empty, stop recursion and return an empty string
&& // otherwise, return an array made of:
[ a.splice(0, n), // the next chunk
...g(a) // followed by the result of a recursive call
] // (the last call leads to ...'', which adds nothing)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 12 [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")
```
⊢⊂⍨(⍴⊢)⍴1↑⍨⊣
```
Big thanks to [Ad√°m](https://codegolf.stackexchange.com/users/43319/ad%C3%A1m) for basically doing basically all the golfing (and for basically all the APL knowledge I have currently >\_>).
### Explanation
```
⊂⍨ Partitioned enclose (commuted, i.e. left and right switched) - for each ⍵ in left, ⍺ in right, if ⍺ = 0, create a new sub-array, push ⍵ to latest sub-array
⊢ Right argument of entire expression
⍴ Reshape - Change size of right into dimensions specified by left
(⍴ ) Shape of (here, there is only one dimension - length)
⊢ Right argument of entire expression
↑⍨ Take (commuted) - takes ⍺ elements from left where ⍺ is right. Extra elements (zeroes here) are automatically added
1 1
⊣ Left argument of entire expression
```
### Execution
Arguments `2`, `1 2 3 4 5 6 7`. Note that APL arrays are of the form `a b c`, with optional surrounding parentheses.
```
⊣ 2
1 1
↑⍨ 1↑2 = 1 0
⊢ 1 2 3 4 5 6 7
(⍴ ) ⍴1 2 3 4 5 6 7 = 7
⍴ 7⍴1 0 = 1 0 1 0 1 0 1
⊢ 1 2 3 4 5 6 7
⊂⍨ 1 0 1 0 1 0 1⊂1 2 3 4 5 6 7 = (1 2)(3 4)(5 6)(7)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/@v8ahvql/wo941mnogZrCrXqizr4t6Un6FQn6egm6aLYgssS0pSk1Vf9S1ODUvMSknNdjRJwTIAap3jlQvTswpUdf8/6hr0aOupke9KzQe9W4BcjSBlOGjtolAEaDS/2mP2iY86u0DavH0f9TVfGi9MUgOaGGQM5AM8fAM/g@kgYqMFNIUDBWMFIwVTBRMFcy4IKLGWEVNsIqimaBgjt0MuLgJujgA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 61 bytes
```
lambda A,n:[A,[A[x:x+n]for x in range(0,len(A),n)]][n<len(A)]
```
[Try it online!](https://tio.run/##ZZBNboMwEIXX@BQjJITdulITki6ssmDRRc/gWBUBkyBRg8CR6Ompx5AfWhZPeOab5@fpfuy5NclUpYepyb@PZQ4ZN0JmXGZyFOOzUVXbwwi1gT43J01feaMNzRg3TClp3ueTmqwe7AApSALuo3LDYcsh4bDjsOfwptwf40szzmMO8RGlQClRNEqFckI5o9Sxm0tuczfTlYFDtv@RnSvvmasqQvTY6cLq8qu9LCEDuSalz6g4Nv6ay1U@X1glnKfQDntzOk9dLTzwcB1xkXCt9X2tuEa/QsYECdq0ok/@KGvFSND1tbE0/DRATRqVTBxsNITRlZBCvGweuI/luQtGV89HxzuaFfaSNw5E9GDCqGXTLw "Python 3 – Try It Online")
Modifies [Henry T's existing Python 3 solution](https://codegolf.stackexchange.com/a/180979/85755) to produce valid output for n >= len(A).
Posting as its own answer due to lack of commenting privileges.
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~90~~ ~~84~~ 61 bytes
### Code:
```
[]*_*[].
L*N*[P|R]:-length(P,N),append(P,T,L),T*N*R;P=L,R=[].
```
The input format might be a bit weird, but it is:
```
A * n * Result.
```
For example, for the input:
```
**n** = 2
**A** = [1, 2, 3, 4, 5, 6]
```
You would need to use `[1, 2, 3, 4, 5, 6] * 2 * Result.`.
[Try it online!](https://tio.run/##KyjKz8lP1y0uz/z/PzpWK14rOlaPy0fLTys6oCYo1ko3JzUvvSRDI0DHT1MnsaAgNS8FyA7R8dHUCQEqCrIOsPXRCbIFavr/n4sr2lBHwUhHwVhHwURHwVRHwUxHwVxHwSJWQUvBGIiDUotLc0r0uLgA "Prolog (SWI) – Try It Online")
### Ungolfed version:
```
divide([], _, []).
divide(List, N, [Prefix | Result]) :-
length(Prefix, N), append(Prefix, Remaining, List), divide(Remaining, N, Result)
; Prefix = List, Result = [].
```
[Try it online!](https://tio.run/##TY7LCsIwEEX3@Yq7bGBa8C2KfyBFug1BCo11IKalrY@F/x6jjeLs5tzhzG27xjZ12t/Z@4pvXJlEacKRoLTMRER77gdCHuChMyd@4InC9Fc7aIlNKhDGGlcP52TMw60klG1rXPVDhbmU7NjVhLcvHET7X5BTFEsE6xbx3Q5jgzELq9KZ9@JbT00IU8KMMCcsCEvCirDWHxR9mRAv).
[Answer]
# PHP, 15 bytes
```
$f=array_chunk;
```
requires PHP 7. Call with `$f(ARRAY, N)`.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 13 bytes
```
{*.batch($_)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/WksvKbEkOUNDJV6z9n9xYqVCGoipYainZ6apkJZfpGCkp2di/R8A "Perl 6 – Try It Online")
Curried function wrapping the `batch` built-in.
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 54 bytes
```
import StdEnv
$n l=[l%(i,i+n-1)\\i<-[0,n..length l-1]]
```
[Try it online!](https://tio.run/##Dcu9CsIwEADg3ae4oYLipRitTnbTQXDrmGYI6Y8Hl6vYKPjynn77F7kPomnqXtxDCiRK6TE9MzS5u8h7UQhw7Xi5IqSNGLtuWzoZt0UpS@5lzHdgY73XJof/qqGACpzFHe6xwgMevX7jwGGc1Vxvev5ISBTnHw "Clean – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
i,j=input()
while j:print j[:i];j=j[i:]
```
[Try it online!](https://tio.run/##K6gsycjPM/qfnJ@SqmCroK6u/j9TJ8s2M6@gtERDk6s8IzMnVSHLqqAoM69EISvaKjPWOss2KzrTKvY/RExJCw6UuIDauVIrUpM1wMZpKRhr/jfWiTbUMdIxjuUygbNgYjomOqY6ZjrmOhY6ljqGBrEA "Python 2 – Try It Online")
Assumes that 1 chunk per line is acceptable output.
[Answer]
# Brainfuck, 71 bytes
```
,[>+>+<<-]>>>,[<[>.,<-]>>>++++[<++++++++>-]<.[-]<<<[<+>>+<-]<[->+<]>>>]
```
Dunno if this counts or not... input format:
```
<character whose ascii is n>AAAAAAAAAAAAA
For example, in the input:
1234567890123492034
n is 32 since the ASCII value of space is 32
```
Takes the input and puts in a space every time `n` characters pass
Explanation (no commas because that would break the program):
```
, take n
[>+>+<<-] copy into next two cells (destroys original)
>>>, take first of A into next cell
[ while that input exists
<[>.,<-] if n is nonzero output take next of A subtract one from n
>>>++++[<++++++++>-]<.[-]< n is zero so put a space
<<[<+>>+<-] copy the old n into surrounding cells
<[->+<] move from first cell to second
>>>] take input, do again
```
[Answer]
# Python 3, 46 chars
```
lambda A,n:[A[:n],*(f(A[n:],n)if A[n:]else[])]
```
-1 thanks to @Collin Phillips.
[Try it online!](https://tio.run/##Hcs7DsIwEEXRrUzpQa/AhK8lCq/DTGGEDSOFSWTSsHoT0V3p6M7f5TXZ0Ov11sf8vj8yRVhIMQUTbFx1MVkQGGulf5bxU5Kw9Do1UlKjlu1ZnIffcpib2rJeyWOHAXsccMQJZ1xWFihz/wE)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 3 bytes
```
{/}
```
This is an anonymous block that takes an array of numbers and a number from the stack, and replaces them by an array of arrays.
[Try it online!](https://tio.run/##S85KzP0fbahgpGCsYKJgqmAWy2Xyv1q/9n9dwX8A "CJam – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
ƒ°‚Çé
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//8jCR019//9HRxvqGOkY65jomOqYxeqYxP6PAgA "Brachylog – Try It Online")
[Answer]
# [Elixir](https://elixir-lang.org/), 16 bytes
```
Enum.chunk_every
```
[Try it online!](https://tio.run/##S83JrMgs@p9mq6bx3zWvNFcvOaM0Lzs@tSy1qPK/vpEml6e/XmZecUFqcolCmp5GtKGOgpGOgrGOgomOgqmOglkskE@MImNiFJlo/gcA "Elixir – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 1 byte
```
‚™™
```
[Try it online!](https://tio.run/##S85ILErOT8z5///RqlX//0crGRoZm5iamVtYKukomMQCAA "Charcoal – Try It Online") Charcoal's default I/O makes it difficult to demonstrate using anything except strings. If you want a full program that takes numeric lists and outputs formatted lists then this can be done as follows:
```
E⪪AN⪫ι,
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM3sUAjuCAns0TDM6@gtERDU0cBzPArzU1KLdLQBPK98jPzNDJ1FJR0lDQ1Na3//4@ONtRRMNJRMNZRMNFRMNVRMNNRMNdRsNBRsIwFCsX@1y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Ôº° Input array
‚™™ Split into chunks of
N Input number
E Map over chunks
ι Current chunk
‚™´ Joined with
, Literal `,`
Implicitly print each chunk on its own line
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~78~~ ~~77~~ 43 bytes
```
a=>b=>{int i=0;return a.GroupBy(_=>i++/b);}
```
[Try it online!](https://tio.run/##Xc5NS8QwEAbge3/FsKeEjrW7fhxME1BREfYoeFgWSUNqg7uJpK2yhPz2mg0riHNI4J0nM1HDmRrM/DhZ1Tw/2GmvvWx3ujF2FJgO/Bv@B0JAB3wmElvKRUgRGF4zr8fJW5DVk3fT592BvHFhyvK8pSzOrCi@pAcz6v0AHKz@3mzDEld4gZd4hdeR5b7qJ/txBB3JFFe0enG33ssDoWlG5zyQvDCZmqWrOb2p1tq@j32KypIWoYBUSWupeiC/q8HYE9@YLc3mWPfODm6nq1ef0NpYTRZZ3YQ6QljGBYLBPCD9Ic4/ "C# (Visual C# Interactive Compiler) – Try It Online")
I think we should be able to just write `int i;` because 0 is the default of int. I let it to avoid the error: `error CS0165: Use of unassigned local variable 'i'`.
[Answer]
# [F# (.NET Core)](https://www.microsoft.com/net/core/platform), 15 bytes
```
Seq.chunkBySize
```
[Try it online!](https://tio.run/##SyvWTc4vSv0fbainZx5bY/c/OLVQLzmjNC/bqTI4sypVweh/jV1BUWZeSVqegpKqo9J/AA "F# (.NET Core) – Try It Online")
Well F# has a [builtin](https://msdn.microsoft.com/en-us/visualfsharpdocs/conceptual/list.chunkbysize['t]-function-[fsharp])...
[Answer]
# [J](http://jsoftware.com/), 4 bytes
```
<\~-
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/bWLqdP9rcqUmZ@QrGCoYKRgrmCiYKpgppCkYYxM0wSZoaGDwHwA "J – Try It Online")
Takes the array as left arg and chunk size as right arg.
Uses a dyadic hook and the [infix adverb](https://code.jsoftware.com/wiki/Vocabulary/bslash#dyadic) with a negative argument, which does what we want by definition.
Note: The return type *must* be boxed because J only allows tables of equal sized items.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes
```
òV
```
[Try it online!](https://tio.run/##y0osKPn///CmsP//ow11jHSMdUx0THXMYrmMFBQUuHQDAQ "Japt – Try It Online")
[Answer]
# [PHP](https://php.net/), 45 bytes
```
function f($a,$b){return array_chunk($a,$b);}
```
[Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MU0jRUEnVUkjSri1JLSovyFBKLihIr45MzSvOyoTLWtf8LijLzSuKLNNI0og11jHSMdUx0TGN1FIw0Na3/AwA "PHP – Try It Online")
[Answer]
# Java 10, ~~106~~ 80 bytes
```
L->n->{for(int l=L.size(),i=0;i<l;)System.out.print(L.subList(i,(i+=n)<l?i:l));}
```
Prints the chunks without delimiter.
[Try it online.](https://tio.run/##dU9LTsMwEN33FKOubMW1KJ8uSByEkJCQyqpLxMJNnWqC40SxUxSqbDkAR@QiwYnSggosbNnz3rxPJndylm1eukRLa@FRotlPAKyTDhPIPMprh5qntUkcFobfj4/oG1uiddGDcWqrqpj9tXRXGFvnqjqyYkhBdMtZbGbxPi0qgsaBFktu8U0RylCchRjpkK4a61TOi9rxsvIk4in1unckyAgGwtBI3@C1pjRsu3Dis5f1WvvsY4VdgRvIfS2ycl5g@/QMkvYVAf5pANr/QIBRrz8ot1Ulm8H3ZGa5tMN8zs7ZBbtkV2zhwwwOh2Yo5iFgJBb@DoLRHuBXOQym8Pn@AdNx3ytwWZa6IX0mymWSqNLTjvCpgjZkxNpJf9ruCw)
### 106 bytes:
```
L->n->{var r=new java.util.Stack();for(int l=L.size(),i=0;i<l;)r.add(L.subList(i,(i+=n)<l?i:l));return r;}
```
Actually returns a list of lists.
[Try it online.](https://tio.run/##fVC7TgMxEOzzFSsqW@dYhEcKfA6iQUIKVUpE4dwj2sTxney9oBCl5QP4RH7kcI5DBKTgwlrP7Kxndmk2ZrjMV21mTQjwaNDtBgCBDGEGy8jKhtDKsnEZYeXkfV@kP9wUA6UPjopF4SfiX1HfddzUqU8MiwdK0O10OHHDyW5jPHjtipcj@YxMtmJclZVn6AisnsqArwXjAvW5wtQq7qXJcxbxZn4Yz1AwTLTjqb3FG8u58gU13oFX@1YNYvy6mdsYv9/CpsIc1nEzbEYe3eLpGQw/bAnghG@w8QUaflu9895sOwN/sCBN6PCRuBCX4kpci3F01f3wnQv1SAGmehzvJOEdBzDbBirWsmpI1tEaWReTncHH2zucJaU0dW237GCG9zV@zd0P9u0n)
**Explanation:**
```
L->n->{ // Method with List and integer parameters and List return-type
var r=new java.util.Stack();// Create an empty List
for(int l=L.size(), // Determine the size of the input-List
i=0;i<l;) // Loop `i` in the range [0, size):
r.add( // Add to the result-List:
L.subList(i, // A sublist of the input-list in the range from `i`
Math.min(i+=n,l))); // to the minimum of: `i` + input-integer or the size
// (and increase `i` by the input-integer at the same)
return r;} // Return the List of Lists of integers as result
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 10 bytes
```
{(0N,x)#y}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qWsPAT6dCU7my9n@aQrSCibWhgpGCsYKJgqmCmULsfwA "K (oK) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 25 bytes
```
->n,a{[*a.each_slice(n)]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ7E6WitRLzUxOSO@OCczOVUjTzO29n@BQlq0kU60oY6RjrGOiY6pjllsLBdI0BiboAma4H8A "Ruby – Try It Online")
If we can return enumerators instead of arrays, then it becomes simply:
# [Ruby](https://www.ruby-lang.org/), 21 bytes
```
->n,a{a.each_slice n}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PJ7E6US81MTkjvjgnMzlVIa/2f4FCWrSRTrShjpGOsY6JjqmOWWysXkl@fCIXSMYYp4wJNpn/AA "Ruby – Try It Online")
[Answer]
# [PicoLisp](http://picolisp.com/), ~~75~~ 74 bytes
```
(de f(n l)(if(>= n(length l))(list l)(cons(head n l)(f n(tail(- 0 n)l)))))
```
[Try it online!](https://tio.run/##fco7DsJADIThnlNMOVsgAQl0cJc8dokly1mRbTj9xlBFihQXU/j7swyzypJr5RiRaNBASXw9YdRo7zL5J9Cb8qNhtoVT7Eb8y@RV6UR5xgUWvPSrzB@xogb3G3j1adDijofraavNobZ77b8x1BU "PicoLisp – Try It Online")
[Answer]
# [Coconut](http://coconut-lang.org/), 8 bytes
```
groupsof
```
[Try it online!](https://tio.run/##S85Pzs8rLfmfpmCrEPM/vSi/tKA4P@1/tIaRjkK0oY6RjrGOiY6pjlmspo6ChjEWMRN0sViFGi07harMAjCdm1igolFQlJlXomCjpaenkKapUGOnALSzuDQ39T8A "Coconut – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 6 bytes
```
òÀf,r
```
[Try it online!](https://tio.run/##K/v///Cmww1pOkVc//8b6hjpGOuY6JjqmP03AQA "V – Try It Online")
Hexdump:
```
00000000: f2c0 662c 720a ..f,r.
```
Explanation:
```
ò " Until an error happens:
f " (f)ind the...
À " n'th...
, " ","
" (If there are less than n commas after the cursor, throw an error)
r " Replace the char under the cursor with...
<cr> " A newline
```
[Answer]
# Clojure, 14 bytes
```
#(partition %)
```
builtins I guess
[Answer]
# [Haskell](https://www.haskell.org/), 26 bytes
```
import Data.Lists
chunksOf
```
Here's a more interesting version, with just a few more bytes (thanks to nimi for five bytes in each solution):
# [Haskell](https://www.haskell.org/), 31 bytes
```
n![]=[]
n!x=take n x:n!drop n x
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P08xOtY2OpYrT7HCtiQxO1UhT6HCKk8xpSi/AMT8n5uYmWdbUJSZV6JirKCooOQB1JWvUJKRWpSq9B8A "Haskell – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~67~~ 65 bytes
*-2 bytes thanks AdmBorkBork*
```
param($n,$a)$a|%{$b+=,$_
if($b.Count-ge$n){,$b;rv b}}
if($b){,$b}
```
[Try it online!](https://tio.run/##fZDNCsIwEITveYqlrJLgKthWL1Io@CCSavyBWmtsVah59rpNRfSgOQxkZr4EpjzdjL3sTZ63uIUEmrbUVh8lFoRaoX4MGsxGCeFKHLYSs8nyVBfVeGewUA1htrBXyJzrQ@@41gmRSgF8SE4JIGUNKaKYZjRXxHd2FKUy7CTqJO5k1slcKfViw18s9SD1FH0g0W@E@o/oqx//63@9r@ABA2g8x@MAamtZzb0068pseDqeyIfWXOq8YmPIi2Lhmz4JXlEwNufgTQbCtU8 "PowerShell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~49~~ 36 bytes
```
function(A,n)split(A,(seq(A)-1)%/%n)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T8NRJ0@zuCAnswTI0ihOLdRw1NQ11FTVV83T/J@mYWhlpmOkyQVhGMMYJpr/AQ "R – Try It Online")
Thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l) for the golf.
] |
[Question]
[
Let’s take a positive integer such as `123`. We define the shifted auto-sum of this integer as follows:
* 123 has 3 digits. We thus consider 3 copies of 123.
* We stack each copy on top of each other, shifted by 1 digit each time:
```
123
123
123
```
* We pad each copy with `0`s (excluding the last one) to get a standard column addition:
```
12300
1230
123
-----
13653
```
### Test cases
```
Input Shifted auto-sum
1 1
12 132
100 11100
123 13653
6789 7542579
4815162342 5350180379464981962
```
### Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ì£U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=7KNV&input=WzEsIDEyLCAxMDAsIDEyMywgNjc4OV0)
Found a 3 that works with numbers.
```
ì£U
ì Convert to base-10 array of digits, do ... and convert back:
£ Map over the array with:
U Return the original input
```
---
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
*sç1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=KnPnMQ&input=WzEsIDEyLCAxMDAsIDEyMywgNjc4OV0)
```
*sç1
* Multiply the input with
s Transform the input as a string:
ç1 Replace each char by 1
```
If it is allowed to take the number as a string:
# [Japt](https://github.com/ETHproductions/japt), 3 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
*ç1
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=Kucx&input=WyIxIiwgIjEyIiwgIjEwMCIsICIxMjMiLCAiNjc4OSJd)
```
*ç1
* Multiply the input with (coercing both sides to number)
ç1 Replace each char by 1
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~4~~ 3 bytes
-1 byte thanks to [Unrelated String](https://codegolf.stackexchange.com/users/85334/unrelated-string).
```
ṁDḌ
```
[Try it online!](https://tio.run/##y0rNyan8///hzkaXhzt6/v//b2hkDAA "Jelly – Try It Online")
A port of [my PARI/GP answer](https://codegolf.stackexchange.com/a/250344/9288).
```
D # To digits
ṁ # Fill with the input
Ḍ # From digits
```
[Answer]
# [Haskell](https://www.haskell.org/), 23 bytes
```
f n=n*read('1'<$show n)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hzzZPqyg1MUVD3VDdRqU4I79cIU/zf25iZp6CrUJuYoGvQkFRZl6JggqIo5CmEG2oY2ikY2hgAKSMdczMLSx1TCwMTQ3NjIxNjGL//0tOy0lML/6vm1xQAAA "Haskell – Try It Online")
Multiplies `n` by the number obtained from replacing each of its digits with a `1`. Same length pointfree:
```
(*)<*>read.('1'<$).show
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX0NL00bLrig1MUVPQ91Q3UZFU684I7/8f25iZp6CrUJuYoGvQkFRZl6JggqIo5CmEG2oY2ikY2hgAKSMdczMLSx1TCwMTQ3NjIxNjGL//0tOy0lML/6vm1xQAAA "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org), 21 bytes
```
\(x)x*10^nchar(x)%/%9
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMGG4ozMtJLUlPjE0pL84tJc26WlJWm6FltjNCo0K7QMDeLykjMSi4AcVX1VS4jcTfPixIKCnEqNZA1DHUMjHUMDAyBlrGNmbmGpY2JhaGpoZmRsYqSpg2a0JkT7ggUQGgA)
Uses an '`x` multiplied by `111`' approach, where the '`111`' is constructed as the next power-of-10 greater-or-equal to `x`, integer-divided by 9.
(now reading the other answers: this is the same approach already used in [xnor's Python answer](https://codegolf.stackexchange.com/a/250340/95126))
[Answer]
# [Python 2](https://docs.python.org/2/), 25 bytes
```
lambda n:10**len(`n`)/9*n
```
[Try it online!](https://tio.run/##DcVLCoAgFEDRuatwqE7yqX2hnTTQSCmwl4QRrd4c3HPTl/cLVQnzUqI7181RnEAKET0yi5Y3o8Dy7kf0FKZ0H5hpYNVaejLjnBcgoAhIWadJ1w8jMQO00Clt1A8 "Python 2 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
₌ẏL+↲›⌊∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwi4oKM4bqPTCvihrLigLrijIriiJEiLCIiLCJcIjFcIlxuXCIxMlwiXG5cIjEyM1wiXG5cIjY3ODlcIlxuXCI0ODE1MTYyMzQyXCIiXQ==)
(yes I know there's a 4 byter, but I liked this approach so much I posted it separately)
Kids these days with their "ten to the power of" approaches. Hasn't anyone ever heard of literal spec interpretation? :p
Takes input as a string.
## Explained
```
₌ẏL+↲›⌊∑
₌ẏL # Push the range [0, len(in)) and len(in)
+ # add those together
↲› # pad the input left with spaces until length for each item in that list and replace all spaces with 0s
⌊∑ # convert each item to int and sum
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 27 bytes
```
n=>(n+'').replace(/./g,1)*n
```
[Try it online!](https://tio.run/##dczLDsIgEAXQvV/RXcEHMLyJqf9CKm00BJrW@PvoShMaZncz596nf/ttXB/L65LyPZRpKGm4oXTqe0zWsEQ/BkQJnc@Aj6mMOW05BhLzjCYE3e8wvnaU/jMcKsrbVPAaM9bE8H3utkV7WytRcW2sa3CjJFfGVQVpQYHmQvJdQQnFwDJhnNTSWXCalw8 "JavaScript (Node.js) – Try It Online")
It is shorter than
```
n=>n*(g=i=>i<n?g(i+9):i/9)`` // 28 bytes
n=>~~(.1**~Math.log10(n)/9)*n // 29 bytes
n=>(10**-~Math.log10(n)-1)/9*n // 30 bytes
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 19 bytes
```
expr ${1//?/1} * $1
```
An unusual example of `expr` being shorter than regular `$[]` arithmetic expansion.
[Try it online!](https://tio.run/##S0oszvhfnpGZk6pQlJqYYq2Qks9VnFqioKuroBLkGuAT@T@1oqBIQaXaUF/fXt@wVkFLQcXwP1dKfl7qf0MuQyMuQwMDIGXMZWZuYcllYmFoamhmZGxixAUA "Bash – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
D1€Ḍ×
```
[Try it online!](https://tio.run/##y0rNyan8/9/F8FHTmoc7eg5P////v6GRMQA "Jelly – Try It Online")
I suspect there's a 4-byter but I can't find one.
```
D Ḍ # To digits...
1€ # Fill with 1
√ó # Multiply by original
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~38~~ ~~36~~ 35 bytes
```
m;f(n){n*=m=exp10(m=log10(n)+1)/9;}
```
[Try it online!](https://tio.run/##XVDbaoQwEH3frxiEhcQL66WuFWtfSr@i@rDExEo1LiZQqfjrteNlbbeBmUzOnDPJCXNKxqapSQSRdJBm2qS8v3ouadK6LXGX1PLoKU7GqZIamkslCYXhALhmQHOl1VsOKQyeDZ6P4bpzEdhwjh7jMdmpOJczzYtfdjDTvVUQnEOUROGDH0Y3FWul0sDeL52JmbMP3q1iI@tf/ayPXzBCw4a/58DY1KLtgMwXV7LgPcrcZCufQFVfvBXk9iR62gBzRxKwrIVNl2Gr4901TludL5Q8uesq7Aqi6T3KEd2/4L/s2iFFEONYgPMMmI8qk2hM26Ds3btKU55vY8fDOH0zUV9KNTmfk1M3Pw "C (gcc) – Try It Online")
*Saved ~~2~~ 3 bytes thanks to [tsh](https://codegolf.stackexchange.com/users/44718/tsh)!!!*
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 16 bytes
```
.+
$.($($.&*1)**
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS0VPQ0VDRU9Ny1BTS@v/f0MuQyMuQwMDIGXMZWZuYcllYmFoamhmZGxiBAA "Retina – Try It Online") Link includes test cases. Explanation: `$($.&*1)` represents the input with its characters replaced by `1`s, which is then implicitly multiplied by the original input. (Retina's multiplication is decimal times unary, so the extra `*` is required to convert one of the decimal numbers to unary for the multiplication, and the `$.(` converts the result back to decimal.)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 7 bytes
Anonymous tacit prefix function.
```
10⊥⊢⊣¨⍕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG9qQMCjtgnGJgqPulsUgFy3ICDX0MjCXOFR71yFgqLMvBIgmZqcWZyZn6dgYqyQkpmeWVKskJ@mAFSlm5RZopAClM1NzFFIy8lPLCn@b2jwqGvpo65Fj7oWH1rxqHfq/zSgiY96@x51NT/qXfOod8uh9caP2iYC7QoOcgaSIR6ewSCHAFUBzeSCs4wQTAMDJGFjONvM3MISzjGxMDQ1NDMyNjECAA "APL (Dyalog Unicode) – Try It Online")
`‚çï` ‚ÄÉstringify
`⊣¨` defer each digit in favour of:
 `⊢` the argument
`10‚ä•`‚ÄÉevaluate as (carrying) base-10 digits
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 15 bytes
```
10⊸×⊸+˜´⊢⊣¨•Fmt
```
[Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMTDiirjDl+KKuCvLnMK04oqi4oqjwqjigKJGbXQKCkbCqCAx4oC/MTLigL8xMDDigL8xMjPigL82Nzg5)
### Explanation
```
10⊸×⊸+˜´⊢⊣¨•Fmt
•Fmt Convert the argument number to a string (list of characters)
⊣¨ Replace each character with
⊢ The argument number
´ Right fold
Àú on this function with reversed arguments:
‚ä∏+ Add the right argument to
10‚ä∏√ó The left argument times 10
```
### Other versions
Another 15-byte solution that constructs a list of powers of 10:
```
+´⊢×10⋆↕∘≠∘•Fmt
```
A 16-byte solution that constructs a list of 10s and multiplication-scans it:
```
+´÷⟜10×`·10¨•Fmt
```
Another 16-byte solution that constructs a string of 1s and evaluates it:
```
⊢×·•BQN·'1'¨•Fmt
```
[Answer]
# [Desmos](https://desmos.com/calculator), 29 bytes
```
f(k)=‚àë_{n=0}^{logk-.5}10^nk
```
[Try It On Desmos!](https://www.desmos.com/calculator/rq2lk2mlns)
Using the formula $$n\cdot\frac{10^{length(n)}-1}9$$
is surprisingly 1 byte longer:
```
f(k)=k(10^{floor(logk)+1}-1)/9
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~17~~ 14 bytes
```
{x*10/(#$x)#1}
```
[Try it online!](https://ngn.codeberg.page/k#eJxLs6qu0DI00NdQVqnQVDas5eJKizY0Mo4FUmbmFpaxAIY+B/0=)
*-3 bytes thanks to ovs!*
Explanations:
```
{x*10/(#$x)#1} Main function. x is input (123)
1 The number 1 (1)
# Duplicate by the amount of
( $x) x converted to string ("123")
# Length times (3)
(This creates an array of integers, which is (1, 1, 1))
10/ Convert the integers to base 10
x* Multiply by x
```
[Answer]
# [Python](https://www.python.org), 57 bytes
```
lambda n:sum(n//10for i in range(len(str(n)))if(n:=n*10))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LYxBDoIwEEX3nmKWramhUxBLDSdRFxipNoGBlLLwLG6aGL2Tt9EGFz_vL17e4z3ew22g-LT18TUHu9Gfqmv686UBMtPcM8oylHbw4MAR-IauLetaYlPwjDjnzjIyNa1Rcv4P7JNOST-gAFS_SZlOLqDc6UpAoXGLpcoLdTIrgNE7Csym3pKIceEX)
# [Python](https://www.python.org), 31 bytes
```
lambda n:int('1'*len(str(n)))*n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhb7cxJzk1ISFfKsMvNKNNQN1bVyUvM0ikuKNPI0NTW18iCqblqn5Rcp5Clk5ilEG-ooGBoBsYEBiGGso2BmbmGpo2BiYWhqaGZkbGIUa8WloFBQBDIvDWQKxIgFCyA0AA)
# [Python](https://www.python.org), 29 bytes
Port of `@xnor's` answer.
```
lambda n:10**len(str(n))//9*n
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhZ7cxJzk1ISFfKsDA20tHJS8zSKS4o08jQ19fUttfIgam5ap-UXKeQpZOYpRBvqKBgaAbGBAYhhrKNgZm5hqaNgYmFoamhmZGxiFGvFpaBQUJSZV6KRBjIHYsSCBRAaAA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~5~~ 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
$g√ó*
```
-1 byte porting [emanresuA's Jelly answer](https://codegolf.stackexchange.com/a/250342/52210)
[Try it online](https://tio.run/##yy9OTMpM/f9fJf3wdK3//w2NjAE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/w8r0w9O1/uv8jzbUMTTSMTQwAFLGOmbmFpY6JhaGpoZmRsYmRrEA).
Alternative 4-byter (port of [*@Bubbler*'s Japt answer](https://codegolf.stackexchange.com/a/250352/52210):
```
gиTβ
```
[Try it online](https://tio.run/##yy9OTMpM/f8//cKOkHOb/v83NDIGAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL//QLO0LObfqv8z/aUMfQSMfQwABIGeuYmVtY6phYGJoamhkZmxjFAgA).
**Explanation:**
```
$ # Push 1 and the input
g # Pop the input, and push its length
√ó # Repeat 1 that many times
* # Multiply it to the (implicit) input-integer
# (after which the result is output implicitly)
g # Push the length of the (implicit) input-integer
–∏ # Repeat the (implicit) input-list that many times
Tβ # Convert it from a base-10 list to a base-10 integer
# (after which the result is output implicitly)
```
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 4 bytes (8 nibbles)
```
`@~.`p$@
```
Inspired by [alephalpha's Jelly answer](https://codegolf.stackexchange.com/a/250347/95126).
```
`p$ # convert input to string
. # map function over each element (characters in string):
@ # second argument (arg1=element, arg2=input)
# so now we have digits-of-input copies of the input
`@ # interpret as digits in base
~ # 10
```
[](https://i.stack.imgur.com/3XdKQ.png)
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 8 bytes
```
Jq./]m|*
```
[Try it online!](https://tio.run/##bY07DoMwFAR7n4I6UsD7fva7AhdIRRNBBwWJUIqEsxtKpHjLGY32ub3m6b1uU/l@xvtQ@rXthuV3K/tjLmgqQwDVMFNAjBWBE58N1xpTDpay/6mkQpo8SIbCiOX6qawROXJyMfEMNzoA "Burlesque – Try It Online")
Takes input as a string (as from standard in) containing number.
```
J # Duplicate input
q./ # Quoted isNumeric (returns 1 for each digit)
]m # Map and concat to string
|* # String multiply
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
I×NI×1Lθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyQzN7VYwzOvoLTErzQ3KbVIQ1NHAUlGyVBJR8EnNS@9JEOjUBMMrP//NzO3sPyvW5YDAA "Charcoal – Try It Online") Link is to verbose version of code. Works with both integer and string input. Explanation:
```
1 Literal string `1`
√ó Repeated by
θ First input
L Digit length
I Cast to integer
√ó Multiplied by
N Input as an integer
I Cast to string
Implicitly print
```
7 bytes but only accepts numeric input in JSON format:
```
I↨χEIθθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwymxOFXD0EBHwTexACJSqKmjUKgJBNb//0ebmVtYxv7XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @alephalpha's Jelly answer.
```
θ Input
I Cast to string
E Map over characters
θ Input
↨χ Convert from "base 10"
I Cast to string
Implicitly print
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 7 bytes
```
a*:1X#a
```
[Try it online!](https://tio.run/##K8gs@P8/UcvKMEI58f///yYWhqaGZkbGJkYA "Pip – Try It Online")
### Explanation
Port of [Bubbler's string-based Japt answer](https://codegolf.stackexchange.com/a/250352/16766):
```
a*:1X#a
#a Length (number of digits) of cmdline argument
1X String of that many 1s
*: (Treat as a number and) Multiply by
a Cmdline argument
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 10
```
?dZAr^9/*p
```
[Try it online!](https://tio.run/##S0oszvhfnpGZk6pQlJqYYq2Qks@Vkqygm6qg9N8@JcqxKM5SX6vgv5KCjY2NgkqQa4BPJFdKfl7qf0MuQyMuQwMDIGXMZWZuYcllYmFoamhmZGxixAUA "Bash – Try It Online")
### Explanation
```
? # Read input
d # duplicate input on stack
Z # push count digits of input to stack
Ar # push 10, reverse top 2 stack elements
^ # calculate power of 10
9/ # divide by 9 to get 111....1
* # multiply by original input
p # print
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
lᵐ×↙?
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P@fh1gmHpz9qm2n//7@hgcH/KAA "Brachylog – Try It Online")
```
ᵐ For each digit of the input,
l get its length (i.e. 1),
ᵐ and concatenate the lengths back into an integer.
√ó‚Üô? Multiply by the input.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `r`, 4 bytes
```
Lẋ₀β
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJyIiwiIiwiTOG6i+KCgM6yIiwiIiwiNjc4OSJd)
Another approach.
## [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 3 bytes
```
ẏ↵*
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwi4bqP4oa1KiIsIiIsIjY3ODkiXQ==)
To get even with these 3 byters, lol.
[Answer]
# [Perl 5](https://www.perl.org/) `-Minteger -pF` , 12 bytes
```
$_*=10**@F/9
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXsvW0EBLy8FN3/L/fxMLQ1NDMyNjE6N/@QUlmfl5xf91fU31DAwNgHRmXklqemrRf90CNwA "Perl 5 – Try It Online")
[Answer]
# perl -p, 12 bytes
```
$_*=s/./1/gr
```
Multiplies itself with `1`, `11`, `111`, etc, depending on the length of the input.
[Try it online!](https://tio.run/##K0gtyjH9/18lXsu2WF9P31A/vej/f0Mj43/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~27~~ 26 bytes
```
#(10^IntegerLength@#-1)/9&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@19Zw9AgzjOvJDU9tcgnNS@9JMNBWddQU99S7X9AUWZeSbSyrl1atHJsrJqCvoNCtaGOgqEREBsYgBjGOgpm5haWOgomFoamhmZGxiZGtf8B "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# Regex `üêá` (PCRE2 v10.35+), 36 bytes
```
^(?*(\1{10}|^x{9})*x(x*$))(?*\2x+)x+
```
[Attempt This Online!](https://ato.pxeger.com/run?1=hVbNbttGED4W0FOsmdTeJamUdNDAFU0brizABhI7UGQ0ja0QNLmUFqGWBLmMZbu-9gF67aWX9pYHSo99jV46-yOJtgSUsKj9mfnm75uRf_-SlHlTy080SZIvl1Y3L5OK7nb3rPHX4bOUZoxT9LY_HOxG_fPjQXRxdjqKfjo9Hp2gvc4zxpO8SSnaV0ovpgedZBpXKCovxyhEQ-vHm5tP1y-bn29v34-mr26m-M9GZN29r88_4kMbX_n3vvfwy8f5_Q8PxJ7juf2cELi42p07ZO5o2b-_-Zc8hbFcZJdhVDp-0PKhFhXjE-nE6owVcErj2cGa3EGHcYFKWIqIVlVR4aTgtUAqAHtG6zqeUILua5H2eglIoP19ZI7lUp1TnuYBqqhoKo784GENU-6TIqUuui6KHBVhFue1hFVmDNzl7vevxkEHwcMyhFUuowk1GJGRwhoH62Jc9E-Ohns2MZcuqtkdLTK8dPy7xUlLnhCirMgHF-hQB5EUjUA9tAyUyPAspYaUBz1kPQleKVsWaFlX3CLLfGRApKmOZJmUzkOn4TWbcJqivOAT_Yp5fUOrQCVsdhslcZ6DGyZ2s4uu8yL5hOzERZ8LliI7jUUMuZNJkksUhgjLG5tsrzCIwXacZWU8U5lZzDgGAOVgeQlEyCnHJen649ALdAiaHahMQgsf9qwAVk5Y6i8L2NmHzxaB8wYQX-5GAooKuhJ-AgsF3QZivGyEVFeBQQmRXdHFfhaLZBqpWOzVWqNVtG5y4eoSBKYH351-GKiTLKspXEK8EMJETB8J2MVnmgjQMpWAXlzYn5Usp9iQ4t3b0ZCUyYskAmcxcQ3Gh8HwPBoNhm9Oz45Gg-PF8eD9aHB2LPfbyifzbTzxyIrBWxUQ0OS-3Q3qbeRaoYdr2YhgHwsaZVUxi8pYCFpxXAHLzy5evzYAbR1oXUHnApK4WIWb7g0sXkOBCJYUXEC4LV66m3j2FECbytmMtUG6PglaQiktxf8KVTRpqpoVfKOgMpsVFVLT5W7JXJgYOUxrrBuZcVdzjwQLxqvygAr3ID2xKBhWAovyQ_2576KyqOFa38D0T_FOd8cYlQ_3ZW5BZits87zX4_LwcAMucpS8g3wCA4N7Kyw9a6U5Tm_07pL7jj8OYNjMIBO4dtHOfEc6Bgmq4XIctvSXSWAhlz24H3I_QI7D2hEvSHlHEDgljeCdKw4hQepAWvEzw9a3Kfrn198Q_LQwuNIjBBxrWdO9JJvyMbsUMdsdBU4zaAj1t-I0rE0ZSbDmnMbd99D2trGxFZquGw7Ph9HZ-ZujUf-EPFJU9Gu112JiiKqhT2xQ-NVZ011Nf5jfJuINk1w-D53Ve1NjZRWleBXfekNrgeWetCeivoSZsRzYOhL46dD_A_zxl9f1Pc_Tu_8A "C++ (GCC) - Attempt This Online")
[Attempt This Online!](https://ato.pxeger.com/run?1=hVbNbttGED4W0FOsmdTeJalUlFHXEU0bri3ABhI7UGQ0ja0QNLmUFqGWBLmMZbu-5gFy7aWXHnPo46THvkYvnf2RRFsCSojk7s7MN_9D_f41LrK6knc4juOvl1Y7K-KSdtu71ujb4FlCU8YpenM06HfDo_PjfnhxdjoMfzk9Hp6g3dYzxuOsTijaU0IvJvuteBKVKCwuRyhAA-vnm5uP19v1r7e374aTnZsJ_rMWaXv32_MP-MDGV96913n47cPs_uUDsWd4Zj8nBAhX3ZlDZo7m_fu7f8lTGMtFdhGEheP5DRsqUTI-lkYsz1gOpzSa7q_w7bcYF6iApQhpWeYljnNeCaQcsKe0qqIxJei-EkmvFwMH2ttD5lgu1TnlSeajkoq65MjzH1Yw5T7OE-qi6zzPUB6kUVZJWKXGwF12f9wZ-S0EF0sRVrEMx9RghIYLaxysk3FxdHI42LWJIbqoYnc0T_HC8B_mJw1-QojSIi-cowPtRJzXAvXQwlEi3bOUGFIW9JD1xHklbFkgZV1xiyzikUIhTbQni6C0Hlo1r9iY0wRlOR_rR8SrG1r6KmDT2zCOsgzMML6bXXid5fFHZMcu-pSzBNlJJCKInQySXKIgQFhSbLK5xCAG23EWmemYzEwjxjEAKAOLSyiEjHJckLY3Cjq-dkFXByriwMIHPcuHlRMU-mVBdR7BvUHgvAbE7W4oIKkgK-HHsFDQTSDGi1pIceUYpBDZJZ3vp5GIJ6HyxV6uNVpJqzoTrk6Bb3rw7en7vjpJ04oCEfwFF8Zi8ojBzj_RWICUyQT04lz_tGAZxaYo3r4ZDkgRv4hDMBYT12C87w_Ow2F_8Pr07HDYP54f998N-2fHcr-pbDJvY0mHLCt4o4QCNLFvdoN6Gr6G68FKNELYR4KGaZlPwyISgpYcl1DlZxevXhmApgy0rqAzAUGcr4J1dAOLV1DAg0UJziHcRl266-rsKYBWlbEpa4K0PeI3mBJaiP9lKmlclxXL-VpGpTbNS6Smy92icmFiZDCtsW5kxl1de8SfV7xKD4jwDoQnEjnDimGefsg_91xU5BWQNQWmf4K32ltGqby4J2MLPBtBs857PS4PD9bgIkfxO8gjMDB4Z4mlZ61Ux-mN3l1yz_FGPgybKUQCVy7amm1JwyBAFRBHQUN-EQQWcNmDewH3fOQ4rOnxvCjvCAKjpBK8dcXBJQgdcKv6TLH1fYL--fwFwaeFAUmPEDCsoU33kmzKx9WlCrPZUWA0g4ZQv2VNw9qkkfgrxmncvQ7a3DQ6NgLTdYPB-SA8O399ODw6IY8EVfk12ms-MURZ0yc6KHx1VmSX0x_mt_F4zSSX10Nr-VzXWGlJKV76t9rQmmGxJ82JqIkwMxYDW3sCnw79H-CPv7yW1215nQ68tls7P-2-1IT_AA "C++ (GCC) - Attempt This Online") - just the test cases (that are small enough to complete in reasonable time)
Takes its input in unary, as the length of a string of `x`s. Returns its output as the number of ways the regex can match. (The rabbit emoji indicates this output method. It can yield outputs bigger than the input, and is really good at multiplying.)
```
^ # Anchor to start; tail = N = input number
(?* # Non-atomic lookahead - try all possibilities to find ones
# resulting in a later match. This is used to multiply the
# number of possible matches outside by the number of
# possible matches inside.
(\1{10}|^x{9})*x # tail -= {any power of 10}
(x*$) # \2 = tail = N - {the power of 10}
)
(?* # Another non-atomic lookahead
\2 # tail = {the power of 10 chosen above}
x+ # Multiply the number of possible matches by tail. This
# applies for each power of 10 found, and those numbers of
# matches will add together.
)
x+ # Add tail possible matches, where tail==N, with the above
# multiplier being applied.
```
# Regex `üêá` (Perl / PCRE), ~~108~~ 76 bytes
```
^(x?)(?=(x*)\2$).*(?=\2((x+)\4{8}(?=\4$))*x{5}$)()?x+.*(?=\2$)(()?x+|\1+$)|x
```
[Try it online!](https://tio.run/##RY/BasJAEIbvPsWyDLLjRk2CQnGzRsFee@qtscEGhYWt2sTClnV77AP0Efsi6SQVehn2@/efmX/O@9rO29cPBrVi3p6qnWUwVYQ626wf18swOJxqAY2OVbZU6Jk5EKE/1@Z4Ybw4chXYyurmbM1F8DGPmveX5kItZTROogT3b50p/1dj0nEBJapuVkMbd/XKZin6lX1KtppqvFVhwFi/2dwEMJnuDfSSEj1UFIkJ7rgDg/pzKvIF1Cjy3EsJVRQH7O5ohsM@ap@UzkgU@4sOZsLZz9c34xOoyHilrxDK8v5hU5bts3A5zdLCjbBIAScjgiIVwkksZv4udDgDxJHz8wAoMHfyZiLq8VokEvDq2jYez@P4Fw "Perl 5 – Try It Online") - Perl v5.28.2 / [Attempt This Online!](https://ato.pxeger.com/run?1=RY-xbsIwEIbVla1vYFkn5MMJOAgkhGMCEt2qTt0aGtEIpEgp0CRIrow79gG6dmFoH6od-yR1AlUX29_5v__-e__YrYr8-H1x-fhMoJDE5Nt0mRPoSYcqnM9uZxPbWm8LBqUSMpxINCRbO0KzK7JNRWi8odKSaa7KXZ5VjPrUK_cPZeVaEs8PvABXT7Uo-q8KV8cxJChrr9JNXBbTPOyjmeZ3wUK5UyykbRHSTM7OBchC1Qjci3M0kLpIhFFNNWSoXnosGkOBLIoM55B6wmK9R9luN1GbpG6NQJJTdMi6lPy8vhHahdQJD-7L2iS5upknyee-Wvujr-t7piNnqZjuYNwH7HYcxH3GNMd4YEa2xgEgdrQZWkCGkeZnkaMGD3HAAQ_65Hn8u4Q_FOIEvw "Perl - Attempt This Online") - Perl v5.36+
[Try it online!](https://tio.run/##fVRtb9MwEP7eX3ELY7WbdGo2QFPTrBpjiA@DoWpIoLVEmeuk1lInchLavfQrP4CfyA@hnONmyxhQtal9vnvuuefOYVnWjRlbPxOSJeWUwyBjiu/ODltsFioIsosJ@DCyXi8WV5f75Zfr68/ns1eLGVl/JcshJUOfLDt0vLdNdzu4Ge8RsrTp@MXtwUpvX2xT2lnevlxtU0KHS3vjhLtqezd27W16t1zTP/EtBzqZH2S267UeuOXFVKSaXNOkhIwf20SKVh7On/odtoQsIMNlEXClUkVYKvMCqmI7c57nYczpLebp9xk6wGAAG6teVnYup4kHihelkuB6q1YpcxFLPoUklbF5hDJfcOVV2ebXAQuTJC0LorWtN8FlkrIr6DAKt8bdtu9hewhbxYZCEnRoAX6yCywi4ZJktOtO/J4HhpApDTLmW2TYtzxc2X5m/ixs0TH@tijaS4Tc3wsKSHWwxo9xUWE3gYTMykKHKw4dxT1oaoSiZIUy0YrnZVKYtVYzinJeOIDFIcu4mJmT9BtnRaou9icmFaL6YJRI55lIOMqyywJMTqgDH49HJ8Gbs/Oj01O4M7tP528PHNgxmc2iTtWjBlNEQLYUp7V@UdXiiGBZ6O2ApYEqjgpCpFSFw/NpH57nY4nD1sA0eTbAzY4h7YdemuMI8Ygu8kYrWokY8yIRkhMzQ0I6Rk/qoY9bt7LijGGyh6BhkQpSOdUyoA7SdSBLczw2J5GQU9Lutje89Ee6Wkj02fKb/ev3pTYO/4ILduVvAxLpY/IHLNNcnU7yhdldSNd2Jx7O/xx1IbkD7WVbE8NScjyc@I34eyGEL/VsDXzpemDbollx3akbCkhKJyHtsWwbaTbyMS00XjWhHxb8/P4DcHLNBUF2jZRmlvQE1vPEl5wRxR348On01AFkLHBEqu9mCB3Yp94TPgZl0IOdnRoRJa1m72Q0OhsFH87eH50fv6OPIu@vTU3ZOtHzZT3G50nO/x@2qa1@vURJmc/@UWWj@lXLPKuZ7pthVJxjLfT@LbK5n63Vutd92ev9YlESxvm6m2i1fgM "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##hVX9TttIEP8/T7G4HOzaDhenpUIxJuIgEkgtVGnQ9Uo4y9jrZFVnbdnrEqD82wfoI96DHDf7kcSQSGeBszM785vvcVwU7UkcP79JaMo4RZ9OhoNueHJ5OgivLs5H4Z/np6MzdNB6w3ic1QlFh0Vc0u7e9KgVT6MShcX1DQrQ0Prj7u7b7dv6r/v7L6Pp@7spfv4bz/sE9wM8t8m4u032bCDGXYznDhm/ezx4kuS7bULs@eP@0zbBpD93jBBQivwx9pxt8mP@TF7jWy6yiyAsHM9vOFeJkvGJ9G7FYzlwaTQ7WpM7ajEuUAFHEdKyzEsc57wSSEVmz2hVRRNK0GMlkl4vBgl0eIgMWx4Vn/Ik81FJRV1y5PlPa5iSjvOEuug2zzOUB2mUVRJWmTFw19399zd@C8HDUoRVksMJNRihkcIaB@sqXZ2cHQ8PbGIuXVSxB5qneOn47wtOQ54QoqzIB@eor4OI81qgHloGSmR4llJDyoMesl4Fr5QtC7SsMbfIMh9pVldTHckyKa2nVs0rNuE0QVnOJ/oV8eqOlr5K2Ow@jKMsAzdM7IYKb7M8/obs2EXfc5YgO4lEBLmTSZJHFAQIyxub7KwwiMF2nGVlOqYys4hxDADKweIaGiGjHBek7d0EHV@HoLsDFXFg4X7P8uHkBIX@saClT@B/iwC/BsS33VBAUUFXwk/goKCbQIwXtZDqKjAoIbJLuqBnkYinoYrFXp01WkmrOhOuLoFvhvPz@deB4qRpReES4oUQJmL6QsDOv9NYgJapBAzpwv6sYBnFpik@fxoNSRHvxSE4i4lrML4OhpfhaDD8eH5xPBqcLtiDL6PBxamkd5RP5td40iGrDt4qoQFN7pvToN5GrhF6sJaNEOhI0DAt81lYRELQkuMSuvzi6sMHA9DUgdEVdC4giYtTsOnewOI1FIhg2YILCLfRl@6mPnsNoE1lbMaaIG2P@A2hhBbif4VKGtdlxXK@UVCZTfMSqe3ysOxc2BgZrHGsB5lxV/ce8Rcdr8oDKrwD6YlEzrASWJQf6s89FxV5Bdf6Bj4LCd5t7xqj8uGezC3IbAXNPu/1uGT2N@AiR8k7yCOwMHhnhaV3rTTH6Z2mrrnneDc@LJsZZAJXLtqd70rHIEEVXN4EDf1lEljA5QweBtzzkeOwZsSLpnwgCJySRvDumENIkDqQVv2ZYuu3BP3z8xeCTwuDK71CwLGGNT1LcihfdpdqzOZEgdMMBkL9rXoazqaMxF9zTuMedtDOjrGxFZipGw4vh@HF5cfj0ckZeaGo2q8xXouNIcqavrJB4auzprva/rC/TcQbNrl8nlqr96bBSktK8Sq@9YHWAkuaNDeivoSdsVzYOhL4dDx32vudzr9xmkWT6rmdKaX2wX8 "C++ (gcc) – Try It Online") - PCRE2 v10.33 / [Attempt This Online!](https://ato.pxeger.com/run?1=hVbNbttGED4W0FOsGdfeJSlXVOLAEE0LrizABhw7UGQ0jaUSNLmUiFBLglzGsh1f-wC55tJLjnmg9NjX6KWzP5JoS0AJS9rZnfnmZ78Z-uv3ME-rUnz8SRh-vzaaaR4WtN08MMY_Bi8iGieMore9Qb_t9y5P-v7VxdnQ_-3sZHiKDhovEhamVUTRoTTamx41wmlQID-_HiMPDYxfb28_3rysfr-7ez-cvr6d4m8Vj5sHP87_wPMuwV0Pz00yam-TPROEURvjuUVGrx4OHoX4apsQc_6w_7hNMOnOLa0EkhQ_jxxrm3yeK8y_f_qXPHdn2MjMPT-3HLcWa8mLhE1EsKu9JINdGsyO1vSOGgnjKIcl92lRZAUOM1ZyJBM1Z7Qsgwkl6KHkUacTggY6PER6WyzlPmVR6qKC8qpgyHEf1zCFHGYRtdFNlqUo8-IgLQWsdKPhrtv7r8duA8GTxAjLmvsTqjF8rYUVDlaXdtU7PR4cmEQf2qhM7mkW42Xgvyx2avqEEOlFPDhDXZVEmFUcddAyUSLSM6QZkhF0kPEseWlsGGBljJhBlvWIgXBTlcmyKI3HRsXKZMJohNKMTdRXwMpbWriyYLM7PwzSFMLQuWvJv0mz8CMyQxt9ypIImVHAA6idKJJYIs9DWJyYZGeFQTS2ZS1vpqVvZhYkDAOADDC_BiKklOGcNJ2x13JVCoodKA89A3c7hgsry8vVjwHU7sFni8B-BYgv2z6HSwVbAT-BhYSuAyUsr7gwl4nBFSKzoAt5FvBw6stczNVaoRW0rFJuqytwda--O_vQlztxXFI4hHwhhQmfPlEws0805GClbwJ6duF_licpxZoU794OByQP90IfgsXE1hgf-oNLf9gfvDm7OB72Txbb_ffD_sWJkHdkTPpXR9IiKwZvFUBAXft6N8hvrVdL3Vurhg9ywKkfF9nMzwPOacFwASy_uDo_1wB1G2hdTuccirhYeZvONSxeQ4EMlhRcQNg1XtqbePYcQLlKk1lSB2k6xK0pRTTn_6tU0LAqyiRjGxWl2zgrkJwu90vmwsRIYapj1cgJsxX3iLtgvLweMGEtKE_AswRLhcX1w_0zx0Z5VsKxOoG3RIR3m7vaqXiYI2oLOlteneedDhOb3Q24yJL6FnIIDAzWWmGpWSvcMXqrpGvmWM7YhWEzg0rg0ka7810RGBSohMOxV7NfFiHxmOjBQ485LrKspJ7xgpT3BEFQwgneHTFICUoH2pKfMTZ-jtA_f35B8GpJ4EiNEAis5k31kmjKp-ySxKx3FASdQEPIvxWnYa2vkbhrwSncwxba2dE-tjzddYPB5cC_uHxzPOydkieGkn619lpMDF5U9JkPCm-dNdvV9If5rTPeMMnF89hYfW9qrLigFK_yW29opbCUSX0iqkOYGcuBrTKBV4f6H-Cvb63mfqulhP8A "C++ (GCC) - Attempt This Online") - PCRE2 v10.40+
[Try it online!](https://tio.run/##hVX9UttGEP/fT3EoFO4kmVomodRCeCh4BmYSyDhmmgZTjSKd7JvIJ410CgbCv32APmIfpHTvw7bAnqnGlm7vdn/7vRcXRXsSx89vEpoyTtHH0@GgG55enQ3C68uLUfj7xdnoHB223jAeZ3VC0VERl7S7Nz1uxdOoRGFxc4sCNLR@u7v79nW//uP@/vNoenA3xc9/4nmf4H6A5zYZd7fJng3EuIvx3CHjt4@HT5J8u02IPX9897RNMOnPHcMElCJ/jD1nm/yYP5PX@JaL7CIIC8fzG8ZVomR8Iq1b7bEcdmk0O17jO24xLlABSxHSssxLHOe8Ekh5Zs9oVUUTStBjJZJeLwYOdHSEzLZcqn3Kk8xHJRV1yZHnP61hSjrOE@qir3meoTxIo6ySsEqNgbvpvju49VsIHpYirIIcTqjBCA0X1jhYZ@n69PxkeGgTc@iiij3QPMVLw39e7DT4CSFKi3xwjvraiTivBeqhpaNEumcpMaQs6CHrlfNK2LJAyhpziyzjkWZ1NdWeLIPSemrVvGITThOU5XyiXxGv7mjpq4DN7sM4yjIww/huqPBrlsffkB276HvOEmQnkYggdjJIcomCAGF5YpOdFQYx2I6zzEzHZGYWMY4BQBlY3EAhZJTjgrS926Djaxd0daAiDizc71k@rJyg0B8LSvoU/lsE9mtA3O@GApIKshJ@AgsF3QRivKiFFFeOQQqRXdIFPYtEPA2VL/ZqrdFKWtWZcHUKfNOcny6@DNROmlYUDsFfcGEipi8Y7Pw7jQVImUxAky70zwqWUWyK4tPH0ZAU8V4cgrGYuAbjy2B4FY4Gww8Xlyejwdlie/B5NLg8k/SOssl8jSUdsqrgrRIK0MS@2Q3qbfgargdr0QiBjgQN0zKfhUUkBC05LqHKL6/fvzcATRloXUHnAoK4WAWbzg0sXkMBD5YluIBwG3Xpbqqz1wBaVcZmrAnS9ojfYEpoIf6XqaRxXVYs5xsZldo0L5GaLg/LyoWJkcEYx7qRGXd17RF/UfEqPSDCOxCeSOQMK4ZF@iH/3HNRkVdwrE/gWkjwbnvXKJUP92RsgWcraNZ5r8flZn8DLnIUv4M8AgODd1ZYetZKdZzeaeqGe45368OwmUEkcOWi3fmuNAwCVMHhbdCQXwaBBVz24FHAPR85Dmt6vCjKB4LAKKkE7445uAShA25Vnym2fkrQP3/9jeBqYXCkRwgY1tCme0k25cvqUoXZ7CgwmkFDqN@qpmFt0kj8NeM07lEH7ewYHVuB6brh8GoYXl59OBmdnpMXgqr8Gu21mBiirOkrHRRunTXZ1fSH@W083jDJ5fPUWr03NVZaUopX/q03tGZY0qQ5EfUhzIzlwNaewNXx7LW8bsvrdOCz3zr45fDXf@M0iybVcztTAO3D/wA "C++ (gcc) – Try It Online") - PCRE2 - just the test cases
Without `(?*`...`)` molecular lookahead, it's much harder to do multiplication. So we reserve half of the number to use as a counter for one operand of the multiplication, letting \$a=\lfloor n/2\rfloor\$ and \$b=n\bmod 2\$, such that \$2a+b=n\$, in order to emulate operations on \$n\$.
We don't actually need to construct the number of the form 111...111 to multiply by. We can pretty much directly sum \$n\$ multiplied by each power of \$10\$, that is to say,
$$\large\left({\sum\_{k=1}^{\lfloor log\_{10}n\rfloor}2{{10^k}\over 2}(2a+b)}\right)+n = \sum\_{k=0}^{\lfloor log\_{10}n\rfloor}10^k n$$
using emulated arithmetic on \$2a+b=n\$.
```
^ # Anchor to start; tail = N = input number
(x?) # \1 = N % 2; tail -= \1
(?=(x*)\2$) # \2 = floor(N / 2)
.* # Find any value of tail ‚â§ N satisfying the
# following:
(?=
# Assert that 2*(tail-\2) is a power of 10
\2 # tail -= \2
(
(x+)\4{8}(?=\4$) # Assert tail is divisible by 10; tail /= 10
)* # Iterate the above as many times as possible,
# minimum zero.
x{5}$ # Assert tail == 5
)
()? # possibleMatches *= 2, for the following:
x+ # possibleMatches *= tail - \2, for the following:
.*(?=\2$) # tail = \2
(
()? # possibleMatches *= 2, for the following:
x+ # possibleMatches += tail
|
\1+$ # possibleMatches += \1
)
|
# Unanchored
x # possibleMatches += N
```
# Regex (.NET), ~~129~~ 117 bytes
`^(?=(x)*)(x?)(?=(x*)\3$)(((?=\3((x+)\7{8}(?=\7$))*x{5}$)(?=((?=.*(?=\3)(?<1>x)*){4}(?=.*(?=\2)(?<1>x)?){2}x)*\3))?x)*`
[Try it online!](https://tio.run/##RZDRaoMwFIZfJcgBc3SK7VY66jILu94TtB2IS2sgjRIjlYbc7gH2iHsRFy3dLg45339@/nNI21y47mou5Qia7TQ/8eGw2Sh@odtw/KAFowNGSIcC5z7C/SMgpR72j5QOMe7X9tlNuAbEaLArB7PVVxrNNo8vi9cpxj65P3l5lwu0S@en3oiFf8dw@xC8NedWSP4ZYA5XluXHRvOyqilIIhQBodreoIWSgUy6VgoTJEEujhTKtGp6ZRJpyHIyxAzKXXZwPoCCYjuhzGFWclCJ5HdeTBzHaKeMMwOdvpemqnlHwyGMQOFtckV70cLwpG464/xli/yfSaIa/3FSKE4CUOTn65uAT0tPuunbzu9Iq7I1vebd7UgMnHNjlqyy7Bc "PowerShell – Try It Online")
[Try it online!](https://tio.run/##RZBBboMwEEX3OYWFRsIDBQFpmzSUUqnrniBJJUSdYMkxyBgFBXnbA/SIvQg1RGkXo5n35@t75KY@M9VWTIgRVLZV7Mj6/WYj2Zm@uuMHzTPao4e0z3GePdwtASm1sFtS2vu4Ww1rM@EKEL1@eDAwW22F3myz@By/TDHDvfmTk5uc45AYu7VGzG0f3dc7560@NVywTwdTuGRReqgVK8qKgiBcEuCy6TQOUGQggrYRXDuBk/IDhSIs607qQGiSTAY/g2Ib7Y0NoCCzLZd6PyspyECwG8cT@z4OU8YpAxW@F7qsWEvd3vVA4nVzweGsuGZBVbfa2Mvi9J9JIGv7cYJLRhyQ5Ofrm4BNC4@q7prWvhGWRaM7xdrrkegYY8Z4ESeLOIpsWy4eV@unXw "PowerShell – Try It Online") - just the test cases
Returns its output as the capture count of `\1`.
This is now a fairly straight port of the Perl/PCRE `üêá` version.
The former 129 byte version actually constructed the number whose digits are all `1` to multiply by – indirectly – by constructing the number \$c\$ whose every digit is a `1` and has one less digit than the input, such that \$10c+1\$ is the actually desired number, then returning \$(10c)(2a+b)+n\$ \$=(10c+1)n\$ as a capture count. That version couldn't return a result for an input of \$0\$, but this version can.
```
^ # Anchor to start; tail = N = input number
(?=(x)*) # \1.captureCount = tail = N
(x?) # \2 = N % 2; tail = tail-\2 == \3 * 2
(?=(x*)\3$) # \3 = floor(N / 2)
(
(
(?= # Lookahead conditional
# Assert that 2*(tail-\3) is a power of 10
\3 # tail -= \3
(
(x+)\7{8}(?=\7$) # Assert tail is divisible by 10; tail /= 10
)* # Iterate the above as many times as possible,
# minimum zero.
x{5}$ # Assert tail == 5
)
# If the above assertion matches, do the following:
(?=
(
(?=
.*(?=\3) # tail = \3
(?<1>x)* # \1.captureCount += tail
){4} # Iterate the above 4 times
(?=
.*(?=\2) # tail = \2
(?<1>x)? # \1.captureCount += tail
){2} # Iterate the above 2 times
x
)* # Iterate the above as many times as possible,
# which will be a number of iterations equal to
# exactly half the current power of 10.
\3 # Assert tail >= \3
)
)?
x
)* # Iterate the above as many times as possible,
# applying the payload to each power of 10
```
I think I may have discovered a bug in the .NET regex engine, or at least the version on TIO, while working on this. The following variant of the same length should have worked, but didn't:
`^(?=(x)*)(x?)(?=(x*)\3$)((?(?=\3((x+)\6{8}(?=\6$))*x{5}$)(?=((?=.*(?=\3)(?<1>x)*){4}(?=.*(?=\2)(?<1>x)?){2}x)*\3))x)*`
[Answer]
# [PHP](https://php.net/), 29 bytes
```
fn($n)=>$n*~-10**strlen($n)/9
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSZvs/LU9DJU/T1k4lT6tO19BAS6u4pCgnFSyob/nfmourLLEoPqU0t0BDJU3DzNzCUlPT@j8A "PHP – Try It Online")
[Answer]
# Knight, 12 bytes
```
O*/^10L=xP9x
```
[Try it online!](https://tio.run/##rVldV9tIEn22f0XjHGy1LAdJMLMZG5lDMpDDGQIZSHYewBOELIPOyrJXkiEMYf56pqr6Qy3bZDe7w4Nldd@qrrpdXVVtot5NFH19kWRRuhjHu0U5TmYvb4dNcyRNrmtDUfkwj5dAeZLd1IbKZCow43iSZDFLU5bOshv6aOrRDycf3zGvej3/cMb86vWf@2dsp3o9PHnDXlWvZx@ZV4EPj88N7MnHYwP68eTd/vkvVsGZhR9t9qf3A9ez@@ewrJiMbsOc2bwSMFFgq1YxHLKdau7k4DeczGCSPPrC8Pvu7hIGlyEMugmYNOUIrGFen54eEwg/9sjJPvpmGHL2VgBA3rD1LkwXMecX2Yg3m@QH7MrFKDhrHZweWl9P7a3fPfc4@Pz@p89fOQy1BgJlAywOpyxA/KDZBKXzMC9ii7PHZiPJSpYMmg0YpQUcZk8WWQQjJBzBezmdO8U8u/BHwaPruE@go5GAOsLD08WBrS1Un8zZ/W1SxsU8jOJmA76nsQXjIG4JMxzWuiwvs8vJZc4eny5GFu@/aHEypZFMmKWtDVjnRYczoUKNbsDoZQbD3a4YATsbcVrE5sCTMCe6jaN/scksZ9lieh3nhbSHWUkxTm6SUmmF1dEdz9EeiafNPJd1mS0t73Y567GO24El0NKEszwuF3nGVEgIMYqKwbINd2GehNdprKwAI9LZfZxbEaynDGFfvjBlXERvERHxqcMlPcka15PAc2CPAj28ZB0eMhmMAMnGi7mFW8okpz0Gb6sGiyNfCG3CjMtOp7Kp1RGbBsLggTaKgRJIEfAdLJuHRcnK2xiUhXkJYLkBtmIUNzTi6Iky1jg5zxoLnx6njW5UZJD5GLplMsvAbIxYdwSmRYqRYjGfI@FcRZUaMek34w9oN8hGHSqU5xnEMaQrjFxpuWDlQ0efaTFwiAOYuvqYstBMFWSU7YSrFtqNpoZpOousHdfxODqIw9oJcjBbpGmYP5iOVvtzZmzP@462jBaU8otsSZqW8HAJmRTWebp/8PrN1a8bxz@fGg6baq@TtXr9Vb0bNcVvj86f0VjGOakMszH79yJUr6j2zlxie3UJQcDbjubiaA0XJLxTF65jnihV5osMd2ggU65dzgpL5Uo6ABDaZRIxmr1eTC78nZG0Q2x0m9KDNqCYw7EqJxZAwf/NNB23VN6hkuOgkmUFcCi0AlHMxPo13C7ztut@ovMYi3usVeaLuAUxqMcxJGF8EkIGwYkWRlarIgH9RN9l1SE6Pr2ezVKYua4z8KyvlVvfcsj@fo9MM69XzEzRxuxvtRGCtpylqWWa6jDXgQrxP5icrZiMVfjd/vsTB2uxCDR4PbrwXNeFcAJX4FW9Fckf8aeS4WNgxKjhLTIAbw5@@PS5HXiqpGOGw6qOD/r0xWMbAIdHxwc2m0ByHDR0aMv1MA1H4dxJ44w6AIMr1RQJzuDcPUfGsiDWJixtWHCshHoJqMW7xMUAikqCkzpvRNP50g4QScmoSiFIUzLCZYr7pIxuLRuYWemhgCMm/yKsU539Tp/hKgIQIKHYhUEW5m1ySqqXfWAtZPmAqnCFoGazzLF0Ub95MeKPVZhBA0W5XSx8BgvXdeeQ8Szedj9P8K9CvgckaBUc3cRlCq2i1aa9bOMOYYkcJxkfJBPLov3EhiC6zdEWB@KUc7HNgTtYays8OLUBYr0DsZ7oHDEbSEIGyl4kSebOysrXlT8Cr2feVDMoaVKsMVeAwWiA@Avms3mcWcbCTitvUasAVgVTUSkhHgPf3XlF47K5sERHMgHTx@gUtHAQsg72dwCH3oHecA1YWoWXBYOsG1ArhCcWkFzSDXpoLaIaNdgB882epaKx8uRX8CT@DG0cnvYVPzdqu043gg3MZCvA45XwgFXSOi8G/OdOX/aJawJZZz5ZgVon1BZbWIO4KkLD4Q6vGsuVdKhEz6k5tDYLFKwfhlVhoBNaH3NdyKS8VUHVBJaXOMyk2udKmKxZ5g7I3CJZOK1YwIMhLj5ImtjPGnWs3aZrVK@H0JFocy@p3W4oszZf2gXYY8EbZ@qo5Yb5i7JQu69jQvR6wqCuNojyJORLTMkYWsb2iG66Ud9tcSdFNPT9TMWSL/Yc@186DGIDCIXDeMoD5aXP14dqFJbqIbtOr1vRxNV31MWhG3XoWcocIf3qrUSnEe3YqtftFUJ2tTtrWFguz2t4sFd4EPu6joXpGtdswgSmEhKAGmRRhgw6l3DJQ9Cg1yN9kigqmcsbLRgta6d/65vEbK0nZvObQpvrhX4nNmsOiasDjfmmlwNJu2A9YD1Ps0xYoN6Dc9bz4Ix5Jtj/TvQupMcaNggQSuv21YirKCei/aErufY5tSt2QPw3lw8ETZIrcEegBIslBr7jleE2zuNOwbIZ9NBJWiYZuw8fgDc2nsGdtIxv4hxk5rMszsokxFsEnOQZu4/ZbXgXA1AqQnjJpmG2gPB5eImj6N01Mg5UEBPFIi3xRwNaXCc8BemZGLXkEmWmnIYsqUd9zyPd5w3RsN0ayqX7eZhibXwAr7NxGo/ZVWX2ldbyiN9EY2YsUjkzRGW9nnrnBG9IqG2Y/qTz4C4F61Lhw6RXy4tBPSvuMfPw75rHAEX78te2NhOAPVZrFGnQYUY2RB2ukFQl1xd1ALEbAVQbowsawqHE0JqNZ302jafRHMMsY8Orvf/XleHf4MpQubKxxpdA@iJd2XuefbHqGpNxeo/VAL5G@KqAbqyzs3rR7qnMYyrQ5rWr9Ie@rKsNe6akTCVa/st/Iy9zkKFGyw86fRNda3OXsUGVdevT332RUb1tdZNBXKN2m9GpkDCocRTUpI00iRKI6Ha1mDD5N3BP/OplNpo175jZu0ixo3rXjlBDfs/vbxu0vBVXhsDosLpmAVq9I2Xy4uHos7Bda2jPBdFLSgfLJc9fV/K2ue4DfC29Q4P/oSFCw/CJWxHp5l@3Q2Zv5IOHuGrXwyaJGgQR/2KSHoToypMAq4/jSQhJEjxTHWaSwWQyph@RwqiEMtXZjDrYc@IIZ8/cYlGZroHQDcofEqZhkmGzysL8JnJIqW3D9zuOP1fR/RL/eWO5ZE39Gvf09cd/vPrpLw "C (gcc) – Try It Online")
Ungolfed:
```
OUTPUT (* (/ (^ 10 (LENGTH (= x PROMPT))) 9) x)
```
] |
[Question]
[
## Challenge:
The challenge is to determine whether or not a color, given it's name, is one of the colors in the rainbow.
When supplied with a color, your program should output a truthy value if it is a color in the rainbow, and a falsy one otherwise.
## Rules:
1. The possible input options are exhaustive, and defined in the test cases. You can assume that you will not receive any other input than the ones defined
2. Character casing for inputs can be one of: UPPER, lower, or Title Case, but must be consistent
3. Standard [loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default?answertab=votes#tab-top) not allowed
## Test Cases:
**Truthy:**
* `red`
* `orange`
* `yellow`
* `green`
* `blue`
* `indigo`
* `violet`
**Falsy:**
* `purple`
* `brown`
* `pink`
* `cyan`
* `maroon`
### Leaderboard:
```
var QUESTION_ID=214678;
var OVERRIDE_USER=97730;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
[Answer]
# [Haskell](https://www.haskell.org/), 28 bytes
```
(`elem`"albedo").(!!8).cycle
```
[Try it online!](https://tio.run/##XcwxEoIwEAXQ3lN8MxZQSG3DTSwIySZmWHYzAWS4vJHOGavXvZddJmKuoX/WZiCmeTCWR/Jq2q65Xh9t5w7HVGebBD28XoBckqy4wTIjnO5a/AJTyEOLlUg4zlN3xEIkGHkjJPEpKt5JmVbzlzSiaxfaX5W3kpkwFt0FOckEd1jBbIuqmPpxgW1c6t3l/AU "Haskell – Try It Online")
If we wrap the input and index at position `8`, the rainbow colors all yield a letter among `"albedo"`, but the non-rainbow colors do not (they yield a letter among `"rwpc"`).
```
redredre d red
orangeor a nge
yellowye l low
greengre e ngr
blueblue b lue
indigoin d igo
violetvi o let
purplepu r ple
brownbro w nbr
pinkpink p ink
cyancyan c yan
maroonma r oon
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 7 bytes
```
A`p
d|e
```
[Try it online!](https://tio.run/##BcFBCoAwDATA@/5D8Bue/IbVLiUYkxKsRfDvdSZ4i6Uxzes2lq0ifxwjmOGRrBAvVb2jBGnYtRFiWYrjEVfeqC2qEnt4N1SxE8ebDFcKd/sB "Retina 0.8.2 – Try It Online") Link includes test cases. Assumes input in lower case. Outputs non-zero for rainbow colours, zero for the other inputs. Explanation: Simply checks that the colour contains the letters `d` or `e` but not `p`.
64-byte version to check against the 21 specific cases of rainbow colours in three different capitalisations:
```
T`L`l`^[A-Z]+$|^.
^(red|orange|yellow|green|blue|indigo|violet)$
```
[Try it online!](https://tio.run/##JcxBCsIwEEbh/X@OChXROwgWN66KK8WS1AwlGCdlaC2FuXuMZvV4m09o8mzTpj6bdDUXE0x3P@5vj12l3QFdLeQ0iuWBdKUQ4qKDELH2YSb17PwQ9eNjoGlbpdQ2J7SNQ0u55CD5Jb/kzxKKhCLhL@EnoUgoEsZZxkDoJS6M0fMLz9Uy3lZi5C8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Either an uppercase input or the leading character is lowercased, after which the exact colours are matched.
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~23~~ ~~19~~ ~~18~~ 12 bytes
```
^"rwpc"?*|9#
```
[Try it online!](https://tio.run/##FYpNCoQwDEbvEheOggfQWcxNhKqxlGaSEtQiePeart77fuIgsZR9mkFzWuHXP2NT9vYDiht8QdSxR5MbiSSbeEVk40Jn7QNvwYvJFYTwMEmnJqrTopLrMwWOhvV2Nf2dijB05QU "K (oK) – Try It Online")
Assumes input in lower case; based off of a flipped version of @Lynn's [Haskell answer](https://codegolf.stackexchange.com/questions/214678/is-it-a-rainbow-color/214687#214687).
* `9#` repeating-take 9 characters of the input, e.g. "purplepur"
* `*|` first-reverse, i.e. last
* `"rwpc"?` lookup character in the string "rwpc", returning either the index of the match, or a null if not present
* `^` check if `null`, i.e. convert nulls to `1` and actual indices to `0`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
,2ḥ93Ḃ
```
[Try it online!](https://tio.run/##Dco9DoMwDAbQ/TtLpzJxnFCsKK2xI4sfZWXpSbp17IDEyEnSixje/J7EXNxv97p92qZuq9f9d7z/69fdqIdakEgoV9MF0YgEHU@EJH2Kijkp04g8WWZCZ7oIcpIXHiUIhmCqcgI "Jelly – Try It Online")
Uses the Jelly hashing function. 5 might be possible.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
Takes input in lower case.
```
CƵl%3%È
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f@djWHFVj1cMd///nFyXmpacCAA "05AB1E – Try It Online") or [Verify all cases!](https://tio.run/##FYo9DsIwDEavUlnqViYGNjpwDMSQUCsyGDsytFVuwIU4AVKvlTrTe9@PvkMkrEs5PUboDucOxlIv24/7Y///1qFewXCCAdSCJHQpyKyrSzJEcUaeW08yUVKXhZTx45Jny9ymaLq2ZyZ5Ou4ltPQKpipw2wE)
`C` converts the color from binary. This allows digits higher than `1`, where upper case characters are `10` to `35` and lower case `36` to `61`:
```
C("red") = "r"*2**2 + "e"*2**1 + "d"*2**0 = 53*4 + 40*2 + 39 = 331
```
`Ƶl` is the compressed integer `148`, the code computes
```
is C(color)%148%3 Èven?
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~22~~ 21 bytes
```
f(int*s){s=*s/203&1;}
```
[Try it online!](https://tio.run/##JY7NbsMgEITvPMWKKhUQ9/9W6j5B1FtPbQ8bwA4qAWuxE0WRn90F97TfaGZWY@56Y5alEz6OKstrblV@eH58uX3S83LjowmTdfCWR@vT/eGdsZKDI/ooTslbCVcGYA5IoJDo66etGoCTs7wBnghj7ypdXAjpXKkn52KFfZhWy0fr@1Tp5FNwI2/@fwwTDWFN7Cmd18rg42@95oKrPiKlVOnjc7crrbkBpVCzgl0igW0Zpcs0DbjdShiorO8E3@RX2NjvWlTYQCcUSqnZvPwB "C (gcc) – Try It Online")
Inspired by ErikF's answer. I wrote a little program to brute-force the constants.
[Answer]
# [R](https://www.r-project.org/), ~~41~~ 33 bytes
```
sd(utf8ToInt(scan(,"")))%%.195<.1
```
[Try it online!](https://tio.run/##K/r/vzhFo7QkzSIk3zOvRKM4OTFPQ0dJSVNTU1VVz9DS1EbP8H9uYlF@ft5/AA "R – Try It Online")
Less elegant than [Giuseppe's solution](https://codegolf.stackexchange.com/a/214683/86301), but ~~3~~ 11 bytes shorter.
Converts the (lowercase) input to ASCII codepoints, takes the standard deviation of the resulting integers, then takes that modulo `0.195` (found by a grid search). The result is less than `0.1` iff the input is truthy.
[Answer]
# [Python 2](https://docs.python.org/2/), 22 bytes
```
lambda s:hash(s)%683%2
```
[Try it online!](https://tio.run/##FYrBCoJAFEXX9RVvM4yCbQoiggLNQYameTJkItXCCFEoFWc2fb29Wd1z77njz7VDv56bw2P@1N/Xuwa7b2vbBjZk292GkRomcND1cOdGpDziaGKdCYJKKIUlQWaE0JSJKvwudSozJLhJVOJKkBcmV14lBkv/zKU@U5yq2LdLbBA1f@6Xi3HqegecWVgdgVkODAIXQRO4MJz/ "Python 2 – Try It Online")
-1 thanks to [ovs](https://codegolf.stackexchange.com/users/64121/ovs), who used the extra degree of freedom afforded by the flexible input casing to save a byte.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~21~~ ~~14~~ ~~12~~ 10 bytes
```
“dʋ»e€µṪ<Ẹ
```
[Try it online!](https://tio.run/##DcsxDsIwDAXQ/Z@Jy6TEigLGjixKlQ2xMHAFToAYQQK6lY1bpBcxXZ/0NsRc3efjNf4u00jz6T492/u2ap@Xt/HxPS/ibhShFiQR6jJ0QDIiQcc9IUvMSXHIyrRH6a0woTMdBCXLFusaBLtgqvIH "Jelly – Try It Online")
Takes input in lowercase. Adaption of [Neil's method](https://codegolf.stackexchange.com/a/214685/66833)
Golfs:
* -10 bytes by changing the compressed string
* -5 bytes by adapting [coltim's method](https://codegolf.stackexchange.com/a/214681/66833)
* -2 bytes by using [Neil's method](https://codegolf.stackexchange.com/a/214685/66833)
## How it works
```
“dʋ»e€µṪ<Ẹ - Main link. Takes S on the left
“dʋ» - Compressed string; Yield "dep"
€ - For each character in "dep":
e - Is it in S?
µ - Use this triplet as the new argument
Ṫ - Take the final element (1 if p is present, else 0)
Ẹ - Are either "d" or "e" in S?
< - The tail is 0 and either "d" or "e" are in S
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~8~~ 7 bytes
```
9ịe“\Ṙ»
```
[Try it online!](https://tio.run/##DcoxDsIwDAXQ/d@od2FJqRWlGDuyKFW2qgsDF2DgCIwsVTY4SXoRw5vfSMzFvWv1TvvyPLTt8ane6vt729eXu9EAtSCRUP5VZ0QjEvQ8EZIMKSquSZkuyJNlJvSmsyAnOeFYguAcTFV@ "Jelly – Try It Online")
Get the ninth character (wrapping) and check if it's in the compressed string `“\Ṙ»` = `“albedo”`.
Port of my Haskell answer. caird saved a byte: the coincidence that *albedo* is an English word actually wins bytes over `9ịe“albedo` or `9ịḟ“rwpc`, owing to Jelly's compression dictionary.
[Answer]
# [R](https://www.r-project.org/), ~~35~~ ~~28~~ ~~27~~ 26 bytes
*Edit: -1 byte thanks to Dom Hastings, and -1 byte thanks to caird coinheringaahing*
```
!grepl("ro|p|c",scan(,''))
```
[Try it online!](https://tio.run/##XY5BDsMgDATvvILSQ0DKF/KTXghxIlTXRkCaRsrfqaOol5483l1rnVu7LRkSWpP5SEcwfQmebN91zrV3ZISqVPDVdg/qnLrrCeZIoH3R80qhRiZdWVcoVXtEHSmttah5@Ln249R/hUjqCg5BVJhMbzh7WkBgB0TeBOQISOaI66lHmuLCAtdXAmnNCU9rzLydyRTpKSPs/txePjOTcar4lHC3V2M/u/YF "R – Try It Online")
Regular-expression check.
'maroon' + 'brown' both contain `'ro'`, 'purple' and 'pink' both contain `'p'`, and 'cyan' contains `'c'`.
[Answer]
# [R](https://www.r-project.org/), ~~60~~ 44 bytes
```
!scan(,"")%in%colors()[c(547,32,536,68,455)]
```
[Try it online!](https://tio.run/##BcFBCoMwEAXQ/b9FBSGBrKqxvUvpIsYhhE5nZNSKp0/fs9ZuW07iQtf5vkqfldU251/ZxfERhnuIwxSmZxhj9O9mtEAtSSFcxKwnihEJZj4IVZZaFL@qTDvWw1YmzKanYK3yQb6S4JtMVdof "R – Try It Online")
-13 thanks to Robin Ryder.
Takes input as all lowercase. Checks to see if the color is *not* one of the excluded colors.
Outgolfed by [Robin Ryder](https://codegolf.stackexchange.com/a/214691/67312) and [Dominic van Essen](https://codegolf.stackexchange.com/a/214711/67312).
[Answer]
# [Perl 5](https://www.perl.org/), ~~13~~ 12 bytes
*Edit: -1 byte by returning null string as falsy, thanks to Nahuel Fouilleul*
```
$_=!/ro|p|c/
```
[Try it online!](https://tio.run/##BcFBCsJADAXQ/T@FglvpyqVnkWkbhmDMD7G1FHp20/dC0h5Vt9fzOiSPOKahKmUGs3kX7GLGDT1FHKOtAvVZO/FTmiyINcMEY3JzhPr7gmlvjk9L0v@MRenfuluc "Perl 5 – Try It Online")
Same approach as [my R answer](https://codegolf.stackexchange.com/a/214711/95126) (with help from Dom Hastings + Caird Coinheringaahing), but probably better suited to [Perl]...
(Edit: realized that porting [Neil's Retina answer](https://codegolf.stackexchange.com/a/214685/95126) is ~~actually shorter at~~ ~~also only~~ now slightly longer at [13 bytes](https://tio.run/##BcFBCsJADAXQ/T@FQnEns3LZs8jU@QzBmITYWgqe3fG9YOptjOk@l/ZluZxLlDGSDZ7VOnFQ1Xf0JA2LboRYk@74iCtXxJahxJK@G0LsecLjqIZXTXf7eazi9h7X@AM))
[Answer]
## [WebAssembly Text Format](https://developer.mozilla.org/en-US/docs/WebAssembly/Understanding_the_text_format), 111 bytes
```
(func(result i32)i32.const 0 i32.load i32.const 8 i32.load i32.add i32.const 13 i32.rem_s i32.const 7 i32.le_s)
```
This function operates on an integer memory array, that should start pre-filled with the chosen color (in Title Case) as a list of ascii code points. (strings can't be provided as normal function arguments in webassembly). The function will return 1 if its a rainbow color, or 0 if its not.
The actual logic behind the function is effectively the following: `return (mem[0] + mem[8]) % 13 <= 7`. (each character of the color takes 4 bytes in the memory array so byte-index 8 refers to a character-index 2). The actual WebAssembly Text Format is designed to feel like a stack machine, so instructions like `i32.const 8` puts an 8 onto the stack while `i32.add` will take two items off the stack, add them, and put the result back on.
The following is a complete WebAssembly file with the above function embedded inside.
```
(module
(import "api" "mem" (memory 1))
(func(result i32)i32.const 0 i32.load i32.const 8 i32.load i32.add i32.const 13 i32.rem_s i32.const 7 i32.le_s)
(export "check" (func 0))
)
```
This can be compiled to a WebAssembly binary (a binary wasm file can be generated and downloaded through online wat to wasm conversion tools like [this one](https://mbebenita.github.io/WasmExplorer/)).
The following javascript runs the compiled binary. It contains the logic to create the memory array, pre-filled with a color. For convenience, it has the binary WebAssembly embedded in it.
```
// Byte array generated by putting the WAT text into https://mbebenita.github.io/WasmExplorer/
// then downloading the resulting wasm file
// then running [...require('fs').readFileSync('path/to/file.wasm')]
const bytes = new Uint8Array([0,97,115,109,1,0,0,0,1,133,128,128,128,0,1,96,0,1,127,2,140,128,128,128,0,1,3,97,112,105,3,109,101,109,2,0,1,3,130,128,128,128,0,1,0,6,129,128,128,128,0,0,7,137,128,128,128,0,1,5,99,104,101,99,107,0,0,10,153,128,128,128,0,1,147,128,128,128,0,0,65,0,40,2,0,65,8,40,2,0,106,65,13,111,65,7,76,11])
// Alternativly, you can read from the raw wasm file after generating it.
// const bytes = require('fs').readFileSync('./output.wasm')
async function initWaModule() {
const mem = new WebAssembly.Memory({initial:1})
const { instance } = await WebAssembly.instantiate(bytes, { api: {mem}, })
return {
isRainbowColor(color) {
// Insert color param into memory
const i32Array = new Uint32Array(mem.buffer);
i32Array.fill(0)
const colorAsCodePoints = [...color].map(c => c.charCodeAt(0))
i32Array.set(colorAsCodePoints)
// Run webassembly function
return !!instance.exports.check()
}
}
}
const TRUE_COLORS = ['Red', 'Orange', 'Yellow', 'Green', 'Blue', 'Indigo', 'Violet']
const FALSE_COLORS = ['Purple', 'Brown', 'Pink', 'Cyan', 'Maroon']
;(async () => {
const { isRainbowColor } = await initWaModule()
console.log('These should be true')
TRUE_COLORS.forEach(color => console.log(color, isRainbowColor(color)))
console.log('These should be false')
FALSE_COLORS.forEach(color => console.log(color, isRainbowColor(color)))
})()
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 8 bytes
*-6 bytes thanks to [@ovs](https://codegolf.stackexchange.com/users/64121/ovs).*
```
'•³€å¤-à
```
[Try it online!](https://tio.run/##ASAA3/9vc2FiaWX//yfigKLCs@KCrMOlwqQtw6D//3llbGxvdw "05AB1E – Try It Online")
```
'•³€å¤-à # full program
- # subtract...
¤ # last element of...
å # is...
€ # each character of...
# implicit input...
å # in...
'•³ # "deep"...
- # from...
# (implicit) each element of...
å # is...
€ # each character of...
# implicit input...
å # in...
'•³ # "deep"
à # greatest element of list
# implicit output
```
[Answer]
# JavaScript (ES9), 23 bytes
Similar to [Neil's Retina answer](https://codegolf.stackexchange.com/a/214685/58563), but with a negative lookbehind to prevent `pur**ple**` from being matched.
```
s=>/d|(?<!pl)e/.test(s)
```
[Try it online!](https://tio.run/##bc87DsIwDAbgnVvA0mSgPQAUNk7AVhjSxg0BE0dJ2qoSdw@oEwiP/j/Lj7saVeyC9WnrSEPu6xzrQ6Vf4rhfe5RQlQliElHmjlwkhBLJiKI5hyHd5mshd6tv6MUmgN7I/5iCcgY4mQGRJk5MAHActDiwo6zT1hAno/0UaZEfKi6uOSmM7Ct@CB7ZRW2gib3MW/fg8m5WbP9TBaJF8hs "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 25 bytes
The case doesn't matter. Returns a Boolean value.
```
s=>parseInt(s,35)%385%3>1
```
[Try it online!](https://tio.run/##bc9NC4JAEAbgez9DCBUqCBGC0GPQvZt1WHW0rW1mmV0Vf/0WnormOO8zzMdDjco1rK3fIrUQuiK4orSKHZzRJ26T5ek6O@TrrNyHhtCRgZ2hPomrCw/@Pt/i9Lj6hi6JGNoo/Y@JFfYgyQzG0CRJzwAoQW0GcZTGVvckyag/hV/kh@IrVidlnPiKHdgacVHNNImXWY1PKW9mJfa/FBMtEt4 "JavaScript (Node.js) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
%%Cz283 2
```
[Try it online!](https://tio.run/##K6gsyfj/X1XVucrIwljB6P//gtKigpxUAA "Pyth – Try It Online")
*Answering my own question now that others have me beat... (FYI I solved this after posting)*
Explanation:
1. Converts to int with base 256
2. Modulo that by 283
3. Modulo by 2.
1 if rainbow color, 0 if not.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-!`, ~~13~~ ~~9~~ 8 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
g8 k`þ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=Zzgga2DDAr4&footer=YAohVQ&input=WyJyZWQiLCJvcmFuZ2UiLCJ5ZWxsb3ciLCJncmVlbiIsImJsdWUiLCJpbmRpZ28iLCJ2aW9sZXQiLCJwdXJwbGUiLCJicm93biIsInBpbmsiLCJjeWFuIiwibWFyb29uIl0tbQ)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~10~~ 9 bytes
```
›⁶³﹪⍘Sβ⁹⁴
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO9KDWxJLVIw8xYR8E3P6U0J1/DKbE4NbgEKJuu4ZlXUFoCZWvqKCQBsaWJpqam9f//BaVFBTmp/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Takes input in lower case. Output is a Charcoal boolean, i.e. `-` if rainbow, nothing if not. Explanation:
```
S Input word
⍘ β Decoded as base 26 using lowercase alphabet
﹪ ⁹⁴ Modulo literal 94
›⁶³ Check whether 63 is greater than the result
Implicitly print
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/) `PYTHONHASHSEED=2537`, 18 bytes
```
lambda x:hash(x)%2
```
[Try it online!](https://tio.run/##RY4xC8JAFIN3f0UQhXaog0UUoYOg0EkFXQSXa/vaHp7vHWerLfjf66GDGTIkkC@ZetRDKQ6abdt4h6MC4hRXhJ6MkRcqR8TITEu@L3QleGox1MC2zhpC5uTFsJpvyHvFuCsnwqNCRvCivBZEjMmXcMU//CV443g5p4d9ujmlp91um8wX8RK2b2rheLZClGNcJtfBqHtWKHTr2n8OunA6H6zT3ARl8B0KwjAceyrT8AE "Bash – Try It Online")
I'm pretty sure this is allowed. An environment variable is just like a command-line option, so this is considered a separate programming language to normal Python. Input in lowercase, outputs `1` or `0`.
[Answer]
# [Python 3](https://docs.python.org/3/ "Python 3"), ~~71~~ ~~56~~ 44 bytes
-15 bytes thanks to @Scott
-12 bytes thanks to @ovs
```
lambda s:(s[0]<'c'<'r'==s[1])==(s[0]in'pcm')
```
[Try it online!](https://tio.run/##HYrBDoIwEETP@hW9bZt40Hgj9EuQQ6EFN5bdZgEJX19bT/PmzaRzezM982RfObpl8E6tjV67e9/CCC0IWLt2j95Y@7dIkMYFTJ5YFCok1YEEDzdgcTSHAmeIkY8Cs4RAJYe4V4/kceYCX@QYtgJplxTrNAgf9ZmQPiXG09W2OGEm6JvrJQnSpieNxuQf "Python 3 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-n`, 18 bytes
```
p 255969480%$_.sum
```
[Try it online!](https://tio.run/##PU87SwNBEO7nVwwkdnqIGDFFmliIhRgsBKuw3g23g3szy@6sa/686@UQy@/B90jl49RWWNk8TiUYx0DIEovlSyTXewwshN5ldChUF@QMzROSDB2sZjf2OkUyNlaZFc5YtYQBE/VMX4Qqf5kYKSF9U18W69IqipYcz8Hjf4F5LaPvYH3EHa6PXbbEsUW82Wy2d9vb@@uLM1mm1l5pgJfkZCR4pxC0wmMiEtiHQvAkA48Kb6yBDA4lzedgn7QKHFg@4eHkBJ5dUpUfjedJuV3JLw "Ruby – Try It Online")
Input in Title Case, output is either a truthy integer or falsey zero.
---
\$255969480\$ is the lowest common multiple of the sums of all of the Title Cased truthy strings, which is also not a multiple of any of the sums of the Title Cased falsey strings. The reason I use Title Case is because the sums share a lot of common factors, reducing the length of the number. This could definitely be ported to various golfing languages to save lots of bytes, ~~which I might do.~~ see below!
---
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 10 bytes
```
ÇO•F;_â•s%
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cLv/o4ZFbtbxhxcB6WLV//99E4vy8/MA "05AB1E – Try It Online")
Same method as the above - input in Title Case, output as either 0 for false or a positive integer for true
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 34 bytes
Function takes a lowercase colour and returns `1` if it is rainbow colour, otherwise `0`.
To save space, I hash the first four characters of the colour with modulo 81 (the first number that didn't have collisions and had all printable remainders) and search for that in the list of hashes for the non-rainbow colours. If there is no match, then it is a rainbow colour.
```
f(int*s){s=!index("D@M1&",*s%81);}
```
[Try it online!](https://tio.run/##JY7BTsMwDIbvfQoTVJRkBWm3idKJA8fBjRNw8JK0i5YlldNuTFOfvSTl5M@yP/tXj51S89xy6wcZxS02d9Zr88vZ2@v7@oFVMpabtain@d565UZt4CUO2oanw7YokgQntJ6fg9UCbgWAOiCBRKKvnyb3AIyMZhWwQOg7k@lqnAuXTB0Z4zPs3biM0nPbhUxnG5wZWPV/ox@pd8vGnsJlUXrrj7mqKy79CSmETB@fu12ypgqkxLpI2Abi2KRQdYpWA65WAnpK6VvOyvgMpf7OosQKWi5RiLqY5j8 "C (gcc) – Try It Online")
I could save two bytes if returning `0` for a rainbow colour and non-zero for a non-rainbow was allowed:
```
f(int*s){!index("D@M1&",*s%81);}
```
[Try it online!](https://tio.run/##JY7BTsMwDIbveQoTVJRkBWm3iTDEgePgxgk4eEnaRWRJ5bYb09RnL0k5@bPsz/7NfWvMPDfCx0H18nrjo3W/gr@@vK3veK36arOWeppvfTRhtA6e@sH69HB4ZiwrcEQfxSl5K@HKAMwBCRQSfX5vSw/AyVleA0@EsXWFLi6EdC7UknOxwD6Myyg/920qdPIpuIHX/ze6kbqwbOwpnRel8/GnVHPBpT8ipVTo/WO3y9ZUg1KoWcYmkcBtDqVzNA24WknoKKdvBK/6R6jsVxEV1tAIhVJqNs1/ "C (gcc) – Try It Online")
[Answer]
# JavaScript (ES6), 20 bytes
```
s=>!/ro|p|c/.test(s)
```
[Try it online!](https://tio.run/##nY4xDsIwDEV3ThEihkaC9gCobHAJhERITQmEOHLSVFXp2QspCzAy@flb8vtXGaVXpF1YWaxgvHe7xipWstGXm3lB@HAPVeQBfMi8GNczhdajgdxgnfFADTAlPXgu1rM9J6j4knEkaWtI1IEx2CaqCcAmOJlmOmlb6RoTRf16GPghPyNtpbpkkZUb9ik6Lvo4sPKVLvp3wyyK4SjET5@zNP6rkGvImUl3Imwnv9P2lqbq5LTfJSHa/@zjEw)
How it works: Get a truthy value if `ro` is present, `p` is present, or `c` is present, then inverts that value so if they are present, the result is falsey, otherwise the result is truthy
[Look at the regex here (Regex101.com)](https://regex101.com/r/Xc6SF5/1)
# JavaScript (ES6), 22 bytes
```
s=>!/p|[^e]n$/.test(s)
```
[Try it online!](https://tio.run/##nY5BjsIwDEX3nCJEXTQSUw6Ayg4ugRgRUlMCwY6cNKhiOHuHlA2wZOXnb8nvn3TSwbD18QepgeHSrzs0ohZDqJfTuf/b/MIWi3kVIcQyqGExMYSBHFSO2lJG7kAYHSBItZhsJEMjZ0ISa2whUw/O0TVTywCYYe@68WSxsS1lSvbxMMptdSBeaXMsk6iX4lW0K27pLupHWtyeHcuk7julPvoctAtvhXzH3o26PdN19HuL5zxNr8f9opkIv7MP/w)
How it works: Get a truthy value if it starts with `p` or ends in `n` without an `e` before it. The `!` inverts that value so it returns true if no match and false if there is a match. I've tried multiple other regex's that end up being the same length, so i went with this one since it's easy enough to explain.
[Look at the Regex here (Regex101.com)](https://regex101.com/r/Hke4OC/1)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~38~~ 31 bytes
-7 thanks to DLosc
```
lambda s:s[-2]in'egou'>'a'<s[1]
```
[Try it online!](https://tio.run/##FYpNDoIwEEbXeoqGzUAiC3VHlIsgiyJtbSwzzVAkhHD22q7e@378Fj6E96ifr@jkNIxSzM3c1bfeIihDC7Qg4TF31z5qYhGERdEBqxEuQCzRqCSbco7WJIaVwsTBLbm3OFpDSX6WnApJ/MLe5WlgWvPTW/wmvDeZ0ySZCKFvzifPFkOpiz0com7FrstQHUUV/w "Python 3 – Try It Online")
Just tests the second and second-to-last characters. Takes a different approach to [aidan0626's submission](https://codegolf.stackexchange.com/a/214694/89774) and doesn't rely on custom hash seeds like [pxeger's](https://codegolf.stackexchange.com/a/214708/89774).
[Answer]
# [Scala](http://www.scala-lang.org/), 17 bytes
```
_.product%237<132
```
Computes the product of the characters' ASCII values modulo 237 and checks whether the result is smaller than 132. Expects its input in title case.
[Try it online!](https://tio.run/##PY9BS8NAFITv/RXDUiEBFWwPgrSK8SAexNKC4Em2m2dYXd5bNxujlPz2mF2lp/c9ZmBmWqOdHmX/TiZiqy3vpQd9R@K6xa33OMyAL@1g23/1CrsYLDdYX6MScaQZ6/H13AepOxNPFsvL1cVyMQJvElAYrM6wo89CbalWp1BPQXNDiV7IOekT3QciTlC5LksPXNtGEj3bKSIm2nTBu6xWQfps31j@SPfuR@f/UQcRVmWZawN@KhodF62yLeYG4W/CDeaH457ClIMqJ/swG8Zf "Scala – Try It Online")
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 12 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
{c]∑“N*.[„;%
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjVCJXVGRjQzJXVGRjNEJXUyMjExJXUyMDFDJXVGRjJFJXVGRjBBLiV1RkYzQiV1MjAxRSV1RkYxQiV1RkYwNQ__,i=Q3lhbg__,v=8)
same method as pxeger's answer.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~46~~ ~~42~~ 41 bytes
Saved 4 bytes thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner)!!!
Saved a byte thanks to [Samathingamajig](https://codegolf.stackexchange.com/users/98937/samathingamajig)!!!
```
f(char*s){s=*s-80&&*s-77&&*s-67&s[3]-87;}
```
[Try it online!](https://tio.run/##ZVBta8IwEP7urzgCSqstc5Otjq4DX4KUdY2UORHbDyWms4xVafqhKP3tXRKrc1tIuCd399w9d9T8oLSuE41u47zL9SN3utwc9jsdYSxLmQerw9eDyBxadlWnWQFfcZppeuvYAnEUEQrGC76OwIEjCvAUGYBIMPJnWKIV9jyylGgWYOxLMPYWKuT6U3dGJHp3iYffJJovgrmnouOALFX63PVfpJ2sRur/OgoI8VFlKwlSEyv3jBZsc9Jwa8D/27@@DVWpp1tGP1kuqEp/WOK7sHyciHcvm139B@eWyS4HTfZNsw0rBa1vN/AJeHpgu0Q7K9JvGkf34rGh11PZOpyW@LNILmqdlqkSIvsSl91iEU00rv/2MuG9zP@Xts9FSqKhELV5iMB8hvYGBMzEaNyA2IDz@Mxx4qgpXbWq@hs "C (gcc) – Try It Online")
Inputs the colour all in caps and return \$1\$ for a colour of the rainbow or \$0\$ otherwise.
[Answer]
# x86 machine code, 8 bytes
Hexdump:
```
6b 01 e7 c1 e8 0a d6 c3
```
Multiplies the 32-bit value at string start by `-25`, and extracts bit 9 from the result. Returns `al = -1` for rainbow colours, and `al = 0` for non-standard ones.
Disassembly:
```
6B 01 E7 imul eax,dword ptr [ecx],0FFFFFFE7h
C1 E8 0A shr eax,0Ah
?? ?? ??
C3 ret
```
Here, `?? ??` represents the "undocumented" [`SALC` instruction](http://www.rcollins.org/secrets/opcodes/SALC.html).
[Answer]
# GAWK, 18 16 bytes
(*-2 thanks to Dominic van Essen*)
```
2>$0=/[de]/*!/p/
```
[Try it online!](https://tio.run/##SyzP/v/fyE7FwFY/OiU1Vl9LUb9A////gtKigpxUAA "AWK – Try It Online")
Translation of Neil's `has "d" or "e" but not "p"` logic. Uses `"2>"` to make sure the condition is always true for any input, and sets `$0` to truthy/falsey so that the default action, which is `print $0`, will output the result.
] |
[Question]
[
1. Your program should output exactly: `Hello world!!!` with or without linefeed after.
2. Your program should take no input.
3. Sourcecode character distribution must be correct according to:
* The number of **numeric characters** (0-9) must be exactly one fibonacci sequence number.
* The number of **other non-numeric characters** !(0-9) in the sourcecode must be exactly the fibonacci sequence number before the above fibonacci sequence number.
Four examples of valid character distribution in sourcecode:
* 13 numeric, 8 non-numeric characters.
* 34 numeric, 21 non-numeric characters.
* 55 numeric, 34 non-numeric characters.
* 89 numeric, 55 non-numeric characters.
This is code-golf, shortest code in bytes wins! Good luck!
Edit: As this question has constraints on the sourcecode size in combination with being code-golf the accepted answer (if more than one share the equal winning character length) will be the answer with most votes (and least character-count): 2014-03-01.
[Answer]
## Windows Command Prompt - 34, 8, 5 chars, (2 below)
\**These ones may or may not be breaking rule 2, but here it is anyway*
```
%~099
```
Name the file:
```
&start call echo Hello world!!!&exit -b .cmd
```
**Now lets corrupt the file-system a little - 2 chars (or less if you want)**
```
A1
```
Name the file (using your preferred unorthodox method):
```
"&start call echo Hello world!!!&exit&.cmd
```
*How does this work:*
Since cmd scripts are invoked with 'cmd.exe /C "%1" %\*' the executed command will be:
```
cmd.exe /C "c:\PATH_TO_THE_SCRIPT\"&start call echo Hello world!!!&exit&.cmd"
```
which will in the following order:
* Fail to execute "c:\PATH\_TO\_THE\_SCRIPT\"
* Open a new shell printing Hello world!\n
* Exit the original shell
[Answer]
# MySQL, 34
```
x'48656C6C6F20776F726C642121'||'!'
```
This is a MySQL expression that evaluates to `Hello world!!!`, assuming the `sql_mode` setting includes `PIPES_AS_CONCAT`. It contains exactly 21 digits and 13 non-digits.
Whether this qualifies as a valid entry, I leave it to the jury.
**Example**
```
mysql> select x'48656C6C6F20776F726C642121'||'!';
+------------------------------------+
| x'48656C6C6F20776F726C642121'||'!' |
+------------------------------------+
| Hello world!!! |
+------------------------------------+
1 row in set (0.00 sec)
```
[Answer]
# C64 BASIC, 55

For fun and nostalgia!
[Answer]
### GolfScript, 55 characters
```
[72 101 108 108 111 32 119 111 114 108 100 33 {.}2*]''+
```
Didn't find a way to have a 34 characters solution, thus I created this one.
[Answer]
# Befunge 98 - 55
```
a"!!!dlrow olleH"ek,@1235813213455891442333776109871597
```
Decided to do it with a newline, since it doesn't cost anything. The numbers are the concatenated values of the Fibonacci sequence.
[Answer]
## Python 34-55
```
print "Hello world%s"%("!"*int(3.141592653589793238462643383279502884197169399375105820))
```
Yes. I waste them digits. What are you gonna do about it?
[Answer]
# Windows PowerShell (probably also Bash), 55
```
curl -L bit.ly/1b9q8ve?1=123581321345589144233377610987
```
You didn't say anything about network access, so here's a dirty solution. I've got a bit.ly URL with few enough letters on the second try. Unfortunately, It's still 21 non-digits, needing 34 digits to be used or wasted.
[Answer]
# C (89 characters)
```
main() {
int i[0000000000000004]={1819043144,1870078063,560229490,2566922529};
puts(i);
}
```
While the above is valid, unfortunately, my efforts to compact it with the following program doesn't meet the spec. I feel like it's worth looking at and maybe someone else can shorten it a bit though (64 characters, 37 numerals, 27 non-numerals). To compile it, you'll have to use clang and with `-fms-extensions`.
```
main(){puts((__int128[]){671944380693508453879479574226248i8});}
```
[Answer]
# sh, 55
```
echo Hello world!!! #1234567890123456789012345678901234
```
[Answer]
# Korn Shell, 21
```
echo $0
#123456789012
```
The script must be called "Hello world!!!" :)
[Answer]
## Python
```
print'092020090920200948656c6c6f20776f726c642121212009200909200920'.decode('hex').strip()
```
digits : 55
non digits: 34
[Answer]
# PHP (55 bytes)
This program uses binary (wow, it's the third time I reuse the same trick). 21 non-numeric characters, 34 numeric characters. No letters, because letters are boring.
## `xxd`
```
0000000: 3c3f 3d7e b79a 9393 90df 8890 8d93 9bde <?=~............
0000010: dede f53b 2331 3233 3435 3637 3839 3031 ...;#12345678901
0000020: 3233 3435 3637 3839 3031 3233 3435 3637 2345678901234567
0000030: 3839 3031 3233 34 8901234
```
[Answer]
# Mathematica 55
```
"Hello World!!!"(34+21!)/000000000051090942171709440034
```
Output
```
Hello World!!!
```
[Answer]
# [Sclipting](http://esolangs.org/wiki/Sclipting) (34 characters)
```
丟0000000000긒괡뉆롲닷댠닶롬뉔밈0000000000併0反
```
Unfortunately Sclipting doesn’t use any ASCII characters at all, so I have to pad the program with 21 useless number characters :(
[Answer]
# Bash, 2 chars
Very well, in the unlikely case Robert's answer is not disqualified, here's mine:
```
$0
```
Name the file `echo Hello world!!!` and execute with `sh`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Ṫ`, 8+13=21 bytes
```
kh6⁽NV33C3ẋ#123456789
```
kh6⁽NV = Hello world
33C = ASCII 33 to !
3ẋ = repeat top of stack three times
(Note that 33C3ẋ is one non numeric less than literal !!! would be)
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyLhuaoiLCIiLCJraDbigb1OVjMzQzPhuosjMTIzNDU2Nzg5IiwiIiwiIl0=)
[Answer]
## Forth or Ruby, 55
(34 numeric + 21 non-numeric)
## Forth
```
." Hello world!!!" \ 3141592653589793238462643383279502
```
## Ruby
```
puts"Hello world!!!"#3141592653589793238462643383279502
```
Using comments to pad feels dirty, but those are valid answers.
[Answer]
# J (55 characters)
(34 numeric + 21 non-numeric)
```
(72 101 108 108 111 32 119 111 114 108 100{a.), 3#33{a.
```
[Answer]
# APL, 55 bytes
```
14↑'Hello world!!!!!!!11111111111111111111111111111111'
```
[Answer]
# C#, 233 Bytes
233 Characters
144 Numeric
89 Non-Numeric Characters
```
/*I suck at CodeGolf!!!*/new List<int>{0072,00101,000108,000108,000111,0000032,00000119,00000111,0000000000114,0000000000108,00000000000000100,00000000000000033,00000000000000033,00000000000000033}.ForEach(c=>Console.Write((char)c));
```
Outputs:
```
Hello world!!!
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 55 bytes
```
"aaaaaaa1234567890123456789012345678901234"`HÁM WŽld!!!
```
[Try it online!](https://tio.run/##y0osKPn/XykRAgyNjE1MzcwtLA1wsZQSPA43@iqEH@rLSVFUVPz/HwA "Japt – Try It Online")
It is basically a simple hello world with some rubbish at the beginning that is ignored but makes the code satisfy the conditions.
[Answer]
# [Pxem](https://esolangs.org/wiki/Pxem), Numeric: 34 bytes + Non-numeric: 21 bytes = 55 bytes.
* Filename: `Hello world!!!.pxxxxx1234567890123456789012345678901234`
* Content: empty
The boring answer. The stupid latter part is nothing but a garbage.
[Try it online!](https://tio.run/##jVh7V@I4FP/fTxE6lSa0pQ2gIrUqg67DrjLqOB5HQE9pi4K1sLQoWtivPnuTFoEyO2c9R5v87jP3kYdPwePPT59sy7K3bbez0y3sFqhldd2iZZeLdrdECzq1t8r6jrtd6BY2AjdEqjs2xs9W8IR0vVAw3MlwMArRae2@enpq1gwcvg1d9OCG9sDvZrN8Zg@eny3fIfua475o/tjzUGE/S7PZRPi8evXFFESc8CF1OFfASUSM2EeuzOKBOhPmZr836jf3366OzIKuF@fg@ddv9ZvTH/e1r5eXx7UrkxpNJIjR5@q3L/fXx5ff6l8bFfltJiATvaF2NstXNUDDQdCbxDP5cyxy@x8S7vPYs0IXBY@cfzAMYfg6GDnB0OuF2azl9awAqQ9IEiMqC@KhMJNMiX2lbLbx/fS0dnZkVrgNzOw5RvDY64YGHyPGlwCu/ThA4ifCLFNmOQOGCgPP2c9C6F8sDwkZ1LW8wBWm02UaV82lJ9PAdZAUaBPtTTMC@POuSVzhO2ozIc4FPHNRGxM8gCRUfaS@hGM6DUdIrQWo1dTV3TaSmi0/15amDyN3iPKxcu2utC1qUaVqiB2jYWgtn8/PwdxdPt/yNc3oVI1ZPG3eMT2UFkRtqBnhMljW1zFKqagNUuDO7jpGKUj7acbyOkb1LVHrpRmL69gu8N2nMbBsp7DtnXWMUhAO0usrrmOUgosvacbtdYzqELFu2m19HaM6RMxN@7i7jlFaErVR2nRhHaMUpF/TjDvrGOwXIhRairG8jtEC@PiWZtxdx2gB/HlPJ0H/BQbuWOlFb61jlEJsw7Tl0jpGdXDnOR3vnXWM6uCOkzZdXsdKkH45jYGLagorAl8mjYHXYhoDZzYZNpOm2LaS7cIhSVPyftWiE9aUE8OB/jth0i2cb5EWbvnsbz7XIqLWKrYKLaoBV6Dlc9Ctk9X@rniGmIm05uvk7d1y2lomahgdDxTOjDdodg1phta8S6isxEUNOdqKDtVHUmK@eXeotMEueICb8RBcKBwi5sJjwhPjKJ8DEvcstg7rGXI3RU1haAdcgBRHMMtEAYyq2tDoXAAasymHoOCD0flgdLSjOeMK25ySxKEyMsQoNneImGrY4jg3qs6RsMpDK2YaQGn5TaS@t3MO0xaOlhBYEo9PO16sxkkWsA15TuPFWbHUDLytXHyozHPfwovUnpvE4wtE5qgKcZkkyeWRXcQtjs9Joon/xq7EniRZ/5WghOZHx1JCtF4Xe1bH9UxTaFGBRHwluDkc@L17O3jpuqPwWc6Im2qbcbcoJob2EPOwemxFVGnNGOkct2hCs5ZdCsYdLLCECAqTPoCxUBEOBYWbJbPE4Cr/75iPRK0zcq0nPoG8VbHgDQZD5A9C9GyF9mPPfxCAVZovV8ZE62BKGL/Kx2o8yfCJzscijP9Oxpt8DDzQh7wHpe5glIQJnDEMEknGR4NKM4mQn380qmfHpvTF9bwBgruD52Qymfxwwn5ooVja2t4p7@r/NZI2al8bV8eNK1OSNvBw1PPDLhz5XKkQn9gOgnhPX22k2hu/YvgdnaMEbgM/g5FtSp@PT@qNCDIvB67rkGAEtzTMh7Pu2LfD3sBH5/iIRN@aT8pfmLTNIwOGbVle0I8xiUZuOB75KCMDz4Ly54IC@D5dUP5aUJi6BeFqhcBMqnSJfIMvSXRpAhd3Q1WNhPlywTPGNRLxdaPaAj3Bl8rth264hXo9393XD0S9oi459iU2IFKDV98dL20ZilAQyAqEYmjd/HdmfuybS7ar@Gzu0dlUgHKB@LObbi9ES6aHsPTXx57n4gyElAyWIwmTCMDpdIxvgLYg@LiuXCtHikdYFrlgdG0Cj@GZnus/hI/4mhisaOtwXa7vmZ5BxhgfmbCWIBzha6Uuywol5B@Br0s4OJJL5Uppi8wWRnpg/RyfrBi@x2dKTblVfpDozBTy9xXUgK6zkOPavWe4vsJi3Qd3BN/hOBSMmgnixi34wHxhfQPulnb2atlsbW@rTHgfG4DV/hHuSs3iVluELejWLJXUWiIctzqw4HIsRksQkJppFgskilngZRH2/LE7YxFnrLW9Uhl49rd2CINi4wuzsWbyw8Q/CKqppbLBsmec49vcj6W12vPon@OrlSAEc8LNcrJeICd95ZpEdVPnFvsmr2MIf5@VrdJX1bZ5zRLFZvU2ByEPbT7vt5dCP1qYhohi3p8kx2pgyeDromnWvZngC4XbykA7sghnYHbBS@TavNhjvIns9ULo7bdC@78Wev9wg0lxN9QVV8L5Yh6hd80V0jOQnqBYEDy8zjGjLxE72IKAxiX@J6vwc2wdgLhssUhUbpKIGIsdI2dStZDD1p5Ocixn8F0K6t9pff2kY26SxeJ@ziNQMWBGyG/CuZOHahQq6NYdwTWs99ILQI3ACoUlxTro73sH/U2v4m32K3ys8THkaBbvsOCZqbehHOCtuLap20SQFs51IRIrXMl5IEzX326/ebqZ8ZkXXzTgHgdnIHtCqyP/iU7tMYwcCUlI7RbmhyPci85xlrA35JI7Li/m@NCNoHB5QT/JsiHL/T3MNmFWtBDyOPz9ZAoDYvx6GWy5juu58MyGPEMrJNsTNIgs1/dAXKZxS/CTps41yhT6JN705XjenkkGO6nY/xfgJmYj/j@IMeuQwTN7UQM4WgMXMXRKSG2UVhimUzyE1311gIY9R3HD3rOrDO3hWHkJ3g3HCl2ynIPS79/PKLR6HtyOS0sBZjf0qMxuSfwuJk2t1yfQhSxTLdDSTqlc3C6VkRRZsinqs@PGUXJqWHCxEDb@d/4TrUl02EeABMCBL3CSJOpwxYMfAQVxerCwORAUUSfSdGKNHiAG9QlKMjdBGz//BQ "ksh – Try It Online")
[Answer]
# Python 3.11, 34+21=55 bytes
Boring answer, uses comments to store extra junk.
```
print("Hello world!!!")#abcdef12345678901234567890123456
```
[Answer]
## Windows Batch
```
echo Hello World!!!::0123456789012345678901234567890123
```
] |
[Question]
[
Given a number n, find x such that x! = n, where both x and n are positive integers. Assume the input n will always be the factorial of a positive integer, so something like n=23 will not be given as input.
Examples: `n=1 -> x=1` (0 is not a positive integer), `n=24 -> x=4`
Shortest code wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 28 bytes (input \$\leq2^{64}\$)
```
lambda n:len(`n**8L`)**.6//1
```
[Try it online!](https://tio.run/##NU5BCsJADLzvK3pse9Akm02ygj/wCR5UVCzUtUhFfH3NCgbCzITJJNNnvj0KLdftfhmP99P52JTNeCntofS97Q5d369kvcblfRvGS4Ob6TmUubm2Q5lec9t1CwYKEogDEgT1TsAQGKLTKGT2B8ecUSphzQAozoRIgaAOTVGNssdAwAgqyrG6IRBkt1k2@8mYkpgyGWSpWhgoalRISj8DEgonBH/EzP@oERwp@yEwVPEFry8 "Python 2 – Try It Online")
This works on inputs up to \$20! =2432902008176640000 \$ that fall within 64-bit integers.
This uses an approximate fit inspired by [Stirling's approximation](https://en.wikipedia.org/wiki/Stirling%27s_approximation). However, the constants were estimated manually and it breaks down for larger values. With Python not having a built-in `log`, we use the digit-length for \$n^8\$ as an approximation for \$c\cdot\log(n)\$. Actually, we use the long value `8L` so that the string representations uniformly end in `L` for "long", which adds one to the lengths.
From there, raising the value to the power of \$0.6\$ and taking the integer part is apparently sufficient to give the correct output up to \$20!\$. It's lucky that the `0.6` is `0.60`, since we'd usually need another digit of precision.
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 2 bytes
```
¯!
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn//9B6xf9pj9omPOrte9TVfGi98aO2iY/6pgYHOQPJEA/P4P9pCoYKRgpmCkYmCoZGBgrmQGxqYGKgYGJgDGQamxlZWBgAAA "APL (Dyalog Extended) – Try It Online")
Exactly the same as [non-extended APL answer](https://codegolf.stackexchange.com/a/205049/78410) but just with the shorter syntax.
`!` is factorial function, `¯` prefix gives the inverse function of it.
[Answer]
# [Python 2](https://docs.python.org/2/), 32 bytes
```
f=lambda n,k=2:n and-~f(n/k,k+1)
```
[Try it online!](https://tio.run/##HcpBDsIgEAXQfU/xd4VINbBsgncZW6ETykAIGzdeHU23L69@@lHEjRH8Sfm1E8Qk71YByb58g5JHMulm9eBcS@vI1I8plAYGCxpJfCtrYJ1eJyDCX@MeaOulMZ2K9d9rY@mIBvPynA2Cinr8AA "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
!€i
```
[Try it online!](https://tio.run/##y0rNyan8/1/xUdOazP///xsaGQAA "Jelly – Try It Online")
```
i The first index (from 1) of the input in
!€ the factorials of every integer from 1 to the input.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
ℕ₁ḟ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1HL1EdNjQ93zP//P@q/kQkA "Brachylog – Try It Online")
A predicate which takes input reversed (i.e., the input is given through the output variable, and the output is given through the input variable). Brachylog more-or-less has a builtin for exactly this, aside from needing to apply the additional constraint of having to output a positive integer, where I say more or less because it's also just the factorial builtin and it works in both directions.
[Answer]
# [J](http://jsoftware.com/), 4 bytes
```
!inv
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/FTPzyv5rcilwpSZn5CukKRiZwFjGZkYWFgYwnqKRwX8A "J – Try It Online")
Inverse of factorial.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~33~~ ~~29~~ 28 bytes
Saved a byte thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!
```
x;f(n){for(x=0;++x-n;n/=x);}
```
[Try it online!](https://tio.run/##TY7NqsIwFIT3PsVQEBKTYvrjH7FuLj6FdSHVahZGaboIlj57PfW2YiBzGM58nCnCa1F0ndcls7wpHxXzmdJC@NBqO8881213PxnLOJoJ6Blbo7642h2OyNBEErHEkjSViGIlseploVLSVCW9SZbxeq1a/eGL26maofqng9zv49xv/ugvAolfnwQDQaXA@rOGEKVpbOHM6/Io2acInw@OMlxDCDN2Hfs6AofwwRy5/i6fFa1LFkzPCHcgnbrcUo8xKuEkdSU@o7MC0Qi3k7Z7Aw "C (gcc) – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 27 bytes
```
->n,x=0{2>n/=x+=1or redo;x}
```
[Try it online!](https://tio.run/##HclBDoIwEAXQq/zgBgKO1C0ZbuAJ1JiqIF0wJbUkNaVnr9Hly3Pr/ZNHvuR9L03gNh57OXCoWVkHNzxtF1IuFZFqKxr0Y0LEZjYIGCftJ3rpedalqVXVYVn9G8WvdlHI25tJDcKf41muqUDKXw "Ruby – Try It Online")
Increment the divisor `x` (initially 0), divide `n` (initially the input value) by `x` and store the result as `n`, repeat until `n=1`. Then `x` is the desired output.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes
Mathematica has the inverse function of the factorial! It's called `InverseFunction@Factorial`. I used a pure (Mathematica for "anonymous") function that returns the factorial by using the exclamation mark, as it's shorter.
```
InverseFunction[#!&]
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE7872Yb898zryy1qDjVrTQvuSQzPy9aWVEt9n9AUWZeiYNbtKGBYux/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
Å!g<
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cKtius3//4ZGBgA "05AB1E – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 39 bytes
```
.+
1 $&$*
+`^(1+) (1\1)+$
1$1 $#2$*
\G1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@by1BBRU1Fi0s7IU7DUFtTQcMwxlBTW4XLUAUooWwElIlxN/z/35DLiMuMy8iEy9DIgMsciE0NTAwA "Retina 0.8.2 – Try It Online") Link includes test cases. Actually calculates the largest factorial that divides `n`. Explanation:
```
.+
1 $&$*
```
Set `x` to `1` and convert `n` to unary.
```
^(1+) (1\1)+$
1$1 $#2$*
```
If `x+1` divides `n`, then increment `x` and divide `n` by the incremented `x`.
```
+`
```
Repeat the above until `x+1` does not divide `n` (hopefully because `n=1` at this point).
```
\G1
```
Convert `x` to decimal.
[Answer]
# [R](https://www.r-project.org/), ~~29~~ 28 bytes (input ≤170!)
```
match(scan(),cumprod(1:170))
```
[Try it online!](https://tio.run/##dYs5DsJAEARzXmJLBDM9Z/MbywQkBsTx/mU/QGWt6nqNcWyf/ba89@2@rOf9ezxfj@uiFy1Z10EzJDTcje4ayNYkYd2RyCwRp5QGs5Fu00I9OwimNQNawYkBpEZK0@fBWDlXaKMTYckipFGAVTRCtWcr1Ox0@cNp/AA "R – Try It Online")
Input is limited to 170!, which is the largest factorial that can be handled as a floating-point number by R; in any case, at larger values, there is a risk that truncated digits in the internal floating-point encoding will affect the output. Obviously the second issue will be fixed when run on an imaginary 'unlimited-precision' R implementation, but the input limitation will always be there (or, with slight modification, a limitation to ≤999!). So...
# [R](https://www.r-project.org/), ~~38~~ 34 bytes
```
n=scan();while(n>(T=T*(F=F+1)))n;F
```
[Try it online!](https://tio.run/##TcExCoAwDAXQ67S6JE38iUgdewIvICIoSAcdPH5dfe9ureZnW2uI03uc1x7qHJa8dKHk0nOMsU6lCSkrjZKIjUXMSQWcQM4AQQ3uqmIG5QE@ggZO9NM@ "R – Try It Online")
*Edit: -4 bytes thanks to tip from Giuseppe*
This version is still subject to the precision limitations of the R implementation, but could (in principle) be run with unlimited input.
Edit: Obviously the ~~large~~ increase in program length to achieve the unimplemented ability to run on unlimited input is rather unsatisfying, so...
# [R](https://www.r-project.org/), ~~30~~ 29 bytes
```
match(n<-scan(),cumprod(1:n))
```
[Try it online!](https://tio.run/##K/r/PzexJDlDI89Gtzg5MU9DUye5NLegKD9Fw9AqT1Pzv7mRwX8A "R – Try It Online")
Only one-byte longer than the input-limited attempt. Unfortunately, on all current R implementations, it is rather slow and is likely to crash with anything but small input values, but - in the words of Osgood Fielding III - 'well, nobody's perfect'
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 22 bytes
```
0?[r1+d_3R/d1<F]dsFx/p
```
[Try it online!](https://tio.run/##lY5LTkNRDEMXxKCJncSJhMSsC2CKEIO@BVQwYfePtDsg0v1Iduxz3M7T3j6@/eX44vvl8Nfr5/Fz/b3cz1PdleoSKzSWxkywCOfs1WkFTDpzpGq5iFUnFEgSEatEzBTDyMDAaIEOc5@OAsfCJfhG9vgau2lIVWAbEZsn3@byQRViEo0Zujt3v1OQqUgXKE5N9wQHW54Fj/TarNjMBwLGu8LpwDJuUnQSUm7Tw6XcDFvyPb4YYZmarK4yoIz@BH46lj73a52tKVdv6c6@q6ylR1QI9t/5Aw "dc – Try It Online")
Input on stdin, and output on stdout.
Works for arbitrarily large inputs (up to the available memory). The TIO sample run is for `200!`.
**How it works**
The description below presumes that the input is a factorial (so all the divisions have no remainder).
```
0
? # Stack is now (top of stack on right):
# x n
# where x = 0 and n is the input number.
[ # Define a macro (to be used as a loop).
# If we write the stack as
# x n
# then we assert the following loop invariant at this point in the cycle:
# n = input / x!
r # Swap. Stack: n x
1+ # Increment. n x+1
d # Duplicate. n x+1 x+1
_3R # Rotate 3 steps clockwise.
# x+1 n x+1
/ # Divide. x+1 n/(x+1)
d1<F # If n/(x+1) > 1, go back to the beginning of the loop.
# Note that the loop invariant is once again true,
# as it should be at the beginning of a new loop iteration.
]dsFx # End macro, call it F, and execute it.
# When we leave the loop, we know the following, where 'x n' is the current stack:
# (1) the loop termination condition was false, so n <= 1,
# and we must actually have
# n = 1
# because the input was a factorial;
# and
# (2) the loop invariant is true, so n = input / x!
#
# It follows that x! = the input, and the stack is now:
# x 1
/ # Divide (to pop the 1). x
p # Print top of stack.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 4 bytes
```
.I*F
```
[Try it online!](https://tio.run/##K6gsyfj/X89Ty@3/f3MjAwA "Pyth – Try It Online")
### Explanation
```
.I*F
.I : Inverse function of
*F : factorial
```
---
# [Pyth](https://github.com/isaacg1/pyth), ~~6~~ 5 bytes
```
fqQ*F
```
[Try it online!](https://tio.run/##K6gsyfj/P60wUMvt/39zIwMA "Pyth – Try It Online")
-1 byte thanks to [@FryAmTheEggman](https://codegolf.stackexchange.com/users/31625/fryamtheeggman)
### Explanation
```
fqQ*F
f : First positive integer value where
Q : input
q : is equal to
*F : factorial of value
```
[Answer]
# Clojure, 73 bytes
```
(defn f[n](loop[x 1](if(= n(reduce *'(range 2(inc x))))x(recur(+ x 1)))))
```
Ungolfed:
```
(defn find-fact [n] ; n = x!. Find x
(loop [x 1]
(if (= n (reduce *' (range 2 (inc x))))
x
(recur (+ x 1)))))
```
Tested out to 1234!, which is the 3281 digit number `51084981466469576881306176261004598750272741624636207875758364885679783886389114119904367398214909451616865959797190085595957216060201081790863562740711392408402606162284424347926444168293770306459877429620549980121621880068812119922825565603750036793657428476498577316887890689284884464423522469162924654419945496940052746066950867784084753581540148194316888303839694860870357008235525028115281402379270279446743097868896180567901452872031734195056432576568754346528258569883526859826727735838654082246721751819658052692396270611348013013786739320229706009940781025586038809493013992111030432473321532228589636150722621360366978607484692870955691740723349227220367512994355146567475980006373400215826077949494335370591623671142026957923937669224771617167959359650439966392673073180139376563073706562200771241291710828132078928672693377605280698340976512622686207175259108984253979970269330591951400265868944014001740606398220709859461709972092316953639707607509036387468655214963966625322700932867195641466506305265122238332824677892386098873045477946570475614470735681011537762930068333229753461311175690053190276217215938122229254011663319535668562288276814566536254139944327446923749675156838399258655227114181067181300031191298489076680172983118121156086627360397334232174932132686080901569496392129263706595509472541921027039947595787992209537069031379517112985804276412719491334730247762876260753560199012424360211862466047511184797159731714330368251192307852167757615200611669009575630075581632200897019110165738489288234845801413542090086926381756642228872729319587724120647133695447658709466047131787467521648967375146176025775545958018149895570817463048968329692812003996105944812538484291689075721849889797647554854834050132592317503861422078077932841396250772305892378304960421024845815047928229669342818218960243579473180986996883486164613586224677782405363675732940386436560159992961462550218529921214223556288943276860000631422449845365510986932611414112386178573447134236164502410346254516421812825350152383907925299199371093902393126317590337340371199288380603694517035662665827287352023563128756402516081749705325705196477769315311164029733067419282135214232605607889159739038923579732630816548135472123812968829466513428484683760888731900685205308016495533252055718190142644320009683032677163609744614629730631454898167462966265387871725580083514565623719270635683662268663333999029883429331462872848995229714115709023973771126468913873648061531223428749576267079084534656923514931496743842559669386638509884709307166187205161445819828263679270112614012378542273837296427044021252077863706963514486218183806491868791174785424506337810550453063897866281127060200866754011181906809870372032953354528699094096145120997842075109057859226120844176454175393781254004382091350994101959406590175402086698874583611581937347003423449521223245166665792257252160462357733000925232292157683100179557359793926298007588370474068230320921987459976042606283566005158202572800000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000`
[Answer]
# [MATLAB/Octave], ~~35 34~~ 26 bytes
```
f=@(n)nnz(cumprod(1:n)<=n)
```
Thanks @David for the feedback! I added the f= to have way to call the function for 2 bytes.
[Answer]
**SWI-Prolog, 50 bytes**
```
:-[library(clpfd)].
c(F,N):-F#=1,N#=1;c(F//N,N-1).
```
[Try it online!](https://tio.run/##fVBNSwNRDDzrr3hFhC68bfOdvIrXHvfsBx50RSkstKwH8devWbw7kDlMMmGSy3yezp/91/dpWQ7983R6m1/nn@04XT7eu5fd9bg91qE79Mebe6xD0l0q@/1Qhx673bKMW5JaHrparlbcllJkky4yRoZga7yWMqA5YQASGvyhlsdut1qYVguHGoEEsZEGCKGzmjuYNmIxNgFDl8YITRsQ8coeQSHA5MbOAqSuaKqSZrAwtNAIBWdDzT4DKAYzaDQ0Fs/t6NSYyEhajrqbIUpTJVHgTJ8KQEYQcWjkjcQtKSdCKeB/1PKUZ66/QYrNLw "Prolog (SWI) – Try It Online")
`c(F,N)` recursively defines factorials, either F = N = 1, or F/N is (N-1)!. To save bytes we used integer division, so the answer is only valid if F is actually a factorial. Prolog infers the correct value for N if not specified.
Algorithm should work for all inputs, although it isn't particularly fast. Tested up to 128!.
[Answer]
# [Rust](https://www.rust-lang.org/), ~~41~~ 32 bytes
```
|mut y|(1..).find(|x|{y/=x;y<2})
```
[Try it online!](https://tio.run/##LY3BDsIgGIPve4q6E5gFMz1OHoaof0Ky/S4IGQvw7LjpemvTr3Xh4ysxJmNZSKQGGF8egck8PHTNU/BYs@iVkoosP0WOOa0XHYf1fi2yAsPB7E2CRr8H9HaIsIwN7G@/3U2Es0Yc/mZ2lv3IJ9GmAq2RStshdse3IKkCL87MQsqdKE2pXw "Rust – Try It Online")
The `.unwrap()` was unnecessary ([Meta post](https://codegolf.meta.stackexchange.com/a/14275/97519)), saving 9 bytes
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
€mΠN
```
[Try it online!](https://tio.run/##yygtzv7//1HTmtxzC/z@//9vZAIA "Husk – Try It Online")
```
€ the index of implicit input in ...
mΠ ... map factorial over ...
N ... the natural numbers
```
[Answer]
# [Erlang (escript)](http://erlang.org/doc/man/escript.html), 45 bytes
Quite similar with ovs's Python answer.
```
f(1.0,Y)->Y;f(X,Y)->f(X/Y,Y+1).
f(X)->f(X,2).
```
[Try it online!](https://tio.run/##Sy3KScxL100tTi7KLCj5z/U/TcNQz0AnUlPXLtI6TSMCzALS@pE6kdqGmnpcQDZERMdIU@9/bmJmnkZ0rKaCrh2XAhBk5luVF2WWpGqkaRiZaAIVAAA "Erlang (escript) – Try It Online")
[Answer]
# [COW](https://bigzaphod.github.io/COW/), 108 bytes
```
oomMOoMOOMoOMMMOOOmoOMMMmoOMoOmOoMOOmoOMMMmoOMMMMOOMOomOomOoMOomoOmoOmoomOomOomOoMoOmoOmoomOoMOomoomoOmoOOOM
```
[Try it online!](https://tio.run/##TYvBCcAwDANXKimULCE0RN5Gz4zv2iLQgrDF@by0M6UABRIiUJvh0lMMnz5io/xwuojOIQ1/xMJx6i/zfsac1ws "COW – Try It Online")
## Explanation
```
moo ] mOo < MOo - OOO * OOM o
MOO [ moO > MoO + MMM = oom ^
[0]: n/(i!) [1]: n/((i-1)!) [2]: i [3]: i_temp
^- ; Read i in [0] and decrement it
[ ; Loop while [0] is non zero ( n/(i!)-1 is checked )
+=*>= ; [0] is incremented and cut/copied in [1]
>+< ; [2] is incremented
[ ; Loop while [1] is non zero ( repeated subtraction begins )
>=>= ; Copy [2] in [3]
[ ; Loop while [3] is non zero
-<<->> ; [3] and [1] are decremented ( [1] is guaranteed to be divisible by [3] )
] ;
<<<+> ; [0] is incremented
] ; [0] is now the product of the biggest x-i factor of n
<- ; [0] is decremented so iff [0] = 1 the loop ends
] ;
>>o ; Print [2] x
```
[Answer]
# Excel, 29 bytes
```
=MATCH(A1,FACT(ROW(1:170)),0)
```
[Answer]
# [Factor](https://factorcode.org/) + `math.factorials`, ~~41~~ 32 bytes
Saved 9 bytes thanks to @Bubbler!
```
[ dup [1,b] [ n! = ] with find ]
```
[Try it online!](https://tio.run/##HY49D4IwGIR3fsUxawgQ4@DHbFxcjFPDUMuLNpRSS4ka8bfja5cb7nlyuUaq0Pv5cj6eDhu05C0ZdDLcY2Re2hsNML2SZoDzFMLbeW0DBnqMZBXDKDZxR/@tbfJBgRJrlCsUZQ58kxRiwgsTcgiGC9Sjg0252qHi@d6hmkVsRbG8Vmwx3TN7av7SaFuz0EmHDMqQ9PMP)
# [Factor](https://factorcode.org/), ~~50~~ 34 bytes
Saved 16 bytes thanks to @Bubbler!
```
[ 1 over [1,b] [ * 2dup = ] find ]
```
[Try it online!](https://tio.run/##Tc0/D4IwEAXwnU/xXNUQIMbBP7NxcTFOhKFCUWJp67UoRvzsWJoYWV4uud@9K1luFfWn4/6wW@HGSXKBmtmrj5CYvHADoXImDDRxa1@aKmlh@L3hMndLD0vfUw1qHbwRI8ESyQJxEgGfYIK0Q4sOkVulME@m3TBD0WiQspj6qcUGmXumNEJk/6PYZRrPz5k7/cmtk2UlC2R96oB6cBqZZEAjUrOhMhecUf8F "Factor – Try It Online")
There's probably a better idiom for this, but I can't find it right now.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 bytes
I was just copying [Bubbler's solution](https://chat.stackexchange.com/transcript/message/54040431#54040431). I didn't write it, so it's community wiki.
```
!⍣¯1
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X/FR7@JD6w3/pz1qm/Cot@9RV/Oh9caP2iY@6psaHOQMJEM8PIP/pykYmXClKRgaGQAA "APL (Dyalog Unicode) – Try It Online")
## Explanation
```
⍣¯1 The inverse of this function:
! Factorial function
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 17 bytes
```
Nθ⊞υ¹W‹Πυθ⊞υLυI⌈υ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroLQ4Q6NUR8EQyC7PyMxJVdDwSS0u1ggoyk8pTS7RKNXUUSjU1FSAqfNJzUsvAbI0QXqLMvNKNJwTi0s0fBMrMnNLc0Himtb//xubGVlYGBj81y3LAQA "Charcoal – Try It Online") Link is to verbose version of code. Actually calculates the lowest factorial not less than `n`. Explanation:
```
Nθ
```
Input `n`.
```
⊞υ¹
```
Push `1` to the predefined empty list.
```
W‹Πυθ
```
Repeat while the product of the list is less than `n`.
```
⊞υLυ
```
Push the length of the list to the list. (This means that the list has an extra `1` in it, but conveniently that doesn't affect the product.)
```
I⌈υ
```
Output the largest element of the list (which is also the last element; either operation works.)
[Answer]
# SimpleTemplate, 72 bytes
Not exactly the smallest, but works.
Uses a naive approach to calculate the factorial up to the chosen number, returning the value if found.
```
{@setf 1}{@forfrom 1toargv.0}{@set*f f,_}{@iff is equalargv.0}{@return_}
```
Notice that this is a *REAL* `{@return}`! The compiler method will give you this value.
To be used as a function, simply wrap it in `{@fn invert_factorial} [...] {@/}`.
---
**Ungolfed version**
This should be easy to understand
```
{@set factorial 1}
{@for i from 1 to argv.0}
{@set* factorial factorial, i}
{@if factorial is equal to argv.0}
{@return i}
{@/}
{@/}
```
The line `{@set* factorial factorial, i}` simply stores ,in `factorial`, the result of multiplying the value `factorial` to `i`.
---
You can test this on:
<http://sandbox.onlinephpfunctions.com/code/61cc7101a868a71d0a7a85cdde57f946bcb2586e>
[Answer]
# [Rust](https://www.rust-lang.org/), 57 bytes
```
fn f(mut y:i32)->i32{let mut x=1; while y>1{x+=1;y/=x;}x}
```
[Try it online!](https://tio.run/##zY9NboQwDIX3nMJlUSVqS4HpKojZ9Ag9QIWKp40UTJQ4IghxdupB6h268e97n@yQIh/HjeCmpsSwGntp9ctV4uaQ4T7LfdPB8mMdwnpttvwk/fra527P@5EiQuTRGDsbI4WlrigENw2WlIatAPjjROjhg4Olb2MIF6U7WZ4WpauAw/jpLKF6PLW6wuzxi1X5Pic3As0Mdw1Y8onL0@uFxY4eVLnt5bN8ECvBT0LzQ4goOdESBq@0Fv3/uWQ/mrYu3upLW/8C "Rust – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 17 bytes
```
b01{+.}{?!.>}w!it
```
[Try it online!](https://tio.run/##SyotykktLixN/f8/ycCwWluvttpeUc@utlwxs@T/fyMTAA "Burlesque – Try It Online")
Explanation:
```
b0 # Parse input as base 10 integer
1 # Push counter to the stack
{+.} w! # Increment counter while
{?!.>} # The input is greater than the factorial of the counter
it # Return just the counter
```
[Answer]
# [R](https://www.r-project.org/), ~~56~~ 52 bytes
```
function(n){while(n>(T=T*(F=F+gmp::as.bigz(1))))1;F}
```
[Try it online!](https://tio.run/##lY5ZSgNhEITfPUaeJgrSXb1H4mNOkAuoOHEgjuKCoHj2sZMb2PAvUNVf1dsybpfxc374mF7mYV7/fD1Nx8dhvh322/3lsNvurg7Pr5vN3fv1/XT4Hnjdwze732UcVpHpFukhrlFkJGYQF7BUX2nkQBmLVYRncAhaLQ2FiUC1FdUqFyURRYGEFKnEXKkOKVKOADcyi9uYKQQLV3QitHnBnexccIeWIVElzCy9nxYIChfhgISUV2apFDrcHKzG3ixt5qkCitOVhYHu2CRNE0RYJ51cYc2gbt6Hu4aSWZR5uhPgJHwufHZ0e@svpWWUc2SH9vTbSluyQkID9N9ZrS@WPw "R – Try It Online")
Thanks to [Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) for the golfs and bug catch!
Takes input as a string.
[Answer]
# [Julia](https://julialang.org), 36 bytes
# [Try it!](https://tio.run/##DcdRCoAgDADQ62xQsJmFBHYXKQYLWWEG3t56f@98syZuXWK3cRO1Q7Q8FdqftNeraMrQMEYbeDXsd1GrIMCOFz8zkacQJkdEiP0D)
```
julia> f=n->findfirst(x->factorial(x)==n,1:n)
julia> @benchmark f(121645100408832000)
BenchmarkTools.Trial:
memory estimate: 0 bytes
allocs estimate: 0
--------------
minimum time: 32.801 ns (0.00% GC)
median time: 33.246 ns (0.00% GC)
mean time: 33.661 ns (0.00% GC)
maximum time: 56.452 ns (0.00% GC)
--------------
samples: 10000
evals/sample: 993
```
] |
[Question]
[
You will receive an array and must return the number of integers that occur more than once.
```
[234, 2, 12, 234, 5, 10, 1000, 2, 99, 234]
```
This will return 2, since each of `234` and `2` appear more than once.
```
[234, 2, 12, 234]
[2, 12, 234, 5, 10, 1000, 2]
```
The list will never be more than 100k integers long, and the integers inside the list will always be in between -100k and 100k.
Integers should be counted if they occur more than once, so if an integer occurs 3 times then it will still only count as one repeated integer.
**Test cases**
```
[1, 10, 16, 4, 8, 10, 9, 19, 2, 15, 18, 19, 10, 9, 17, 15, 19, 5, 13, 20] = 4
[11, 8, 6, 15, 9, 19, 2, 2, 4, 19, 14, 19, 13, 12, 16, 13, 0, 5, 0, 8] = 5
[9, 7, 8, 16, 3, 9, 20, 19, 15, 6, 8, 4, 18, 14, 19, 12, 12, 16, 11, 19] = 5
[10, 17, 17, 7, 2, 18, 7, 13, 3, 10, 1, 5, 15, 4, 6, 0, 19, 4, 17, 0] = 5
[12, 7, 17, 13, 5, 3, 4, 15, 20, 15, 5, 18, 18, 18, 4, 8, 15, 13, 11, 13] = 5
[0, 3, 6, 1, 5, 2, 16, 1, 6, 3, 12, 1, 16, 5, 4, 5, 6, 17, 4, 8] = 6
[11, 19, 2, 3, 11, 15, 19, 8, 2, 12, 12, 20, 13, 18, 1, 11, 19, 7, 11, 2] = 4
[6, 4, 11, 14, 17, 3, 17, 11, 2, 16, 14, 1, 2, 1, 15, 15, 12, 10, 11, 13] = 6
[0, 19, 2, 0, 10, 10, 16, 9, 19, 9, 15, 0, 10, 18, 0, 17, 18, 18, 0, 9] = 5
[1, 19, 17, 17, 0, 2, 14, 10, 10, 12, 5, 14, 16, 7, 15, 15, 18, 11, 17, 7] = 5
```
[Answer]
# [R](https://www.r-project.org/), 20 bytes
Is this what you are after? Uses `table` to count the occurrences of each of the `scan` input values. Tests if count is > 1 and sums the trues.
```
sum(table(scan())>1)
```
[Try it online!](https://tio.run/##K/r/v7g0V6MkMSknVaM4OTFPQ1PTzlDzv6GCoYGCoZmCiYIFiGWpYGipYKRgaKpgaAFiQoTMwQKWCkDCWMHI4D8A "R – Try It Online")
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, 18
```
sort|uniq -d|wc -l
```
[Try it online!](https://tio.run/##S0oszvj/vzi/qKSmNC@zUEE3paY8WUE35/9/I2MTLiMuQyMuEMOUy9AAiAwMgEKWliAhAA "Bash – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
f s=sum[1|x<-[-9^6..9^6],filter(==x)s>[x]]
```
[Try it online!](https://tio.run/##rZLBboMwDIbvPEUOO2wSVCGEEKSxF0GZ1EPR0GhVlU5C2vbszPHvDHbfwcQk8effdt6O8/tpmtZ1UHM3f5z78mt5LvqifXWHA31CPozT/XR77LrlaX7plxDW83G8qE5db@Plrh7UoPoyV6Umc7myufL4a2khM7TUZB6/6aSRbfLjUtFFHbLss8j@jaZIpCVcyRCHKxvHMJ4paaW40iBz9DXT6OuJpSKuznq610AV3aoYaLTE15zGA@x3YLMDx/LakHBcaQNrUJ9nLwqopBOoqmauY0WRahGlIU5wBsECqJlhEcwya7D8ZtJj6RvLq4LgNMe7JCGVwFupWdiDODQgZre/XUvqHEYh3U@pZGoecDFWWonE1DIURq5Jk8UD4VPpRSWll5tWywgRKm3kPPpPsY6LFXFajuUVypuRCacDD7fZOhkfY9hGIbOXcWiIsDu0wSwssjQ7fV60xUcRGFd8rz8 "Haskell – Try It Online") Abuses the fact the the integers in the list are guaranteed to be within -100k and 100k.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~9~~ 8 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
-1 thanks to ngn
Anonymous tacit prefix function.
```
+/1<⊢∘≢⌸
```
[Try it online!](https://tio.run/##VZI9TgMxEIX7nGJ7FuG/XTsSHQ2pkAgXiIRCEwna1EgRRBBBgUSdC9BScxRfZBm/N2aXwuuf2ffNm7FXD5vT2@1qc383DCdn9jzvj/npMz8f88v3sM67t/x6yIePxVXeP/58@bx7l93y@kK@N5eL5bBubNtYI6Nvm9A2ibu5TDKcTJ2MxG2NRD2WdZm8/GhmQrLQ94yOCAcyAHUWiXVMWtYGIPkmwUg80ohEPUDOqK4DPhGYJkA3AZaK5sWPUa8RREdJZEqvZbOEDsQeHgovUIWqHDWq6yAN1MBXR0Qah/ZRewM/XkgG0r4mrXZxVBvCM9phsSVxYGdYGZSVq9eQiNMBW179tH@yyKUTEi8bAS3Va4l2NBagVlfaJaQw/4tSS0Yj@pj0/vXWaiBxGcdmlTc14zOcj/dlmDhMmI59DsTHiaekfso9/wI "APL (Dyalog Unicode) – Try It Online")
`+/` sum of
`1<` whether 1 is less than
…`⌸` for each unique element:
`⊢∘` ignoring the actual unique element,
`≢` the count of its occurrences
[Answer]
# [C (clang)](https://en.cppreference.com/w/c) ~~175~~ ~~117~~ 95 bytes
```
c(*a,*b){return*a-*b;}r(*l,m){qsort(l,m,4,c);return((!m||l[1]-*l)&l[-1]==*l)+(m?r(l+1,m-1):0);}
```
[Try it online!](https://tio.run/##hZRhb5swEIa/51d4rTbZFBTbGDBD0X5Ilg80IRMSkJWm07Q0vz0zd2egaiQiOT7My3Ov7wz7aN@U3a/bbc@DMgyexaWvzm99F5RR8Fxcex40YSsuL6@n/sxdGJpwLwrUcP6lfX9vtmoXBY341mwjtdtsXPjE2x89b55U2EZKfJeiuN4eD9Wx7irWvbVVw/8Kxl/rf9Xp6MK1j7ZyJ8Sq7s6sVNsd27CLCpmSbqQhMyGzeJW7yQ3tpsQNi5f@TkbLLh6m2AnltWCI1YRVAEtROvE0pAGan93zSqODIZZAdf/WMd0PsTFinT5Dl04dA1hL4iSQzmICO0ugZwmG7eYDGLGG3EraVgZ8jYAMDcVUIdxtAvwUHA50g09JNEvYhLAaIQRKgGUQArYTZNppUA@ormA3HmubIlYCJ/WW/NZgyRcT19AsFmZwYcaqspnbbGoZdcmnpi5bTEIDnMdk2ZcUN@pCPbq1iMWDBSqqVUwlUZN3AygyTmWGfPJTEfKxCGRWkoxOMZ01OhH@hsUwmyo9HGaoBb0Ocnof8uk0SHRlZjk0Ns1gumxm2JLZ4RRdixWA27Lu@J9TfRDssmLsd@8Wj/zh6@Fn9xD2vFQhvq@lEkJAa9Zr58Pc02qv1R@0yT1t7LXxstZ4rVnWJl6bLGtTr00/aNN72sxrs@U6WK@1y9zca/Nlv669vhkS1aMWv8dMFqvr7T8)
This is the first time I've submitted one of these, so let me know if there are any issues with formatting or anything.
Updates from the comments:
* -58 to 117 bytes from Jo King
* -80 to 95 bytes from ASCII-only
[original submission](https://tio.run/##hZTRjpswEEXf8xXuVl3hhCjGGDCifEnKAxuSCikhLZutVs3y7el4ZhxYNRKRHBv7@sz1jGG33h3r7uft1nYXsQv@nNtmKerwRV77/eWt78QygJWlrNc8eCkGJ@3dkzhuq/Akr27YlKr4/XruL8ExPIWv7d/9@RAct6qS4U4WhzNtaMuoaL@XpzV0qxXsPAQgaldR9aWEvvr4aEu3Kp@f4XEdVSVOy2uzWhXDwJ6aYrh9bfaHttuL7u20PwbvUgQc811u/MhFlwsXt462lSjFNQpFpKCloTChsPSUQwdNQ5dAs/ToVzKehrHrYhCqoRCE1YyNEJaSdORpDIM038P@SJMDN1ZIhX8LTPgRNiYs6DNyCeoYwVoxJ8FwlgLYSQA9CeCOmzswYQ27VXysDPmaABkZijlDdNoE@Sk6dHRDuxSZZWzCWE0QBiXIMgRB2wkx7di4BpxXtBvfc5sSViEn9Zb80XDKJ5PmyCwlxrkw96yKidtsLBlXyYfmKlsKwg2dx2zZp5QOCkN9d2sJSxcLVZyrmFMSjd4Notg4pxnjqf@SkN@TwGYVy/gW813jG@EXLA2zMdPuMmMu@HVQ4/uQj7dBkSsziaGpaIbCZRPDls26WzQUCwSf6rbDj4gU14UQv3qYPARP35of3VPYB3UU0vtaR1JKLM1mAz7MI632Wv1JmzzSxl4bz2uN15p5beK1ybw29dr0kzZ9pM28NpvPg/VaO8/NvTaf9wvl9cVQpL5r@TurisVw@wc)
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 40 bytes
```
n=>n.GroupBy(c=>c).Count(c=>c.Count()>1)
```
The first draft of the spec was unclear, and I thought it mean return all the elements that appear more than once. This is the updated version.
Somehow I didn't notice that my code returned the number of elements that appeared once. Thanks to Paul Karam for catching that!
[Try it online!](https://tio.run/##XY49C8IwFEV3f0XIYgIx1KqD9mNQVAqCooODOMT4CoEaS5oIIv722oYO6nAv53J48GQ1kJWqV07LOFtqdwMjLgXEStuUtZUntU5Szdfm7sr5k8gklZQv7k5bzx3SdEjrqPcQBolkD@K6URoI5XsoCyGBYIQZxl/79LfPfke9o1EW/DHOdOksmqFX8MZM/Lqts43sXE4EP5SFsqTP@pQfoABpSfM93wlTAaU0qk/haMxQyNCwiedJw0GbIPBiOvXi/AE "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
Ù¢≠O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8MxDix51LvD//z/aUEfB0ACIzXQUTHQULCA8SyAFxEZAyhSILSBcmIw5VBjIBlHGQIUGsQA "05AB1E – Try It Online")
or as a [Test Suite](https://tio.run/##VVK5ccNAEMtdBQtgcC9vlXucOnGmUSDNKHDkwFW4BGUal2J34kboPQA3pILlPUtggd37@Dxf3q/r28vz@nv7@f77ur@u83qM8xSDxzJPZZ6Mp4MvHsmX6mE8jkzTte/7kv3HcHo6xgj8wuxGkcAMgrE6JCYW7fsAIv@a03i@UYhnM4hSEK6C3khoO8K0I@yODl1PkNYGxkRIY8ks27RQwbhAQ@crRMFVIka4CmghBroqKWwL9VG9gZ7sTAHQZRQdcnE1GsI7yqHZXriwM3QG5ODVGIx0CsjK0jMaQhe@Tc7EYSMhq1kW4yasAC1V6hJKhEdTkhSU0WPS/DW1kTBu29as/qa6Nw1SrQ4sXHaciX0upG87TSY9fc6nfw)
**Explanation**
```
O # sum
≠ # the false values
¢ # in the count
Ù # of each unique digit in input
```
[Answer]
# [Python 3](https://docs.python.org/3/), 38 bytes
```
lambda a:sum(a.count(x)>1for x in{*a})
```
[Try it online!](https://tio.run/##hZNRS8MwFIXf/RUBX1opkiZpkwrzj2geqlIcbO2YG0zE316Te27aTgsOsmVJ852Tc28Pn6f3oddjt3ked@3@5a0V7cPHeZ@196/DuT9ll/yx7IajuIht/3XXfufj4bgN6132pLQphCpEGQbNqzCXcUhJG01DG17898nz241QNxO5ZFBdiIB1@BdgZQPBKOTwN@1YXm5gQ4cHpWeyWZBL4tV4ekYqUiJg@tW4WTQR55LA4dv52XM1k8MRC6/hgCa2koyqSNFBwy001EIjXrrxK2SKwmJYBOBoFm1pjgrXrkiiJp9RwOCU9GLVc9RmcGRVhDPgkPkKWDcPrgdnTKa1/0uWhKqTsXRHWkrBYg2WkVA0YqaEF57r6wpy0ZIBrrubupE6UrJFByk@ZjFVK72BbqMHOTfN2ZTzDQzR2D5HTpLydxr1VRpsWaZXBDhuQO6RtOEwtXPqscn9agW5kbiKeO/IZIIplNBA0C5cO3Yc28ozefwB "Python 3 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ĠITL
```
**[Try it online!](https://tio.run/##y0rNyan8///IAs8Qn////0cbGZvoKBjpKBgCMZhtCmQbgLCBAVjC0hIsEQsA "Jelly – Try It Online")**
...Or `ĠIƇL`
### How?
```
ĠITL - Link: list of integers e.g. [234, 2, 12, 234, 5, 10, 1000, 2, 99, 234]
Ġ - group indices by value [[2,8],5,6,3,9,[1,4,10],7]
I - incremental differences [[6],[],[],[],[],[3,6],[]]
T - truthy indices [1,6]
L - length 2
```
`IƇ` would filter to keep only truthy results of `I` (`[[6],[3,6]]`) which also has the desired length.
[Answer]
# [J](http://jsoftware.com/), ~~11~~ 9 bytes
-2 bytes thanks to Jonah!
```
1#.1<1#.=
```
[Try it online!](https://tio.run/##ZVHLToVADF3LV5zo4sbEkOkMMMONfI2RGDcu7tpvx55TwGskZCidnkfbz229LT0SrkibPfX26seyPXePPS7r0l/wgu8r1lvXvb99fOEhPisMlmATBjRGM2xGho2wxjBSVYkZfhTkhBNsjpp4ueOy8xAVZ4FlcnuQHJu82J8DPKNSc0Lx0EmJGJ2tkaMdHPngMP7@Kie5qs6RWV0pUpSmy9E5JohzYFXCvbIzCuuQ0UED62lgRLStVwNRw5QuJzg5YpJK@AIboEf@UZc9OPkQ3eKvssWcglQzbch7l7RQpL7XVX7zCeaSeKGOihqw3YSnIAvqnXTpn20JJ91o41qZZh6Zhphpi3C@t61V1JhkllxgMic2kK0e2k3CvpjtBw "J – Try It Online")
## Original solution:
```
1#.(1<#)/.~
```
[Try it online!](https://tio.run/##ZVLLTsNADLz3K0b0UCqh4N1NsrsV/RpEhLhw6Bl@PXjGTSkiihLH63nYzse6XM4DDCfYmvbDY3rZH5@H7/W4exhwWM7DAU/4OmG57HZvr@@fWJDLiIyUFUxI5reZp3pnaitLOpkxojHqSJ0wBzSGkapKdNIUZMMNnBw18/CKy85DVDwL5Z3bA3OsebFfG7ijUnNG8dBJiZicrZGjbRx540j8/FU2uarOkVldKVKUpsvJOWaIc2SV4V7ZGYV1yOSgkfU0MCHa1q2BqGFKlxvYHDFLJXyBDdAjv6jLHpx8jG7xVznFnIJUM22xJS7KpNZIpbrKd76BuSQeqKOiBtLVhKcgC@qddPbPtoQtfgSCtDLNPDINMdMWYb@3rVXUmGSWXGAyJzaSrW7aTcK@mPUH "J – Try It Online")
Explanation:
```
/.~ group the list by itself
( ) for each group
1<# is the length greater than 1
1#. sum by base-1 conversion
```
[Answer]
# Java 8, ~~74~~ 73 bytes
```
L->L.stream().filter(i->L.indexOf(i)<L.lastIndexOf(i)).distinct().count()
```
[Try it online.](https://tio.run/##dZRNT@MwEIbv/AofE6lYzlfjCHalPSJl4cBxtQeTpsgldVHisosQv72MZyZNWiBSEseeeead8Tgb82IuN6unQ9OZYRC/jXVvF0JY59t@bZpW3IZPIe4eNm3jRRNtwEHuve3kr743r7UdvKjjKzB6v4DH4I23jbgVTvwQh/ryZy0H37dmG8VybTugRjZMWrdq/9@tIxtf1xJC@5vjRCxXALWu8eDT7PYO3oerAH/eP3QA5xgvO7sSWxAc3fveusc/f4WJSa1vBx@lWb4Q6UIkcOO4gLEKt1K4UFW4gOLZJ2GT5UKAg6YvMEsqQgWEps9xpeTpigJkYKhOkAmClmQ2sVIMgaTxnZHYED2MFRLhqec8MCxJGphlSEwVAwqMo4msZ@R0Rg45VicKFadRIjol35JEZFwRyq5A9BJVBXBOXqcJp@TMgAIZOTmj0oJYerq51lw/VJjNkQoZy1HGmAlOjUWjORJIdQgK8rPqUfaIGCPx5uljs2DDKNaiCc1uJQ3TOZJ6BS24HBlnn0xSc8SwTq4kxlLf5Msi1dizxOH24b0eFzQNy6mgoTfP@7qadpn6H0WNjJQ2Jac45UylZoWhOz4ddDyEGOIGfhmPbS@lPB7D@9fBt1u523v5DCfUdy5ysolc@0988Rs5/7UM0gw4b2K4KPD74QM)
**Explanation:**
```
L-> // Method with ArrayList parameter and integer return-type
L.stream() // Create a stream of the input-list
.filter(i-> // Filter it by:
L.indexOf(i) // Where the first index of a value
<L.lastIndexOf(i)) // is smaller than the last index of a value
.distinct() // Deduplicate this filtered list
.count() // And return the count of the remaining values
```
[Answer]
# [Uiua](https://uiua.org), 7 [bytes](https://www.uiua.org/pad?src=U0JDUyDihpAgK0BcMOKKlwpEZWNvZGUg4oaQIOKHjOKKjy0x4pa9wrEu4o2Y4ouv4oav4oqCwq8x4qe74ouv4qe7LOKHjOKItSjihpjCrzHii68rMjU2KSAtQFwwKzEKJnAg4oqCIjggYml0IGVuY29kaW5nOlx0IiBTQkNTICLih4ziio8tMeKWvcKxLuKNmOKLr-KGr-KKgsKvMeKnu-KLr-Knuyzih4ziiLUo4oaYwq8x4ouvKzI1NikiIOKKgitAXDDih6ExMjkiLiziiLY74oiYwqzCscKv4oy14oia4peL4oyK4oyI4oGFPeKJoDziiaQ-4omlKy3Dl8O34pe_4oG_4oKZ4oan4oal4oig4qe74paz4oeh4oqi4oeM4pmt4ouv4o2J4o2P4o2W4oqa4oqb4oqd4pah4oqU4omF4oqf4oqC4oqP4oqh4oav4oaZ4oaY4oa74per4pa94oyV4oiK4oqXL-KIp1xc4oi14omh4oi64oqe4oqg4o2l4oqV4oqc4oip4oqT4oqD4oqZ4ouF4o2Y4o2c4o2a4qyaJz_ijaPijaQh4o6L4oas4pqCzrfPgM-E4oiefl9bXXt9KCnCr0AkXCLihpB8IyIKJnAg4oqCImRlY29kZWQ6XHQiIERlY29kZSAiwqPCsS0xwrjChy7DjMKlwrPCsMKIMcKfwqXCnyzCo8K_KMK1wogxwqUrMjU2KSIg4oqCK0BcMOKHoTEyOSIuLOKItjviiJjCrMKxwq_ijLXiiJril4vijIrijIjigYU94omgPOKJpD7iiaUrLcOXw7fil7_igb_igpnihqfihqXiiKDip7vilrPih6HiiqLih4zima3ii6_ijYnijY_ijZbiipriipviip3ilqHiipTiiYXiip_iioLiio_iiqHihq_ihpnihpjihrvil6vilr3ijJXiiIriipcv4oinXFziiLXiiaHiiLriip7iiqDijaXiipXiipziiKniipPiioPiipnii4XijZjijZzijZrirJonP-KNo-KNpCHijovihqzimoLOt8-Az4TiiJ5-X1tde30oKcKvQCRcIuKGkHwjIg==)
```
/+>1⍘⊚⊛
```
[Try it!](https://uiua.org/pad?src=ZiDihpAgLys-MeKNmOKKmuKKmwoKZiBbwq8xIMKvMSDCrzIgwq8yIDAgMCAxIDEgMiAyIDMgNCA1IDYgN10KZiBbMSAyIDMgOTkgNCA1IDk5IDZdCmYgWzEgMiAzXQpmIFtd)
```
/+>1⍘⊚⊛
⊛ # classify (i.e. map integers -> naturals)
⍘⊚ # inverse where (occurrences)
>1 # where are they greater than one?
/+ # sum
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 34 bytes
```
->a{a.uniq.count{|x|a.count(x)>1}}
```
[Try it online!](https://tio.run/##hZPLboMwEEX3fIWlblqJImMbbBbJjyAvaNSo3aQPgZQK@HZqzx1j1E0jORmwfe6dR76nl5/tetqez8M8VNPt/au6fEy3cV7uy4Dw8f50rtd164teaVMKVYo6LIqbEMu4pKSNrqMNL/77lA8noYq@5vttKQLN4Skw6g46ke/wmHYsv@6grsNB6QE0AVgTpsWhTFIkQJz0q5FH1I6xJF74dn532BR9OGnhLJzThFSSCQ0JOaDdAa0O6Jhi5zOQ8rVYFlk6iqIJzfVAbg2RW3IVuQa3pBdHh1GJeRHREMXgOlltQHN5ca25fmRR@x0oidAmGykRepWKhncwiDJEfbNXLzts0RTuQ5LjDrp9nGikJBtyUOBrFqHKXca40D7XRHMB6uzXEITNcjlJSf5JuaWU2aBMEw0KTxB3O204hDZXNA6nPzaFJ4Ebg38HWUoMha4Y6NiDR8f@4oB4Bvrqdbi8zcu4fIprP/p1@wU "Ruby – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 15 bytes
```
+*.repeated.Set
```
[Try it online!](https://tio.run/##VZLBTsMwDIbP5Cl8YhurqiRN00zTJnHgxg3EpcphEpk0qUC1lgNCPHtJbIeWgxs3iT//ttOHa2enty@4PcNh2t6V19CH0xhey6cwTnvxOQR4DsO4F@L8cYXu8h6G47Ec@u4yrleH1Qa@xc1lgPO6bKUvH17uHzcFbMtWefEztaoAJaPZAkwBjv52cYmm41JHc/SbTxrejn5aqnhReoADGNEqhRBLV2aORjxS8hrjlKbMyZdIi18XWZBwtWjjvYZUxVsVArXk@BrTOAK7BVgvwKm8nc84rLQha6g@h14SUHEnqKoauRYVJaqhKEniGKcpmAE1MgwFo8yaWG427jH3DeVVnnES422WkEvArdws2iNx1ICU3fx1LauzNArufk7FU3MEZ0OlFUvMLaPCoqvzZOmB4Cn3ouLS1azVIIKFchsxj/xXrMViWZzkY36F/GZ4wvnAkdvMnUyP0c@j4NnzOCSJMAu0plkYytIs9DnWlh6FT7hf "Perl 6 – Try It Online")
Pretty self explanatory. An anonymous code block that gets the count (`+`) of the `Set` of elements among the `repeated` elements of the input (`*`).
I've realised I've posted almost the [exact same solution](https://codegolf.stackexchange.com/a/174605/76162) for a related question.
[Answer]
# [Python 3](https://docs.python.org/3/), 63 bytes
```
lambda l:len(C(l)-C({*l}))
from collections import Counter as C
```
[Try it online!](https://tio.run/##TZPbboMwDIav16fwKk3ARKUQAqSVuOIxul6wDjSkFCqgk6Zpz84S2xkgmZw//7aT@/f8OfTp0pZvi6lv7x81mJNp@rAKTXSowp9X8xtFu3YcbnAdjGmuczf0E3S3@zDOUA2Pfm5GqCeolnYY4VpPTQxftXk00PVw3p3PSQyJsJbHoGLQNDraxpq0TWZN09CvFDxt@65J7UZxiQHUJXbABDE5bVpJEh0gx7f2ZCLJt@sL5Nm/djT7ZQi0OwtSZveliJSCCRk60oTWG7TcoF2IR0QSEOMtyAqKUmPPiUg5HxRbhuQcVTmuolOCBXqgpOOMyJCi6DhKzYimV@Ncc/5QYuqgBBRIyL0MHwhO@aTRHAmkNDj/as0effl/UbgO3h1XUBOeDdWmLNOnjoKzXblWma4LrnNOUk5AsupVCGGxnE70JLYh5z5kFih4A99KvkFcbb@gqVusGXWXkyLnovBN4MIIEqI2cElVUeSn2GjUrM9dEMt0wMtp93Qfu34O9234cijUFEG5hxd@U23o2igOyjKArvVjKEt@bo2ZGgiey4DfX7T8AQ "Python 3 – Try It Online")
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), ~~8~~ 7 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function using [Jonah's method](https://codegolf.stackexchange.com/questions/180302/count-repetitions-of-an-array/180303#comment434677_180309).
```
+/1<∪⍧⊢
```
[Try it online!](https://tio.run/##VZI9TgMxEIX7nGL7bBT/7dorpaMhFRLhApF2QxMBBQWpkSKElAgKbkBDxR04ii@yjOeN8VJ4/TP7vnkz9vZhv@gP2/397WJ4ehzu@qEfx/lSr@bLePqML1/jLh7f4ukczx/rq/j6/PNt4/GddpvrC/reXK43467SdaUVjbauXF0F7DqaaBiaGhoB2xzxckzrNFn6Uc2IpFnfIloQhskMyDNJtEHStFYMom8gDMU9jFDUMsgo0TWMDwCGCdBMgKmiLvlR4tUz0UDikdJK2SihYWLLHhLPQcVVGWhE17DUQcO@GiBCGdJH6Q37sURSLG1z0myXj3JDcAY7KDYldugMKmNl5so1BOBksC0rfuo/mcfSEAmXzQEp1UqJuhhzrBZX0iVOof4XJZaUROQxyf3LreVAwNKXZqU3NcMz7Mp9KSR2E6ZBnx3wfuIpiJ90z78 "APL (Dyalog Extended) – Try It Online")
`+/` the total number occurrences
literally the sum of Truths
`1<` where one is less than
`∪` the unique elements'
`⍧` count in
`⊢` the unmodified argument
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
f(h:t)=sum[1|filter(==h)t==[h]]+f t
f _=0
```
[Try it online!](https://tio.run/##rVJBboMwEDyHV/jQQ6JyMMZgU8kvQajiEAQqRFFCbv07Xe@sC@q5h2WN1zM7s/bYP7@u87xtw3n8WC/h@Vra4nuY5vX6OIcwXtYQ2rHr3ge1ZoP6DHpb@ummgro/ptuq3tTS39VAuc1Oqi1yVWiKOlc2Vx5/DSUKQ6mi8PhNFSfbtI6ppIO6y075/3IVzFCjvpMY5maKlAlUGLSNa81U9PVMRCccxFC9ZCqjBVlxAw9Kf6A0B8roqoEmLYodcxqAHNqWYh5GKuasWUdktECJNwOUICsGW6BYWwUSv4fMU2bEmkrm0gyuU@MkmrfSYLAHSbAcW9s0IThkbOKWK/EglGBppWhKg4ETWhrmwtVzSSyXYrTYxVnGizKZFjfRf62JLC01eVzyGuQGU8Fj6fahxTf2@zCb/e40mtsDq8HELRq4gy4vmuKdd932Aw "Haskell – Try It Online")
Count suffixes where the first element `h` appears exactly once in the part `t` that comes after.
---
# [Haskell](https://www.haskell.org/), 40 bytes
```
import Data.List
f l=length$nub$l\\nub l
```
[Try it online!](https://tio.run/##rVIxcoMwEKzNK1RQMhkhCSQKdynzA9sFmbFjJoIwNnk/Od2eApM6xXFCp93bPenePz@vMa7rMM5fj0W99kv/8jY8l@Km4jFep4/lXk7f72U8nympuI79MKmjmh/DtKhSjf2sbpRPxUGd6krVmqKtlKtUwF9HicJQaigCfnPFyzatU7J0UF@KQ/W/XDUztKhvJIa5mSJnAtUGbdNaMxV9AxPRCQ8xVLdMZbQgG24QQBl2lGZHmVx10KRFsWdOA5BHWyvmYaRhzpZ1JEYHlHgzQAmyYbADirU1IAlbyDxlRqzJMpdmcJsbZ9G8lQeDPUiC5dTa5QnBIWMzt1xJAKEES7OiKQ8GTmhpmAtXzyWxbMVovYlzjBdlMi1uov9aE1laavK45DXIDeZCwNJvQ0tv7PdhdtvdaTR3O1aDiTs08DtdQTSlO79c1h8 "Haskell – Try It Online")
Stealing the method from other answers.
[Answer]
# Haskell, 41 bytes
```
f[]=0
f(a:s)=sum[1|filter(==a)s==[a]]+f s
```
This solution basically counts how many elements of the list have the same element appear exactly once later in the list.
[Answer]
# PHP, 39 bytes
a nice occasion to use [variable variables](http://php.net/manual/language.variables.variable.php):
```
foreach($argv as$v)$r+=++$$v==2;echo$r;
```
takes input from command line arguments. Run with `-nr` or [try it online](http://sandbox.onlinephpfunctions.com/code/081554dada9f6dac7b07a632e62d82ad8b1e746c).
---
`$argv[0]` is `-` and that appears only once in the arguments, so it does not affect the result.
[Answer]
# [Haskell](https://www.haskell.org/), 47 bytes
```
f[]=0
f(a:b)|x<-filter(/=a)b,x/=b=1+f x|1>0=f b
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py061taAK00j0SpJs6bCRjctM6cktUhD3zZRM0mnQt82ydZQO02hosbQzsA2TSHpf25iZp5tQVFmXolKWrShDggaAaExEBvqmAChQex/AA "Haskell – Try It Online")
This is the naïve approach. There is likely something that could be done to improve this.
```
f[]=0
```
We return `0` for the empty list
```
f(a:b)
```
In the case of a non-empty list starting with `a` and then `b`.
```
|x<-filter(/=a)b,x/=b=1+f x
```
If filtering `a` out of `b` is different from `b` (that is `a` is in `b`) then we return 1 more than `f` applied to `b` with the `a`s filtered out.
```
|1>0=f b
```
If filtering `a`s doesn't change `b` then we just run `f` across the rest.
Here is another similar approach that has the same length:
```
f[]=0
f(a:b)|elem a b=1+f(filter(/=a)b)|1>0=f b
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/Py061taAK00j0SpJsyY1JzVXIVEhydZQO00jLTOnJLVIQ982URMoZWhnYJumkPQ/NzEzz7agKDOvRCUt2lAHBI2A0BiIDXVMgNAg9j8A "Haskell – Try It Online")
[Answer]
# JavaScript (ES6), 40 bytes
```
a=>a.map(o=x=>n+=(o[x]=-~o[x])==2,n=0)|n
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/R1i5RLzexQCPftsLWLk/bViM/uiLWVrcORGna2hrp5NkaaNbk/U/OzyvOz0nVy8lP10jTiDbUUTA0AGIzHQUTHQULCM8SSAGxEZAyBWILCBcmYw4VBrJBlDFQoUGspiYXmsnmQLH/AA "JavaScript (Node.js) – Try It Online")
[Answer]
# Wolfram Language 34 bytes
```
Length@DeleteCases[Gather@#,{x_}]&
```
`Gather` groups identical integers into lists.
`DeleteCases[...{x_}]` eliminates lists containing a single number.
`Length` returns the number of remaining lists (each containing two or more identical integers.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~12~~ ~~11~~ ~~9~~ ~~8~~ 6 bytes
```
ü èÈÊÉ
```
With lots of help from @ASCII-Only, and suggestions from @Shaggy and @Luis felipe De jesus Munoz.
[Try it online!](https://tio.run/##y0osKPn///AehcMrDncc7jrc@f9/tKGOgqEBEJvpKJjoKFhAeJZACoiNgJQpEFtAuDAZc6gwkA2ijIEKDWIB "Japt – Try It Online")
[Answer]
# Pyth, 6 bytes
```
l{.-Q{
```
[Try it here](http://pyth.herokuapp.com/?code=l%7B.-Q%7B&input=%5B1%2C%2010%2C%2016%2C%204%2C%208%2C%2010%2C%209%2C%2019%2C%202%2C%2015%2C%2018%2C%2019%2C%2010%2C%209%2C%2017%2C%2015%2C%2019%2C%205%2C%2013%2C%2020%5D&test_suite=1&test_suite_input=%5B1%2C%2010%2C%2016%2C%204%2C%208%2C%2010%2C%209%2C%2019%2C%202%2C%2015%2C%2018%2C%2019%2C%2010%2C%209%2C%2017%2C%2015%2C%2019%2C%205%2C%2013%2C%2020%5D%0A%5B11%2C%208%2C%206%2C%2015%2C%209%2C%2019%2C%202%2C%202%2C%204%2C%2019%2C%2014%2C%2019%2C%2013%2C%2012%2C%2016%2C%2013%2C%200%2C%205%2C%200%2C%208%5D%0A%5B9%2C%207%2C%208%2C%2016%2C%203%2C%209%2C%2020%2C%2019%2C%2015%2C%206%2C%208%2C%204%2C%2018%2C%2014%2C%2019%2C%2012%2C%2012%2C%2016%2C%2011%2C%2019%5D%0A%5B10%2C%2017%2C%2017%2C%207%2C%202%2C%2018%2C%207%2C%2013%2C%203%2C%2010%2C%201%2C%205%2C%2015%2C%204%2C%206%2C%200%2C%2019%2C%204%2C%2017%2C%200%5D%0A%5B12%2C%207%2C%2017%2C%2013%2C%205%2C%203%2C%204%2C%2015%2C%2020%2C%2015%2C%205%2C%2018%2C%2018%2C%2018%2C%204%2C%208%2C%2015%2C%2013%2C%2011%2C%2013%5D%0A%5B0%2C%203%2C%206%2C%201%2C%205%2C%202%2C%2016%2C%201%2C%206%2C%203%2C%2012%2C%201%2C%2016%2C%205%2C%204%2C%205%2C%206%2C%2017%2C%204%2C%208%5D%0A%5B11%2C%2019%2C%202%2C%203%2C%2011%2C%2015%2C%2019%2C%208%2C%202%2C%2012%2C%2012%2C%2020%2C%2013%2C%2018%2C%201%2C%2011%2C%2019%2C%207%2C%2011%2C%202%5D%0A%5B6%2C%204%2C%2011%2C%2014%2C%2017%2C%203%2C%2017%2C%2011%2C%202%2C%2016%2C%2014%2C%201%2C%202%2C%201%2C%2015%2C%2015%2C%2012%2C%2010%2C%2011%2C%2013%5D%0A%5B0%2C%2019%2C%202%2C%200%2C%2010%2C%2010%2C%2016%2C%209%2C%2019%2C%209%2C%2015%2C%200%2C%2010%2C%2018%2C%200%2C%2017%2C%2018%2C%2018%2C%200%2C%209%5D%0A%5B1%2C%2019%2C%2017%2C%2017%2C%200%2C%202%2C%2014%2C%2010%2C%2010%2C%2012%2C%205%2C%2014%2C%2016%2C%207%2C%2015%2C%2015%2C%2018%2C%2011%2C%2017%2C%207%5D&debug=0)
### Explanation
```
l{.-Q{
{Q Deduplicate the (implicit) input.
.-Q Remove the first instance of each from the input.
l{ Count unique.
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 7 bytes
```
ọzt;1xl
```
[Try it online!](https://tio.run/##VVI5TsRAEPyKH@BgTs@seIrlgCWAYCUkhMSRQUDGJ3gB@T6BV7AfMT1VNbIJ2nO0q7qqe44P1zd3L6f727BePr4v728/X0/r7/nz9fHKP5/WdZ79OHhnMY1DGofK08EWi2BLtqg89kzRte3bEu1Ht4yz98BPzG4UAcwg6KtBfGDRtncgsm81GssXCrFsBFFwwmXQVxLWHWHYETZHh6bHSWsBYyCksGSUbVrIYJygofElouAqECNcBjQRA12ZFHUL9VG9gZ5oTA7QqRftcnHVG8I7yqHZVjixM3QGZOfVGCrpFJAVpac3hC5sG4yJw0ZCVqMs@k1YAlqq1CWUcP9NSZJTRo9J89fUeqJyW7ZmtTfVvGmQarVj4bTjDOxzIn3ZaarS0@a8LH8 "Brachylog – Try It Online")
Explanation:
```
ọ For every unique element E of the input, [E, how many times E occurs]
zt The last elements of the previous value.
;1x With every 1 removed,
l how many there are.
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 6 bytes
```
e:uDul
```
[Try it online!](https://tio.run/##S0/MTPz/P9Wq1KU05///aCNjEwUjBUMjBRDDVMHQAIgMDIBClpYgoVgA "Gaia – Try It Online")
```
e | eval as a list
: | duplicate
u | uniquify
D | multiset difference; keep only repeated elements
u | uniquify
l | find length
```
[Answer]
# [Arturo](https://arturo-lang.io), ~~49~~ 31 bytes
```
$=>[tally&|enumerate[k,v]->v>1]
```
[Try it](http://arturo-lang.io/playground?IGYI8n)
-18 bytes due to Arturo 0.9.83 providing `tally` and `enumerate`.
```
$ => [ ; a function
tally & ; create a dictionary of elements and their occurrences from the input
| ; then...
enumerate[k,v]-> ; count the number of key-value pairs where...
v>1 ; the value (occurrences) is greater than one
] ; end function
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 7 bytes
```
ĐỤ⇹ɔ⁻žŁ
```
[Try it online!](https://tio.run/##K6gs@f//yISHu5c8at95csqjxt1H9x1t/P8/2kxHwURHwdAQiEG0uY6CMYQCCRkBKTOoDIQHRKZQDOIaQLUaxwIA "Pyt – Try It Online")
```
Đ implicit input; Đuplicate on the stack
Ụ get Ụnique elements
⇹ɔ ɔount occurrences of each in original list
⁻žŁ decrement; remove žeros; get Łength; implicit print
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `L`, 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Uæc1Q
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPVUlQzMlQTZjMVEmZm9vdGVyPSZpbnB1dD0lNUIxJTJDJTIwMTklMkMlMjAxNyUyQyUyMDE3JTJDJTIwMCUyQyUyMDIlMkMlMjAxNCUyQyUyMDEwJTJDJTIwMTAlMkMlMjAxMiUyQyUyMDUlMkMlMjAxNCUyQyUyMDE2JTJDJTIwNyUyQyUyMDE1JTJDJTIwMTUlMkMlMjAxOCUyQyUyMDExJTJDJTIwMTclMkMlMjA3JTVEJmZsYWdzPUw=)
#### Explanation
```
Uæc1Q # Implicit input
U # Uniquify the input
æ # Filter it by:
c # Count in the input
1Q # Is not equal to 1
# Push the length
# Implicit output
```
[Answer]
# [Element](https://github.com/PhiNotPi/Element), 40 bytes
```
_(#'{"2:0+4:'~1+";~2=[''1+""]$2+'[(#]'}`
```
[Try it online!](https://tio.run/##S81JzU3NK/n/P15DWb1aycjKQNvESr3OUFvJus7INlpdHchSilUx0laP1lCOVa9N@P8/2kBHwVhHwUxHwVBHwVRHwQjIgHDMwBKGRmAOSAwoawImQfLmYI5FLAA "Element – Try It Online")
This requires input to be in a precise format like `[234, 2, 1000, 2, 99, 234]` (enclosed with `[]` with a comma and space between integers).
**Explanation:**
```
_ input
(# delete the [ at start of input
'{" '} WHILE the string is non-empty
'{"2: '} duplicate it
'{" 0+ '} add 0 to coerce to integer (gets next number in array)
'{" 4: '} make 3 additional copies
'{" ' '} temporarily move 1 copy to control stack
'{" ~ '} fetch the current map value for given integer
'{" 1+ '} increment map value
'{" " '} retrieve temporary copy of integer (the key for the map)
'{" ; '} store updated map value
'{" ~ '} fetch map value again (1 if 1st instance, 2 if 2nd, etc.)
'{" 2= '} test for map value = 2, this is the first duplication
'{" [ ] '} IF
'{" ['' ] '} move stuff from main stack to control stack
'{" [ 1+ ] '} increment the counter of duplicate (bottom of stack)
'{" [ ""] '} move stuff back to main stack
'{" $ '} take length of current integer
'{" 2+ '} add 2 (for the comma and space)
'{" '[ ]'} FOR loop with that number
'{" '[(#]'} trim those many characters from front of input string
` output result
```
] |
[Question]
[
# Introduction
I have decided that this Christmas, as a "present" to a friend, I wish to purchase the things described in the classic song "The 12 Days of Christmas". The only problem is, I don't know how to calculate the total price!
# Your Task
Given a list of prices (in order from first to last), calculate the total price of all the items if they were ordered as described by the song.
Remember, each item is ordered once more than the one before it, and this repeats for as many days as there are items!
## Example
The first few lines of the song:
>
> On the 1st day of Christmas, my true love gave to me
>
> A partridge in a pear tree
>
>
> On the 2nd day of Christmas, my true love gave to me
>
> Two turtle doves,
>
> And a partridge in a pear tree.
>
>
> On the 3rd day of Christmas, my true love gave to me
>
> Three French hens,
>
> Two turtle doves,
>
> And a partridge in a pear tree.
>
>
> \$\vdots\$
>
>
>
The song then continues, each day adding in a new present, with the number increasing each time (e.g. "4 calling birds", "5 gold rings", etc.). up to a total of 12 days.
Therefore, the total number of each item as the song continues for 12 days goes: 1 partridge on day 1, 2 partridges and 2 doves on day 2, 3 partridges, 4 doves, and 3 French hens on day 3, etc.
# Rules and Scoring
Your program should take as input a list of prices (which can be of any length), and calculate the total price in the manner described above. Programs which give me the wrong answer for their inputs will be disqualified. Shortest size in bytes wins!
# Examples
```
[20, 20, 20]: 200
[25, 10]: 70
[10, 25, 10, 75]: 550
```
# Example price table
Feel free to use this table to test your program. The correct output should be 51765.02.
| Item | Price |
| --- | --- |
| A partridge in a pear tree | 27.50 |
| A turtle dove | 25.00 |
| One French hen | 5.00 |
| One calling bird | 70.00 |
| A gold ring | 65.00 |
| One goose a-laying | 25.00 |
| One swimming swan | 500.00 |
| A milkmaid hired for 1hr | 4.25 |
| One lady dancing | 289.65 |
| One lord leaping | 318.26 |
| One piper piping | 100.83 |
| One drummer drumming | 100.13 |
Or, as a single list of prices:
```
[27.50, 25.00, 5.00, 70.00, 65.00, 25.00, 500.00, 4.25, 289.65, 318.26, 100.83, 100.13]
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~4~~ 3 bytes
```
Œ˜O
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6KTTc/z//482MtczNdBRMDLVMwBSENLcAEyZQXgwKQOIqImekSlQ0MJSzwxIGxta6BmZ6SgYAmUtjCG0oXEsAA "05AB1E – Try It Online")
sublists, flatten, sum.
I actually found this approach as I was trying writing an APL solution which ended up being almost identical to [my answer](https://codegolf.stackexchange.com/questions/237700/even-sum-subarrays/237720#237720) for even-sum-subarrays.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes
```
JƤSḋ
```
[Try it online!](https://tio.run/##y0rNyan8/9/r2JLghzu6////b2SuZ2qgo2BkqmcApCCkuQGYMoPwYFIGEFETPSNToKCFpZ4ZkDY2tNAzMtNRMATKWhhDaENjAA "Jelly – Try It Online")
-1 byte thanks to [pxeger](https://codegolf.stackexchange.com/users/97857/pxeger)!
Ignores the strings as input, just takes a list of 12 prices
## How it works
Basically, the number of each item is given as
```
Day 1: 1
Day 2: 1 2
Day 3: 1 2 3
Day 4: 1 2 3 4
...
Day 12: 1 2 3 4 5 6 7 8 9 10 11 12
Total : 12 22 30 36 40 42 42 40 36 30 22 12
```
Which is just the prefixes of the range `[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]`, summed down the columns. We then multiply each price by the quantity and take the total
```
JƤSḋ - Main link. Takes a list of 12 prices P on the left
Ƥ - Over the prefixes of P:
J - Convert to a length range
S - Sums of the columns
ḋ - Dot product with P
```
# [Jelly](https://github.com/DennisMitchell/jelly), 3 bytes
```
ẆFS
```
[Try it online!](https://tio.run/##y0rNyan8///hrja34P///xuZ65ka6CgYmeoZACkIaW4ApswgPJiUAUTURM/IFChoYalnBqSNDS30jMx0FAyBshbGENrQGAA "Jelly – Try It Online")
A port of [ovs' answer](https://codegolf.stackexchange.com/a/237977/66833) - sublists, flatten, sum
[Answer]
# JavaScript (ES6), 35 bytes
Expects an array of prices.
```
a=>a.map(v=>t+=p+=v*++i,i=t=p=0)&&t
```
[Try it online!](https://tio.run/##XY1BDoIwEEX3noIVaS1O2kILLoaLGBcNgoEgbaTh@nVi48bNvMx/fzKLO9w@vOcQL5t/jGnC5LB38HKBHdhHgUHgcRZirmaMGFDysoxp8Nvu1xFW/2QTu@kWjKwKbUAS8mzlFzZvPyVz2oA2FHZXsMRadaBtVSiyXZ2p6jvnp78/DXXpjBok0wc "JavaScript (Node.js) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 26 bytes
```
!x=sum(cumsum(x.*keys(x)))
```
[Try it online!](https://tio.run/##NclLCoAgGATgq9ROI3585KNFJ4kWES0sk6gEO71Z0mY@Zmbx1ow0xFiG7vQbmvz2EqBa5/tEAWMc98O4yzpU9kyBIHXBBJBETkU@ZG7/RfLaABNp1C3IJKcamKwLml7Ns5QPOD4 "Julia 1.0 – Try It Online")
[Answer]
# Excel, ~~52~~ ~~69~~ 59 bytes
Saved 10 bytes thanks to [MarcMush](https://codegolf.stackexchange.com/questions/237965/total-cost-of-the-12-days-of-christmas/238050?noredirect=1#comment539902_238050) pointing out how Excel interprets empty cells when doing math.
```
=SUM(LET(n,COUNT(A:A)+1,s,SEQUENCE(n),IFNA(A:A*s*(n-s),0)))
```
Input is in the range `A:A`.
* `LET(n,COUNT(A:A)+1` defines `n` to be one more than the number of cells in the range `A:A` that are a number. Why we need it to be one *more* will be clear later.
* `LET(~,s,SEQUENCE(n)` defines `s` to be a vertical array of numbers 1 to the value of `n` we just defined. This is a list of how many of each gift is given at a time. 1 partridge, 2 doves, 3 hens, etc. (Lots of birds...)
* `(n-s)` is best explained with an example. If there are 12 entries, this is `(13-[1-13])` which becomes `([12-0])` which is how many days each gift is given. IE, the first gift is given on all 12 days and the 13th gift is given on 0 days because the list isn't that long.
* `A:A*s*(n-s)`, then, is `(Value of each gift) * (number of times that gift is given on each day) * (number of days a gift is given)` which is, therefore, a list of the total value of each gift item over all the days.
* `IFNA(~,0)` accounts for the fact that the calculation above fails when the cell is empty because a number times an empty string is an error for Excel. This turns those errors into zeros.
* `SUM(LET(~,IFNA(~)))` sums up all the values.
The screenshot below shows the last three steps in columns `C:E`.
[](https://i.stack.imgur.com/LHM32.png)
[Answer]
# [R](https://www.r-project.org/), 33 bytes
Or **[R](https://www.r-project.org/)>=4.1, 26 bytes** by replacing the word `function` with `\`.
```
function(p)(rev(n<-seq(p))*n)%*%p
```
[Try it online!](https://tio.run/##NYlJCoAwEATvvsKLMCM6ZDExir5GDHiJu9@Pg8FLF111RD9Gf4fpWtYAG8IxPxCG@px3flgGLMpiix4mUC0ZUeXKkGCkbcUHm96fRLINKcPSdWSZWjpStsolV6cTpUbMPDS9xPgC "R – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 4 bytes
```
ss.:
```
[Try it online!](https://tio.run/##K6gsyfj/v7hYz@r//2gjcz1TAx0FI1M9AyAFIc0NwJQZhAeTMoCImugZmQIFLSz1zIC0saGFnpGZjoIhUNbCGEIbGscCAA "Pyth – Try It Online")
[15 bytes](https://tio.run/##K6gsyfj/3ydXyy3FOam4Uqcy3ik45///aCNzPVMDHQUjUz0DIAUhzQ3AlBmEB5MygIia6BmZAgUtLPXMgLSxoYWekZmOgiFQ1sIYQhsaxwIA "Pyth - Try It Online") (ungolfed) to avoid floating point precision errors.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~36~~ 30 bytes
```
->g{r=w=0;g.sum{|x|r+=x*w+=1}}
```
[Try it online!](https://tio.run/##LYlBDkAwEEWvYs2YTKdaFRkXERsLVhKpCIKzF43Nez/v@7U/wiAhb8bTyyZUj7is03ntl89kT7dM1H2HORnalks0BGyQCCJK@mjj/jPFVCAbYFehNaCVQ7ag3sfpKKW7Ljw "Ruby – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
żḂ*Þ•
```
[Try It Online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCLFvOG4girDnuKAoiIsIiIsIiIsIlsyNy41MCwgMjUuMDAsIDUuMDAsIDcwLjAwLCA2NS4wMCwgMjUuMDAsIDUwMC4wMCwgNC4yNSwgMjg5LjY1LCAzMTguMjYsIDEwMC44MywgMTAwLjEzXSJd)
Vyxal is able to do the times-reverse thing more efficiently than Jelly (because you need the `$` for chaining in Jelly, and Vyxal has a bifurcate command), but unfortunately it does not have 1-byte dot product like Jelly does, so the byte save gets canceled out.
Unfortunately (for me), caird+pxeger have found a 4-byter. I mean, I could pretty trivially get one by cheating:
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 4 bytes
```
żḂ**
```
[Try It Online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCLFvOG4gioqIiwiIiwicyIsIlsyNy41MCwgMjUuMDAsIDUuMDAsIDcwLjAwLCA2NS4wMCwgMjUuMDAsIDUwMC4wMCwgNC4yNSwgMjg5LjY1LCAzMTguMjYsIDEwMC44MywgMTAwLjEzXSJd)
but I'll try to figure something out.
# [Vyxal](https://github.com/Vyxal/Vyxal), 4 bytes
```
ÞSf∑
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDnlNm4oiRIiwiIiwiWzI3LjUwLCAyNS4wMCwgNS4wMCwgNzAuMDAsIDY1LjAwLCAyNS4wMCwgNTAwLjAwLCA0LjI1LCAyODkuNjUsIDMxOC4yNiwgMTAwLjgzLCAxMDAuMTNdIl0=)
4 bytes by porting the same solution (ovs's) that everyone else is. Thanks to lyxal for finding this.
# [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 2 bytes
```
ÞS
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwiw55TIiwiIiwiWzI3LjUwLCAyNS4wMCwgNS4wMCwgNzAuMDAsIDY1LjAwLCAyNS4wMCwgNTAwLjAwLCA0LjI1LCAyODkuNjUsIDMxOC4yNiwgMTAwLjgzLCAxMDAuMTNdIl0=)
Flag abuse for the win. Credit to Aaroneous Miller.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 4 bytes
```
ḋƤJS
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLhuIvGpEpTIiwiIiwiIixbIjI3LjUwLCAyNS4wMCwgNS4wMCwgNzAuMDAsIDY1LjAwLCAyNS4wMCwgNTAwLjAwLCA0LjI1LCAyODkuNjUsIDMxOC4yNiwgMTAwLjgzLCAxMDAuMTMiXV0=)
-1 byte thanks to caird coinheringaahing
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~54~~ 53 bytes
```
d;f(x,n)float*x;{for(*x*=d=n;--d;)*x+=~d*(d-n)*x[d];}
```
[Try it online!](https://tio.run/##ZVHbboMwDH3fV1hIlQIFxmX0soztYdpXtGhiSejQulARpKFV7NPHHG5FHRJ24mP7HDvMOTDWtpxmpLalmR2LtLJqes6Kkli1FfNYUsfh1LTqZfzDLcIdiecdT2jT5rKCzzSXxITzDeDXlUMlVLVLIIZzsHYjz4Ygcj10vV17nVv1txHy@uidG0QY3GzdFfrQ37jBygYf0U3Yez9saMelyTXTq@y5/GAAehGiPglWCd6Dkb/WhGMKK6SqgL2npYVWsA9R9nnGvn4J9vX2Gf/IsGF@D42RoCiBaPpcclFjmUeH4wOo/FsUGRnZzdshYE0RCstllz0ubRxGYqdhoA5P6ASfSkzIiLEzzEvwImOQgPSy6z7vPC9fqIUbZDhW/qRnuzfQdo@VJ7O@zYWBaNQGOWfttquQ0tLgNSAQmFZ/PYYWe0qVLs7SN0UEOKBMlO0LZ/t/2gScR9CKYaH2ErUqe3ot3WYU3dw07S/LjulBtc7XHw "C (gcc) – Try It Online")
*Saved a bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs the list of prices as a pointer to an array along with its length (because pointers in C carry no length info).
Returns the total cost in the first element of the array.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 3 bytes
```
ΣΣQ
```
[Try it online!](https://tio.run/##yygtzv7//9zic4sD////H21krmdqoGNkqmdgoAMmzA1ApBmYDRU2AAuZ6BmZ6hhZWOqZmeoYG1roGZnpGAJlLIzBlKFxLAA "Husk – Try It Online")
Uninventive port of [ovs's O5AB1E answer](https://codegolf.stackexchange.com/a/237977/95126): upvote that one instead.
[Answer]
# APL+WIN, 16 bytes
Prompts for prices.
```
+/(n×⌽n←⍳⍴v)×v←⎕
```
[Try it online! Thanks to Dyalog Classic.](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcQJanP5BlyPWooz3tv7a@Rt7h6Y969uYBxR71bn7Uu6VM8/D0MhCvb@p/oBqu/2lcRuZ6pgpGpgqmCuYGCmYQpoGBgokekGFkYakHFDI2tNAzMlMwNDDQszAGU4bGAA "APL (Dyalog Classic) – Try It Online")
[Answer]
# x86 32-bit machine code, 23 bytes
```
d9 ee 31 c0 dd 04 c2 40 50 0f af c1 50 da 0c 24 de c1 58 58 e2 ee c3
```
Following the `fastcall` calling convention, takes the length in ECX and the address of an array of double-precision floating-point numbers in EDX, and returns the result on the FPU register stack.
[Try it online!](https://tio.run/##fVJdT4MwFH3vr7jBmAAyZLAPdM6nPZqoi4kP20JKKYykUELBzC3762KBjQ0f7MO9nNNTzr23JYOIkKq6iVPCyoDCkyiCmJvbZ9SjWOzXHPI8XBR57JcF9TxVDbEoCGZM04DxNIKAlz6jEOBvQbgo1DgtIDXOtI61GcIiARUp69SMGPcx68RKTZ7BY4NArpAF@w7seA4U74w6NGROM4r7anj/fF0u4O1jCSsa7O5cXYo3nUJ21Z2ucVaKbY@Ik5KdTMg/srDRLa68RHZxCXEQZJfDPOt7/sGMS6JtpeNyKr/lvFA9wwTHaTNMnEfEALLFOei6BF8aOqBafhpxPTux2sAcDvbUHFsG2GPTkqmNU6tJkxadt6yWHZn2WJLugzmR2Rm6pj0xYCh3XafNQ@c4a9yyXBYTqsqtaY9ewnWqGJc7F/Ge8lBtKtHur9HK2mhGW6KmtT@SXZZ5CtYMHVFV/ZCQ4UhUg8SxZZBPZS59KPsF)
Assembly:
```
.text
.global dayscost
.intel_syntax noprefix
dayscost:
fldz # Push 0 onto the FPU register stack, for a running total.
xor eax, eax # EAX = 0, for the current day number.
repeat:
fld QWORD PTR [edx+8*eax] # Push the new item's price onto the FPU register stack.
inc eax # Add 1 to EAX. It is now the 1-indexed day number.
push eax # Push EAX onto the regular stack.
imul eax, ecx # Multiply EAX by the number of remaining days.
push eax # Push the product onto the regular stack.
fimul DWORD PTR [esp] # Multiply the price by that product.
faddp # Add the full product to the running total.
pop eax # Pop the product from the regular stack.
pop eax # Pop to restore the day number in EAX.
loop repeat # Repeat, counting down the number of remaining days in ECX.
ret # Return.
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-p`, 15 bytes
Using the insight from [@Arnauld's answer](https://codegolf.stackexchange.com/a/237971/9365).
```
$\+=$x+=$_*$.}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lRttWpQKI47VU9Gqr//83MtczNeAyMtUzMOACE@YGINIMzIYKG4CFTPSMTLmMLCz1zEy5jA0t9IzMuAyBMhbGYMrQ@F9@QUlmfl7xf90CAA "Perl 5 – Try It Online")
---
# [Perl 5](https://www.perl.org/) + `-pa`, 26 bytes
```
$\+=(@F-$-++)*$_*$-for@F}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lRttWw8FNV0VXW1tTSyVeS0U3Lb/Iwa22@v9/I3M9UwMFI1M9AwMFMGFuACLNwGyosAFYyETPyFTByMJSz8xUwdjQQs/ITMEQKGNhDKYMjf/lF5Rk5ucV/9ctSAQA "Perl 5 – Try It Online")
[Answer]
# Fortran, 116 bytes
[Try it Online.](https://tio.run/##LYlBDoMgAATvvIKbYCkBLGolHngKLdhoCDTo/ylSL7uTmSWmI5lw/yx/yDk544nxPr7NYV7eTZNGEya7KsG2JICrOaRRwPjSGtgI15mToApsBVa1z/tNow23G3DB2qjqgm9aw9GghVGBG7KfLWcugBioZFBIyhisM7Bz@8qXZlU9qJBQjE/aS9jxkYoe8lLGrh7vfg)
```
real,allocatable::A(:),s;read*,n
allocate(A(n));read*,A
do i=1,n;do j=1,i;s=s+A(j)*j
enddo;enddo
print'(f0.2)',s
end
```
Another demo of our old friend, Fortran (emphasis on old). Elegance, simplicity and flexibility are not words that spring to mind. The requirement to allow `n` inputs forced me to write those chunky `allocate` statements.
[Answer]
# Python 3, ~~69~~ ~~64~~ ~~61~~ 55 bytes
Takes a list of floats as input.
```
lambda l:sum(o*-~c*(len(l)-c)for c,o in enumerate(l))
```
[Try it here!](https://tio.run/##JYpLDsIgFADX3uKlq/dqS/jYj17FuKgVIgkFQmHh6bHR1UwmEz/5HbyqL23AoKNbPSWdS/Kwlw3vxoUlY6B2bZfnjmuPTvtjOwsiMCHB2gWwHrQvm05L1ug6QQ@qMVmf0aD1sWQktkdnMzbQEFGVExtADjDAxGH8K@dwYYfI@cqOpMTM5AiCczarH4T6Ag)
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 27 bytes
```
a->Pol((x*Ser(a))'/y=1-x)%y
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmD7P1HXLiA/R0OjQis4tUgjUVNTXb/S1lC3QlO18n9BUWZeiUaaRrSRuZ6pgY6CkameAZCCkOYGYMoMwoNJGUBETfSMTIGCFpZ6ZkDa2NBCz8hMR8EQKGthDKENjWM1Nf8DAA "Pari/GP – Try It Online")
See the input as a polynomial \$A=\sum\_{i=0}^{n-1}a\_ix^i\$. The derivative of \$A\ x\$ is \$(A\ x)'=\sum\_{i=0}^{n-1}(i+1)\ a\_ix^i\$. So \$(A\ x)'/(1-x)=\sum\_{i=0}^{n-1}(\sum\_{j=0}^{i}(j+1)\ a\_j)x^i+O(x^n)\$. Then we only need to take the first \$n\$ terms and evaluate it at \$x=1\$.
[Answer]
# [SimpleTemplate](https://github.com/ismael-miguel/SimpleTemplate) 0.84, 86 bytes
This full program expects a variable number of arguments passed to the `render()` method. [Argument unpacking](https://www.php.net/manual/en/functions.arguments.php#example-159) can be used for convenience. Each argument is 1 gift.
```
{@eachargv}{@inc__}{@set*__ __,argc}{@set*_ __,_}{@incby_ T}{@incby-1argc}{@/}{@echoT}
```
The result is displayed on standard output, by default.
This works the same way as [@caird coinheringaahing](https://codegolf.stackexchange.com/users/66833/caird-coinheringaahing) [answer in Jelly](https://codegolf.stackexchange.com/questions/237965/total-cost-of-the-12-days-of-christmas/237968#237968).
However, everything is done manually, to obtain the `Total` row on the table.
---
## Ungolfed:
The code above looks like gibberish, so, bellow is an ungolfed version of it:
```
{@set total 0}
{@each argv as value key key}
{@inc by 1 key}
{@set* key key, argc}
{@set* value key, value}
{@inc by value total}
{@inc by -1 argc}
{@/}
{@echo total}
```
Yeah ... It still looks like gibberish...
---
## About the language:
There are a few important things to notice here:
* Plenty of whitespace isn't mandatory.
`{@eachargv}` and `{@each argv}` do the same.
* The line `{@set total 0}` isn't golfed to `{setT 0}`: it was removed because the `{@incby_ T}` will define the variable `T`.
* The line `{@each argv as value key key}` is golfed into `{@eachargv}`.
By default, the `{@each}` loop uses the variable `_` for the value and `__` for the key, if none were provided.
This allows skipping all the "fluff" after `argv`.
* `{@inc by 1 key}` and `{@inc__}` increment the `key` (or `__`) variable by 1.
Due to rubbish math support, this has to be done.
* `{@set*__ __,argc}` and `{@set* key key, argc}` both multiply the `key` variable by `argc`.
The variable `argc` contains the length of the `argv` variable.
This will calculate the number of times that the current gift was gifted on all 12 days.
This should be `1 * 12`, `2 * 11`, `3 * 10` ... (`(key + 1) * argc`).
* `{@set*_ __,_}` and `{@set* value key, value}` will multiply the `key` variable by the `value`, and save it into the `value` variable.
* `{@incby_ T}` and `{@inc by value total}` will increment the `total` by the `value` calculated before.
* `{@incby-1argc}` and `{@inc by -1 argc}` will decrement the `argc` variable by 1.
This variable, initially, has the length of the `argv` array.
At the end, the value will be `0`.
* `{@echoT}` and `{@echo total}` will display the total.
Yeah ... Very confusing...
---
## Running the code:
You can run the code on: <http://sandbox.onlinephpfunctions.com/code/b775fddea1ae9c869962f893ac915c8087cb779a>
Please pick a version between 5.6 and 7.4.13. Can't fix the 8.0.0 compatibility issue without invalidating this answer.
[Answer]
# IBM/Lotus Notes Formula Language, 102 bytes
```
Z:=L:=@Elements(i);T:=0;C:=1;@For(X:=1;X<=L;X:=X+1;@Set("T";T+i[X]*Z*C);@Set("Z";Z-1);@Set("C";C+1));T
```
There is no online interpreter for Notes so here is a screenshot of the expected output:
[](https://i.stack.imgur.com/QbWCZ.png)
After more years than I can remember working with Lotus Notes and several posts on here, this will probably be my last Formula Language post as our company has just decommissioned the last Notes application that I was responsible for and my designer client will most likely soon be removed.
The end of an era. RIP, LN.
[Answer]
# TI-Basic, 9 bytes
```
sum(cumSum(AnscumSum(1 or Ans
```
Takes input in `Ans`. Output is stored in `Ans` and displayed. Does not work for empty lists as TI-Basic does not support them.
[Answer]
# Zsh, 65 bytes
[Try It Online.](https://tio.run/##LYnBDsIgEETvfMUmYsJqsoGtUDyQ2O8wXolw0KZ4suHb0ZJeZua9@ZZniwpXUUKbgpI3FPG9QAK1GiJ5qLhh3jFVVKqcw3TPj1NGFPOSXp8IR@IIsrQqIvBIVgNb0hp6jHpL1/eudVcXYgvsr@QsDMYTOzD/xw@9zNB@)
```
A=($@)
for i ({1..$#})for j ({1..$i})((s+=A[j]*j))
printf %.2f $s
```
Had to use `printf` to fix the output - Zsh arithmetic gives a funky result of `51765.019999999982` otherwise
[Answer]
# [convey](http://xn--wxa.land/convey/), 33 bytes
Dude, i love convey
```
v<-1
12"0<
{**+@}
1">>^
^"=12
^+1
```
[Try it online!](https://xn--wxa.land/convey/run.html#eyJjIjoidjwtMVxuMTJcIjA8XG57KiorQH1cbjFcIj4+XlxuXlwiPTEyXG5eKzEiLCJ2IjoxLCJpIjoiWzI3LjUwLCAyNS4wMCwgNS4wMCwgNzAuMDAsIDY1LjAwLCAyNS4wMCwgNTAwLjAwLCA0LjI1LCAyODkuNjUsIDMxOC4yNiwgMTAwLjgzLCAxMDAuMTNdIn0=)
The start of the process:
[](https://i.stack.imgur.com/lDmpY.gif)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
IΣEθ×ι×⊕κ⁻Lθκ
```
[Try it online!](https://tio.run/##NYnBCsMgEER/xeMGrKhpjKHHngoNFNpbyEGsNJLENsb0961UMod5u2/0oLx@qynGm7cuwFmtAe7bDK36wILRw85mBbsfF6e9mY0L5gljgVFr3bbC1bhXGGBJYixyTjF2Ha9JRTHiFaEJuWv6h8jfPtFsj4RXScqGiMSSScIFRiytssxkZd/Hw3f6AQ "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of my golf to @GingerIndustries' Python answer.
```
θ Input list
E Map over prices
ι Current price
× Multiplied by
κ Current index
⊕ Incremented
× Multiplied by
θ Input list
L Length
⁻ Minus
κ Current index
Σ Take the sum
I Cast to string
Implicitly print
```
[Answer]
# [Rust](https://www.rust-lang.org/) 137 Bytes
```
fn r(v: Vec<f64>)->f64{let mut c=0.;let k=v.len()as f64;let s=v.iter().map(|x|{c+=1.;x*c*(k-c+1.)}).collect::<Vec<f64>>();s.iter().sum()}
```
[Try it out!](https://tio.run/##NY7BroJADEX3fkV1NVVsZkCQB8JnuHl5CzIZE@LAM8xgTJBvxyKhi57ce9u0Xe/8NN1a6MQzg6vRl1tyKvFYMgZrPDS9B11IymdxL55kTSuwcsADX8@xV3vTCaSmeoj36z3oQ6Eof@31XtyP@qAIRyT9b63RPssu65VSYO7WXdc3Asf5k6aq@QIMG@B6dHXrbbsVu2HcBfOXRm9/wzPFMoAwJslY@ll@kSxqjeTiniiM2Ux/KGFGKqUwCUBxmkYLVfSHuBmnDw)
[Answer]
# Python 3, ~~145~~ 137 bytes
```
p=list(map(eval,input().split()))
n=len(p)
d=1
t=0
for x in range(12):
t=t+p[d-1]*d*(12-(d-1))
d+=1
print(t)
```
[Try it online!](https://tio.run/##LYvLCsIwFET3@Yq7TKoNediHQr5EXBRSNRDTS3sV/foYg5szwxkGP3Rfks0ZXQwb8ceEfH5NcR8SPokLuWEMJYVgycU5cRTMO83IKXZdVnhDSLBO6TZzbcSJATna4dm3@tL4priWl17e4HflhmtIxEnkbAbZKTCdVAoqBvVjX/tfq6oO0nRgxqPsO7B6lKYHXZbR1tA2fwE)
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
i=input()
t,c,l=0,1,len(i)
for x in i:t+=x*l*c;l-=1;c+=1
print t
```
[Try it online!](https://tio.run/##NYnNCgIhFEb3PsVdzo@JV9OxBp8kWkmRII4MN5ie3iRp8x2@c8qHXltWtUYfc3nTMDLigScvOfL0yEMc2XPb4YCYIV5p9seUprCmk8c1zB5Z2WMmoFpvahFGclBGyIa@i/zB9vdPstuzUKZJdxG2UaMTynLAVp3uRH3/Ag "Python 2 – Try It Online")
Python 2 because it will directly take the list as input and saves 1 byte by not needing the brackets for `print`.
[Answer]
# [Scratch](https://scratch.mit.edu/), 223 bytes
[Try it online!](https://scratch.mit.edu/projects/608676129/)
Alternatively, 23 blocks
```
when gf clicked
delete all of[S v
repeat until<(answer)=[F
add(answer)to[S v
ask[]and wait
end
set[I v]to[-1
set[T v]to[
repeat(length of[S v
change[I v]by(1
repeat((length of[S v])-(I
change[T v]by((I)*(item((I)+(1))of[S v
```
## Explanation
```
when gf clicked Initiates code
delete all of[S v Clears the "Shopping" list
repeat until<(answer)=[F Loops code until the user inputs "F"
add(answer)to[S v Adds user's input to the "Shopping" list
ask[]and wait Prompts the user to give input
end Marks the end of code to be looped
set[I v]to[-1 Resets the Item being accounted for
set[T v]to[ Resets the Total cost of the items
repeat(length of[S v Loops code for each item on the list
change[I v]by(1 Increments the Item to be checked
repeat((length of[S v])-(I Loops code for each day the item is purchased
change[T v]by((I)*(item((I)+(1))of[S v Adds (item cost * quantity) to the total
```
[Answer]
# [APOL](https://esolangs.org/wiki/APOL), 63 bytes
```
v(1 s(i));v(2 []);f(⌬(¹) a(2 x(x(+(∈ 1) I(∋)) -(l(¹) ∈))));⊕(²)
```
[Answer]
# [Haskell](https://www.haskell.org/), 69 bytes
```
f x=sum$map sum[(map$uncurry(*))$zip x[1..n]|n<-[1..genericLength x]]
```
[Try it online!](https://tio.run/##NclNDsIgEAXgq7BgYU2dALU/JnbnsjdoWJCGtsSChNKkGu@OKHEz35v3ZrHe5bIEpe3DeXQTXkCnVh9GtLfrprEWFkX7Qwx4M8Pm3PNwzDL8UhbtPQUw/G2up2@apJFODZ00k5/RznnQQpnWOmU8HntWQ0lyxEogkXRr8qNK338iqT0DK2PZXKCKFrQBVuWIxrUpkrTg4QM "Haskell – Try It Online")
] |
[Question]
[
As most of you probably know, (byte-addressable) hardware memories can be divided into two categories - *little-endian* and *big-endian*. In little-endian memories the bytes are numbered starting with 0 at the little (least significant) end and in big-endian ones the other way round.
**Fun fact**: These terms are based on [Jonathan Swift](https://en.wikipedia.org/wiki/Jonathan_Swift)'s book [Gulliver's Travels](https://en.wikipedia.org/wiki/Gulliver%27s_Travels) where the Lilliputian king ordered his citizens to break their eggs on the little end (thus the little-endians) and the rebels would break theirs on the big end.
## How swapping works
Suppose we have an unsigned integer (32bit) `12648430` in memory, in a big-endian machine that might look as follows:
```
addr: 0 1 2 3
memory: 00 C0 FF EE
```
By inverting the byte-order we get the hexadecimal integer `0xEEFFC000` which is `4009738240` in decimal.
## Your task
Write a program/function that receives an unsigned 32bit integer in decimal and outputs the resulting integer when swapping the endianness as described above.
## Rules
* Input will always be in the range `0` to `4294967295`
* Output can be printed to STDOUT (trailing newlines/spaces are fine) or returned
* Input and output are in decimal
* Behavior on invalid input is left undefined
## Test cases
```
0 -> 0
1 -> 16777216
42 -> 704643072
128 -> 2147483648
12648430 -> 4009738240
16885952 -> 3232235777
704643072 -> 42
3735928559 -> 4022250974
4009738240 -> 12648430
4026531839 -> 4294967279
4294967295 -> 4294967295
```
[Answer]
# x86\_32 machine language, 3 bytes
```
endian_swap: # to be called with PASCAL REGISTER calling convention
0f c8 bswap eax
c3 ret
```
This is a bit of a cheat. The Pascal register calling convention (see [Wikipedia](https://en.wikipedia.org/wiki/X86_calling_conventions#List_of_x86_calling_conventions)) is a bit like \_\_fastcall, except it passes the first parameter in eax, and eax also contains the return value. It's also callee-cleanup, but since we don't use the stack for anything other than the return pointer we don't need to do anything. This allows us to avoid a mov or xchg and just use bswap directly.
[Answer]
# x86\_64 machine language Linux, ~~5~~ 4 bytes
```
0: 0f cf bswap %edi
2: 97 xchg %eax,%edi
3: c3 retq
```
Thanks to [@peter ferrie](https://codegolf.stackexchange.com/users/61382/peter-ferrie) for -1.
[Try it online!](https://tio.run/##fZDbisIwFEXf/YpDRUgGR9Jcmhwc/Avf@iJpqwEnM4wWCjLfXtN4B5uH0Cz2XhtS@7m1tp86b/dtVX8djpX7WexW/bSqG@draEhHgZDWH9zW1xU4fyQf9IUpzcquKTsbDurwFRkNVh8i@N44T@hpAvD7F7ghkM1amLWlz@bA5mGeUaDL93k@5Pl4LvlQkDyxwE3c4CbRKYxRqOLW7T7e1kwWUjAd63cY7wstFHKjFK4H4wkT72IMtTBcsug8YcrhhRK5EXh17pj6fyix0BzVxXlgdP77Mw "C (gcc) – Try It Online")
[Answer]
# C (gcc) , ~~20~~, ~~29~~ 17 bytes
@hvd's suggestion.
```
__builtin_bswap32
```
[Try it online!](https://tio.run/##ZcxLCsIwFIXheVZRCpWmtDS9yc2DgisRShtRAnotfeBAdOsxjh0cOHyD3zdX72NbxWGY9nDbAg3T@hxnCbFq2X0MVBJ/XR5L2X9WP9KlzItzXh@I93xeAm0/2LPmmBX7ifKa6r9QCvD@HQXrmALWgU3TyiqZRFuLDoEZoXQCA0waiQ4somNKCGekBSXSBY2yszIpOOW0AYdf)
Old answer;
```
#include<byteswap.h>
bswap_32
```
include should be import.
[Answer]
# [Japt](https://github.com/ETHproductions/japt/), ~~10~~ 14 bytes
```
sG ùT8 ò w ¬nG
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=c0cg+VQ4IPIgdyCsbkc=&input=OA==)
---
## Explanation
Convert input integer to a base-16 string (`sG`), use `0` to pad the start to length 8 (`ùT8`), split to an array of 2 character strings (`ò`), reverse (`w`), rejoin to a string (`¬`) and convert back to base-10 (`nG`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
⁴4*+b⁹ḊṚḅ⁹
```
[Try it online!](https://tio.run/##y0rNyan8//9R4xYTLe2kR407H@7oerhz1sMdrUD2////Dc0sLEwtTY0A "Jelly – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 44 bytes
```
f=lambda x,i=3:x and(x%256)<<8*i|f(x>>8,i-1)
```
[Try it online!](https://tio.run/##RZDNasMwEITP8VPspWAXFaRdrX5CnBcJobhNTA2tbRIFXOi7uxtbJCftaGY/DRp/09fQ4zy39Xfz83FqYFJdTdsJmv5UTi/Irtrtwmv315bTfh9U92aqOZ2v6f2zuZ6vUMOh2By0An1UMhgFxnnv0bhFW1TgtXWWtMc1gUEBGuttIGdDvpNJIgqs1tFTQJtxLgSOLBBCQiQW9GI8mLKycskTRwzM8U5BRBaSXUs8oNIuP5UNdEwm0H0Ho43Oo4@5@CojP63IYh2Loh0u0PXjLSkYbklOUfD8k22xGS9dn8q2XFIV1HUOVvM/ "Python 2 – Try It Online")
[Answer]
# APL+WIN 14 bytes
```
256⊥⌽(4⍴256)⊤⎕
```
Explanation
```
⎕ prompt for screen input
(4⍴256)⊤ 4 byte representation in base 256
⌽ reverse bytes
256⊥ bytes from base 256 to integer
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 24 bytes
```
IntegerReverse[#,256,4]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n1aaZ/vfM68kNT21KCi1LLWoODVaWcfI1EzHJFbtf0BRZl5JNFCNgr6DQrWhjoKJkY6CoZEFkDAzsTAxNgAxLCxMLU2B4uYGJmZAIXOj2tj/AA "Wolfram Language (Mathematica) – Try It Online")
Reverses the input interpreted as an integer in base 256 with 4 digits.
[Answer]
# [C#](https://www.microsoft.com/net/core/platform), 70 68 bytes
This is probably not optimal.
**68:**
```
Func<uint,uint>f=n=>((n=n>>16|n<<16)&0xFF00FF00)>>8|(n&0xFF00FF)<<8;
```
**70:**
```
uint e(uint n){n=n>>16|n<<16;return(n&0xFF00FF00)>>8|(n&0xFF00FF)<<8;}
```
[Try it online!](https://tio.run/##jY5BC4JAEIXP7q9YPIQLJWOFSGteBE91Kqjrui6xYCO5axjqbzfzEB07DPPe8HjfSLOSVa3GsTEab/T0MlbdOfl1/kHjgxMiS2EMPStj01l1xDFWWC1po9FS5c0LWYd7TJIg7DGOg5DXyjY1eriANssAPsOSJOp/LiyOIz6Qb9@z0gU9Co0eI86EcdIKTVUq/1Jrq6Z3lOd2sLtGg7ucuNAKkedSFgVj/I80BLCGDWzn9ECGcXwD "C# (.NET Core) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~12~~ 10 bytes
```
3F₁‰R`})₁β
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f2O1RU@Ojhg1BCbWaQNa5Tf//GxqZmViYGBsAAA "05AB1E – Try It Online") Explanation:
```
₁ Integer constant 256
‰ [Div, Mod]
R Reverse
` Flatten to stack
3F } Repeat 3 times
) Collect results
₁β Convert from base 256
```
[Answer]
## JavaScript (ES6), ~~45~~ 43 bytes
```
f=(n,p=0,t=4)=>t?f(n>>>8,p*256+n%256,t-1):p
```
[Answer]
# PPC Assembly (32-bit), 8 bytes
```
endian_swap: # WORD endian_swap(WORD)
7c 60 1c 2c LWBRX 3,0,3
4e 80 00 20 BLR
```
How this works:
* PPC calling convention puts the first 32-bit word parameter into SP+24, and shadows that address into GPR3.
* [LWBRX](https://www.ibm.com/support/knowledgecenter/en/ssw_aix_61/com.ibm.aix.alangref/idalangref_lwbrx_lbx_lwbri_instrs.htm) takes load GPR3 (third operand) and zero-extends it (second operand) into EA, then reads 4 bytes in reverse order and stores it into GPR3 (first operand).
* GPR3 holds the return value.
* BLR returns from the function (branches to the address in the LR register)
Unfortunately there aren't any online PPC assembly emulators that I could find to demonstrate. Sorry!
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 9 bytes
```
žJ+₁в¦R₁β
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6D4v7UdNjRc2HVoWBKTPbfr/3xAA "05AB1E – Try It Online")
-1 thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil).
Port of my Jelly answer.
[Answer]
# Befunge, ~~62~~ 61 or 49 bytes
```
0&0v!p22:/3g22/*:*82\+%*:*82+<
@.$_:28*:*%00p\28*:**00g28*:*^
```
[Try it online!](http://befunge.tryitonline.net/#code=MCYwdiFwMjI6LzNnMjIvKjoqODJcKyUqOio4Mis8CkAuJF86MjgqOiolMDBwXDI4KjoqKjAwZzI4KjoqXg&input=NDI)
This is using standard Befunge on the reference interpreter, and we thus need to account for the fact that memory cells are 8-bit signed, and correct for possible signed overflow.
On implementations with unsigned memory cells (e.g. PyFunge), or where the range is greater than 8 bits (e.g. FBBI), we can get away without those checks, saving 12 bytes.
```
0&0v!p22:/3g22/*:*82\+g<
@.$_:28*:*%00p\28*:**00^
```
[Try FBBI online!](http://befunge-93-fbbi.tryitonline.net/#code=MCYwdiFwMjI6LzNnMjIvKjoqODJcK2c8CkAuJF86MjgqOiolMDBwXDI4KjoqKjAwXg&input=NDI)
[Try PyFunge online!](http://befunge-93-pyfunge.tryitonline.net/#code=MCYwdiFwMjI6LzNnMjIvKjoqODJcK2c8CkAuJF86MjgqOiolMDBwXDI4KjoqKjAwXg&input=NDIK)
Although note that PyFunge has a bug processing integer input, so when testing on TIO you need to follow the number in the input field with a space or line break.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~12~~ 10 bytes
```
7Y%1Z%P7Z%
```
[Try it online!](https://tio.run/##y00syfn/3zxS1TBKNcA8SvX/f0MzCwtTS1MjAA) Or [verify all test cases](https://tio.run/##DcgpEsNADAVRrnsMl752ngMEhMQo5jbz/ScCXdX17vO59m/nd8mx3nms/fpsJiEDCWoKK9ORqPJ2ULLFQII01Rvl3mTMnVownkW4Suko2joS7X8).
### Explanation
```
% Implicitly input a number, read as a double
7Y% % Cast to uint32
1Z% % Convert to uint8 without changing underlying data. The result is
% an array of four uint8 numbers, each corresponding to a byte of
% the original number's representation
P % Flip array
7Z% % Convert back to uint32 without changing underlying data. The array
% of four uint8 numbers is interpreted as one uint32 number.
% Implicitly display
```
[Answer]
# C, 50 bytes
```
#define f(i) (i>>24|i>>8&65280|(i&65280)<<8|i<<24)
```
[Try it online!](https://tio.run/##VYxBi4MwFITv/oqH0iVPbFFxF6HBX1D2Vnro7iEbE/sgTUtMvNT9602VPe1lmPlmGLkdpIwZWWlCr4CPvjf0s7t0yT9GtwXFrFearALNCIFR19XNvGj79vFet@XM6M8g5@1MnNcNRrIeroIsW41wgyxAXoSDPF/ChPBIAIA0WyvooEK4u2WqWboJXzYtNGPBjjRY1ePonb8Fs26nc/VdfB4Ph6IqEXG/vjjlg7NQ7pPfGJv6KbURwxi3J2HMCw "C (gcc) – Try It Online")
To be more portable, I didn't want to use any functions that aren't in ANSI C. :-)
Like @hvd, I also cribbed Polynomial's answer. Due to C's operator precedence, I had to add parentheses around the third term.
[Answer]
# JavaScript (ES6), ~~51~~ 45 bytes
*Saved 6 bytes with @Neil's help*
```
n=>(n>>>24|n>>8&65280|(n&65280)<<8|n<<24)>>>0
```
### Test cases
```
let f=
n=>(n>>>24|n>>8&65280|(n&65280)<<8|n<<24)>>>0
console.log(f(0 )) // -> 0
console.log(f(1 )) // -> 16777216
console.log(f(42 )) // -> 704643072
console.log(f(128 )) // -> 2147483648
console.log(f(16885952 )) // -> 3232235777
console.log(f(704643072 )) // -> 42
console.log(f(3735928559)) // -> 4022250974
console.log(f(4009738240)) // -> 12648430
console.log(f(4026531839)) // -> 4294967279
console.log(f(4294967295)) // -> 4294967295
```
[Answer]
# J, 16 bytes
```
|.&.((4#256)#:])
```
[Try it online!](https://tio.run/##VY@xCsMwDET3fIUhUJIl2CfJsgpZ@gGdunYqCaVLh3Tsv7shdgLdfHfSPfmV8@zGwX2H09B13EJi357vfdNcL4O7TctnaabH8@28G93sfBFhEyGqKkIsHmMz1XNk8oo6ibTZCKycKHLa/fW5zm0he29KCbzXx5TEpBQSCCBZUSU8AGW1ckhJDEnEaiMAWVu5HncQyuWVvoeIQiFR3YWxRYXa/rGiTf5ik5x/)
Working on shortening the right-hand expression. I think I can shave off a few bytes by making this work with a beta J version. I swear I saw on here that you can end a train with a noun in a new beta version...
# Explanation
```
|.&.((4#256)#:])
((4#256)#:]) Convert to 4 two-byte blocks
#: Debase to
4#256 4 digits base 256
&. Apply right function, left function, then inverse of right
|. Reverse digits
```
Convert to 4 digits base 256, reverse the digits, then convert back to decimal. Basically, perform the algorithm that is provided in the OP. This is perhaps the one time where it's helpful that J's mixed base conversion requires you to specify the number of digits, although it would be 2 fewer bytes if I could end the train in a noun (`(#:~4#256)` instead).
[Answer]
# Excel VBA, ~~103~~ 92 Bytes
Anonymous VBE immediate window function that takes input from range `[A1]` converts to hex, reverses bytes, and outputs to the VBE immediate window
```
h=[Right(Rept(0,8)&Dec2Hex(A1),8)]:For i=0To 3:s=s+Mid(h,7-2*i,2):Next:[B1]=s:?[Hex2Dec(B1)]
```
[Answer]
# [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) assembly, 6 DECLEs = 8 bytes
This code is intended to be run on an [Intellivision](https://en.wikipedia.org/wiki/Intellivision).
A CP-1610 opcode is encoded with a 10-bit value, known as a 'DECLE'. This function is 6 DECLEs long, starting at $480C and ending at $4811.
The CP-1610 has 16-bit registers, so we're using two of them (R0 and R1) to store a 32-bit value.
```
ROMW 10 ; use 10-bit ROM
ORG $4800 ; start program at address $4800
;; example call
4800 0001 SDBD ; load 0xDEAD into R0
4801 02B8 00AD 00DE MVII #$DEAD, R0
4804 0001 SDBD ; load 0xBEEF into R1
4805 02B9 00EF 00BE MVII #$BEEF, R1
4808 0004 0148 000C CALL swap32 ; call our function
480B 0017 DECR PC ; loop forever
;; swap32 function
swap32 PROC
480C 0040 SWAP R0 ; 16-bit SWAP of R0
480D 0041 SWAP R1 ; 16-bit SWAP of R1
480E 01C1 XORR R0, R1 ; exchange R0 and R1
480F 01C8 XORR R1, R0 ; using 3 consecutive eXclusive OR
4810 01C1 XORR R0, R1
4811 00AF JR R5 ; return
ENDP
```
### Execution dump
```
R0 R1 R2 R3 R4 R5 R6 R7 CPU flags instruction
------------------------------------------------------------------
0000 4800 0000 0000 01FE 1041 02F1 4800 ------iq SDBD
0000 4800 0000 0000 01FE 1041 02F1 4801 -----D-q MVII #$DEAD,R0
DEAD 4800 0000 0000 01FE 1041 02F1 4804 ------iq SDBD
DEAD 4800 0000 0000 01FE 1041 02F1 4805 -----D-q MVII #$BEEF,R1
[DEAD BEEF]0000 0000 01FE 1041 02F1 4808 ------iq JSR R5,$480C
DEAD BEEF 0000 0000 01FE 480B 02F1 480C ------iq SWAP R0
ADDE BEEF 0000 0000 01FE 480B 02F1 480D S------q SWAP R1
ADDE EFBE 0000 0000 01FE 480B 02F1 480E S------q XORR R0,R1
ADDE 4260 0000 0000 01FE 480B 02F1 480F ------iq XORR R1,R0
EFBE 4260 0000 0000 01FE 480B 02F1 4810 S-----iq XORR R0,R1
[EFBE ADDE]0000 0000 01FE 480B 02F1 4811 S-----iq MOVR R5,R7
EFBE ADDE 0000 0000 01FE 480B 02F1 480B ------iq DECR R7
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 10 bytes
```
@swapbytes
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en99@huDyxIKmyJLX4f6JtaWZeibGRhomRpjVXmkai5n8A "Octave – Try It Online")
This may be the first time that Octave has the exact same score as its golfing derivative, MATL. Of course, in this case, it's Octave that has the built-in, rather than MATL, making it a lot easier.
Defines a handle to the built-in `swapbytes`, which takes any data type, swaps the endianness and outputs the result. In this case, the input is a 32-bit unsigned integer.
[Answer]
# C#, ~~44~~ 36 bytes
```
n=>n>>24|n>>8&65280|n&65280<<8|n<<24
```
[Try it online!](https://tio.run/##jY7NCoJAFIXXzlNcXISCyWQWkqMboVWtCmo7jkMM2JWcMQr12c2MoGWb8wOHjyP0XFS1HIZGK7zA4amNvMbkt/k7hbeYEFFyreEotcmm1BJLG26UgG2DgjUKjQdvTUFCApikmKZB2I0azdarIKIdfpyxqEPGgnCkfhn3ShWw5wodl1gj2soq1FUp/VOtjBwvSMdu6eYc9bYH0qEPzvNciKJw3fiPNV3QgC5pOK170g/DCw)
This was originally based on [Polynomial's C# answer](https://codegolf.stackexchange.com/a/149061/16385), who suggested I post a new answer with my improvements on it, but the approach taken [in Arnauld's JavaScript answer](https://codegolf.stackexchange.com/a/149058/16385) turned out to be even shorter in C#.
[Answer]
# [R](https://www.r-project.org/), 86 bytes
I thought there was already an answer (or two) in R for this question, but I must have been mistaken or they had the same issues that I had with R not doing signed ints. That issue took out any builtins that could have helped. I tried the 256 base conversion, but it ended up being to long, but I think there is still room for someone smarter than me to do that. Then I ended up with the following which it a base 2 conversion swapping the order in a recursive function.
```
f=function(x,y=0,i=31)'if'(i+1,f(x-(2^i*z),y+(2^((3-i%/%8)*8+i%%8)*(z=2^i<=x)),i-1),y)
```
[Try it online!](https://tio.run/##VY9LbsMgEIb3PUU2VpgYKzAPGKRwlW4qIbFJpaqRnFzexTi1EjYDfP8Dfpal5HK7fv3W76uZ7T07WzN5ONZyNHX0tph5MvhZTw@w97HtjKGpDudB4aRjHdZpHrkpLnkGsHXyTQhLMQ4O@8r54D6K8e9XPsQY0YdGGOGVRMeByUVcTajwgtBzZKXA2lmbTQgbY@dSJEXuZUFVkuCTERIiSWtsbM@Hzbf2UCRJqCIJtixElJbH6/P24M7@azvBIOSVni5MnELEmPqntkOSN5Zk@QM "R – Try It Online")
```
f=function(x,y=0,i=31) # set up the function and initial values
'if'(i+1, # test for i >= 0
f( # recursively call the function
x-(2^i*z), # remove 2^i from x when 2^i <= x
y+(2^ # add to y 2 to the power of
((3-i%/%8)*8+i%%8) # calc to swap the order of the bytes
*(z=2^i<=x)), # when 2^i <= x
i-1), # decrement i
y) # return y
```
[Answer]
# [R](https://www.r-project.org/), 41 bytes
```
function(n)n%/%256^(0:3)%%256%*%256^(3:0)
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/TyNPM09VX9XI1CxOw8DKWFMVxFTVgggYWxlo/k/TMDSy0PwPAA "R – Try It Online")
[Verify all test cases!](https://tio.run/##JchJCgIxEEDRq7gJJFJipYakqvEsgjQEBImNw8LTx4iLD5/3GG13Ooz27uvreu@xpx6OgbScIy6cwm/D/g@8YBrPy7bdPnGNCBmEIJPNipjwlGKmrgQVpUyoBFxZnUzVQRC9spHgXCrK2XgquXip5JqgpfEF)
Uses a base-256 conversion as MickyT suggested [here](https://codegolf.stackexchange.com/a/149297/67312). R does not have unsigned 32-bit integers, nor does it have 64-bit integers. This prevents us from using bitwise operations but this approach (and likely MickyT's) is probably still shorter since R's bitwise operators are quite verbose.
Utilizes number 4 of [this tip](https://codegolf.stackexchange.com/a/138046/67312), taking into account that we're never getting a number as large as `256^4`.
`n%/%256^(0:3)%%256` extracts the bytes, and `%*%`, the matrix product, is the dot product in this situation, with `256^(3:0)` effecting the reversed order of bytes. `%*%` will return a 1x1 `matrix` containing the endian-reversed value.
[Answer]
# ARM machine language Linux, 8 bytes
```
0: e6bf0f30 rev r0, r0
4: e12fff1e bx lr
```
To try this yourself, compile and run the following on a Raspberry Pi or Android device running GNUroot
```
#include<stdio.h>
#define f(x) ((unsigned int(*)(unsigned int))"0\xf\xbf\xe6\x1e\xff/\xe1")(x)
int main(){
printf( "%u %u\n", 0, f(0) );
printf( "%u %u\n", 1, f(1) );
printf( "%u %u\n", 42, f(42) );
printf( "%u %u\n", 128, f(128) );
printf( "%u %u\n", 16885952, f(16885952) );
printf( "%u %u\n", 704643072, f(704643072) );
printf( "%u %u\n", 3735928559U, f(3735928559U) );
printf( "%u %u\n", 4009738240U, f(4009738240U) );
printf( "%u %u\n", 4026531839U, f(4026531839U) );
printf( "%u %u\n", 4294967295U, f(4294967295U) );
}
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 21 bytes
```
$_=unpack V,pack N,$_
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rY0ryAxOVshTAdM@emoxP//b2hmbm5uZGj2L7@gJDM/r/i/bgEA "Perl 5 – Try It Online")
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 72+31=103 bytes
```
m=>BitConverter.ToUInt32(BitConverter.GetBytes(m).Reverse().ToArray(),0)
```
[Try it online!](https://tio.run/##jZFfS8MwFMWfzafIYwuzpDf/qR04UREUxCk@ly5IYEu1ySZj7LPXWDfm3vISuJfzyzknaf1l2/VmWHvrPvB864NZVej/VDxa91Whdtl4j593yIcm2BbfrV17tbYuTPDvOcXz7@bz1i1s45yJyhoPq3o6s@GmcxvTB9MXr93bgwsUsrPtvQmzbTA@W@XFi4lLb7I8aq/7vtlm@YTkQ4WOrpvOLvBTY12Wox26iLf4bmmK994GE3Oa7DxFRnJc15jkVYK2HLWlkFJCKZIQBiMjCROMEglpPqBGCkommaKCqUQsKqPLyDJCtKQKWGI1oRTX/C8tBQpAeayZxJ7KjcZpHamkXIPiXB/iAgCPkVnas57ajV9ybJ7GguC0VPTgDJppIUHqxA/9k2t@RsexQnu0H34A "C# (.NET Core) – Try It Online")
+31 for `using System;using System.Linq;`
I was hoping to use `Array.Reverse` inline, but it wasn't to be (see alternative below).
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 87+13=100 bytes
```
m=>{var a=BitConverter.GetBytes(m);Array.Reverse(a);return BitConverter.ToUInt32(a,0);}
```
[Try it online!](https://tio.run/##jZFRa8MgFIWf56/wMYGuJFeNSpbCOrYx2KCsG3uWVIbQmqGmo5T@9sylLaVvvgji@Tzn3Nv627Zzeui9sd94ufNBb2rUrpX3eLFHPqhgWvzU2/auNzZM8P85w8tf9fNoV0ZZq6OywcOmme23ymHVzE146OxWu6Dd9FmH@S5on23y@t45tZu@6/jkdaby2unQO4uvgI/u88UGApmaFHl9GGp0DrHtzAq/KWOzHO3RTUR8t9bTL2eCfjVWZ9ehsiLHTYPjJwnactSWFeccyioJoTAyvKAVJQWHNB8QIwUl5VSQiopELCqjy8jSopCcCKCJ1SohmGTHtAQIAGGxZhJ7KTcap3UknDAJgjF5igsALEamaWO9tBtXcm6exkLFSCnIyRkklRUHLhMXepRLdkXHa40O6DD8AQ "C# (.NET Core) – Try It Online")
+13 for `using System;`
This solution care of @JeppeStigNielsen; removing the restriction of having everything inline saved 3 bytes.
[Answer]
# [REXX](http://www.rexx.org/), 42 bytes
```
say c2d(left(reverse(d2c(arg(1))),4,'0'x))
```
[Try it online!](https://tio.run/##K0qtqPj/vzixUiHZKEUjJzWtRKMotSy1qDhVI8UoWSOxKF3DUFNTU8dER91AvUJT8////@YGJmYmxgbmRgA "Rexx (Regina) – Try It Online")
Ungolfed:
```
n=arg(1) -- take n as argument
n=d2c(n) -- convert from decimal to character (bytes)
n=reverse(n) -- reverse characters
n=left(n,4,'0'x) -- extend to four bytes, padding with zeros
n=c2d(n) -- convert from bytes to decimal again
say n -- output result
```
[Answer]
## Swift, 28 bytes
```
{(n:UInt32)in n.byteSwapped}
```
[Answer]
# [Perl 5](https://www.perl.org/), 27 bytes
```
say hex unpack H8,pack I,<>
```
[Try it online!](https://tio.run/##K0gtyjH9/784sVIhI7VCoTSvIDE5W8HDQgdMe@rY2P3/b2JkaWJpZm5kafovv6AkMz@v@L@ur6megaEBAA "Perl 5 – Try It Online")
] |
[Question]
[
I'm reproducing the second part of the first day of Advent of Code, with [permission from the creator.](https://twitter.com/ericwastl/status/699455417768923137)
Santa is trying to deliver presents in a large apartment building, but he can't find the right floor - the directions he got are a little confusing. He starts on the ground floor (floor 0) and then follows the instructions one character at a time.
An opening parenthesis, `(`, means he should go up one floor, and a closing parenthesis, `)`, means he should go down one floor.
The apartment building is very tall, and the basement is very deep; he will never find the top or bottom floors.
Given a set of instructions, find the position of the first character that causes him to enter the basement (floor -1).
As examples:
input `)` causes him to enter the basement at character position 1.
input `()())` causes him to enter the basement at character position 5.
A long input is given [here](http://pastebin.com/Hu9qVf7b) that should yield the solution 1797.
This is code golf, so the shortest solution wins!
[Answer]
# Jelly, ~~8~~ 7 bytes
```
O-*+\i-
```
*Thanks to @Sp3000 for golfing off 1 byte!*
[Try it online!](http://jelly.tryitonline.net/#code=Ty0qK1xpLQ&input=&args=IigpKCkoKCkoKSgpKCgpKCkoKCgpKCgoKSkpKCgoKSgoKCgoKSgpKCgoKCgpKSkoKSgoKCgoKSkoKCgoKCgoKCkoKCgoKCgoKCgoKSgoKCgpKSgoKSgpKCgpKCgoKSgpKCgpKCgpKSgoKSgoKCgoKSgoKCkoKSgpKCgoKCgpKSgoKCgoKCgpKCgpKCgoKCkoKSkoKCkoKCgoKCkpKSgpKSgoKSkoKCkoKCkoKSkpKSkpKSkpKCgoKCgoKCgoKCgoKCkoKSkoKSgpKSgpKSgoKSkpKSgoKCgpKCkoKSgoKCgoKSgoKCgpKCgpKCgpKCkoKCkoKCkoKSgoKSgoKCgoKCgoKSkoKCkpKCgpKSgpKSkpKCgoKSgpKSgpKCgoKCgpKCkoKCgpKSkoKCgoKSgpKCkoKSkpKSgoKSkpKSgoKCgoKSkoKCgoKSgpKSgoKSkoKCkpKSgoKSgoKCgoKSgpKSkpKCkpKCgoKSgoKSkoKCgoKSgoKCgoKSgoKCkoKCkpKCkpKSkoKCgpKSkoKSgpKCgpKCgpKSkpKSgoKCgoKCgoKCkoKSkoKCgoKCkoKSgoKCgoKSgoKSgpKSgoKCgoKCkoKCkoKSkoKSkpKCkpKCgoKCkpKSgpKCgpKCgpKCgpKCgoKCgpKCgpKSgoKSkpKCgoKCgoKSgpKCgpKCkoKSgoKSgoKCgpKSgpKSgoKCgpKCkoKCkoKSkpKCgoKCkoKSgoKCgpKSgpKSgoKSgoKSkoKSkoKSgpKCgpKSgpKCkoKSgoKCkoKCgoKSgoKSkoKCgpKCkoKCgpKSgpKSkoKCgpKCkpKSgoKCkoKSgpKSgoKCgoKSgoKSgpKCgpKCgoKCkpKSgpKCgpKSkpKSgoKCkoKCgoKSgpKCkpKSgoKSgoKCgpKSgpKCgpKCgoKSgpKSgoKSgoKSgpKCgpKCkpKCgpKSgpKCgoKCkoKCkoKSkoKSgoKCgoKSgoKCkpKSkpKCkpKCkpKSgoKCkoKSgpKCkoKCkpKCkoKSkoKSgpKCkoKCgoKCkpKSkpKCgpKCgoKCkoKSgoKCgoKCgoKSkoKSkpKCkoKCgoKCkoKCgpKSgpKCgpKCkpKCgpKSgpKSkoKCkoKCkoKSkoKCgoKCgoKCkpKSkoKCgoKSkpKCkpKSkpKSgpKSkoKSkoKCgpKSgoKSgpKCgoKSkoKSgpKSgpKSkpKSgpKCgoKSgpKCkpKCgpKSgoKCkpKCgoKCgpKCkpKCkpKCkoKSgpKCgoKCkpKSgpKSkpKCkoKSkpKCkpKCgpKCkoKSgoKSgoKCgoKCgpKCkpKSgpKSgpKSkoKSgoKCgpKCgoKCkpKCgoKCgpKCkoKSgoKSkpKCkpKCkoKSkpKSkoKSkoKSkpKCkpKCgoKSkoKSgpKSgoKCgoKCkpKCkpKCgoKSkoKSkpKSgoKCgpKSgoKCgpKSgoKCgoKCkoKCgoKCgpKSgoKSgoKSgpKSgpKSgoKSgoKSkoKCkpKSgoKSgoKCgoKSkpKCkpKCkpKSkpKCkpKSkoKCgpKCgpKSkpKSgpKSkpKCgoKCgoKSkoKSkpKCkpKCkpKSkpKCkpKSkpKCgoKCkpKSgpKSkpKSgoKCkpKSgoKCkoKCgpKCgpKCgpKSgpKCkpKSkoKCkoKSgpKCgpKSgpKSkoKSgoKCgoKSkpKSkpKSkoKCkpKCgpKCgoKSgpKSkoKCkpKSgoKSkpKCgpKCgoKSkpKSkpKSgpKCkoKCgoKCkoKSkpKCkoKSkoKSkpKSkpKSgpKCkoKSkpKCgpKCgoKSkoKCkpKSgoKCkoKSgpKCkpKCkoKCgoKSgoKCgoKSkoKSkpKSgpKCgoKCgpKCgpKSkpKSkpKCkpKSkoKSgpKCkpKCkpKSgoKSkpKSkoKCkoKSkoKSkpKSkpKSgoKCkpKSkpKSkpKCkpKCkpKSgpKCgoKSkoKSkpKSgoKSgoKCkpKSgpKSkoKCkpKSkpKSgoKSkpKCkoKSkoKSgpKSkoKCgpKCgpKSkoKSgpKCkoKSkpKSkoKSkoKSgpKSkoKSkoKCkpKCkoKSkpKCkpKSgoKCkpKSkpKCkoKSgoKSgpKSkpKSkoKSgpKCkpKSgoKCgoKSkpKCkpKSkpKCgpKCgpKSkpKCgpKCkpKSkoKCgpKSgpKSgoKSkpKCkpKSkpKCkoKSkpKSgpKCkpKCkoKSkpKSkpKSkpKSgpKCkpKSkpKCkpKSkoKCgpKSgoKCkpKSkpKCkpKSkoKCgoKSgpKSkpKSkpKSgoKSkpKCkoKSkpKCgpKSkoKSkpKSkoKSgpKSkpKSkoKSkoKCgoKCkoKSkpKSkpKSkoKSkpKSgpKCkpKSkpKSkpKSgpKSkoKSkpKSkoKSkpKSkpKSgoKSkpKSkpKSkpKSgpKSkpKSkpKSkpKSkpKSkpKCkpKCkpKCgoKSkpKSkpKSkpKSgpKSkoKCgpKSkpKCkpKSkpKSkpKSgpKSgpKCgpKSkpKSkpKCkpKSkpKSgpKCkoKSgpKSgpKCgpKCkoKSgoKSgpKSgoKSkpKCkoKSgpKCgpKCkpKSkoKSkoKSkpKSgpKSkpKSgpKSkpKSkpKSgpKCkoKSgpKCkpKCgpKSgpKSgpKCkpKCkpKSkpKCgpKCkoKSgpKCkpKSkpKCkpKSgpKSgpKSkpKCgoKSgpKSgpKCkpKSkoKSkpKCkpKSkpKCgpKCkpKSkoKSkpKSkpKSkpKCgoKCkpKSgpKCkpKSkpKSkpKSkpKSkpKSkpKSkpKSgoKSkpKCgpKCgoKSkpKCkpKSkoKSkoKCkpKSgoKSgoKSgoKSkpKSkpKCkoKCkpKSgpKSkoKSgpKSkpKSkpKSkpKSkpKCkoKCgpKCkpKCgpKSgpKSgpKCgpKSkpKSkoKSkoKSgpKSgoKCkoKSkpKSkoKCkoKSkpKSkoKSkoKSgoKSkoKSkpKSkpKSkpKSkpKSkpKSkpKSkpKCkpKSgoKSgoKSgpKSkpKSkpKSgpKCkoKCgpKSkoKSkpKSkpKSgoKCkpKSkoKSkpKSkpKSkpKCgoKSkpKCkpKCkoKSkpKCkpKCkoKSkpKCgoKSkpKCkpKSkpKSkpKSkpKSgoKSgpKSgpKSkoKCkpKCgoKSgoKSgpKSkoKCkoKSkoKCkpKSkoKSgpKSgoKSgoKSkoKSgpKSkpKSgpKSkoKSgoKSkpKSkpKSgoKSkpKSkpKSkpKSkoKCkpKSgpKSkpKSkpKSkpKCkpKSkpKSgpKSkpKCgpKSkpKSkoKSkpKSkoKCkpKCkpKSkpKSkpKSkoKSgoKSkpKSkoKSgpKSkpKCkpKCgpKSkoKSgpKSkpKSkpKSkpKSkpKSgpKSgpKCkpKSkpKCkpKSkpKSkoKSkpKSkpKCkpKSkpKCgpKSgoKSgpKCkoKSgoKCkpKCkpKSgpKSgoKSkpKCgoKSkoKSkpKCkpKCkpKCgpKSgoKSgpKSkpKSgpKSkoKCkpKCkoKSgoKCkpKCgpKSkpKCgpKSkpKCkpKSgpKSkpKSkpKSkpKCkoKCgoKCgpKSgpKSkpKCgpKSgpKSkpKSgoKSkpKSgoKCkpKSgpKCgoKCgoKCgpKSkpKSgpKCkpKSgoKSkpKSkpKCkoKCkpKSkpKCgpKCkpKSgpKSkoKSkpKSkpKSkoKCkoKSkoKSkpKSkpKSkpKCkpKSkoKCkpKSgpKSgpKSkoKCkpKCkoKCgpKSgpKSgpKCkpKCkpKCgpKCgpKSkpKSgpKSkpKSkpKCgoKSgpKSgoKSkoKSgpKCgpKCkpKSkoKSgpKSkoKCkpKCgpKSgoKSkpKCkpKSkoKSkpKCgpKSkoKSgpKSkoKCgoKCkpKSkpKCkpKSgoKCkoKSgpKSkpKSgpKSkoKSkpKCkpKSkoKCkpKSgpKSkpKSgoKSkpKSgpKSkoKSkoKSgoKSkpKCkoKSkpKSgpKSkpKSkpKSgpKSkpKCkpKSkoKSgpKSkpKSkpKCgpKSkoKSkoKSkpKSgpKSkoKSgpKCkpKCkpKSkpKSkpKSkpKSkpKCkpKSkoKSkpKCgpKCkpKSkpKCkpKSkoKSkoKSgoKSkpKSgpKSkpKSkpKSkpKSkpKSkpKSkoKSgpKCkpKCkpKSkpKSgpKCkoKSgoKCkoKCkpKSgpKCkoKCkpKCkoKSkoKSkpKCkpKSkpKCkoKSgpKSkpKSkpKCgoKSkpKSkpKSkpKCkoKCkoKCkoKCgoKCgoKSgpKCgoKSgpKSkpKSkpKSkpKSkoKSkpKCkpKSkpKSgoKCkpKCkpKCgpKSkoKSkpKSgpKSkpKSkoKSkoKSgpKCkpKCgpKSkpKCkpKSkoKSgpKSgpKSgoKSkpKSkpKSkoKSgpKCgpKSkpKCkpKSgpKSkpKCkpKCkpKCkpKCkpKSkpKSkpKSgpKSkoKCkoKSgpKCkpKCkpKCkpKSkoKCkpKCkpKSkpKSkpKCkoKSgpKSgpKSkpKSgpKSkpKCkpKCkoKCkpKCkpKSkpKSkpKCkoKSkoKSkpKCgpKCkoKCkpKCkpKSkoKSgoKSgoKCkoKSgoKCkoKSgoKCgoKCkpKCgpKCkpKCkpKSgoKSkoKSkpKCgpKSkpKCgpKSkpKSkpKSgpKSkoKSkpKCgoKSkpKCkpKSgpKSkpKSkpKSkoKSkpKSkpKSkpKCgoKSgpKCkpKCgpKSkoKCgoKSkpKCgpKSkpKCkpKSgoKCkpKCgoKCkpKSkoKSgpKSkpKCkpKSkpKSgoKCkpKSkpKSgoKSkoKSkoKCgoKCgoKSkoKSkoKSgoKSkpKCkoKCkoKCgpKCkpKSkoKCgpKSgpKCgpKCgpKSkpKSgoKSkoKCkoKSgpKSgoKSkpKSgpKSgoKCkoKCgoKSkoKSkpKSgoKCgpKCkpKCkpKSkoKSkoKSgoKSkoKSkoKCgoKCkoKSkpKSkoKSkoKCgpKSkoKSgpKCkoKSgoKSkoKCgoKCgoKCkoKSgpKCgoKSkpKCkpKCgpKCkpKSkoKCkpKCkpKCgoKCgpKCkoKCkpKSkpKCkoKCgpKSkpKCgoKSkoKSkpKCkoKCgoKSkpKCkpKSkoKSkpKCgoKSgoKSkpKCgpKSgoKSgoKCgoKSkoKCgoKCkoKSgoKSgpKSkoKCgoKSkoKCkpKSkpKCgoKCgpKCgpKSkoKCkpKSkpKSgoKCkpKSgoKSkpKCgoKSgoKCgpKCgpKSkoKCkoKCkoKCgpKCgpKSgoKSgoKSgoKSgoKSgpKCgoKSkpKCkpKCgoKCkpKCgpKCgpKSkpKSgoKSkpKCkoKSkpKCgpKSkpKCgpKSgpKCgoKCkpKCgpKSkoKSgoKCgoKSgpKSkpKSgpKSgoKSkpKSkoKCgpKSgpKCgoKCgpKCgoKCkpKSgpKSgpKSgoKCgpKSkoKSgpKSgoKCkpKCgpKSgpKSgoKSkoKSgoKSkoKSgoKSgpKCgoKCgoKCkoKSkpKSkoKSgpKCgoKCkoKSkpKSkoKSgpKSgpKCgoKCkoKCkpKSgoKSgoKSgpKSgoKSgoKSkpKSkoKCgoKCgpKCgoKCkpKCkpKSkpKSgoKCgoKCkoKCgpKCkoKCgpKSgpKSgoKCgoKCgpKCgpKSgoKSgpKCgoKSgpKCkoKSgpKCkoKSgoKSgpKSkoKSgoKCgpKSkoKSkpKCgoKCgoKCgpKSgoKCgpKCgoKSgpKSgpKCgoKCgpKSgoKCgpKCgpKSkpKCkoKCgpKCgpKCkoKSgoKCkpKCgoKSgpKSgpKSkoKSkpKCkpKSkoKSkoKCgoKCgoKSkpKCgpKCgpKCkoKSkpKCgpKCgoKSgoKSgoKSkpKCkoKCgpKCgoKCkoKSgpKCgoKSkoKCgoKCgpKSgpKCgpKSkoKSkoKSkoKCgpKCgpKSkpKCgpKCgpKCkpKCgpKSgoKCkpKCkpKCkpKCgoKCkoKSgpKCgpKSkpKSkoKSkoKCkpKSkpKSkoKSkpKSkpKSgpKSgoKCkoKSgpKSkoKCgpKCgoKCgoKCkpKSgoKCgpKCgoKCgpKCkoKSgoKCgpKSkoKSkoKSgoKSgpKCgoKCkoKCgpKCkoKSgpKCkpKCkoKSkpKCkoKSgpKCgpKCgpKSgoKCkpKSkpKCgpKSkoKSkpKSkpKSkoKSgoKSgpKCgoKCgoKSkoKSgoKSgoKCgoKCkoKCgpKCgpKCkoKSkoKCkoKCgoKCgoKCgpKCgoKCgoKCkpKCkoKCgoKCkoKSgpKCgoKSgoKCkoKCgoKCgoKSkpKCgoKSkpKSkpKSkoKSkoKSkpKCgoKSgoKSkpKCkoKCkoKSgoKSgoKCkpKCgoKSgpKCgoKCgoKCgoKCgoKCkoKSkoKCkoKSgpKSkoKCgoKCkoKCgoKCgoKSkoKCkpKSgpKSgoKSgpKCgoKSgpKSkoKSgoKCgoKCgoKSgoKCkoKSgoKCgoKCgpKCgoKCkpKSkoKCgpKSkpKCgoKCgoKCgoKSgpKCgoKCgoKCgpKSgoKCgoKCkoKSkoKCgoKSkoKCgpKSgpKCgoKCgpKCgoKCgoKCgpKCgpKCgoKCkoKCgoKCgoKSgoKCgpKCgoKCgoKCgoKCgoKSgpKCgoKSgpKCgpKSkoKCgpKCkoKCgoKSgoKCgpKSkpKCgoKCgpKSgpKCgpKCgoKCkpKCkoKCkoKCgoKSkoKCgoKCgoKCgoKCgpKSkoKSkpKSgoKCgoKCgpKSgoKCkoKSgoKCgoKSgpKSgpKSgoKCgoKSgpKSkoKCgpKSgoKCgoKCkoKCkoKSgoKSgpKCkoKCgpKSgoKSgoKCkoKSgoKCgoKSgoKCgoKCkoKCgpKCgpKCgoKCgpKCkpKCgoKCgoKCkoKCgoKCgpKCkoKCkoKCkoKCgoKCkpKSkoKCkpKCgpKSgoKSkoKCgoKCkoKCkoKSgoKCgoKSgoKCgoKSgpKCgoKSgoKCgoKCgpKSkpKCgoKCgoKSkpKSkoKSkpKCgpKCgoKCgoKCgoKSgoKCgpKSgpKSgoKCgpKSkpKCgpKCgpKCgoKSkoKCgoKSgoKCkoKSgoKCgoKCkoKCgpKCkoKCgoKSkoKSgoKSkpKCgoKCgoKCgpKSgoKSgoKCgoKCkpKSgoKCkoKCgpKCgoKSkpKCgpKSgpKSgoKCgoKSgoKCgoKSkoKSgoKSkpKCgoKCkoKCgoKCgoKCgoKCgoKCgoKSkoKCgoKCgoKCgoKSkpKCgoKCkoKCkoKSgpKCkoKCgoKCgoKSgoKCkpKCkoKCgoKCgoKCgpKCgpKSgoKCgoKCgoKCgoKCkoKCkoKCgpKSgpKCgoKSgpKCgpKCgpKCkoKCgoKCkoKSgoKCkpKCgpKCgoKSgpKCgpKCkoKCgoKCkoKCgoKCgoKCkpKSkoKCgoKCkpKCgpKSgpKCgoKCkoKSgoKCkoKSgoKCgoKSgoKCkoKCgoKSgoKCkpKCgoKCkoKSgpKCgoKCgpKCgoKCgpKCkoKCkoKCkoKCgoKCgoKCgpKSgoKSgoKCgoKCkpKCgpKCkpKCgoKCgoKCgpKCkpKCkoKCkoKCgoKCkoKCgpKSgoKSgpKCkpKCgoKCgpKCkoKCgoKSgoKCgoKSkoKCkpKCgpKCkoKCgoKCgoKCgoKSgpKSkoKSgoKCgpKSgoKSgoKSgoKCgoKCgpKSgoKSgpKCkpKCgpKSkoKSgpKCgoKCkoKCgoKSgoKCkpKCgpKCgoKCgoKCgpKCgpKCgpKCgoKSgoKCgoKCkoKCkoKCgpKCgpKCgoKCgoKCkoKCgoKCkoKSgoKCgoKSgoKCgpKCgoKSkoKCkoKCkoKCgpKCkoKCgoKCkoKSgoKSkoKSgoKSkoKCgoKSkoKCkoKCgoKCgoKCgpKCkpKCgoKCgoKCgoKCkoKCkpKCkoKCgoKCkpKSkoKSkpKCkoKSgoKCgoKCkoKSgoKCgoKCgpKSgoKSgpKCgoKCkoKCkoKCgoKCgoKCkoKCkoKCgoKCgoKCkpKCgpKSgoKCgoKSgoKCkoKCkpKSkoKCgoKCkoKSgpKSgoKSkpKCgoKSgpKSgoKCgoKSgoKCgoKCkoKCkoKCkpKCgpKCgpKCkoKSkoKCgoKCgpKCgoKCgoKSgoKCgoKSgpKCgoKCgoKCgoKSgpKSkoKCkoKCgoKCgoKSkoKCgoKCkpKCkoKCkoKCgoKSgpKCkoKCgoKSgoKSgoKSkoKCkpKCgoKCgoKSgoKSkoKSkoKCgoKCkpKCgpKSgoKSgoKCgpKCgoKCgoKSkoKCgoKCkpKCkpKCgoKSgoKCgoKCgoKSgoKCgpKSgoKSgoKSkpKCgoKCgoKCgoKCkoKCgpKCgoKSgpKCgpKCgoKCgpKSgoKCgpKCgoKSkoKCgoKCkpKCgpKCgoKCkoKCgoKSgoKSgoKCgoKSgoKCgpKSgoKSgoKCgpKCgpKCkoKCkoKCkoKCgpKCkoKCkoKSkoKCkpKCkpKCgoKSgoKSgoKCgpKCgoKCkoKCgoKSgpKCgoKCgoKCgoKCkoKCgoKCgoKCgoKSgpKCgoKCkoKCgoKSgpKSgoKCgoKSgoKSgoKCgpKCkoKSgoKCkpKCgoKCgoKCgoKCgpKSgoKSgoKCgpKCgoKCgpKCkpKCgoKCgpKCgoKSkpKCgoKCkoKSgpKCgoKCgoKSgoKCgoKCgoKSkoKCgpKCkpKCgpKCgoKCgpKSgoKCgoKCgoKCkpKCgpKCgoKSgoKCgoKCgoKCgoKSgpKCgoKSgoKCkoKSkpKCgoKCkoKSkoKSgpKSgpKCgoKCkoKSkoKSgpKCgpKCgpKCgoKCgoKCgpKSgpKSkoKCkpKCkpKSgpKSgpKCkoKCgpKSgpKCgoKSgoKCgoKSgoKCkoKCgpKSgoKCgoKCkoKCgoKCgoKSgoKSkpKSgoKSkpKCkpKCgoKCkpKSgoKCkoKSgoKSgoKCgpKSkoKCgoKCkpKCkoKCgoKSkpKSkoKSgoKSgoKSkoKSgoKCgoKCkpKCgpKCgpKCgpKSgoKSkoKSgoKCkoKSgpKCgoKCgpKCgpKSgoKCkoKSkoKCkoKCkpKSgoKSgoKSgoKSgpKCgpKSgpKCkoKCkoKCgpKSgpKCgoKSkpKSkoKSkpKCgoKSgoKSgpKCkoKSgoKCkoKSkoKCkpKSgpKSgpKCgpKCgoKCgoKCgoKCkpKCkpKCgoKSgoKCkoKCgoKCgoKSkoKSgoKCgoKSkoKCgoKSkoKCgpKCgpKCkoKSgoKCkpKCgpKCgoKSkoKCgoKSgoKCgoKSgpKCgoKSgoKSgoKCgoKCkpKCkpKSgpKCgoKCgoKCkpKSgoKCkpKCgoKCkoKSkpKCgoKCkpKCgpKSgpKSkoKCgoKCgoKCkpKCgpKSgpKSgpKCgpKSgoKCgoKCkpKSgpKCgoKSkpKCkoKCkoKSgoKCkoKSgpKCkoKSgpKSgoKCgoKCgi)
### How it works
```
O-*+\i- Main link. Input: s (string)
O Ordinal; replace each character with its code point.
This maps "()" to [48, 49].
-* Apply x -> (-1) ** x.
This maps [48, 49] to [1, -1].
+\ Compute the cumulative sum, i.e., the list of partial sums.
i- Find the first index of -1.
```
[Answer]
## Python 2, 44 bytes
```
try:input()
except Exception,e:print e[1][2]
```
This clever solution was found by hallvabo, xsot, mitchs, and whatisgolf on [this problem on Anarchy golf](http://golf.shinh.org/p.rb?Advent%20of%20Code%20Not%20Quite%20Lisp#Python). If any of you want to post it instead, I'll remove this.
The trick is to let Python's parser do the work. The function `input()` tries to evaluate an input string, and throws an error on the first unmatched paren. This error, when caught, has form
```
SyntaxError('unexpected EOF while parsing', ('<string>', 1, 1, ')'))
```
which includes the character number where the error took place.
[Answer]
## Python, ~~79~~ 77 Bytes
```
lambda m:[sum([2*(z<')')-1for z in m][:g])for g in range(len(m)+1)].index(-1)
```
There is probably a better way to do this, but I'm out of ideas.
Also this is my first post on codegolf.
Thanks to @Erwan. for golfing off 2 bytes.
[Answer]
## CJam, 10 bytes
```
0l'_*:~1#)
```
or
```
0l'_*~]1#)
```
or (credits to Dennis)
```
Wl+'_*:~1#
```
[Test it here.](http://cjam.aditsu.net/#code=0l'_*%3A~1%23)&input=()())()()
### Explanation
As A Simmons already noted, `()` is a lucky choice for CJam since those are the decrement/increment operators, respectively. That means if we're starting from zero we're looking for the step at which Santa reaches floor 1.
```
0 e# Push 0, the initial floor.
l e# Read input.
'_* e# Riffle the input string with underscores, which duplicate the top of the stack.
:~ e# Evaluate each character, using a map which wraps the result in an array.
1# e# Find the position of the first 1.
) e# Increment because we're looking for a one-based index.
```
[Answer]
# C, 55 bytes
```
g;main(f){for(;f;g++)f+=81-getchar()*2;printf("%d",g);}
```
Try it [here](http://ideone.com/FowLNx).
Edit: Not sure why I left an unused variable in there...
[Answer]
# Python 3, 59
Saved 3 bytes thanks to grc.
I really dislike doing manual string indexing in Python. It feels so wrong.
```
def f(x):
c=q=0
while-~c:c+=1-(x[q]>'(')*2;q+=1
return q
```
[Answer]
## [Labyrinth](http://github.com/mbuettner/labyrinth), 18 bytes
```
+(+"#(!@
: :
%2_,
```
[Try it online!](http://labyrinth.tryitonline.net/#code=KygrIiMoIUAKOiAgOgolMl8s&input=KCkoKSkpKCgpKSg) This answer was the result of collaborating with @MartinBüttner.
### Explanation
The usual Labyrinth primer (I say "usual", but I actually rewrite this every time):
* Labyrinth is a stack-based 2D language, with execution starting from the first valid char (here the top left). At each junction, where there are two or more possible paths for the instruction pointer to take, the top of the stack is checked to determine where to go next. Negative is turn left, zero is go forward and positive is turn right.
* The stack is bottomless and filled with zeroes, so popping from an empty stack is not an error.
* Digits in the source code don't push the corresponding number – instead, they pop the top of the stack and push `n*10 + <digit>`. This allows the easy building up of large numbers. To start a new number, use `_`, which pushes zero.
This code is a bit weird since, for golfing purposes, the main loop combines two tasks into one. For the first half of the first pass, here's what happens:
```
+(+ Add two zeroes, decrement, add with zero
This leaves -1 on the stack
" NOP at a junction. -1 is negative so we try to turn left, fail, and
turn right instead.
: Duplicate -1
```
Now that the stack has been initialised with a -1 on top, the actual processing can start. Here's what the main loop does.
```
, Read a byte of input
_2% Take modulo 2.
:+ Duplicate and add, i.e. double
( Decrement
This maps "(" -> -1, ")" -> 1
+ Add to running total
" NOP at a junction. Go forward if zero, otherwise turn right.
: Duplicate the top of the stack
```
The last duplicate adds an element to the stack for every iteration we perform. This is important because, when we hit zero and go forward at the NOP, we do:
```
# Push stack depth
( Decrement
! Output as num
@ Terminate
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~12~~ 11 bytes
*1 byte saved using Dennis' idea of computing -1 raised to the input string*
```
1_j^Ys0<f1)
```
[**Try it online!**](http://matl.tryitonline.net/#code=MV9qXllzMDxmMSk&input=KCkoKSgoKSgpKCkoKCkoKSgoKCkoKCgpKSkoKCgpKCgoKCgpKCkoKCgoKCkpKSgpKCgoKCgpKSgoKCgoKCgoKSgoKCgoKCgoKCgpKCgoKCkpKCgpKCkoKCkoKCgpKCkoKCkoKCkpKCgpKCgoKCgpKCgoKSgpKCkoKCgoKCkpKCgoKCgoKCkoKCkoKCgoKSgpKSgoKSgoKCgoKSkpKCkpKCgpKSgoKSgoKSgpKSkpKSkpKSkoKCgoKCgoKCgoKCgoKSgpKSgpKCkpKCkpKCgpKSkpKCgoKCkoKSgpKCgoKCgpKCgoKCkoKCkoKCkoKSgoKSgoKSgpKCgpKCgoKCgoKCgpKSgoKSkoKCkpKCkpKSkoKCgpKCkpKCkoKCgoKCkoKSgoKCkpKSgoKCgpKCkoKSgpKSkpKCgpKSkpKCgoKCgpKSgoKCgpKCkpKCgpKSgoKSkpKCgpKCgoKCgpKCkpKSkoKSkoKCgpKCgpKSgoKCgpKCgoKCgpKCgoKSgoKSkoKSkpKSgoKCkpKSgpKCkoKCkoKCkpKSkpKCgoKCgoKCgoKSgpKSgoKCgoKSgpKCgoKCgpKCgpKCkpKCgoKCgoKSgoKSgpKSgpKSkoKSkoKCgoKSkpKCkoKCkoKCkoKCkoKCgoKCkoKCkpKCgpKSkoKCgoKCgpKCkoKCkoKSgpKCgpKCgoKCkpKCkpKCgoKCkoKSgoKSgpKSkoKCgoKSgpKCgoKCkpKCkpKCgpKCgpKSgpKSgpKCkoKCkpKCkoKSgpKCgoKSgoKCgpKCgpKSgoKCkoKSgoKCkpKCkpKSgoKCkoKSkpKCgoKSgpKCkpKCgoKCgpKCgpKCkoKCkoKCgoKSkpKCkoKCkpKSkpKCgoKSgoKCgpKCkoKSkpKCgpKCgoKCkpKCkoKCkoKCgpKCkpKCgpKCgpKCkoKCkoKSkoKCkpKCkoKCgoKSgoKSgpKSgpKCgoKCgpKCgoKSkpKSkoKSkoKSkpKCgoKSgpKCkoKSgoKSkoKSgpKSgpKCkoKSgoKCgoKSkpKSkoKCkoKCgoKSgpKCgoKCgoKCgpKSgpKSkoKSgoKCgoKSgoKCkpKCkoKCkoKSkoKCkpKCkpKSgoKSgoKSgpKSgoKCgoKCgoKSkpKSgoKCgpKSkoKSkpKSkpKCkpKSgpKSgoKCkpKCgpKCkoKCgpKSgpKCkpKCkpKSkpKCkoKCgpKCkoKSkoKCkpKCgoKSkoKCgoKCkoKSkoKSkoKSgpKCkoKCgoKSkpKCkpKSkoKSgpKSkoKSkoKCkoKSgpKCgpKCgoKCgoKCkoKSkpKCkpKCkpKSgpKCgoKCkoKCgoKSkoKCgoKCkoKSgpKCgpKSkoKSkoKSgpKSkpKSgpKSgpKSkoKSkoKCgpKSgpKCkpKCgoKCgoKSkoKSkoKCgpKSgpKSkpKCgoKCkpKCgoKCkpKCgoKCgoKSgoKCgoKCkpKCgpKCgpKCkpKCkpKCgpKCgpKSgoKSkpKCgpKCgoKCgpKSkoKSkoKSkpKSkoKSkpKSgoKCkoKCkpKSkpKCkpKSkoKCgoKCgpKSgpKSkoKSkoKSkpKSkoKSkpKSkoKCgoKSkpKCkpKSkpKCgoKSkpKCgoKSgoKCkoKCkoKCkpKCkoKSkpKSgoKSgpKCkoKCkpKCkpKSgpKCgoKCgpKSkpKSkpKSgoKSkoKCkoKCgpKCkpKSgoKSkpKCgpKSkoKCkoKCgpKSkpKSkpKCkoKSgoKCgoKSgpKSkoKSgpKSgpKSkpKSkpKCkoKSgpKSkoKCkoKCgpKSgoKSkpKCgoKSgpKCkoKSkoKSgoKCgpKCgoKCgpKSgpKSkpKCkoKCgoKCkoKCkpKSkpKSkoKSkpKSgpKCkoKSkoKSkpKCgpKSkpKSgoKSgpKSgpKSkpKSkpKCgoKSkpKSkpKSkoKSkoKSkpKCkoKCgpKSgpKSkpKCgpKCgoKSkpKCkpKSgoKSkpKSkpKCgpKSkoKSgpKSgpKCkpKSgoKCkoKCkpKSgpKCkoKSgpKSkpKSgpKSgpKCkpKSgpKSgoKSkoKSgpKSkoKSkpKCgoKSkpKSkoKSgpKCgpKCkpKSkpKSgpKCkoKSkpKCgoKCgpKSkoKSkpKSkoKCkoKCkpKSkoKCkoKSkpKSgoKCkpKCkpKCgpKSkoKSkpKSkoKSgpKSkpKCkoKSkoKSgpKSkpKSkpKSkpKCkoKSkpKSkoKSkpKSgoKCkpKCgoKSkpKSkoKSkpKSgoKCgpKCkpKSkpKSkpKCgpKSkoKSgpKSkoKCkpKSgpKSkpKSgpKCkpKSkpKSgpKSgoKCgoKSgpKSkpKSkpKSgpKSkpKCkoKSkpKSkpKSkpKCkpKSgpKSkpKSgpKSkpKSkpKCgpKSkpKSkpKSkpKCkpKSkpKSkpKSkpKSkpKSkoKSkoKSkoKCgpKSkpKSkpKSkpKCkpKSgoKCkpKSkoKSkpKSkpKSkpKCkpKCkoKCkpKSkpKSkoKSkpKSkpKCkoKSgpKCkpKCkoKCkoKSgpKCgpKCkpKCgpKSkoKSgpKCkoKCkoKSkpKSgpKSgpKSkpKCkpKSkpKCkpKSkpKSkpKCkoKSgpKCkoKSkoKCkpKCkpKCkoKSkoKSkpKSkoKCkoKSgpKCkoKSkpKSkoKSkpKCkpKCkpKSkoKCgpKCkpKCkoKSkpKSgpKSkoKSkpKSkoKCkoKSkpKSgpKSkpKSkpKSkoKCgoKSkpKCkoKSkpKSkpKSkpKSkpKSkpKSkpKSkpKCgpKSkoKCkoKCgpKSkoKSkpKSgpKSgoKSkpKCgpKCgpKCgpKSkpKSkoKSgoKSkpKCkpKSgpKCkpKSkpKSkpKSkpKSkoKSgoKCkoKSkoKCkpKCkpKCkoKCkpKSkpKSgpKSgpKCkpKCgoKSgpKSkpKSgoKSgpKSkpKSgpKSgpKCgpKSgpKSkpKSkpKSkpKSkpKSkpKSkpKSkoKSkpKCgpKCgpKCkpKSkpKSkpKCkoKSgoKCkpKSgpKSkpKSkpKCgoKSkpKSgpKSkpKSkpKSkoKCgpKSkoKSkoKSgpKSkoKSkoKSgpKSkoKCgpKSkoKSkpKSkpKSkpKSkpKCgpKCkpKCkpKSgoKSkoKCgpKCgpKCkpKSgoKSgpKSgoKSkpKSgpKCkpKCgpKCgpKSgpKCkpKSkpKCkpKSgpKCgpKSkpKSkpKCgpKSkpKSkpKSkpKSgoKSkpKCkpKSkpKSkpKSkoKSkpKSkpKCkpKSkoKCkpKSkpKSgpKSkpKSgoKSkoKSkpKSkpKSkpKSgpKCgpKSkpKSgpKCkpKSkoKSkoKCkpKSgpKCkpKSkpKSkpKSkpKSkpKCkpKCkoKSkpKSkoKSkpKSkpKSgpKSkpKSkoKSkpKSkoKCkpKCgpKCkoKSgpKCgoKSkoKSkpKCkpKCgpKSkoKCgpKSgpKSkoKSkoKSkoKCkpKCgpKCkpKSkpKCkpKSgoKSkoKSgpKCgoKSkoKCkpKSkoKCkpKSkoKSkpKCkpKSkpKSkpKSkoKSgoKCgoKCkpKCkpKSkoKCkpKCkpKSkpKCgpKSkpKCgoKSkpKCkoKCgoKCgoKCkpKSkpKCkoKSkpKCgpKSkpKSkoKSgoKSkpKSkoKCkoKSkpKCkpKSgpKSkpKSkpKSgoKSgpKSgpKSkpKSkpKSkoKSkpKSgoKSkpKCkpKCkpKSgoKSkoKSgoKCkpKCkpKCkoKSkoKSkoKCkoKCkpKSkpKCkpKSkpKSkoKCgpKCkpKCgpKSgpKCkoKCkoKSkpKSgpKCkpKSgoKSkoKCkpKCgpKSkoKSkpKSgpKSkoKCkpKSgpKCkpKSgoKCgoKSkpKSkoKSkpKCgoKSgpKCkpKSkpKCkpKSgpKSkoKSkpKSgoKSkpKCkpKSkpKCgpKSkpKCkpKSgpKSgpKCgpKSkoKSgpKSkpKCkpKSkpKSkpKCkpKSkoKSkpKSgpKCkpKSkpKSkoKCkpKSgpKSgpKSkpKCkpKSgpKCkoKSkoKSkpKSkpKSkpKSkpKSkoKSkpKSgpKSkoKCkoKSkpKSkoKSkpKSgpKSgpKCgpKSkpKCkpKSkpKSkpKSkpKSkpKSkpKSgpKCkoKSkoKSkpKSkpKCkoKSgpKCgoKSgoKSkpKCkoKSgoKSkoKSgpKSgpKSkoKSkpKSkoKSgpKCkpKSkpKSkoKCgpKSkpKSkpKSkoKSgoKSgoKSgoKCgoKCgpKCkoKCgpKCkpKSkpKSkpKSkpKSgpKSkoKSkpKSkpKCgoKSkoKSkoKCkpKSgpKSkpKCkpKSkpKSgpKSgpKCkoKSkoKCkpKSkoKSkpKSgpKCkpKCkpKCgpKSkpKSkpKSgpKCkoKCkpKSkoKSkpKCkpKSkoKSkoKSkoKSkoKSkpKSkpKSkpKCkpKSgoKSgpKCkoKSkoKSkoKSkpKSgoKSkoKSkpKSkpKSkoKSgpKCkpKCkpKSkpKCkpKSkoKSkoKSgoKSkoKSkpKSkpKSkoKSgpKSgpKSkoKCkoKSgoKSkoKSkpKSgpKCgpKCgoKSgpKCgoKSgpKCgoKCgoKSkoKCkoKSkoKSkpKCgpKSgpKSkoKCkpKSkoKCkpKSkpKSkpKCkpKSgpKSkoKCgpKSkoKSkpKCkpKSkpKSkpKSgpKSkpKSkpKSkoKCgpKCkoKSkoKCkpKSgoKCgpKSkoKCkpKSkoKSkpKCgoKSkoKCgoKSkpKSgpKCkpKSkoKSkpKSkpKCgoKSkpKSkpKCgpKSgpKSgoKCgoKCgpKSgpKSgpKCgpKSkoKSgoKSgoKCkoKSkpKSgoKCkpKCkoKCkoKCkpKSkpKCgpKSgoKSgpKCkpKCgpKSkpKCkpKCgoKSgoKCgpKSgpKSkpKCgoKCkoKSkoKSkpKSgpKSgpKCgpKSgpKSgoKCgoKSgpKSkpKSgpKSgoKCkpKSgpKCkoKSgpKCgpKSgoKCgoKCgoKSgpKCkoKCgpKSkoKSkoKCkoKSkpKSgoKSkoKSkoKCgoKCkoKSgoKSkpKSkoKSgoKCkpKSkoKCgpKSgpKSkoKSgoKCgpKSkoKSkpKSgpKSkoKCgpKCgpKSkoKCkpKCgpKCgoKCgpKSgoKCgoKSgpKCgpKCkpKSgoKCgpKSgoKSkpKSkoKCgoKCkoKCkpKSgoKSkpKSkpKCgoKSkpKCgpKSkoKCgpKCgoKCkoKCkpKSgoKSgoKSgoKCkoKCkpKCgpKCgpKCgpKCgpKCkoKCgpKSkoKSkoKCgoKSkoKCkoKCkpKSkpKCgpKSkoKSgpKSkoKCkpKSkoKCkpKCkoKCgoKSkoKCkpKSgpKCgoKCgpKCkpKSkpKCkpKCgpKSkpKSgoKCkpKCkoKCgoKCkoKCgoKSkpKCkpKCkpKCgoKCkpKSgpKCkpKCgoKSkoKCkpKCkpKCgpKSgpKCgpKSgpKCgpKCkoKCgoKCgoKSgpKSkpKSgpKCkoKCgoKSgpKSkpKSgpKCkpKCkoKCgoKSgoKSkpKCgpKCgpKCkpKCgpKCgpKSkpKSgoKCgoKCkoKCgoKSkoKSkpKSkpKCgoKCgoKSgoKCkoKSgoKCkpKCkpKCgoKCgoKCkoKCkpKCgpKCkoKCgpKCkoKSgpKCkoKSgpKCgpKCkpKSgpKCgoKCkpKSgpKSkoKCgoKCgoKCkpKCgoKCkoKCgpKCkpKCkoKCgoKCkpKCgoKCkoKCkpKSkoKSgoKCkoKCkoKSgpKCgoKSkoKCgpKCkpKCkpKSgpKSkoKSkpKSgpKSgoKCgoKCgpKSkoKCkoKCkoKSgpKSkoKCkoKCgpKCgpKCgpKSkoKSgoKCkoKCgoKSgpKCkoKCgpKSgoKCgoKCkpKCkoKCkpKSgpKSgpKSgoKCkoKCkpKSkoKCkoKCkoKSkoKCkpKCgoKSkoKSkoKSkoKCgoKSgpKCkoKCkpKSkpKSgpKSgoKSkpKSkpKSgpKSkpKSkpKCkpKCgoKSgpKCkpKSgoKCkoKCgoKCgoKSkpKCgoKCkoKCgoKCkoKSgpKCgoKCkpKSgpKSgpKCgpKCkoKCgoKSgoKCkoKSgpKCkoKSkoKSgpKSkoKSgpKCkoKCkoKCkpKCgoKSkpKSkoKCkpKSgpKSkpKSkpKSgpKCgpKCkoKCgoKCgpKSgpKCgpKCgoKCgoKSgoKCkoKCkoKSgpKSgoKSgoKCgoKCgoKCkoKCgoKCgoKSkoKSgoKCgoKSgpKCkoKCgpKCgoKSgoKCgoKCgpKSkoKCgpKSkpKSkpKSgpKSgpKSkoKCgpKCgpKSkoKSgoKSgpKCgpKCgoKSkoKCgpKCkoKCgoKCgoKCgoKCgoKSgpKSgoKSgpKCkpKSgoKCgoKSgoKCgoKCgpKSgoKSkpKCkpKCgpKCkoKCgpKCkpKSgpKCgoKCgoKCgpKCgoKSgpKCgoKCgoKCkoKCgoKSkpKSgoKCkpKSkoKCgoKCgoKCgpKCkoKCgoKCgoKCkpKCgoKCgoKSgpKSgoKCgpKSgoKCkpKCkoKCgoKCkoKCgoKCgoKCkoKCkoKCgoKSgoKCgoKCgpKCgoKCkoKCgoKCgoKCgoKCgpKCkoKCgpKCkoKCkpKSgoKCkoKSgoKCgpKCgoKCkpKSkoKCgoKCkpKCkoKCkoKCgoKSkoKSgoKSgoKCgpKSgoKCgoKCgoKCgoKCkpKSgpKSkpKCgoKCgoKCkpKCgoKSgpKCgoKCgpKCkpKCkpKCgoKCgpKCkpKSgoKCkpKCgoKCgoKSgoKSgpKCgpKCkoKSgoKCkpKCgpKCgoKSgpKCgoKCgpKCgoKCgoKSgoKCkoKCkoKCgoKCkoKSkoKCgoKCgoKSgoKCgoKCkoKSgoKSgoKSgoKCgoKSkpKSgoKSkoKCkpKCgpKSgoKCgoKSgoKSgpKCgoKCgpKCgoKCgpKCkoKCgpKCgoKCgoKCkpKSkoKCgoKCgpKSkpKSgpKSkoKCkoKCgoKCgoKCgpKCgoKCkpKCkpKCgoKCkpKSkoKCkoKCkoKCgpKSgoKCgpKCgoKSgpKCgoKCgoKSgoKCkoKSgoKCgpKSgpKCgpKSkoKCgoKCgoKCkpKCgpKCgoKCgoKSkpKCgoKSgoKCkoKCgpKSkoKCkpKCkpKCgoKCgpKCgoKCgpKSgpKCgpKSkoKCgoKSgoKCgoKCgoKCgoKCgoKCgpKSgoKCgoKCgoKCgpKSkoKCgoKSgoKSgpKCkoKSgoKCgoKCgpKCgoKSkoKSgoKCgoKCgoKCkoKCkpKCgoKCgoKCgoKCgoKSgoKSgoKCkpKCkoKCgpKCkoKCkoKCkoKSgoKCgoKSgpKCgoKSkoKCkoKCgpKCkoKCkoKSgoKCgoKSgoKCgoKCgoKSkpKSgoKCgoKSkoKCkpKCkoKCgoKSgpKCgoKSgpKCgoKCgpKCgoKSgoKCgpKCgoKSkoKCgoKSgpKCkoKCgoKCkoKCgoKCkoKSgoKSgoKSgoKCgoKCgoKCkpKCgpKCgoKCgoKSkoKCkoKSkoKCgoKCgoKCkoKSkoKSgoKSgoKCgoKSgoKCkpKCgpKCkoKSkoKCgoKCkoKSgoKCgpKCgoKCgpKSgoKSkoKCkoKSgoKCgoKCgoKCgpKCkpKSgpKCgoKCkpKCgpKCgpKCgoKCgoKCkpKCgpKCkoKSkoKCkpKSgpKCkoKCgoKSgoKCgpKCgoKSkoKCkoKCgoKCgoKCkoKCkoKCkoKCgpKCgoKCgoKSgoKSgoKCkoKCkoKCgoKCgoKSgoKCgoKSgpKCgoKCgpKCgoKCkoKCgpKSgoKSgoKSgoKCkoKSgoKCgoKSgpKCgpKSgpKCgpKSgoKCgpKSgoKSgoKCgoKCgoKCkoKSkoKCgoKCgoKCgoKSgoKSkoKSgoKCgoKSkpKSgpKSkoKSgpKCgoKCgoKSgpKCgoKCgoKCkpKCgpKCkoKCgoKSgoKSgoKCgoKCgoKSgoKSgoKCgoKCgoKSkoKCkpKCgoKCgpKCgoKSgoKSkpKSgoKCgoKSgpKCkpKCgpKSkoKCgpKCkpKCgoKCgpKCgoKCgoKSgoKSgoKSkoKCkoKCkoKSgpKSgoKCgoKCkoKCgoKCgpKCgoKCgpKCkoKCgoKCgoKCgpKCkpKSgoKSgoKCgoKCgpKSgoKCgoKSkoKSgoKSgoKCgpKCkoKSgoKCgpKCgpKCgpKSgoKSkoKCgoKCgpKCgpKSgpKSgoKCgoKSkoKCkpKCgpKCgoKCkoKCgoKCgpKSgoKCgoKSkoKSkoKCgpKCgoKCgoKCgpKCgoKCkpKCgpKCgpKSkoKCgoKCgoKCgoKSgoKCkoKCgpKCkoKCkoKCgoKCkpKCgoKCkoKCgpKSgoKCgoKSkoKCkoKCgoKSgoKCgpKCgpKCgoKCgpKCgoKCkpKCgpKCgoKCkoKCkoKSgoKSgoKSgoKCkoKSgoKSgpKSgoKSkoKSkoKCgpKCgpKCgoKCkoKCgoKSgoKCgpKCkoKCgoKCgoKCgoKSgoKCgoKCgoKCgpKCkoKCgoKSgoKCgpKCkpKCgoKCgpKCgpKCgoKCkoKSgpKCgoKSkoKCgoKCgoKCgoKCkpKCgpKCgoKCkoKCgoKCkoKSkoKCgoKCkoKCgpKSkoKCgoKSgpKCkoKCgoKCgpKCgoKCgoKCgpKSgoKCkoKSkoKCkoKCgoKCkpKCgoKCgoKCgoKSkoKCkoKCgpKCgoKCgoKCgoKCgpKCkoKCgpKCgoKSgpKSkoKCgoKSgpKSgpKCkpKCkoKCgoKSgpKSgpKCkoKCkoKCkoKCgoKCgoKCkpKCkpKSgoKSkoKSkpKCkpKCkoKSgoKCkpKCkoKCgpKCgoKCgpKCgoKSgoKCkpKCgoKCgoKSgoKCgoKCgpKCgpKSkpKCgpKSkoKSkoKCgoKSkpKCgoKSgpKCgpKCgoKCkpKSgoKCgoKSkoKSgoKCgpKSkpKSgpKCgpKCgpKSgpKCgoKCgoKSkoKCkoKCkoKCkpKCgpKSgpKCgoKSgpKCkoKCgoKCkoKCkpKCgoKSgpKSgoKSgoKSkpKCgpKCgpKCgpKCkoKCkpKCkoKSgoKSgoKCkpKCkoKCgpKSkpKSgpKSkoKCgpKCgpKCkoKSgpKCgoKSgpKSgoKSkpKCkpKCkoKCkoKCgoKCgoKCgoKSkoKSkoKCgpKCgoKSgoKCgoKCgpKSgpKCgoKCgpKSgoKCgpKSgoKCkoKCkoKSgpKCgoKSkoKCkoKCgpKSgoKCgpKCgoKCgpKCkoKCgpKCgpKCgoKCgoKSkoKSkpKCkoKCgoKCgoKSkpKCgoKSkoKCgoKSgpKSkoKCgoKSkoKCkpKCkpKSgoKCgoKCgoKSkoKCkpKCkpKCkoKCkpKCgoKCgoKSkpKCkoKCgpKSkoKSgoKSgpKCgoKSgpKCkoKSgpKCkpKCgoKCgoKA)
```
1_ % number -1
j % take string input
^ % element-wise power. This transforms '(' to 1 and ')' to -1
Ys % cumulative sum
0< % true for negative values
f % find all such values
1) % pick first. Implicit display
```
[Answer]
## Grep+AWK, 51 Bytes
```
grep -o .|awk '/\(/{s++}/)/{s--}s<0{print NR;exit}'
```
The `grep` command places each character on a new line.
[Answer]
## Pyth, 13 bytes
```
f!hsm^_1Cd<zT
```
Explanation
```
- autoassign z = input()
f - First where V returns Truthy.
<zT - z[:T]
m - [V for d in ^]
Cd - ord(d)
^_1 - -1**^
s - sum(^)
!h - not (^+1)
```
[Try it here](http://pyth.herokuapp.com/?code=f!hsm%5E_1Cd%3CzT&input=%28%29%28%29%29&debug=0)
### Old algorithm, 15 bytes
```
f!h-/J<zT\(/J\)
```
Explanation:
```
- autoassign z = input()
f - First where V returns Truthy.
<zT - z[:T]
J - autoassign J = ^
/ \( - ^.count("(")
/J\) - J.count(")")
- - ^-^
!h - not (^+1)
```
[Try it here](http://pyth.herokuapp.com/?code=f!h-%2FJS%3CzT%5C%28%2FJ%5C%29&input=%28%29%28%29%29&debug=0)
Or if allowed to use chars other than `(` and `)`, **9 bytes** (moving pre-processing to input)
```
f!.v+<zT1
```
Explanation
```
- autoassign z = input()
f - First where V returns Truthy.
<zT - z[:T]
+ 1 - ^+"1"
.v - eval(^)
! - not ^
```
[Try it here](http://pyth.herokuapp.com/?code=f!.v%2B%3CzT1&input=hthtt&debug=0)
[Answer]
## JavaScript (ES6), 58 bytes
```
f=(s,t=s)=>s<')'?f(s.replace('()',''),t):t.length-s.length+1
```
Works by recursively removing a pair of matching `()`s until the first character is a `)`. Warning: Don't try this on strings that don't have enough `)`s. Example:
```
((()())()))
((())()))
(()()))
(()))
())
)
```
At this point it sees that 12 characters were deleted in total so that the answer is 13.
[Answer]
# Oracle SQL 11.2, ~~160~~ 159 bytes
```
SELECT MIN(l)FROM(SELECT l,SUM(m)OVER(ORDER BY l)p FROM(SELECT LEVEL l,DECODE(SUBSTR(:1,LEVEL,1),'(',1,-1)m FROM DUAL CONNECT BY LEVEL<=LENGTH(:1)))WHERE p=-1;
```
Un-golfed
```
SELECT MIN(l) -- Keep the min level
FROM(
SELECT l,SUM(m)OVER(ORDER BY l)p -- Sum the () up to the current row
FROM(
SELECT LEVEL l,DECODE(SUBSTR(:1,LEVEL,1),'(',1,-1)m -- ( equal 1 and ) equal -1
FROM DUAL
CONNECT BY LEVEL<= LENGTH(:1)
)
)
WHERE p=-1 -- Keep the rows where the () sum is equal to -1
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~22~~ 21
```
!M`^((\()|(?<-2>.))+
```
[Try it online](http://retina.tryitonline.net/#code=IU1gXigoXCgpfCg_PC0yPi4pKSsK&input=KCgpKCkpKSgpKQ) or [try the big test case.](http://retina.tryitonline.net/#code=IU1gXigoXCgpfCg_PC0yPi4pKSsK&input=KCkoKSgoKSgpKCkoKCkoKSgoKCkoKCgpKSkoKCgpKCgoKCgpKCkoKCgoKCkpKSgpKCgoKCgpKSgoKCgoKCgoKSgoKCgoKCgoKCgpKCgoKCkpKCgpKCkoKCkoKCgpKCkoKCkoKCkpKCgpKCgoKCgpKCgoKSgpKCkoKCgoKCkpKCgoKCgoKCkoKCkoKCgoKSgpKSgoKSgoKCgoKSkpKCkpKCgpKSgoKSgoKSgpKSkpKSkpKSkoKCgoKCgoKCgoKCgoKSgpKSgpKCkpKCkpKCgpKSkpKCgoKCkoKSgpKCgoKCgpKCgoKCkoKCkoKCkoKSgoKSgoKSgpKCgpKCgoKCgoKCgpKSgoKSkoKCkpKCkpKSkoKCgpKCkpKCkoKCgoKCkoKSgoKCkpKSgoKCgpKCkoKSgpKSkpKCgpKSkpKCgoKCgpKSgoKCgpKCkpKCgpKSgoKSkpKCgpKCgoKCgpKCkpKSkoKSkoKCgpKCgpKSgoKCgpKCgoKCgpKCgoKSgoKSkoKSkpKSgoKCkpKSgpKCkoKCkoKCkpKSkpKCgoKCgoKCgoKSgpKSgoKCgoKSgpKCgoKCgpKCgpKCkpKCgoKCgoKSgoKSgpKSgpKSkoKSkoKCgoKSkpKCkoKCkoKCkoKCkoKCgoKCkoKCkpKCgpKSkoKCgoKCgpKCkoKCkoKSgpKCgpKCgoKCkpKCkpKCgoKCkoKSgoKSgpKSkoKCgoKSgpKCgoKCkpKCkpKCgpKCgpKSgpKSgpKCkoKCkpKCkoKSgpKCgoKSgoKCgpKCgpKSgoKCkoKSgoKCkpKCkpKSgoKCkoKSkpKCgoKSgpKCkpKCgoKCgpKCgpKCkoKCkoKCgoKSkpKCkoKCkpKSkpKCgoKSgoKCgpKCkoKSkpKCgpKCgoKCkpKCkoKCkoKCgpKCkpKCgpKCgpKCkoKCkoKSkoKCkpKCkoKCgoKSgoKSgpKSgpKCgoKCgpKCgoKSkpKSkoKSkoKSkpKCgoKSgpKCkoKSgoKSkoKSgpKSgpKCkoKSgoKCgoKSkpKSkoKCkoKCgoKSgpKCgoKCgoKCgpKSgpKSkoKSgoKCgoKSgoKCkpKCkoKCkoKSkoKCkpKCkpKSgoKSgoKSgpKSgoKCgoKCgoKSkpKSgoKCgpKSkoKSkpKSkpKCkpKSgpKSgoKCkpKCgpKCkoKCgpKSgpKCkpKCkpKSkpKCkoKCgpKCkoKSkoKCkpKCgoKSkoKCgoKCkoKSkoKSkoKSgpKCkoKCgoKSkpKCkpKSkoKSgpKSkoKSkoKCkoKSgpKCgpKCgoKCgoKCkoKSkpKCkpKCkpKSgpKCgoKCkoKCgoKSkoKCgoKCkoKSgpKCgpKSkoKSkoKSgpKSkpKSgpKSgpKSkoKSkoKCgpKSgpKCkpKCgoKCgoKSkoKSkoKCgpKSgpKSkpKCgoKCkpKCgoKCkpKCgoKCgoKSgoKCgoKCkpKCgpKCgpKCkpKCkpKCgpKCgpKSgoKSkpKCgpKCgoKCgpKSkoKSkoKSkpKSkoKSkpKSgoKCkoKCkpKSkpKCkpKSkoKCgoKCgpKSgpKSkoKSkoKSkpKSkoKSkpKSkoKCgoKSkpKCkpKSkpKCgoKSkpKCgoKSgoKCkoKCkoKCkpKCkoKSkpKSgoKSgpKCkoKCkpKCkpKSgpKCgoKCgpKSkpKSkpKSgoKSkoKCkoKCgpKCkpKSgoKSkpKCgpKSkoKCkoKCgpKSkpKSkpKCkoKSgoKCgoKSgpKSkoKSgpKSgpKSkpKSkpKCkoKSgpKSkoKCkoKCgpKSgoKSkpKCgoKSgpKCkoKSkoKSgoKCgpKCgoKCgpKSgpKSkpKCkoKCgoKCkoKCkpKSkpKSkoKSkpKSgpKCkoKSkoKSkpKCgpKSkpKSgoKSgpKSgpKSkpKSkpKCgoKSkpKSkpKSkoKSkoKSkpKCkoKCgpKSgpKSkpKCgpKCgoKSkpKCkpKSgoKSkpKSkpKCgpKSkoKSgpKSgpKCkpKSgoKCkoKCkpKSgpKCkoKSgpKSkpKSgpKSgpKCkpKSgpKSgoKSkoKSgpKSkoKSkpKCgoKSkpKSkoKSgpKCgpKCkpKSkpKSgpKCkoKSkpKCgoKCgpKSkoKSkpKSkoKCkoKCkpKSkoKCkoKSkpKSgoKCkpKCkpKCgpKSkoKSkpKSkoKSgpKSkpKCkoKSkoKSgpKSkpKSkpKSkpKCkoKSkpKSkoKSkpKSgoKCkpKCgoKSkpKSkoKSkpKSgoKCgpKCkpKSkpKSkpKCgpKSkoKSgpKSkoKCkpKSgpKSkpKSgpKCkpKSkpKSgpKSgoKCgoKSgpKSkpKSkpKSgpKSkpKCkoKSkpKSkpKSkpKCkpKSgpKSkpKSgpKSkpKSkpKCgpKSkpKSkpKSkpKCkpKSkpKSkpKSkpKSkpKSkoKSkoKSkoKCgpKSkpKSkpKSkpKCkpKSgoKCkpKSkoKSkpKSkpKSkpKCkpKCkoKCkpKSkpKSkoKSkpKSkpKCkoKSgpKCkpKCkoKCkoKSgpKCgpKCkpKCgpKSkoKSgpKCkoKCkoKSkpKSgpKSgpKSkpKCkpKSkpKCkpKSkpKSkpKCkoKSgpKCkoKSkoKCkpKCkpKCkoKSkoKSkpKSkoKCkoKSgpKCkoKSkpKSkoKSkpKCkpKCkpKSkoKCgpKCkpKCkoKSkpKSgpKSkoKSkpKSkoKCkoKSkpKSgpKSkpKSkpKSkoKCgoKSkpKCkoKSkpKSkpKSkpKSkpKSkpKSkpKSkpKCgpKSkoKCkoKCgpKSkoKSkpKSgpKSgoKSkpKCgpKCgpKCgpKSkpKSkoKSgoKSkpKCkpKSgpKCkpKSkpKSkpKSkpKSkoKSgoKCkoKSkoKCkpKCkpKCkoKCkpKSkpKSgpKSgpKCkpKCgoKSgpKSkpKSgoKSgpKSkpKSgpKSgpKCgpKSgpKSkpKSkpKSkpKSkpKSkpKSkpKSkoKSkpKCgpKCgpKCkpKSkpKSkpKCkoKSgoKCkpKSgpKSkpKSkpKCgoKSkpKSgpKSkpKSkpKSkoKCgpKSkoKSkoKSgpKSkoKSkoKSgpKSkoKCgpKSkoKSkpKSkpKSkpKSkpKCgpKCkpKCkpKSgoKSkoKCgpKCgpKCkpKSgoKSgpKSgoKSkpKSgpKCkpKCgpKCgpKSgpKCkpKSkpKCkpKSgpKCgpKSkpKSkpKCgpKSkpKSkpKSkpKSgoKSkpKCkpKSkpKSkpKSkoKSkpKSkpKCkpKSkoKCkpKSkpKSgpKSkpKSgoKSkoKSkpKSkpKSkpKSgpKCgpKSkpKSgpKCkpKSkoKSkoKCkpKSgpKCkpKSkpKSkpKSkpKSkpKCkpKCkoKSkpKSkoKSkpKSkpKSgpKSkpKSkoKSkpKSkoKCkpKCgpKCkoKSgpKCgoKSkoKSkpKCkpKCgpKSkoKCgpKSgpKSkoKSkoKSkoKCkpKCgpKCkpKSkpKCkpKSgoKSkoKSgpKCgoKSkoKCkpKSkoKCkpKSkoKSkpKCkpKSkpKSkpKSkoKSgoKCgoKCkpKCkpKSkoKCkpKCkpKSkpKCgpKSkpKCgoKSkpKCkoKCgoKCgoKCkpKSkpKCkoKSkpKCgpKSkpKSkoKSgoKSkpKSkoKCkoKSkpKCkpKSgpKSkpKSkpKSgoKSgpKSgpKSkpKSkpKSkoKSkpKSgoKSkpKCkpKCkpKSgoKSkoKSgoKCkpKCkpKCkoKSkoKSkoKCkoKCkpKSkpKCkpKSkpKSkoKCgpKCkpKCgpKSgpKCkoKCkoKSkpKSgpKCkpKSgoKSkoKCkpKCgpKSkoKSkpKSgpKSkoKCkpKSgpKCkpKSgoKCgoKSkpKSkoKSkpKCgoKSgpKCkpKSkpKCkpKSgpKSkoKSkpKSgoKSkpKCkpKSkpKCgpKSkpKCkpKSgpKSgpKCgpKSkoKSgpKSkpKCkpKSkpKSkpKCkpKSkoKSkpKSgpKCkpKSkpKSkoKCkpKSgpKSgpKSkpKCkpKSgpKCkoKSkoKSkpKSkpKSkpKSkpKSkoKSkpKSgpKSkoKCkoKSkpKSkoKSkpKSgpKSgpKCgpKSkpKCkpKSkpKSkpKSkpKSkpKSkpKSgpKCkoKSkoKSkpKSkpKCkoKSgpKCgoKSgoKSkpKCkoKSgoKSkoKSgpKSgpKSkoKSkpKSkoKSgpKCkpKSkpKSkoKCgpKSkpKSkpKSkoKSgoKSgoKSgoKCgoKCgpKCkoKCgpKCkpKSkpKSkpKSkpKSgpKSkoKSkpKSkpKCgoKSkoKSkoKCkpKSgpKSkpKCkpKSkpKSgpKSgpKCkoKSkoKCkpKSkoKSkpKSgpKCkpKCkpKCgpKSkpKSkpKSgpKCkoKCkpKSkoKSkpKCkpKSkoKSkoKSkoKSkoKSkpKSkpKSkpKCkpKSgoKSgpKCkoKSkoKSkoKSkpKSgoKSkoKSkpKSkpKSkoKSgpKCkpKCkpKSkpKCkpKSkoKSkoKSgoKSkoKSkpKSkpKSkoKSgpKSgpKSkoKCkoKSgoKSkoKSkpKSgpKCgpKCgoKSgpKCgoKSgpKCgoKCgoKSkoKCkoKSkoKSkpKCgpKSgpKSkoKCkpKSkoKCkpKSkpKSkpKCkpKSgpKSkoKCgpKSkoKSkpKCkpKSkpKSkpKSgpKSkpKSkpKSkoKCgpKCkoKSkoKCkpKSgoKCgpKSkoKCkpKSkoKSkpKCgoKSkoKCgoKSkpKSgpKCkpKSkoKSkpKSkpKCgoKSkpKSkpKCgpKSgpKSgoKCgoKCgpKSgpKSgpKCgpKSkoKSgoKSgoKCkoKSkpKSgoKCkpKCkoKCkoKCkpKSkpKCgpKSgoKSgpKCkpKCgpKSkpKCkpKCgoKSgoKCgpKSgpKSkpKCgoKCkoKSkoKSkpKSgpKSgpKCgpKSgpKSgoKCgoKSgpKSkpKSgpKSgoKCkpKSgpKCkoKSgpKCgpKSgoKCgoKCgoKSgpKCkoKCgpKSkoKSkoKCkoKSkpKSgoKSkoKSkoKCgoKCkoKSgoKSkpKSkoKSgoKCkpKSkoKCgpKSgpKSkoKSgoKCgpKSkoKSkpKSgpKSkoKCgpKCgpKSkoKCkpKCgpKCgoKCgpKSgoKCgoKSgpKCgpKCkpKSgoKCgpKSgoKSkpKSkoKCgoKCkoKCkpKSgoKSkpKSkpKCgoKSkpKCgpKSkoKCgpKCgoKCkoKCkpKSgoKSgoKSgoKCkoKCkpKCgpKCgpKCgpKCgpKCkoKCgpKSkoKSkoKCgoKSkoKCkoKCkpKSkpKCgpKSkoKSgpKSkoKCkpKSkoKCkpKCkoKCgoKSkoKCkpKSgpKCgoKCgpKCkpKSkpKCkpKCgpKSkpKSgoKCkpKCkoKCgoKCkoKCgoKSkpKCkpKCkpKCgoKCkpKSgpKCkpKCgoKSkoKCkpKCkpKCgpKSgpKCgpKSgpKCgpKCkoKCgoKCgoKSgpKSkpKSgpKCkoKCgoKSgpKSkpKSgpKCkpKCkoKCgoKSgoKSkpKCgpKCgpKCkpKCgpKCgpKSkpKSgoKCgoKCkoKCgoKSkoKSkpKSkpKCgoKCgoKSgoKCkoKSgoKCkpKCkpKCgoKCgoKCkoKCkpKCgpKCkoKCgpKCkoKSgpKCkoKSgpKCgpKCkpKSgpKCgoKCkpKSgpKSkoKCgoKCgoKCkpKCgoKCkoKCgpKCkpKCkoKCgoKCkpKCgoKCkoKCkpKSkoKSgoKCkoKCkoKSgpKCgoKSkoKCgpKCkpKCkpKSgpKSkoKSkpKSgpKSgoKCgoKCgpKSkoKCkoKCkoKSgpKSkoKCkoKCgpKCgpKCgpKSkoKSgoKCkoKCgoKSgpKCkoKCgpKSgoKCgoKCkpKCkoKCkpKSgpKSgpKSgoKCkoKCkpKSkoKCkoKCkoKSkoKCkpKCgoKSkoKSkoKSkoKCgoKSgpKCkoKCkpKSkpKSgpKSgoKSkpKSkpKSgpKSkpKSkpKCkpKCgoKSgpKCkpKSgoKCkoKCgoKCgoKSkpKCgoKCkoKCgoKCkoKSgpKCgoKCkpKSgpKSgpKCgpKCkoKCgoKSgoKCkoKSgpKCkoKSkoKSgpKSkoKSgpKCkoKCkoKCkpKCgoKSkpKSkoKCkpKSgpKSkpKSkpKSgpKCgpKCkoKCgoKCgpKSgpKCgpKCgoKCgoKSgoKCkoKCkoKSgpKSgoKSgoKCgoKCgoKCkoKCgoKCgoKSkoKSgoKCgoKSgpKCkoKCgpKCgoKSgoKCgoKCgpKSkoKCgpKSkpKSkpKSgpKSgpKSkoKCgpKCgpKSkoKSgoKSgpKCgpKCgoKSkoKCgpKCkoKCgoKCgoKCgoKCgoKSgpKSgoKSgpKCkpKSgoKCgoKSgoKCgoKCgpKSgoKSkpKCkpKCgpKCkoKCgpKCkpKSgpKCgoKCgoKCgpKCgoKSgpKCgoKCgoKCkoKCgoKSkpKSgoKCkpKSkoKCgoKCgoKCgpKCkoKCgoKCgoKCkpKCgoKCgoKSgpKSgoKCgpKSgoKCkpKCkoKCgoKCkoKCgoKCgoKCkoKCkoKCgoKSgoKCgoKCgpKCgoKCkoKCgoKCgoKCgoKCgpKCkoKCgpKCkoKCkpKSgoKCkoKSgoKCgpKCgoKCkpKSkoKCgoKCkpKCkoKCkoKCgoKSkoKSgoKSgoKCgpKSgoKCgoKCgoKCgoKCkpKSgpKSkpKCgoKCgoKCkpKCgoKSgpKCgoKCgpKCkpKCkpKCgoKCgpKCkpKSgoKCkpKCgoKCgoKSgoKSgpKCgpKCkoKSgoKCkpKCgpKCgoKSgpKCgoKCgpKCgoKCgoKSgoKCkoKCkoKCgoKCkoKSkoKCgoKCgoKSgoKCgoKCkoKSgoKSgoKSgoKCgoKSkpKSgoKSkoKCkpKCgpKSgoKCgoKSgoKSgpKCgoKCgpKCgoKCgpKCkoKCgpKCgoKCgoKCkpKSkoKCgoKCgpKSkpKSgpKSkoKCkoKCgoKCgoKCgpKCgoKCkpKCkpKCgoKCkpKSkoKCkoKCkoKCgpKSgoKCgpKCgoKSgpKCgoKCgoKSgoKCkoKSgoKCgpKSgpKCgpKSkoKCgoKCgoKCkpKCgpKCgoKCgoKSkpKCgoKSgoKCkoKCgpKSkoKCkpKCkpKCgoKCgpKCgoKCgpKSgpKCgpKSkoKCgoKSgoKCgoKCgoKCgoKCgoKCgpKSgoKCgoKCgoKCgpKSkoKCgoKSgoKSgpKCkoKSgoKCgoKCgpKCgoKSkoKSgoKCgoKCgoKCkoKCkpKCgoKCgoKCgoKCgoKSgoKSgoKCkpKCkoKCgpKCkoKCkoKCkoKSgoKCgoKSgpKCgoKSkoKCkoKCgpKCkoKCkoKSgoKCgoKSgoKCgoKCgoKSkpKSgoKCgoKSkoKCkpKCkoKCgoKSgpKCgoKSgpKCgoKCgpKCgoKSgoKCgpKCgoKSkoKCgoKSgpKCkoKCgoKCkoKCgoKCkoKSgoKSgoKSgoKCgoKCgoKCkpKCgpKCgoKCgoKSkoKCkoKSkoKCgoKCgoKCkoKSkoKSgoKSgoKCgoKSgoKCkpKCgpKCkoKSkoKCgoKCkoKSgoKCgpKCgoKCgpKSgoKSkoKCkoKSgoKCgoKCgoKCgpKCkpKSgpKCgoKCkpKCgpKCgpKCgoKCgoKCkpKCgpKCkoKSkoKCkpKSgpKCkoKCgoKSgoKCgpKCgoKSkoKCkoKCgoKCgoKCkoKCkoKCkoKCgpKCgoKCgoKSgoKSgoKCkoKCkoKCgoKCgoKSgoKCgoKSgpKCgoKCgpKCgoKCkoKCgpKSgoKSgoKSgoKCkoKSgoKCgoKSgpKCgpKSgpKCgpKSgoKCgpKSgoKSgoKCgoKCgoKCkoKSkoKCgoKCgoKCgoKSgoKSkoKSgoKCgoKSkpKSgpKSkoKSgpKCgoKCgoKSgpKCgoKCgoKCkpKCgpKCkoKCgoKSgoKSgoKCgoKCgoKSgoKSgoKCgoKCgoKSkoKCkpKCgoKCgpKCgoKSgoKSkpKSgoKCgoKSgpKCkpKCgpKSkoKCgpKCkpKCgoKCgpKCgoKCgoKSgoKSgoKSkoKCkoKCkoKSgpKSgoKCgoKCkoKCgoKCgpKCgoKCgpKCkoKCgoKCgoKCgpKCkpKSgoKSgoKCgoKCgpKSgoKCgoKSkoKSgoKSgoKCgpKCkoKSgoKCgpKCgpKCgpKSgoKSkoKCgoKCgpKCgpKSgpKSgoKCgoKSkoKCkpKCgpKCgoKCkoKCgoKCgpKSgoKCgoKSkoKSkoKCgpKCgoKCgoKCgpKCgoKCkpKCgpKCgpKSkoKCgoKCgoKCgoKSgoKCkoKCgpKCkoKCkoKCgoKCkpKCgoKCkoKCgpKSgoKCgoKSkoKCkoKCgoKSgoKCgpKCgpKCgoKCgpKCgoKCkpKCgpKCgoKCkoKCkoKSgoKSgoKSgoKCkoKSgoKSgpKSgoKSkoKSkoKCgpKCgpKCgoKCkoKCgoKSgoKCgpKCkoKCgoKCgoKCgoKSgoKCgoKCgoKCgpKCkoKCgoKSgoKCgpKCkpKCgoKCgpKCgpKCgoKCkoKSgpKCgoKSkoKCgoKCgoKCgoKCkpKCgpKCgoKCkoKCgoKCkoKSkoKCgoKCkoKCgpKSkoKCgoKSgpKCkoKCgoKCgpKCgoKCgoKCgpKSgoKCkoKSkoKCkoKCgoKCkpKCgoKCgoKCgoKSkoKCkoKCgpKCgoKCgoKCgoKCgpKCkoKCgpKCgoKSgpKSkoKCgoKSgpKSgpKCkpKCkoKCgoKSgpKSgpKCkoKCkoKCkoKCgoKCgoKCkpKCkpKSgoKSkoKSkpKCkpKCkoKSgoKCkpKCkoKCgpKCgoKCgpKCgoKSgoKCkpKCgoKCgoKSgoKCgoKCgpKCgpKSkpKCgpKSkoKSkoKCgoKSkpKCgoKSgpKCgpKCgoKCkpKSgoKCgoKSkoKSgoKCgpKSkpKSgpKCgpKCgpKSgpKCgoKCgoKSkoKCkoKCkoKCkpKCgpKSgpKCgoKSgpKCkoKCgoKCkoKCkpKCgoKSgpKSgoKSgoKSkpKCgpKCgpKCgpKCkoKCkpKCkoKSgoKSgoKCkpKCkoKCgpKSkpKSgpKSkoKCgpKCgpKCkoKSgpKCgoKSgpKSgoKSkpKCkpKCkoKCkoKCgoKCgoKCgoKSkoKSkoKCgpKCgoKSgoKCgoKCgpKSgpKCgoKCgpKSgoKCgpKSgoKCkoKCkoKSgpKCgoKSkoKCkoKCgpKSgoKCgpKCgoKCgpKCkoKCgpKCgpKCgoKCgoKSkoKSkpKCkoKCgoKCgoKSkpKCgoKSkoKCgoKSgpKSkoKCgoKSkoKCkpKCkpKSgoKCgoKCgoKSkoKCkpKCkpKCkoKCkpKCgoKCgoKSkpKCkoKCgpKSkoKSgoKSgpKCgoKSgpKCkoKSgpKCkpKCgoKCgoKA) (The URL is large for the big test case, let me know if it breaks for you, seems OK in chrome.)
1 byte saved thanks to Martin!
We match the first set of balanced parentheses and extract it, then we count the number of times the empty string will match that result. I'm not sure if this is the nicest way to do this in Retina, particularly if PCRE mode makes it shorter, but using the `$#_` replacement seemed to be longer because of off by one errors and the problem of having more than one match.
This algorithm causes odd behaviour for invalid input, it essentially assumes that if Santa doesn't make it to the basement, he mysteriously teleports there after the other movements.
[Answer]
# Mathematica, ~~62~~ 55 bytes
```
Position[Accumulate[(-1)^ToCharacterCode@#],-1][[1,1]]&
```
All of the long function names! Works similarly to Simmons' CJam answer.
[Answer]
## Python, 44 bytes
```
f=lambda s,i=1:i and-~f(s[1:],i-1+2*(s<')'))
```
The floor `i` starts at `1` so that we terminate on `i` being the falsey value `0`. If not terminated, recursively add one to result with the first character removed and the floor number updated based on that character.
[Answer]
# Ruby, 47 bytes
Anonymous function.
```
->s{i,l=-1,0;l+=s[i+=1]>?(?-1:1 while l>-1;i+1}
```
[Answer]
## APL, 18 chars
```
{1⍳⍨¯1=+\¯1*')'=⍵}
```
In English:
* `¯1*')'=⍵`: -1 where input =")", 1 otherwise;
* `+\`: running sum;
* `1⍳⍨¯1=`: find the index of the first -1.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ 10 bytes
neat backwards solution with 1/2 literal from [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)
```
€.∫mȯ-.%2c
```
```
-- implicit last parameter (⁰ variable)
c -- get char code
%2c -- get the remainder of int div 2 `( => 0, ) => 1`
-.%2c -- subtract 1/2 from either that 1 or 0
ȯ-.%2c -- compose the 3 functions [-. %2 c] together (map only takes one function)
∫mȯ-.%2c -- map over all the chars and get cumulative sum
€.∫mȯ-.%2c -- find the first index where the element is equal to 1/2
```
old solution: <https://pastebin.com/Ut8Wne6w>
[Try it online!](https://tio.run/##yygtzv6f@6ip8dC2/4@a1ug96lide2K9rp6qUfL///81NDU0NTU0gAQQgEguTS4NCNDEBAA)
[Answer]
# CJam, ~~12~~ 10 Bytes
```
0q{~_}%1#)
```
[Try it here.](http://cjam.aditsu.net/#code=0q%7B~_%7D%251%23)&input=()()(()()()(()()((()((()))((()((((()()((((()))()((((())(((((((()(((((((((()(((())(()()(()((()()(()(())(()((((()((()()()((((())((((((()(()(((()())(()((((()))())(())(()(()()))))))))((((((((((((()())()())())(())))(((()()()((((()(((()(()(()()(()(()()(()(((((((())(())(())())))((()())()((((()()((()))(((()()()())))(())))((((())(((()())(())(()))(()((((()())))())((()(())(((()((((()((()(())())))((()))()()(()(()))))((((((((()())((((()()((((()(()())(((((()(()())()))())(((()))()(()(()(()((((()(())(()))(((((()()(()()()(()(((())())(((()()(()()))(((()()(((())())(()(())())()()(())()()()((()(((()(())((()()((())()))((()()))((()()())((((()(()()(()(((()))()(()))))((()(((()()()))(()(((())()(()((()())(()(()()(()())(())()(((()(()())()((((()((()))))())()))((()()()()(())()())()()()((((()))))(()(((()()(((((((())()))()((((()((())()(()())(())()))(()(()())(((((((())))(((()))())))))()))())((())(()()((())()())()))))()((()()())(())((())((((()())())()()()(((()))())...(((((()((((()()((((((((()()))(()((((((())((((())()(()(((()()()(((()(()(())(())(((((()(())())((((())(())(()(((()(((((())((((())())((()(((((((()(((())(()(()))(((((((((()((()((()()(()((((())(((()((())((((())(()(((()(((()(()((((()(((())(()(((()(()()(()(()((()()(()())(())())((()(()(((()(((()(((()()(((((((((()(((((((((()()(((()(((()())((((()(()(((()()()((())((((((((((())(()(((()((((()())((((()((()))(((()()()(((((()(((((((())((()())(()((((())((((((((())(()((()((((((((((()()((()((()()))(((()())()())()(((()())()()(()(()(((((((())()))(())()))())()()((())()((()((((()((()((())(((((()((((((()(())))(()))())(((()))((()()(()(((()))((((())()(((()))))()(()(())()(((((())(()(()(())(())()((()()()((((()(())((()())(()(()))(()(()(()()(())()()(()((())()((()))))()))((()(()()()()((()())(()))())()(()(((((((((())())((()((()((((((())()((((())(((())((()(()()()((())(()((())(((()((((()()((()(()(((((())()))()((((((()))((())(((()()))(((())(())()))(((((((())(())())()(())(((((()))()((()))()(()()((()()()()()())(((((((%0A)
Two bytes saved thanks to Martin.
Explanation:
```
0 Load 0 onto the stack
q Load input onto the stack without evaluating
{ } Code block
~_ Evaluate the next command and duplicate the top stack element. The format of the question is good for CJam and Golfscript since ) and ( are increment and decrement operators (though the wrong way round).
% Map this code block over the string. This yields an array of Santa's floor positions
1# Find the first instance of a 1, since decrement and increment are swapped
) Fix the off-by-1 error caused by zero-indexing
```
[Answer]
# Javascript, 117 bytes
```
o=f=0;i=prompt().split('');for(c in i){switch (i[c]){case '(':f++;break;case ')':f--;if(f<0){alert(o+1);i=[];}}o++;}
```
Ignores other characters. Uses `prompt` and `alert`.
[Answer]
### Perl, 34 + 1 = 35 bytes
```
$.+=s+.+++s+\)++while")"gt$_;$_=$.
```
Thanks to Dennis for some tips.
Run with the `-p` flag. It works in Perl 5.10, but later versions need a space here: `++ while`
Older, ungolfed version:
```
$_ = <>; # get a line of input
while ($_ lt ')') { # while it begins with a (
s/.//; # remove the first (
s/\)//; # remove the first )
$i += 2; # increase index by 2
}
print $i + 1; # print the position
```
[Answer]
# Befunge 25 bytes
Outputs in unary. This starts you on floor one, and will go until 0.
```
1<\1_v#:+-*2%2~
:#._@>$1>
```
[Answer]
## Javascript, 57 bytes
```
p=>{c=0;for(i in p){c+=p[i]==')'?-1:1;if(c<0)return+i+1}}
```
Pretty simple, just iterates over input, incs if '(' decs if ')'. Returns on first negative.
[Answer]
## Racket (102)
```
(λ(s)(let l((c 0)(b 0)(s(string->list s)))(if(> 0 b)c(l(+ 1 c)((if(eqv?(car s)#\()+ -)b 1)(cdr s)))))
```
**Ungolfed**
```
(λ (input)
(let loop ((count 0) (balance 0) (chars (string->list input)))
(if (> 0 balance)
count
(loop (+ 1 count)
((if (eqv? (car chars) #\() + -) balance 1)
(cdr chars)))))
```
[Answer]
## Lua, ~~92~~ ~~89~~ 87 Bytes
It takes in a command-line argument.
**Edit: Saved 3 Bytes**
**Edit: Saved 2 bytes, and corrected a bug that could happen on edge cases, it now outputs via its exit code**
```
r=0i=0(...):gsub(".",function(c)i=i+1r=r+(c==")"and-1or 1)if r<0then os.exit(i)end end)
```
### Ungolfed
```
r,i=0,0 -- set r (the actual floor), and i(the character count)
(...):gsub(".",function(c) -- apply an anonymous functions on each character of the input
i,r=i+1, -- increment i
r+(c==")"and -1 or 1) -- decrement r if c==")", increment it otherwise
if r<0 then os.exit(i)end -- if r==-1, exit and output the current index
end)
```
[Answer]
## [k](https://en.wikipedia.org/wiki/K_(programming_language))/[kona](https://github.com/kevinlawler/kona), ~~23~~ 21 bytes
2 bytes saved by removing unnecessary parentheses.
```
{1+(+\1 -1"()"?x)?-1}
```
Usage:
```
k){1+(+\1 -1"()"?x)?-1} "())"
3
```
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 14 bytes
```
1+0⊐˜1+`¯1⋆-⟜@
```
Anonymous tacit function that takes a string and returns an integer wrapped in a [unit array](https://mlochbaum.github.io/BQN/doc/enclose.html#whats-a-unit). Prepend `⊑` to get a plain integer instead.
[Run it online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAgMSsw4oqQy5wxK2DCrzHii4Yt4p+cQAoKRiAiKCgpKSkpKCki)
### Explanation
```
1+0⊐˜1+`¯1⋆-⟜@
-⟜@ Subtract null character from each character (yields list of charcodes)
¯1⋆ Take -1 to the power of each
1+` Scan with addition (cumulative sum), starting at 1
0⊐˜ Find the index of the first 0
1+ Add 1 because BQN uses 0-based indexing
```
[Answer]
# C, 73 bytes
```
main(f,c){f=c=0;for(;f!=-1;c++){f+=1-((getchar()&1)<<1);}printf("%d",c);}
```
Expects input on STDIN; no characters other than `(` and `)` may appear in the input (at least until we've reached the answer). Input *must* be ASCII.
Emits the answer on STDOUT.
Uses the 1-bit difference between the ASCII for `(` and `)`.
```
/* old-style arguments, implicitly int */
main(x, f)
{
/* c is our character counter, f is the floor*/
c = f = 0;
/* increase c while f is not -1 */
for (;f != -1; c++) {
/* use difference in LSB to add one for (, subtract one for ) */
f += 1-((getchar()&1)<<1);
}
/* answer */
printf("%d", c);
}
```
Nicely-formatted version:
[Answer]
## PowerShell, ~~75~~ ~~65~~ 62 bytes
```
[char[]]$args[0]|%{$c+=(1,-1)[$_%40];$d++;if($c-lt0){$d;exit}}
```
Uses a similar technique as on [Parenthifiable binary numbers](https://codegolf.stackexchange.com/a/64063/42963) to loop through all the input characters, keeping a running `$c`ounter of `+1` for each `(` and `-1` for each `)`, then testing whether we've hit negative (i.e., we're in the basement).
Edit - saved 10 bytes by iterating over the actual characters rather than their indices
Edit 2 - saved 3 additional bytes by swapping equality check for modulo so casting is implicit
[Answer]
# Javascript (ES6), ~~68~~ 67 bytes
```
(s,r,f=0)=>s.split``.map((l,i)=>(f+=l=='('?1:-1,f<0?r=r||++i:0))&&r
```
Takes input as first argument
# Explanation
```
(s, r, f=0) //Gets string, declares r and f to equal undefined and 0
=>
s.split`` //Splits string into character array
.map( //Loops over array
(l, i)=>(
f += //Increment f
l=='(' ? 1 : -1, //By either 1 or -1 depending on character
f<0 ? //If the floor is less than 0
r=r||++i //And is first time below, r equals index (+1 to make it '1 indexed not 0')
: 0)
&&r //Return index
```
] |
[Question]
[
Continued fractions are expressions that describe fractions iteratively. They can be represented graphically:
$$
a\_0 +\cfrac 1
{a\_1 + \cfrac 1
{a\_2 + \cfrac 1
{\ddots + \cfrac 1
{a\_n}
}
}
}
$$
Or they can be represented as a list of values: \$[a\_0 ; a\_1, a\_2, \dots, a\_n]\$
### The challenge:
take a base number: \$a\_0\$ and a list of denominator values: \$[a\_1, a\_2, \dots, a\_n]\$ and simplify the continued fraction to a simplified rational fraction: return or print numerator and denominator separately.
### Examples:
* \$\sqrt 19\$: `[4;2,1,3,1,2]: 170/39`
* \$e\$: `[1;0,1,1,2,1,1]: 19/7`
* \$\pi\$: `[3;7,15,1,292,1]: 104348/33215`
* \$ϕ\$: `[1;1,1,1,1,1]: 13/8`
### Example implementation: (python)
```
def foo(base, sequence):
numerator = 1
denominator = sequence[-1]
for d in sequence[-2::-1]:
temp = denominator
denominator = d * denominator + numerator
numerator = temp
return numerator + base * denominator, denominator
```
### Winning:
shortest code in bytes: --no builtins that do the entire problem allowed--
[Answer]
# J, ~~8~~ 5 bytes
Same as [this](https://codegolf.stackexchange.com/a/93235/43319), but uses a build-in for rationals.
Argument is {a0,a1,a2,a3,...} as a list of J extended precision rational numbers. Result is the fraction as a J extended precision rational number.
```
(+%)/
```
`(+%)` the plus-the-reciprocal-of
`/` reduction over
[Try it online!](https://tio.run/##y/r/P83WSkNbVVP/f2pyRr5CmoKCSZGhgoIRiDAEEcZwFkiMC6YKLGIAlzNE1WSIrBRsgjlY2BSh1tIIQ6EhqnGoxH8A "J – Try It Online")
-3 thanks to [miles](https://codegolf.stackexchange.com/users/6710/miles).
[Answer]
## Haskell, ~~37~~ ~~36~~ 18 bytes
```
foldr1$(.(1/)).(+)
```
This function expects Haskell's `Ratio` type as input. Usage example:
```
Prelude Data.Ratio> ( foldr1$(.(1/)).(+) ) [4%1,2,1,3,1,2]
170 % 39
```
Note: one explicit `Ratio` in the input list (`4%1`) is enough, the type systems figures out that the others have to be `Ratio`s, too.
Edit: @Lynn saved a byte. Thanks!
Edit II: removed the `import` (see this [discussion on meta](http://meta.codegolf.stackexchange.com/q/10081/34531)).
[Answer]
## [GolfScript](http://www.golfscript.com/golfscript/), 13 bytes
```
~]-1%{\-1?+}*
```
[Try it online!](http://golfscript.tryitonline.net/#code=fl0tMSV7XC0xPyt9Kg&input=Mwo3IDE1IDEgMjkyIDE)
Yay for GolfScript's [hidden rationals](https://codegolf.stackexchange.com/a/26553/8478). :)
### Explanation
GolfScript's only "official" number type is integers. But the exponentiation operator doesn't cast its result to integer and conveniently the native result of an integer exponentiation in Ruby (the language of GolfScript's interpreter) is a rational number. So we can easily get fractions by raising something to the power of -1. Conveniently, we want reciprocals anyway...
```
~] # Evaluate input and wrap all a_i in a list.
-1% # Reverse the list so that a_n is at the start and a_0 at the end.
{ # Fold... (apply this block to each element from a_n-1 down to a_0, with
# the previous result on the stack)
\ # Swap previous result with current a_i.
-1? # Raise previous result to the power of -1, computing its reciprocal
# as a rational number.
+ # Add a_i.
}*
```
[Answer]
# LabVIEW, 36 equivalent bytes
Fairly straight forward naive implementation using OP's algorithm. Is there a nicer way to do this?
[](https://i.stack.imgur.com/eZ6ee.png)
[Answer]
## Mathematica, ~~23~~ 22 bytes
```
Fold[#2+1/#&]@*Reverse
```
Essentially [a port of my GolfScript answer](https://codegolf.stackexchange.com/a/93224/8478). Here are some alternatives:
For 24 bytes, we can write a recursive variadic function:
```
f@n_=n
n_~f~m__:=n+1/f@m
```
For 21 bytes, we can even define a "variadic operator", but its calling convention would be so weird, that I'm reluctant to count this one:
```
±n_=n
n_ ±m__:=n+1/±m
```
You would have to call this with a *sequence* of the input values, e.g. `±Sequence[3, 7, 15, 1, 292, 1]` or `±##&[3, 7, 15, 1, 292, 1]`.
And also for 21 bytes, there would be the (forbidden) built-in:
```
FromContinuedFraction
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 10 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
Does not even use a build-in for rationals.
Takes {a0,a1,a2,a3,...} as argument, returns {denominator,numerator}.
```
1(,÷∨)+∘÷/
```
`1(,÷∨)` 1-prepended-to divided by the GCD of 1 and
`+∘÷` plus-the-reciprocal-of
`/` reduction over
[TryAPL online!](http://tryapl.org/?a=f%u21901%28%2C%F7%u2228%29+%u2218%F7/%20%u22C4%20f%A8%284%2C2%2C1%2C3%2C1%2C2%29%281%2C0%2C1%2C1%2C2%2C1%2C1%29%283%2C7%2C15%2C1%2C292%2C1%29%281%2C1%2C1%2C1%2C1%2C1%29&run)
[Answer]
## Python 2, 62 bytes
```
a=d=0
b=c=1
for n in input():a,b=b,n*b+a;c,d=d,n*d+c
print b,d
```
It's unfortunately not as golfy (see [@xnor's answer](https://codegolf.stackexchange.com/a/93254/21487) for shorter), but it calculates the fraction without needing to reverse the input. This uses the ["magic table"](http://www.maths.usyd.edu.au/u/bobh/UoS/MATH3009/wk2.pdf) approach for convergents – given the last two fractions `a/c` and `b/d`, the next fraction is `(n*b+a)/(n*c+d)`.
For instance, for pi:
```
3 7 15 1 292 1
0 1 3 22 333 355 103993 104348
1 0 1 7 106 113 33102 33215
```
We can see that `15*22 + 3 = 333`, `15*7 + 1 = 106`, `1*333 + 22 = 355`, `1*106 + 7 = 113`, etc.
[Answer]
# M, 5 bytes
```
Ṛİ+¥/
```
The input is a list of the values `[a0, a1, ..., aN]` and it outputs a rational number.
[Try it online!](http://m.tryitonline.net/#code=4bmaxLArwqUv&input=&args=NCwyLDEsMywxLDI) or [Verify all test cases.](http://m.tryitonline.net/#code=4bmaxLArwqUvCsOH4oKs&input=&args=W1s0LDIsMSwzLDEsMl0sWzEsMCwxLDEsMiwxLDFdLFszLDcsMTUsMSwyOTIsMV0sWzEsMSwxLDEsMSwxXV0)
## Explanation
```
Ṛİ+¥/ Input: list A
Ṛ Reverse A
/ Reduce A from left to right using
¥ A dyadic chain
İ Take the reciprocal of the left value
+ Add the reciprocal to the right value
Return and print implicitly
```
[Answer]
## Haskell, 30 bytes
```
foldr(\h(n,d)->(h*n+d,n))(1,0)
```
Recursively adds each layer going outward, updating `n/d` to `h+(1/(n/d))`, which equals `h+d/n` or `(h*n+d)/n`. The fraction is stored as a tuple of `(num,denom)`. The initial fraction of `(1,0)` flips to `0/1` which is `0`.
[Answer]
## Python, 50 bytes
```
f=lambda l,n=1,d=0:l and f(l,l.pop()*n+d,n)or(n,d)
```
Builds the continued fraction from the end of the list going backwards, repeatedly updating the fraction `n/d` on the last element `x` as `n/d -> 1+1/(n/d) == (x*n+d)/n`.
[Answer]
## Common Lisp, 54
A somewhat verbose fold-right:
```
(lambda(s)(reduce(lambda(a r)(+(/ r)a))s :from-end t))
```
### Tests
```
PASS NAME ACTUAL EXPECTED
===============================================
T √19 170/39 170/39
T ℯ 19/7 19/7
T π 104348/33215 104348/33215
T ϕ 13/8 13/8
```
[Answer]
# Julia (53 Bytes)
This is my first time ever using Julia, if I overlooked an iterator I could have used to lose some more bytes, let me know. Here's a hint to anyone who doesn't know what language to choose for this specific challenge: <https://en.wikipedia.org/wiki/Rational_data_type>
```
f(x,c)=(a=0;for b in x[end:-1:1];a=1//(b+a);end;a+c;)
```
* Reverse the input array.
* Iterate through it with rational division.
* Add c to the decimal result.
[Answer]
## Javascript (ES6), 55 bytes
```
s=>eval('for(F=[1,0];s+"";)F=[s.pop()*F[0]+F[1],F[0]]')
```
### Test cases
```
var f =
s=>eval('for(F=[1,0];s+"";)F=[s.pop()*F[0]+F[1],F[0]]')
console.log(f([4, 2, 1, 3, 1, 2]));
console.log(f([1, 0, 1, 1, 2, 1, 1]));
console.log(f([3, 7, 15, 1, 292, 1]));
console.log(f([1, 1, 1, 1, 1, 1]));
```
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), ~~18~~ 16 bytes
```
XUq~W%{2$*+\}/]p
```
[Online interpreter](http://cjam.aditsu.net/#code=XUq~W%25%7B2%24*%2B%5C%7D%2F%5Dp&input=%5B3%207%2015%201%20292%201%5D).
```
XU Push 1 and 0 to the stack
q~W% Push input, eval and reverse it
{ }/ For each n in the reversed input...
2$ Copy numerator
*+ Calculate n*denominator + numerator
\ Swap numerator and denominator
]p Wrap in array and output
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~19~~ 17 bytes
```
R¬V¦vyY*X+YUV}YX)
```
**Explanation**
Input taken as a list of numbers
```
# variable X is initialized as 1
R¬V¦ # reverse the list, remove the first item and store it in variable Y
v } # for each item N left in list
yY*X+ V # store N*Y+X in Y
YU # store Y in X
YX) # wrap X and Y in a list
```
[Try it online!](http://05ab1e.tryitonline.net/#code=UsKsVsKmdnlZKlgrWVVWfVlYKQ&input=WzMsNywxNSwxLDI5MiwxXQ)
[Answer]
## JavaScript (ES6), 44 bytes
```
a=>a.reduceRight(([n,d],v)=>[v*n+d,n],[1,0])
```
[Answer]
## Javascript (ES6), 50 bytes
```
f=(s,n=1,d=s.pop())=>s+""?f(s,d,s.pop()*d+n):[d,n]
```
It's thanks to Arnauld's answer, before seeing it I was stuck to 66 bytes:
```
f=(b,s,i=s.length-1,n=1,d=s[i])=>i?f(b,s,--i,d,s[i]*d+n):[n+b*d,d]
```
Example:
Call: `f([1, 0, 1, 1, 2, 1, 1])`
Output: `Array [ 19, 7 ]`
[Answer]
# [Perl 6](https://perl6.org), 24 bytes
```
{[R[&(1/*+*)]](@_).nude}
```
## Explanation:
* `1 / * + *` is a lambda with two parameters (`*`) which takes the reciprocal of the first, and adds the second. ( returns a [Rat](https://docs.perl6.org/type/Rat) )
* `R[&(…)]` uses that as if it was an infix operator and reverses it.
( including making it right associative )
* `[…](@_)` takes that and uses it to reduce the input.
* `… .nude` returns the ***nu***merator and ***de***nominator of the [Rat](https://docs.perl6.org/type/Rat).
* `{ … }` make it a bare block lambda with implicit parameter `@_`.
## Usage:
```
say {[R[&(1/*+*)]](@_).nude}(3,7,15,1,292,1) #*/# (104348 33215)
my &code = {[R[&(1/*+*)]](@_).nude}; # stupid highlighter */
say code 4,2,1,3,1,2; # (170 39)
say code 1,0,1,1,2,1,1; # (19 7)
say code 1,1,1,1,1,1; # (13 8)
```
[Answer]
## [Zephyr](https://github.com/dloscutoff/zephyr), 145 bytes
```
input n as Integer
set a to Array(n)
for i from 1to n
input a[i]as Integer
next
set r to a[n]
for i from 1to n-1
set r to(/r)+a[n-i]
next
print r
```
Zephyr is the first programming language I ever created. It was designed to be intuitive and have clean syntax--rather at the expense of brevity. Why am I golfing with it, you ask? Because, unlike any language I've written since, it has a built-in `Fraction` type. You can even use the division operator `/` as a unary operator for "inverse" (a feature I borrowed for Pip).
Now, there are significant limitations. The biggest problem for this challenge is that arrays must be defined with fixed size, which means that the program starts by reading the size of the array from the user. (I hope this is ok; the alternative is hardcoding the size.) There's also the minor problem that operator precedence doesn't exist, meaning multi-operator expressions have to have parentheses.
Here's an example run:
```
C:\Zephyr> python zephyr.py contfrac.zeph
6
1
1
1
1
1
1
13/8
```
[Answer]
# Ruby, 34 bytes
```
->a{a.reverse.inject{|b,i|i+1r/b}}
```
This performs a right fold (by reversing and then left folding), adding each element to 1 over the running total (the elements to the right). Ruby has the Rational type, which is really nice. And literal rationals are a number suffixed with `r`.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 4 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
╣╩┼►
```
[Run and debug it](https://staxlang.xyz/#p=b9cac510&i=[4,2,1,3,1,2]%0A[1,0,1,1,2,1,1]%0A[3,7,15,1,292,1]%0A[1,1,1,1,1,1]&a=1&m=2)
As small as it is, it's not a built-in. The built-in rationals help quite a bit though. Unpacked to ascii, the program is `rksu+`.
1. Reverse the array.
2. Fold the array using `(a, b) => (a + 1/b)`.
[Answer]
# APL(NARS), 15+1 chars, 30+2 bytes
```
{1=≢⍵:↑⍵⋄+∘÷/⍵}
```
Translation in Apl(Nars) from Adam J solution...
the input allowed for that function will be
all list of integer numbers, where the first element
will be of type rational. Test:
```
f←{1=≢⍵:↑⍵⋄+∘÷/⍵}
f 4x 2 1 3 1 2
170r39
f 1x 0 1 1 2 1 1
19r7
f 3x 7 15 1 292 1
104348r33215
f 1x 1 1 1 1 1
13r8
f 3x 89 888 999 11 222 373 7282 9272 3839 2828
158824716824887954093160207727r52744031585005490644982548907
f ,0x
0
f ,9x
9
```
so it would be 15 chars as length of function and 1 char for "x" for enter the type of input I want
and exit the type I want...
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
Ḟ·+\
```
[Try it online!](https://tio.run/##yygtzv7//@GOeYe2a8f8//8/2kTHSMdQxxiIjWIB "Husk – Try It Online")
pretty simple with `TNum` being a rational type.
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), ~~6~~ 5 bytes
```
‡Ė+ḭƒ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%80%A1%C4%96%2B%E1%B8%AD%C6%92&inputs=%5B4%2C2%2C1%2C3%2C1%2C2%5D&header=&footer=)
I added `foldr` lol.
## Explained
```
‡Ė+ḭƒ
‡Ė+ # lambda x, y: 1 / x + y
ḭ # reduce input by ↑, going right-to-left
ƒ # fractionify the result
```
] |
[Question]
[
>
> This was one of a series of challenges leading up to Brain-Flak's birthday. Find out more [here](https://hackmd.io/KwRgnARiAcCGAsBaaEBMAGR8DG8Cmis0AZsVhPLOtsWAOzQAmIQA?view).
>
>
>
# Challenge
For this challenge your objective will be to find the very first pair of matching brackets in a fully matched string of `()[]{}<>` brackets. To borrow [DJMcMayhem's](https://codegolf.meta.stackexchange.com/users/31716/djmcmayhem) definition of a fully matched string:
* For the purpose of this challenge, a "bracket" is any of these characters: `()[]{}<>`.
* A pair of brackets is considered "matched" if the opening and closing brackets are in the right order and have no characters inside of them, such as
```
()
[]{}
```
Or if every subelement inside of it is also matched.
```
[()()()()]
{<[]>}
(()())
```
Subelements can also be nested several layers deep.
```
[(){<><>[()]}<>()]
<[{((()))}]>
```
* A string is considered "Fully matched" if and only if each pair of brackets has the correct opening and closing bracket in the right order.
# Input
Input will consist of a single nonempty string or char array containing only the characters `()[]{}<>`, and is guaranteed to be fully matched. You may take input in any reasonable manner that corresponds with our [i/o defaults](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
# Output
The output of your program or function will be the index of the bracket which closes the first one. Output *must* be either `0` or `1` indexed. Again, output may be in any reasonable manner that corresponds with our [i/o defaults](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
# Test Cases
```
Input 0-indexed 1-indexed
() 1 2
(<>) 3 4
<[]{<>}> 7 8
{}{}{}{} 1 2
[[]<>[]] 7 8
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), fewest bytes wins!
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~685, 155, 151~~, 137 bytes
```
(())({<{}({}()<(()()()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>
([{}()]{})(({})){{}({}[()])(<()>)}{}(<>)<>{{}<>{}({}<>)}{}(<>[]<>)>()}<>)
```
[Try it online!](https://tio.run/nexus/brain-flak#NYzBDYBQCEPXaQ9uQFiEcHAOwuxYvhoaAqW8AUiUVUOiaX2LznXMSfOCZrLUA0w5XS2ZI/Ytdf0iB3RCMAjSL0SMjZ@r/W6kRgfXmYldI8Wqnut@AA "Brain-Flak – TIO Nexus")
136 bytes of code, plus one byte for `-a`. One indexed.
530 bytes golfed off! That's probably the largest golf I've ever done.
14 bytes saved thanks to Riley!
This abuses a formula of the opening/closing parenthesis: if you take the ASCII values, increment it by one, and take modulo of 4, the openers (`({[<`) will always get `0` or `1`, whereas the closers (`)}]>`) will always get 2 or 3.
Explanation:
```
#Push 1
(())
#While true
({<
#Pop stack height
{}
#Compute (TOS + 1) % 4
({}()<(()()()())>)({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]{})
#Decrement if positive
(({})){{}({}[()])(<()>)}{}
#Push 0 onto alternate
(<>)
#Toggle back
<>
#Pop two zeros from alternate if closer
{{}<>{}({}<>)}{}
#Push height of alternate stack
(<>[]<>)
#Make each time through evaluate to 1
>()
#Endwhile
}
#Push the number of loops onto the offstack
<>)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~17 16~~ 10 bytes
-1 thanks to carusocomputing
-6 thanks to Adnan for his amazing insight that "after incrementing, the second last bit is 0 for an opening bracket and 1 for an closing bracket"
```
Ç>2&<.pO0k
```
[Try it online!](https://tio.run/nexus/05ab1e#K6v8H6ykUW0TrRRcfHjpoe02egX@Btn/df5HK2loKukoadjYgSib6NhqG7taOyCzuhYCgczo6Fgbu@jYWKVYAA "05AB1E – TIO Nexus")
```
Ç # Get input as ASCII values
> # Increment
2& # And with 2 (0 for open and 2 for close brackets)
< # decrement
.p # prefixes
O # Sum
0k # Print the index of the first 0
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~11~~ ~~10~~ 9 bytes
```
O’&2’+\i0
```
[Try it online!](https://tio.run/nexus/jelly#@@//qGGmmhGQ0I7JNPj/cPeWw@2PmtZE/v@vocmlYWOnyWUTHVttY1drx1VdC4Fc0dGxNnbRsbEA "Jelly – TIO Nexus")
## Explanation
The idea here was to find a "magic formula" that can distinguish opening from closing brackets. I originally used `O%7&2` (i.e. "take the ASCII code, modulo 7, bitwise-and 2"), but @ETHproductions suggested `O’&2` (which replaces the modulo 7 with a decrement); both return 0 for one sort of bracket and 2 for the other. Subtracting 1 (`’`) will make these results into -1 and 1.
The rest of the code is `+\`. `+\` produces a cumulative sum. If a set of brackets is correctly matched, it will contain the same number of -1s and 1s, i.e. its cumulative sum will be 0. Then we just need to return the index of the first 0 in the resulting list; we can do that with `i0`.
[Answer]
# Vim, 23 bytes
```
:se mps+=<:>
%DVr<C-a>C1<esc>@"
```
[Try it online!](https://tio.run/nexus/v#@29VnKqQW1CsbWtjZcel6hJWxOhsKO2g9P@/TXUtCNoBAA "V – TIO Nexus")
I'm really sad about this answer. This solution is beautifully elegant and short, but, by default, vim does not consider `<` and `>` to be matched, so I need 13 bytes of boilerplate code. Otherwise, this would just be 10 bytes.
I would have posted a V answer, but that would only be one byte shorter, namely changing `Vr` to `Ò`, since `Vr` is a common vim-idiom.
This is 1-indexed but could be trivially modified to be 0-indexed by changing the `1` to a `0`.
```
:se mps+=<:> " Stupid boilerplate that tells vim to consider `<` and `>` matched
% " Jump to the bracket that matches the bracket under the cursor
D " Delete everything from here to the end of the line
V " Visually select this whole line
r<C-a> " Replace each character in this selection with `<C-a>`
" This conveniently places the cursor on the first char also
C " Delete this whole line into register '"', and enter insert mode
1<esc> " Enter a '1' and escape to normal mode
@" " Run the text in register '"' as if typed. Since the `<C-a>` command
" Will increment the number currently under the cursor
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~26~~ 24 bytes
```
M!`^.(?<-1>([[({<])*.)*
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w31cxIU5Pw95G19BOIzpao9omVlNLT1OL6/9/DU0uDRs7TS6b6NhqG7taO67qWgjkio6OtbGLjo0FAA "Retina – Try It Online")
Result is 1-based.
### Explanation
A very different Retina solution that is essentially based on a single (and very readable...) regex. This uses a new technique I discovered yesterday for matching balanced strings using [balancing groups](https://stackoverflow.com/a/17004406/1633117).
```
M!`^.(?<-1>([[({<])*.)*
```
Find (`M`) and return (`!`) all matches of the regex `^.(?<-1>([[({<])*.)*`. That regex skips the first character of the string and then uses balancing groups to keep track of the nesting depth. Any of `[({<` increase the depth (kept track of by group `1`) and any other character decreases the depth (in principle, the `.` allows the depth to be decreased by opening brackets as well, but since the regex is matched greedily, the backtracker will never attempt that). The weird trick is that the `(?<-1>...)` encloses group `1` which works because the popping from a balancing group happens at the *end* of the group. This saves two bytes over the standard approach in the form `((open)|(?<-2>close))*`. The match necessarily stops at the bracket that closes the first one, because we skipped it, so it isn't accounted for in the stack depth (and the stack depth can't go negative).
The length of this match is the 0-based index of the bracket we're looking for.
```
```
Simply count the number of empty matches in this string. The empty regex always matches once more than there are characters in the string, so this gives us the 1-based index of the bracket we're looking for.
[Answer]
# [Retina](https://github.com/m-ender/retina), 24 bytes
```
.(([[({<])|(?<-2>.))*$
```
[Try it online!](https://tio.run/nexus/retina#JcIxCoBADATAft@hsBG8wjrE0kcsgftHvLfHQmZ2PrMHKbE87eXt5xXD7NiAbhroYXBleaxArR@k9FDmBw "Retina – TIO Nexus")
This is inspired by [Martin Ender's solution](https://codegolf.stackexchange.com/a/118055/62393).
### Explanation
The first line is a regex that matches a character followed by a balanced string going all the way to the end of the main string (for a detailed explanation of how balancing groups are used in this regex see Martin's answer). Since regexes look for matches from left to right, this will find the longest balanced proper subfix, that is everything after the bracket that closes the first one, plus the bracket itself.
The following line is empty, so we replace the match with an empty string, meaning that we now only need to count the remaining characters to get the (0-indexed) desired result.
The last empty line counts the number of matches of the empty string in the string, which is one more than the number of characters in the string, equivalent to the 1-indexed result.
[Answer]
# [Perl 5](https://www.perl.org/), 28 bytes
*Saved 6 bytes by using just `.` instead of `[>})\]]`, from Martin Ender's [Retina answer](https://codegolf.stackexchange.com/a/118055/55508).*
27 bytes of code + `-p` flag.
```
/([<{([](?0)*.)+?/;$_=$+[0]
```
[Try it online!](https://tio.run/nexus/perl5#JcIxDoAgDADAva9AZCgSgd0CD6kNk5sxxJXwdhzM3bq0673V3mZApo4sWKLdvHUlHKYm4zjKPJSpyielz0dPtICULRBLpzwy9PEDZqHMIh8 "Perl 5 – TIO Nexus")
Recursive regex, what a beautiful invention.
The regex looks for an opening bracket (`[<{([]`), followed by *reccursive call* (`?0`), followed by a closing bracket (`.`). All of this non-greedily (`+?`) so it matches as short as possible from the beginning. The index of the end of the match is the answer, and as it happens, it can be found in `$+[0]`.
[Answer]
# [V](https://github.com/DJMcMayhem/V), 4 bytes
```
%Dø.
```
[Try it online!](https://tio.run/##K/v/X9Xl8A69//@jo2Nt7KJjYwE "V – Try It Online")
This, unlike most V answers, uses 0-indexing. I'm extremely proud of this answer, and how far my language has come. Explanation:
```
% " Jump to the first bracket match
D " Delete everything under and after the cursor
ø " Count the number of times the following regex is matched:
. " Any character
```
[Answer]
## JavaScript (ES6), ~~55~~ ~~53~~ 52 bytes
*Saved 1 byte thanks to @Adnan*
```
f=([c,...s],i=1)=>(i-=-c.charCodeAt()&2)&&1+f(s,++i)
```
For every opening bracket, taking its char-code mod 4 gives us 0 or 3; for the closing brackets, it gives us 1 or 2. Therefore, we can distinguish between opening and closing brackets by negating the bracket's char-code (which flips the bits and subtracts 1) and taking the second least significant bit; that is, `n&2`.
[Answer]
## C, ~~75~~ ~~72~~ ~~56~~ ~~55~~ ~~54~~ 45 bytes
```
a;f(char*s){return(a-=(-*s++&2)-1)?1+f(s):0;}
```
See it [work online](https://tio.run/nexus/c-gcc#hcpBDsIgEAXQPaeYNNHMFEmsS4t4EGRBrEQWUgPVDeHstaYbVzI/mfzkv9n2Dq93G9tEOd6mVwxoxQlFmzjfHkh0dO64w0THfV9mHyZ4WB8Q3qMfgFhmjMFyz7hMDqHZDJfQwA6@HakhIOj/CKmqRmqTpSqq5nJZU3NaG6m0MT9ufWX@AAf).
If you want the output to be 1-indexed instead of 0-indexed, replace the last `0` with `1`.
[Answer]
# Python 2.7 + Numpy, 85 79 bytes
My first attempt at code golf:
```
from numpy import*
lambda s:list(cumsum([(ord(x)+1&2)-1for x in s])).index(0)
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 97 bytes (96 for code, 1 for flag)
```
{}<>(())({<(<()>)<>({<({}[()])><>([{}]())<>}{})<>(<{}>())<>{({}[()])<>([{}])<>}{}<>({}{})>()}{})
```
Run with the `-a` flag.
[Try it online!](https://tio.run/nexus/brain-flak#NcuxDcBQCEPBdewiGyAWQRSZw2J2AvlJBU8crTIHSMhgoHNyVlWASZ8KVQ4wL9VeTeVv61cfOmT/V47Z0Q3zSIJ93Q8 "Brain-Flak – TIO Nexus")
Explanation:
```
#Skip the first open bracket
{}
#Place a 1 on stack B, representing the nesting depth
<>(())
#Start a loop, until the depth is 0
({<
#Divide the ASCII code by 2, rounding up
(<()>)<>({<({}[()])><>([{}]())<>}{})<>
#Replace TOS B with a 1
(<{}>())
#Swap back to stack A
<>
#Negate the 1 on stack B n times (n = ASCII value+1/2)
{({}[()])<>([{}])<>}{}
#Swap back to stack B
<>
#Add the 1/-1 (depending on Open/close bracket) to the nesting depth accumulator
({}{})
#Count loop cycles
>()
#end loop, print result implicitly by pushing to the stack
}{})
```
It just works, okay.
[Answer]
## [Retina](https://github.com/m-ender/retina), 34 bytes
```
^.
!
T`([{}])`<<<>
+T`p`!`<!*>
\G!
```
[Try it online!](https://tio.run/nexus/retina#JcKxCcAwDATA/rdQEZATyASPWi/gTpHRCOmNZneKcHdozz1vCEaqr4qWJA3XyDclKafh6bK3NiitgR6LVoZVP7gHzSM@ "Retina – TIO Nexus")
Result is 0-based.
### Explanation
```
^.
!
```
Replace the first character with a `!`. This causes the bracket that we're looking for to be unmatched.
```
T`([{}])`<<<>
```
Convert parentheses, square brackets and braces to angle brackets. Since the string is guaranteed to be fully matched, we don't care about the actual types at all, and this saves some bytes in the next step.
```
+T`p`!`<!*>
```
Repeatedly (`+`) replace each character in all matches of `<!*>` with `!`s. That is, we match pairs of brackets which contain no further unprocessed brackets and turn them into further exclamation marks. This will turn the entire string except the unmatched closing bracket into exclamation marks.
```
\G!
```
Count the number of leading exclamation marks, which is equal to the 0-based position of the first non-exclamation-mark (i.e. the unmatched bracket). The `\G` anchors each match to the previous one, which is why this doesn't count the `!`s after said bracket.
[Answer]
# Ruby, ~~35~~ 34 bytes
```
p$_[/[<{(\[](\g<0>)*[>})\]]/].size
```
Based on [Dada's Perl5 answer](https://codegolf.stackexchange.com/a/118008/61350). Output is 1-indexed. Requires the Ruby interpreter be invoked with the `-n` option (implicit `while gets` loop).
Edit: This is also ~~35~~ 34 bytes, but is another possible starting point to reduce this answer further.
```
p$_[/[<{(\[](\g<0>)*[>})\]]/]=~/$/
```
Edit2: Removed unnecessary spaces after `p`.
Edit3: A couple more 34-byte answers.
```
~/[<{(\[](\g<0>)*[>})\]]/;p$&.size
p~/[<{(\[](\g<0>)*[>})\]]/+$&.size
```
[Answer]
# PHP, 116 Bytes
```
for($l=["("=>")","["=>"]","{"=>"}","<"=>">"][$f=$argn[0]];;$d>0?$i++:die("$i"))$d+=$f!=($n=$argn[$i])?$n==$l?-1:0:1;
```
[Online Version](http://sandbox.onlinephpfunctions.com/code/f70b11a0d57e74feff9b9b43a0a0b2c0502dbe41)
[Answer]
# [Python](https://docs.python.org/3/), 76 bytes
```
f=lambda s,r=[],i=0:(i<1or sum(r))and f(s[1:],r+[(ord(s[0])+1&2)-1],i+1)or i
```
Recursive function that uses the ordinal 2nd LSB as a flag for open vs close trick used by many found by Adnan (and probably others). Tail hits when the cumulative sum of `-1` for open and `1` for close reaches zero. The index is kept in a variable as it's byte-cheaper than using `len(r)`, indexing is 1-based.
**[Try it online!](https://tio.run/nexus/python3#JY1BC4MwDIXP26/oxTWhHViP0vaPhBwcTihMHa2exN/uUkYg3wu8vHdN4TPMr3FQxeZAbFNoe0jerVmVfYaMOCyjmqCQ69lmQ7DmUa6W0bhHh08nP8ah@NM1yd7eZVNpUaABtdXgY4UnPnw8o8jj/I9IIvaRmDX299s3p2UD3biu6KamWKmtRLx@ "Python 3 – TIO Nexus")**
[Answer]
# [Python 3](https://docs.python.org/3/), ~~59~~ ~~55~~ ~~50~~ 49 bytes
```
f=lambda s,n=1:n and-~f(s[1:],n+1-(-ord(s[1])&2))
```
Output is 0-indexed. The formula to determine the bracket direction was first discovered by @ETHProductions and improved by @Adnan.
[Try it online!](https://tio.run/nexus/python3#JY3BCsMgEETP7VfsJV0lerCnIsYfkT1YRAi0m6K9hfTXkw1lDvMGhpm9Tq/8fpYM3fDkPEPmYn9V9eQ8GR6dVXZp5cykb3et97o06DAzoNJoUIV4Wki0hrhFwXX7SzAlCjERob9ePm3mr8LBPjrCIH@AVuogX7J6AA "Python 3 – TIO Nexus")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
¦⁽øβǑ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLCpuKBvcO4zrLHkSIsIiIsIlsoKXs8Pjw+WygpXX08PigpXSgpIl0=)
```
Ǒ # First index
¦ # In prefixes of input
⁽-- # Where...
øβ # Brackets are balanced
```
[Answer]
## Batch, 172 bytes
```
@set/ps=
@set/ai=d=0
:l
@set/ai+=1,d-=1
@set c="%s:~,1%"
@set "s=%s:~1%
@for %%a in ("<" "(" "[" "{")do @if %%a==%c% set/ad+=2&goto l
@if %d% gtr 0 goto l
@echo %i%
```
1-indexed. `<>`s are of course special characters in Batch so not only do I have to quote all over but I can't even do tricks such as making them `goto` labels.
[Answer]
# R, 126 Bytes
```
s=readline();i=0;r=0;for(c in strsplit(s,"")[[1]]){if(grepl("[\\[\\(\\{<]",c))i=i+1 else i=i-1;if(i==0){print(r);break};r=r+1}
```
[Answer]
# [Julia](https://julialang.org), 42 bytes
```
!S=argmin(cumsum(2(s∈"([{<")-1 for s=S))
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBzZyUxJJE22guJQ1NJQU4sLVTMNIBitnYIUSBYiZAMZvo2Gobu1o7JaiYBVCsuhYClZD0RkfH2thFx8YiqYtdWlqSpmtxU0sx2DaxKD03M08juTS3uDRXw0ij-FFHh5JGdLWNkqauoUJafpFCsW2wpiZUhyJIQCNYp0DTFuReLk6HxOLi1KISBaBJtgVcqXkpEIULFkBoAA)
[Answer]
# C, 127 bytes
[**Try Online**](http://ideone.com/9RN7Eb)
```
c(x){x-40&x-60&x-91&x-123?-1:1;}
f(i,t)char*t;{return i?f(i+c(*t),t+1):t;}
s(char*t){return f(c(*t),t+1)-t;}
```
**Output**
```
2 ()
4 (<>)
8 <[]{<>}>
2 {}{}{}{}
8 [[]<>[]]
```
] |
[Question]
[
# ...counted!
You will pass your program a variable which represents a quantity of money in dollars and/or cents and an array of coin values. Your challenge is to output the number of possible combinations of the given array of coin values that would add up to the amount passed to the code. If it is not possible with the coins named, the program should return `0`.
Note on American numismatic terminology:
* 1-cent coin: penny
* 5-cent coin: nickel
* 10-cent coin: dime
* 25-cent coin: quarter (quarter dollar)
**Example 1:**
Program is passed:
```
12, [1, 5, 10]
```
(12 cents)
Output:
```
4
```
There are 4 possible ways of combining the coins named to produce 12 cents:
1. 12 pennies
2. 1 nickel and 7 pennies
3. 2 nickels and 2 pennies
4. 1 dime and 2 pennies
**Example 2:**
Program is passed:
```
26, [1, 5, 10, 25]
```
(26 cents)
Output:
```
13
```
There are 13 possible ways of combining the coins named to produce 26 cents:
1. 26 pennies
2. 21 pennies and 1 nickel
3. 16 pennies and 2 nickels
4. 11 pennies and 3 nickels
5. 6 pennies and 4 nickels
6. 1 penny and 5 nickels
7. 16 pennies and 1 dime
8. 6 pennies and 2 dimes
9. 11 pennies, 1 dime, and 1 nickel
10. 6 pennies, 1 dime, and 2 nickels
11. 1 penny, 1 dime, and 3 nickels
12. 1 penny, 2 dimes, and 1 nickel
13. 1 quarter and 1 penny
**Example 3:**
Program is passed:
```
19, [2, 7, 12]
```
Output:
```
2
```
There are 2 possible ways of combining the coins named to produce 19 cents:
1. 1 12-cent coin and 1 7-cent coin
2. 1 7-cent coin and 6 2-cent coins
**Example 4:**
Program is passed:
```
13, [2, 8, 25]
```
Output:
```
0
```
There are no possible ways of combining the coins named to produce 13 cents.
---
This has been through the Sandbox. Standard loopholes apply. This is code golf, so the answer with the fewest bytes wins.
[Answer]
## Haskell, ~~37~~ 34 bytes
```
s#l@(c:d)|s>=c=(s-c)#l+s#d
s#_=0^s
```
Usage example: `26 # [1,5,10,25]` -> `13`.
Simple recursive approach: try both the next number in the list (as long as it is less or equal to the amount) and skip it. If subtracting the number leads to an amount of zero, take a `1` else (or if the list runs out of elements) take a `0`. Sum those `1`s and `0`s.
Edit: @Damien: saved 3 bytes by pointing to a shorter base case for the recursion (which also can be found in [@xnors answer](https://codegolf.stackexchange.com/a/96900/34531)).
[Answer]
## Mathematica, ~~35~~ 22 bytes
*Thanks to miles for suggesting `FrobeniusSolve` and saving 13 bytes.*
```
Length@*FrobeniusSolve
```
Evaluates to an unnamed function, which takes the list of coins as the first argument and the target value as the second. `FrobeniusSolve` is a shorthand for solving Diophantine equations of the form
```
a1x1 + a2x2 + ... + anxn = b
```
for the `xi` over the non-negative integers and gives us all the solutions.
[Answer]
# Jelly ([fork](https://github.com/miles-cg/jelly/tree/frobenius)), 2 bytes
```
æf
```
This relies on a [branch](https://github.com/miles-cg/jelly/tree/frobenius) of Jelly where I was working on implementing Frobenius solve atoms so unfortunately you cannot try it online.
## Usage
```
$ ./jelly eun 'æf' '12' '[1,5,10]'
4
$ ./jelly eun 'æf' '26' '[1,5,10,25]'
13
$ ./jelly eun 'æf' '19' '[2,7,12]'
2
$ ./jelly eun 'æf' '13' '[2,8,25]'
0
```
## Explanation
```
æf Input: total T, denominations D
æf Frobenius count, determines the number of solutions
of nonnegative X such that X dot-product D = T
```
[Answer]
# Pyth, 8 bytes
```
/sM{yS*E
```
Raw brute force, too memory intensive for actual testing. This is O(2*mn*), where *n* is the number of coins and *m* is the target sum. Takes input as `target\n[c,o,i,n,s]`.
```
/sM{yS*EQQ (implicit Q's)
*EQ multiply coin list by target
S sort
y powerset (all subsequences)
{ remove duplicates
sM sum all results
/ Q count correct sums
```
[Answer]
## Haskell, 37 bytes
```
s%(h:t)=sum$map(%t)[s,s-h..0]
s%_=0^s
```
Using some multiple of the first coin `h` decreases the required sum `s` to a non-negative value in the decreasing progression `[s,s-h..0]`, which then must be made with the remaining coins. Once there's no coins left, check that the sum is zero arithmetically as `0^s`.
[Answer]
## JavaScript (ES6), ~~51~~ 48 bytes
```
f=(n,a,[c,...b]=a)=>n?n>0&&c?f(n-c,a)+f(n,b):0:1
```
Accepts coins in any order. Tries both using and not using the first coin, recursively calculating the number of combinations either way. `n==0` means a matching combination, `n<0` means that the coins exceed the quantity while `c==undefined` means that there are no coins left. Note that the function is very slow and if you have a penny coin then the following function is faster (don't pass the penny coin in the array of coins):
```
f=(n,a,[c,...b]=a)=>c?(c<=n&&f(n-c,a))+f(n,b):1
```
[Answer]
## Perl, 45 bytes
Byte count includes 44 bytes of code and `-p` flag.
```
s%\S+%(1{$&})*%g,(1x<>)=~/^$_$(?{$\++})^/x}{
```
Takes the coin values on the first line, and the targeted amount on the second line :
```
$ perl -pE 's%\S+%(1{$&})*%g,(1x<>)=~/^$_$(?{$\++})^/x}{' <<< "1 5 10 25
26"
13
```
**Short explanations:**
```
-p # Set $_ to the value of the input,
# and adds a print at the end of the code.
s%\S+%(1{$&})*%g, # Converts each number n to (1{$&})* (to prepare the regex)
# This pattern does half the job.
(1x<>) # Converts the target to unary representation.
=~ # Match against.. (regex)
/^ $_ $ # $_ contains the pattern we prepared with the first line.
(?{$\++}) # Count the number of successful matches
^ # Forces a fail in the regex since the begining can't be matched here.
/x # Ignore white-spaces in the regex
# (needed since the available coins are space-separated)
}{ # End the code block to avoid the input being printed (because of -p flag)
# The print will still be executed, but $_ will be empty,
# and only $\ will be printed (this variable is added after every print)
```
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~10~~ 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
œċЀS€€Fċ
```
**[Try it online!](http://jelly.tryitonline.net/#code=xZPEi8OQ4oKsU-KCrOKCrEbEiw&input=U3VtX3tqPTAuLmt9ICgtMSleaiAqIChrLWopXm4gKiBiaW5vbWlhbChuKzEsIGopLg&args=WzEsNSwxMCwyNV0+MjY)**
### How?
```
œċЀS€€Fċ - Main link: coins, target
Ѐ - map over right argument, or for each n in [1,2,...,target]
œċ - combinations with replacement, possible choices of each of n coins
S€€ - sum for each for each (values of those selections)
F - flatten into one list
ċ - count occurrences of right argument
```
[Answer]
# JavaScript (ES6), 59 bytes
```
f=(n,c)=>n?c.reduce((x,y,i)=>y>n?x:x+f(n-y,c.slice(i)),0):1
```
Coins are input from highest to lowest, e.g. `f(26,[100,25,10,5,1])`. If you have a penny, remove it and use this much faster version instead:
```
f=(n,c)=>n?c.reduce((x,y,i)=>y>n?x:x+f(n-y,c.slice(i)),1):1
```
This uses a recursive formula much like @nimi's. I originally wrote this a few days ago when the challenge was still in the sandbox; it looked like this:
```
f=(n,c=[100,25,10,5])=>n?c.reduce((x,y,i)=>y>n?x:x+f(n-y,c.slice(i)),1):1
```
The only differences being the default value of `c` (it had a set value in the original challenge), and changing the `0` in the `.reduce` function to `1` (this was two bytes shorter and a bazillion times faster than `c=[100,25,10,5,1]`).
---
Here's a modified version which outputs all combinations, rather than the number of combinations:
```
f=(n,c)=>n?c.reduce((x,y,i)=>y>n?x:[...x,...f(n-y,c.slice(i)).map(c=>[...c,y])],[]):[[]]
```
[Answer]
# PHP, 327 Bytes
```
function c($f,$z=0){global$p,$d;if($z){foreach($p as$m){for($j=0;$j<=$f/$d[$z];){$n=$m;$n[$d[$z]]=$j++;$p[]=$n;}}}else for($p=[],$j=0;$j<=$f/$d[$z];$j++)$p[]=[$d[$z]=>$j];if($d[++$z])c($f,$z);}$d=$_GET[a];c($e=$_GET[b]);foreach($p as$u){$s=0;foreach($u as$k=>$v)$s+=$v*$k;if($s==$e&count($u)==count($d))$t[]=$u;}echo count($t);
```
[Try it](http://sandbox.onlinephpfunctions.com/code/9f0d8ad9a8c645219cb9ec9cd6685b7a55e4ebda)
[Answer]
## Axiom, ~~63~~ 62 bytes
1 byte saved by @JonathanAllan
```
f(n,l)==coefficient(series(reduce(*,[1/(1-x^i)for i in l])),n)
```
This approach uses generating functions. Probably that didn't help bring down the code size. I think this is the first time that in my playing with Axiom I went as far as defining my own function.
The first time the function is called it gives a horrendous warning, but still produces the correct result. After that, everything is fine as long as the list isn't empty.
[Answer]
# R, ~~81~~ ~~76~~ 63 bytes
Thanks to @rturnbull for golfing away 13 bytes!
```
function(u,v)sum(t(t(expand.grid(lapply(u/v,seq,f=0))))%*%v==u)
```
Example (note that `c(...)` is how you pass vectors of values to R):
```
f(12,c(1,5,10))
[1] 4
```
Explanation:
`u` is the desired value, `v` is the vector of coin values.
```
expand.grid(lapply(u/v,seq,from=0))
```
creates a data frame with every possible combination of 0 to k coins (k depends on the denomination), where k is the lowest such that k times the value of that coin is at least u (the value to achieve).
Normally we would use `as.matrix` to turns that into a matrix, but that is many characters. Instead we take the transpose of the transpose (!) which automatically coerces it, but takes fewer characters.
`%*% v` then calculates the monetary value of each row. The last step is to count how many of those values are equal to the desired value `u`.
Note that the computational complexity and memory requirements of this are horrific but hey, it's code golf.
[Answer]
# J, 27 bytes
```
1#.[=](+/ .*~]#:,@i.)1+<.@%
```
## Usage
```
f =: 1#.[=](+/ .*~]#:,@i.)1+<.@%
12 f 1 5 10
4
26 f 1 5 10 25
13
19 f 2 7 12
2
13 f 2 8 25
0
```
## Explanation
```
1#.[=](+/ .*~]#:,@i.)1+<.@% Input: target T (LHS), denominations D (RHS)
% Divide T by each in D
<.@ Floor each
These are the maximum number of each denomination
1+ Add 1 to each, call these B
,@i. Forms the range 0 the the product of B
] Get B
#: Convert each in the range to mixed radix B
] Get D
+/ .*~ Dot product between D and each mixed radix number
These are all combinations of denominations up to T
[ Get T
= Test if each sum is equal to T
1#. Convert as base 1 digits to decimal (takes the sum)
This is the number of times each sum was true
```
[Answer]
# TSQL, 105 bytes
This can only handle up to one dollar with these 4 coin types. The ungolfed version can handle up to around 4 dollars, but very slow - on my box this takes 27 seconds. Result is 10045 combinations b.t.w.
Golfed:
```
DECLARE @ INT = 100
DECLARE @t table(z int)
INSERT @t values(1),(5),(10),(25)
;WITH c as(SELECT 0l,0s UNION ALL SELECT z,s+z FROM c,@t WHERE l<=z and s<@)SELECT SUM(1)FROM c WHERE s=@
```
Ungolfed:
```
-- input variables
DECLARE @ INT = 100
DECLARE @t table(z int)
INSERT @t values(1),(5),(10),(25)
-- query
;WITH c as
(
SELECT 0l,0s
UNION ALL
SELECT z,s+z
FROM c,@t
WHERE l<=z and s<@
)
SELECT SUM(1)
FROM c
WHERE s=@
-- to allow more than 100 recursions(amounts higher than 1 dollar in this example)
OPTION(MAXRECURSION 0)
```
**[Fiddle](https://data.stackexchange.com/stackoverflow/query/560877/a-penny-saved-is-a-penny)**
[Answer]
## [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp) repl, 66 bytes
```
(d C(q((Q V)(i Q(i(l Q 0)0(i V(s(C(s Q(h V))V)(s 0(C Q(t V))))0))1
```
Recursive solution: tries using the first coin and not using the first coin, then adds the results from each. Exponential time complexity and no tail-recursion, but it computes the test cases just fine.
Ungolfed (key to builtins: `d` = define, `q` = quote, `i` = if, `l` = less-than, `s` = subtract, `h` = head, `t` = tail):
```
(d combos
(q
((amount coin-values)
(i amount
(i (l amount 0)
0
(i coin-values
(s
(combos
(s amount (h coin-values))
coin-values)
(s
0
(combos
amount
(t coin-values))))
0))
1))))
```
Example usage:
```
tl> (d C(q((Q V)(i Q(i(l Q 0)0(i V(s(C(s Q(h V))V)(s 0(C Q(t V))))0))1
C
tl> (C 12 (q (1 5 10)))
4
tl> (C 26 (q (1 5 10 25)))
13
tl> (C 19 (q (2 7 12)))
2
tl> (C 13 (q (2 8 25)))
0
tl> (C 400 (q (1 5 10 25)))
Error: recursion depth exceeded. How could you forget to use tail calls?!
```
[Answer]
# PHP, 130 bytes
```
function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2));
```
99 byte recursive function (and 31 bytes of calling it) that repeatedly removes the value of the current coin from the target and calls itself with the new value and the other coins. Counts the number of times the target reaches 0 exactly. Run like:
```
php -r "function r($n,$a){if($c=$a[0])for(;0<$n;$n-=$c)$o+=r($n,array_slice($a,1));return$o?:$n==0;}echo r($argv[1],array_slice($argv,2));" 12 1 5 10
```
[Answer]
## Racket 275 bytes
```
(set! l(flatten(for/list((i l))(for/list((j(floor(/ s i))))i))))(define oll'())(for((i(range 1(add1(floor(/ s(apply min l)))))))
(define ol(combinations l i))(for((j ol))(set! j(sort j >))(when(and(= s(apply + j))(not(ormap(λ(x)(equal? x j))oll)))(set! oll(cons j oll)))))oll
```
Ungolfed:
```
(define(f s l)
(set! l ; have list contain all possible coins that can be used
(flatten
(for/list ((i l))
(for/list ((j
(floor
(/ s i))))
i))))
(define oll '()) ; final list of all solutions initialized
(for ((i (range 1
(add1
(floor ; for different sizes of coin-set
(/ s
(apply min l)))))))
(define ol (combinations l i)) ; get a list of all combinations
(for ((j ol)) ; test each combination
(set! j (sort j >))
(when (and
(= s (apply + j)) ; sum is correct
(not(ormap ; solution is not already in list
(lambda(x)
(equal? x j))
oll)))
(set! oll (cons j oll)) ; add found solution to final list
)))
(reverse oll))
```
Testing:
```
(f 4 '[1 2])
(println "-------------")
(f 12 '[1 5 10])
(println "-------------")
(f 19 '[2 7 12])
(println "-------------")
(f 8 '(1 2 3))
```
Output:
```
'((2 2) (2 1 1) (1 1 1 1))
"-------------"
'((10 1 1) (5 5 1 1) (5 1 1 1 1 1 1 1) (1 1 1 1 1 1 1 1 1 1 1 1))
"-------------"
'((12 7) (7 2 2 2 2 2 2))
"-------------"
'((3 3 2) (2 2 2 2) (3 2 2 1) (3 3 1 1) (2 2 2 1 1) (3 2 1 1 1) (2 2 1 1 1 1) (3 1 1 1 1 1) (2 1 1 1 1 1 1) (1 1 1 1 1 1 1 1))
```
Following recursive solution has some error:
```
(define (f s l) ; s is sum needed; l is list of coin-types
(set! l (sort l >))
(define oll '()) ; list of all solution lists
(let loop ((l l)
(ol '())) ; a solution list initialized
(when (not (null? l))
(set! ol (cons (first l) ol)))
(define ols (apply + ol)) ; current sum in solution list
(cond
[(null? l) (remove-duplicates oll)]
[(= ols s) (set! oll (cons ol oll))
(loop (rest l) '())
]
[(> ols s) (loop (rest l) (rest ol))
(loop (rest l) '())
]
[(< ols s) (loop l ol)
(loop (rest l) ol)
])))
```
Does not work properly for:
```
(f 8 '[1 2 3])
```
Output:
```
'((1 1 1 2 3) (1 2 2 3) (1 1 1 1 1 1 1 1) (2 3 3) (1 1 1 1 1 1 2) (1 1 1 1 2 2) (1 1 2 2 2) (2 2 2 2))
```
(1 1 3 3) is possible but does not come in solution list.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 15 bytes
```
s+\Fṁḷ
2*BW;ç/Ṫ
```
[Try it online!](http://jelly.tryitonline.net/#code=cytcRuG5geG4twoyKkJXO8OnL-G5qg&input=&args=MjY+MSw1LDEwLDI1&debug=on) or [Verify all test cases.](http://jelly.tryitonline.net/#code=cytcRuG5geG4twoyKkJXO8OnL-G5qgrDpyI&input=&args=MTIsMjYsMTksMTM+WzEsNSwxMF0sWzEsNSwxMCwyNV0sWzIsNywxMl0sWzIsOCwyNV0&debug=on)
This was more of an exercise in writing an efficient version in Jelly without using builtins. This is based on the typical dynamic programming approach used to calculate the number of ways for making change
## Explanation
```
s+\Fṁḷ Helper link. Input: solutions S, coin C
s Slice the solutions into non-overlapping sublists of length C
+\ Cumulative sum
F Flatten
ḷ Left, get S
ṁ Mold the sums to the shape of S
2*BW;ç/Ṫ Main link. Input: target T, denominations D
2* Compute 2^T
B Convert to binary, creates a list with 1 followed by T-1 0's
These are the number of solutions for each value from 0 to T
starting with no coins used
W Wrap it inside another array
; Concatenate with D
ç/ Reduce using the helper link
Ṫ Tail, return the last value which is the solution
```
[Answer]
# [Actually](http://github.com/Mego/Seriously), 15 bytes
Golfing suggestions welcome. [Try it online!](http://actually.tryitonline.net/#code=4pWXO1Jg4pWc4oiZ4pmCU-KVlOKZgs6jaWBNYw&input=MTAKWzEsNSwxMF0)
```
╗;R`╜∙♂S╔♂Σi`Mc
```
**Ungolfing**
```
Implicit input n, then the list of coins a.
╗ Save a to register 0.
;R Duplicate n and create a range [1..n] from that duplicate.
`...`M Map the following function over that range. Variable i.
╜ Push a from register 0.
∙ Push the i-th Cartesian power of a.
♂S Sort each member of car_pow.
╔ Uniquify car_pow so we don't count too any duplicate coin arrangements.
♂Σ Take the sum of each coin arrangement.
i Flatten the list.
c Using the result of the map and the remaining n, push map.count(n).
Implicit return.
```
[Answer]
# Python, 120 bytes
```
from itertools import*
lambda t,L:[sum(map(lambda x,y:x*y,C,L))-t for C in product(range(t+1),repeat=len(L))].count(0)
```
Bruteforces through all combinations of coins up to target value (even if the smallest is not 1).
] |
[Question]
[
What I'd like to see is your attempts at writing a kind of "story" that has a fairly easy to read meaning, but also creating a valid code fragment. For example, this (BBC) BASIC code:
```
LET customer = "sober"
REPEAT
INPUT "more beer"
UNTIL customer = "drunk"
```
(based on <http://img.rakuten.com/PIC/12184048/0/1/300/12184048.jpg> for the idea)
Rules/guidelines:
* The code must be valid in the language you specified - Anybody must be able to run it without needing to create any fancy
* Strings, comments, or anything that allows free text to be added to the code, may be used, but for at most 3 words per string (and you can't put multiple strings or comments in a row)
* Your code does not have to result in any sensible output when it's executed. It can even be an infinite loop, as long as the code is valid and it represents something sensible(\*) when read in English.
* Any interpunction in your code will be ignored in the story.
* Variables do not need to be defined. The code you make here is just a code *fragment*. You will **lose 5 points** for calling an undefined variable/keyword/label/etc. though.
* for every individual built-in keyword/statement/function/etc you use, you **receive 15 points**. These include `for` and `if`, but also built-in functions such as `replace()`. Libraries do not count as built-in functions, but you're free to use them.
* for every letter, number, or underscore in your code, you **receive 1 point**.
* for every line/block of code that is unrelated(\*) to the story, or uses keywords/statements/etc with no meaning(\*) in English, you **lose 20 points**, and the involved characters will **not** count towards the 1 point per letter/number. To keep it fair to the languages that need data types like `int` when defining variables, data types are ignored completely. This means they don't receive 10 points for being a keyword, they won't receive points for the involved characters, but they also don't cause point loss.
* It is not allowed to just make something valid English by inserting a comment to "fill in the blanks".
* Since this is a [popularity-contest](/questions/tagged/popularity-contest "show questions tagged 'popularity-contest'"), for every upvote to your answer you will **receive 25 points**.
* Make sure to specify which language your code is in, and the formula you used to count the amount of points your answer gets.
* The answer with the most points, using this system above, wins.
* Using this system, the above example code would get `4*15 + 53*1 = 113` initial points.
(\*) *over-analysation / objectification part:* to keep this as objective as possible, "sensible" or "unrelated" means the following: If the piece of code uses words that are not English, it's not valid (for example, `const` or `int` are not English words, but `foreach` or `typeof` is 2 English words merged, so that is okay). Also, even if you use valid English words such as `print` or `echo`, these will have to fit in with the story with their *original* meaning (so 'putting ink on paper' and 'reflecting sound', not 'showing on a screen'). And with 'fit in', I mean that the subject of the story must be related to it.
*I hope this last "disclaimer" meets the requirement of defining objective criteria.*
[Answer]
# css (114)
I'm new to the golf scene. Not sure if CSS counts as 'code'. But here's a stab at it.
The year is still young...
```
body {width: 110%}
.pants {overflow: visible}
.newYear {transform: scale(.8)}
```
If I understand the scoring:
* every individual built-in keyword = 4 \* 15
* every letter/number = 1 \* 54
* every unrelated line = 0
= initial score: 114
[Answer]
**SQL love poem**
```
SELECT * FROM Night_Sky
WHERE Beauty LIKE "yours"
```
>
> 0 results returned
>
>
>
I'm a little unsure of the rules here, as my output is obviously important to the story, but not part of the code. So I'm ignoring it as far as scoring is concerned.
I'm also counting the "\*" (star) for one point, despite it not being alphanumeric or underscore, because it is important to the story.
So my score is (4\*15)+(40\*1)=100
Potentially minus 10 for the two undefined variables, but that depends on your existing database.
[Answer]
# Shakespeare!
```
The Infamous Hello World Program.
Romeo, a young man with a remarkable patience.
Juliet, a likewise young woman of remarkable grace.
Ophelia, a remarkable woman much in dispute with Hamlet.
Hamlet, the flatterer of Andersen Insulting A/S.
Act I: Hamlet's insults and flattery.
Scene I: The insulting of Romeo.
[Enter Hamlet and Romeo]
Hamlet:
You lying stupid fatherless big smelly half-witted coward!
You are as stupid as the difference between a handsome rich brave
hero and thyself! Speak your mind!
You are as brave as the sum of your fat little stuffed misused dusty
old rotten codpiece and a beautiful fair warm peaceful sunny summer's
day. You are as healthy as the difference between the sum of the
sweetest reddest rose and my father and yourself! Speak your mind!
You are as cowardly as the sum of yourself and the difference
between a big mighty proud kingdom and a horse. Speak your mind.
Speak your mind!
[Exit Romeo]
Scene II: The praising of Juliet.
[Enter Juliet]
Hamlet:
Thou art as sweet as the sum of the sum of Romeo and his horse and his
black cat! Speak thy mind!
[Exit Juliet]
Scene III: The praising of Ophelia.
[Enter Ophelia]
Hamlet:
Thou art as lovely as the product of a large rural town and my amazing
bottomless embroidered purse. Speak thy mind!
Thou art as loving as the product of the bluest clearest sweetest sky
and the sum of a squirrel and a white horse. Thou art as beautiful as
the difference between Juliet and thyself. Speak thy mind!
[Exeunt Ophelia and Hamlet]
Act II: Behind Hamlet's back.
Scene I: Romeo and Juliet's conversation.
[Enter Romeo and Juliet]
Romeo:
Speak your mind. You are as worried as the sum of yourself and the
difference between my small smooth hamster and my nose. Speak your
mind!
Juliet:
Speak YOUR mind! You are as bad as Hamlet! You are as small as the
difference between the square of the difference between my little pony
and your big hairy hound and the cube of your sorry little
codpiece. Speak your mind!
[Exit Romeo]
Scene II: Juliet and Ophelia's conversation.
[Enter Ophelia]
Juliet:
Thou art as good as the quotient between Romeo and the sum of a small
furry animal and a leech. Speak your mind!
Ophelia:
Thou art as disgusting as the quotient between Romeo and twice the
difference between a mistletoe and an oozing infected blister! Speak
your mind!
[Exeunt]
```
[Source(I have no clue how to write Shakespeare. Or read it for that matter)](http://en.wikipedia.org/wiki/Shakespeare_%28programming_language%29). I'm also very confused as to how to score it. Also, I'm surprised nobody has posted [the classic Char Lotte and Char Lie](http://www.ioccc.org/1990/westley.c)
[Answer]
Johnny's life story
```
kid=spawnKidFromParents(mother, father)
kid.live()
recycle()
def spawnKidFromParents(mother, father):
kid=father.censor(mother)
kid.name=Names.babyNames.orderBy("popularity").pop()
return kid
```
person class (select methods only)
```
def live(self):
try:
while(self.health > 0):
self.wakeUp()
self.work()
self.eat()
self.sleep()
except LossOfLifeException:
self.closeEyes()
def wakeUp(self):
while ( (self.laziness + self.calendar.today.importance * (1 - self.fatigue)) < random.randint(0,100)):
pass
self.openEyes()
self.stand()
self.dress()
def work(self):
for money in range(self.wallet.EMPTY, self.wallet.MAX_CAPACITY):
type()
def eat(self):
while(self.hunger < self.FOOD_CAPACITY * 0.8 - self.diet):
popcorn.pop()
def sleep(self):
self.undress()
self.layDown()
self.closeEyes()
pass
```
[Answer]
# Perl 3
**Not my work**, but I'm saddened that nobody has referenced **black perl** here yet...
```
BEFOREHAND: close door, each window & exit; wait until time.
open spellbook, study, read (scan, select, tell us);
write it, print the hex while each watches,
reverse its length, write again;
kill spiders, pop them, chop, split, kill them.
unlink arms, shift, wait & listen (listening, wait),
sort the flock (then, warn the "goats" & kill the "sheep");
kill them, dump qualms, shift moralities,
values aside, each one;
die sheep! die to reverse the system
you accept (reject, respect);
next step,
kill the next sacrifice, each sacrifice,
wait, redo ritual until "all the spirits are pleased";
do it ("as they say").
do it(*everyone***must***participate***in***forbidden**s*e*x*).
return last victim; package body;
exit crypt (time, times & "half a time") & close it,
select (quickly) & warn your next victim;
AFTERWARDS: tell nobody.
wait, wait until time;
wait until next year, next decade;
sleep, sleep, die yourself,
die at last
# Larry Wall
```
This gem used to be valid code on Perl 3. [Wikipedia](http://en.wikipedia.org/wiki/Black_Perl) says there are several updates for perl 5, but that's not the point really, is it?
[Answer]
# GW-BASIC: 1\*-5 + 7\*15 + 76\*1 = 176 points
```
LET criminal = "free"
FOR day = 1 to 100
PRINT "evaluation"
NEXT day
IF criminal = "bad"
THEN
GOTO JAIL
```
Subtracted 5 points for undefined label `JAIL`.
[Answer]
# Python - 15\*28 + 1\*905 == 1325
```
Once="upon a time"
there=was="a";print"ce";he=wanted=to_marry=a=princess="but"
he="tried almost";all_princesses=but=they=were=not"real"and"";the="";print"ce"+wanted+a+'real';print"cess"
for princesss in`all_princesses`:
the=princesss is not(`the`+`1`)
now=the;print"ce" is "sad"
he=was+"worried"+he+"would"+`not""`;ever=find=a;print"cess"
1=="evening"+a+"terrible storm occurred"
suddenly=a+princess+"appeared"+`but`+was+"soaked to"+`the`+"bone"
but=she=said=she=was=a=real=princess
`the`+"old queen";thought=we=will=soon=find=out;
but=she+said+"nothing"+but+"went to"+`the`+"bedroom where"+`the`+princess+"would sleep"and"put"+a+"pea beneath"+`20`+"mattresses";
the="";print"cess";having=slept=on=it=all=night=","+was+"asked how"+she+"slept";
while she in{"response","answered."}:
print"ce,"+"my eyes"+were+"open"+all+night and "I"+was+"lying on"+a+"gigantic bowling ball.";
I=am="black"and"blue"+all+"over";"it" is "horrible"
this="confirmed"+she+was+a+real+princess
None==but+a+princess is "so sensitive"
print"ce" and she+"married"
for now in "good fortune"+he+"found"+a+real+princess:
print"ce"and the+princess+"lived happily"+ever+"after"
```
My rendition of `The printcess [sic] and the pea`
Sadly, there is a syntax error on this line: `I=am="black"and"blue"+all+"over";"it" is "horrible"` and I can't seem to figure it out.
[Answer]
# Ruby, A LOT (44124 - 20 \* 4 + 15 \* 1 = 44504 points??)
"Short" story? Ha. So long that it's too long for a Stack Exchange answer! I had to remove about half of it because of the maximum character limit :(
Full code [can be found here](http://pastebin.com/raw.php?i=0Ltb8dJ3). It does not output anything. (Before, it for some reason crashed with a stack overflow, so I had to wrap it in `begin ... rescue SystemStackError`.)
Thanks, <http://longestjokeintheworld.com>!
```
def method_missing*a;end
class Module;def const_missing*a;end;end
(Kernel.methods+methods-[:eval,:object_id,:__send__]).each{|m|eval"def #{m}*a;end"}
begin talking using an interesting voice please to enhance the story
So theres a man crawling through the desert
Hed decided to try his SUV in_ a little bit of crosscountry travel had great fun zooming over the badlands and_ through the sand got lost hit a big rock and_ then_ he couldnt get it started again
There were no cell phone towers anywhere near so his cell phone was useless
He had no family his parents had died a few years before in_ an auto accident and_ his few friends had no idea he was out here
He stayed with the car for_ a day or_ so but his one bottle of water ran out
and_ he was getting thirsty
He thought maybe he knew the direction back now that hed paid attention to the sun and_ thought hed figured out which way was north so he decided to start walking
He figured he only had to go about some miles or_ so and_ hed be back to the small town hed gotten gas in_ last
He thinks about walking at night to avoid the heat and_ sun but based upon
how dark it actually was the night before and_ given that he has no flashlight hes afraid that hell break_ a leg or_ step on a rattlesnake
So
he puts on some sun block puts the rest in_ his pocket for_ reapplication
later brings an umbrella hed had in_ the back of the SUV with him to give
him a little shade pours the windshield wiper fluid into his water bottle
in_ case_ he gets that desperate brings his pocket knife in_ case_ he finds a cactus that looks like it might have water in_ it and_ heads out in_ the
direction he thinks is right
He walks for_ the entire day
By the end_ of the day hes really thirsty
Hes
been sweating all day and_ his lips are starting to crack
Hes reapplied the sunblock twice and_ tried to stay under the umbrella but he still feels sunburned
The windshield wiper fluid sloshing in_ the bottle in_ his pocket is really getting tempting now
He knows that its mainly water and_ some ethanol and_ coloring but he also knows that they add some kind of poison to it to keep people from drinking it
He wonders what the poison is and_
whether the poison would be worse than dying of thirst
He pushes on trying to get to that small town before dark
By the end_ of the day he starts getting worried
He figures hes been walking at least some miles an hour according to his watch for_ over some hours
That means that if_ his estimate was right that he should be close to the
town
But he doesnt recognize any of this
He had to cross a dry creek bed a mile or_ two back and_ he doesnt remember coming through it in_ the SUV
He figures that maybe he got his direction off just a little and_ that the dry creek bed was just off to one side of his path
He tells himself that hes close and_ that after dark hell start seeing the town lights over one of these hills and_ thatll be all he needs
As it gets dim enough that he starts stumbling over small rocks and_ things
he finds a spot and_ sits down to wait for_ full dark and_ the town lights
Full dark comes before he knows it
He must have dozed off
He stands back
up and_ turns all the way around
He sees nothing but stars
He wakes up the next_ morning feeling absolutely lousy
His eyes are gummy and_ his mouth and_ nose feel like theyre full of sand
He so thirsty that he cant even swallow
He barely got any sleep because it was so cold
Hed forgotten how cold it got at night in_ the desert and_ hadnt noticed it the night before because hed been in_ his car
He knows the Rule of Threes three minutes without air three days without water three weeks without food then_ you die
Some people can make it a little longer in_ the best situations
But the desert heat and_ having to walk and_ sweat isnt the best situation to be without water
He figures unless_ he finds water this is his last day
He rinses his mouth out with a little of the windshield wiper fluid
He waits a while_ after spitting that little bit out to see if_ his mouth goes numb or_ he feels dizzy or_ something
Has his mouth gone numb
Is it just in_
his mind
Hes not_ sure
Hell go a little farther and_ if_ he still doesnt
find water hell try drinking some of the fluid
Then he has to face his next_ harder question which way does he go from here
Does he keep walking the same way he was yesterday assuming that he still knows which way that is or_ does he try a new direction
He has no idea what to do_
Looking at the hills and_ dunes around him he thinks he knows the direction he was heading before
Just going by a feeling he points himself somewhat to the left of that and_ starts walking
As he walks the day starts heating up
The desert too cold just a couple of hours before soon becomes an oven again
He sweats a little at first and_ then_ stops
He starts getting worried at that when_ you stop sweating he knows that means youre in_ trouble usually right before heat stroke
He decides that its time to try the windshield wiper fluid
He cant wait
any longer if_ he passes out hes dead
He stops in_ the shade of a large
rock takes the bottle out opens it and_ takes a mouthful
He slowly
swallows it making it last as long as he can
It feels so good in_ his dry
and_ cracked throat that he doesnt even care about the nasty taste
He takes
another mouthful and_ makes it last too
Slowly he drinks half the bottle
He figures that since hes drinking it he might as well drink enough to
make some difference and_ keep himself from passing out
Hes quit worrying about the denaturing of the wiper fluid
If it kills him
it kills him if_ he didnt drink it hed die anyway
Besides hes pretty
sure that whatever substance they denature the fluid with is just designed to make you sick their way of keeping winos from buying cheap wiper fluid for_ the ethanol content
He can handle throwing up if_ it comes to that
He walks
He walks in_ the hot dry windless desert
Sand rocks hills
dunes the occasional scrawny cactus or_ dried bush
No sign of water
Sometimes hell see a little movement to one side or_ the other but whatever moved is usually gone before he can focus his eyes on it
Probably birds lizards or_ mice
Maybe snakes though they usually move more at night
Hes careful to stay away from the movements
After a while_ he begins to stagger
Hes not_ sure if_ its fatigue heat
stroke finally catching him or_ maybe he was wrong and_ the denaturing of the wiper fluid was worse than he thought
He tries to steady himself and_ keep going
After more walking he comes to a large stretch of sand
This is good
He
knows he passed over a stretch of sand in_ the SUV he remembers doing
donuts in_ it
Or at least he thinks he remembers it hes getting woozy
enough and_ tired enough that hes not_ sure what he remembers any more or_ if_
hes hallucinating
But he thinks he remembers it
So he heads off into it
trying to get to the other side hoping that it gets him closer to the town
He was heading for_ a town wasnt he
He thinks he was
He isnt sure any more
Hes not_ even sure how long hes been walking any more
Is it still morning
Or has it moved into afternoon and_ the sun is going down again
It must be afternoon it seems like its been too long since he started out
He walks through the sand
After a while_ he comes to a big dune in_ the sand
This is bad
He doesnt
remember any dunes when_ driving over the sand in_ his SUV
Or at least he
doesnt think he remembers any
This is bad
But he has no other direction to go
Too late to turn back now
He figures
that hell get to the top of the dune and_ see if_ he can see anything from
there that helps him find the town
He keeps going up the dune
Halfway up he slips in_ the bad footing of the sand for_ the second or_ third
time and_ falls to his knees
He doesnt feel like getting back up hell
just fall down again
So he keeps going up the dune on his hand and_ knees
While crawling if_ his throat werent so dry hed laugh
Hes finally
gotten to the hackneyed image of a man lost in_ the desert crawling through
the sand on his hands and_ knees
If would be the perfect image he imagines if_ only his clothes were more ragged
The people crawling through the desert
in_ the cartoons always had ragged clothes
But his have lasted without any
rips so far
Somebody will probably find his dessicated corpse half buried in_ the sand years from now and_ his clothes will still be in_ fine shape
shake the sand out and_ a good wash and_ theyd be wearable again
He wishes his throat were wet enough to laugh
He coughs a little instead and_ it hurts
He finally makes it to the top of the sand dune
Now that hes at the top
he struggles a little but manages to stand up and_ look around
All he sees
is sand
Sand and_ more sand
Behind him about a mile away he thinks he
sees the rocky ground he left to head into this sand
Ahead of him more
dunes more sand
This isnt where he drove his SUV
This is Hell
Or close enough
Again he doesnt know what to do_
He decides to drink the rest of the wiper
fluid while_ figuring it out
He takes out the bottle and_ is removing the
cap when_ he glances to the side and_ sees something
Something in_ the sand
At the bottom of the dune off to the side he sees something strange
Its a flat area in_ the sand
He stops taking the cap of the bottle off and_ tries to look closer
The area seems to be circular
And its dark darker than the sand
And there seems to be something in_ the middle of it but he cant tell what it is
He looks as hard as he can and_ still can tell from
here
Hes going to have to go down there and_ look
He puts the bottle back in_ his pocket and_ starts to stumble down the dune
After a few steps he realizes that hes in_ trouble hes not_ going to be able to keep his balance
After a couple of more sliding tottering steps he falls and_ starts to roll down the dune
The sand it so hot when_ his body hits it that for_ a minute he thinks hes caught fire on the way down like a movie car wreck flashing into flames as it goes over the cliff before it ever even hits the ground
He closes his eyes and_ mouth covers his face with his hands and_ waits to stop rolling
He stops at the bottom of the dune
After a minute or_ two he finds enough
energy to try to sit up and_ get the sand out of his face and_ clothes
When
he clears his eyes enough he looks around to make sure that the dark spot
in_ the sand it still there and_ he hadnt just imagined it
So seeing the large flat dark spot on the sand is still there he begins
to crawl towards it
Hed get up and_ walk towards it but he doesnt seem to
have the energy to get up and_ walk right now
He must be in_ the final stages
of dehydration he figures as he crawls
If this place in_ the sand doesnt
have water hell likely never make it anywhere else_
This is his last
chance
He gets closer and_ closer but still cant see whats in_ the middle of the
dark area
His eyes wont quite focus any more for_ some reason
And lifting
his head up to look takes so much effort that he gives up trying
He just
keeps crawling
Finally he reaches the area hed seen from the dune
It takes him a minute of crawling on it before he realizes that hes no longer on sand hes now crawling on some kind of dark stone
Stone with some kind of marking on it a pattern cut into the stone
Hes too tired to stand up and_ try to see what the pattern is so he just keeps crawling
He crawls towards the center
where his blurry eyes still see something in_ the middle of the dark stone
area
His mind detached in_ a strange way notes that either his hands and_ knees are so burnt by the sand that they no longer feel pain or_ that this dark
stone in_ the middle of a burning desert with a pounding punishing sun
overhead doesnt seem to be hot
It almost feels cool
He considers lying
down on the nice cool surface
Cool dark stone
Not a good sign
He must be hallucinating this
Hes
probably in_ the middle of a patch of sand already lying face down and_
dying and_ just imagining this whole thing
A desert mirage
Soon the
beautiful women carrying pitchers of water will come up and_ start giving him
a drink
Then hell know hes gone
He decides against laying down on the cool stone
If hes going to die here
in_ the middle of this hallucination he at least wants to see whats in_ the
center before he goes
He keeps crawling
Its the third time that he hears the voice before he realizes what hes
hearing
He would swear that someone just said Greetings traveler
You do_
not_ look well
Do you hear me
He stops crawling
He tries to look up from where he is on his hands and_
knees but its too much effort to lift his head
So he tries something
different he leans back and_ tries to sit up on the stone
After a few
seconds he catches his balance avoids falling on his face sits up and_
tries to focus his eyes
Blurry
He rubs his eyes with the back of his hands
and_ tries again
Better this time
Yep
He can see
Hes sitting in_ the middle of a large flat dark expanse
of stone
Directly next_ to him about three feet away is a white post or_
pole about two inches in_ diameter and_ sticking up about four or_ five feet
out of the stone at an angle
And wrapped around this white rod tail with rattle on it hovering and_
seeming to be ready to start rattling is what must be a fifteen foot long
desert diamondback rattlesnake looking directly at him
He stares at the snake in_ shock
He doesnt have the energy to get up and_
run away
He doesnt even have the energy to crawl away
This is it his
final resting place
No matter what happens hes not_ going to be able to
move from this spot
Well at least dying of a bite from this monster should be quicker than
dying of thirst
Hell face his end_ like a man
He struggles to sit up a
little straighter
The snake keeps watching him
He lifts one hand and_ waves
it in_ the snakes direction feebly
The snake watches the hand for_ a
moment then_ goes back to watching the man looking into his eyes
Hmmm
Maybe the snake had no interest in_ biting him
It hadnt rattled yet
that was a good sign
Maybe he wasnt going to die of snake bite after all
He then_ remembers that hed looked up when_ hed reached the center here
because he thought hed heard a voice
He was still very woozy he was
likely to pass out soon the sun still beat down on him even though he was
now on cool stone
He still didnt have anything to drink
But maybe he had
actually heard a voice
This stone didnt look natural
Nor did that white
post sticking up out of the stone
Someone had to have built this
Maybe
they were still nearby
Maybe that was who talked to him
Maybe this snake
was even their pet and_ thats why it wasnt biting
He tries to clear his throat to say Hello but his throat is too dry
All
that comes out is a coughing or_ wheezing sound
There is no way hes going
to be able to talk without something to drink
He feels his pocket and_ the
bottle with the wiper fluid is still there
He shakily pulls the bottle out
almost losing his balance and_ falling on his back in_ the process
This isnt
good
He doesnt have much time left by his reckoning before he passes
out
He gets the lid off of the bottle manages to get the bottle to his lips
and_ pours some of the fluid into his mouth
He sloshes it around and_ then_
swallows it
He coughs a little
His throat feels better
Maybe he can talk
now
He tries again
Ignoring the snake he turns to look around him hoping to
spot the owner of this place and_ croaks out Hello
Is there anyone here
He hears from his side Greetings
What is it that you want
He turns his head back towards the snake
Thats where the sound had seemed
to come from
The only thing he can think of is that there must be a
speaker hidden under the snake or_ maybe built into that post
He decides
to try asking for_ help
Please he croaks again suddenly feeling dizzy Id love to not_ be
thirsty any more
Ive been a long time without water
Can you help me
Looking in_ the direction of the snake hoping to see where the voice was
coming from this time he is shocked to see the snake rear back open its
mouth and_ speak
He hears it say as the dizziness overtakes him and_ he
falls forward face first on the stone Very well
Coming up
A piercing pain shoots through his shoulder
Suddenly he is awake
He sits
up and_ grabs his shoulder wincing at the throbbing pain
Hes momentarily
disoriented as he looks around and_ then_ he remembers the crawl across the
sand the dark area of stone the snake
He sees the snake still wrapped
around the tilted white post still looking at him
He reaches up and_ feels his shoulder where it hurts
It feels slightly wet
He pulls his fingers away and_ looks at them blood
He feels his shoulder
again his shirt has what feels like two holes in_ it two puncture holes
they match up with the two aching spots of pain on his shoulder
He had been
bitten
By the snake
Itll feel better in_ a minute He looks up its the snake talking
He
hadnt dreamed it
Suddenly he notices hes not_ dizzy any more
And more
importantly hes not_ thirsty any more at all
Have I died
Is this the afterlife
Why are you biting me in_ the
afterlife
Sorry about that but I had to bite you says the snake
Thats the way I
work
It all comes through the bite
Think of it as natural medicine
You bit me to help me
Why arent I thirsty any more
Did you give me a
drink before you bit me
How did I drink enough while_ unconscious to not_ be
thirsty any more
I havent had a drink for_ over two days
Well except for_
the windshield wiper fluid
hold it how in_ the world does a snake talk
Are you real
Are you some sort of Disney animation
No says the snake Im real
As real as you or_ anyone is anyway
I
didnt give you a drink
I bit you
Thats how it works its what I do_
I
bite
I dont have hands to give you a drink even if_ I had water just
sitting around here
The man sat stunned for_ a minute
Here he was sitting in_ the middle of the
desert on some strange stone that should be hot but wasnt talking to a
snake that could talk back and_ had just bitten him
And he felt better
Not
great he was still starving and_ exhausted but much better he was no
longer thirsty
He had started to sweat again but only slightly
He felt
hot in_ this sun but it was starting to get lower in_ the sky and_ the cool
stone beneath him was a relief he could notice now that he was no longer
dying of thirst
I might suggest that we take care of that methanol you now have in_ your
system with the next_ request continued the snake
I can guess why you
drank it but Im not_ sure how much you drank or_ how much methanol was left
in_ the wiper fluid
That stuff is nasty
Itll make you go blind in_ a day or_
two if_ you drank enough of it
Ummm nnext request said the man
He put his hand back on his hurting
shoulder and_ backed away from the snake a little
Thats the way it works
If you like that is explained the snake
You
get three requests
Call them wishes if_ you wish The snake grinned at his
own joke and_ the man drew back a little further from the show of fangs
But there are rules the snake continued
The first request is free
The
second requires an agreement of secrecy
The third requires the binding of
responsibility The snake looks at the man seriously
By the way the snake says suddenly my name is Nathan
Old Nathan
Samuel used to call me
He gave me the name
Before that most of the Bound
used to just call me Snake
But that got old and_ Samuel wouldnt stand
for_ it
He said that anything that could talk needed a name
He was big into
names
You can call me Nate if_ you wish Again the snake grinned
Sorry
if_ I dont offer to shake but I think you can understand my shake sounds
somewhat threatening The snake give his rattle a little shake
Umm my name is Jack said the man trying to absorb all of this
Jack
Samson
Can I ask you a question Jack says suddenly
What happened to the
poisonumm in_ your bite
Why arent I dying now
How did you do_ that
What do_ you mean by thats how you work
Thats more than one question grins Nate
But Ill still try to answer
all of them
First yes you can ask me a question The snakes grin gets
wider
Second the poison is in_ you
It changed you
You now no longer need
to drink
Thats what you asked for_
Or well technically you asked to not_
be thirsty any more but any more is such a vague term
I decided to make
it permanent now as long as you live you shouldnt need to drink much at
all
Your body will conserve water very efficiently
You should be able to
get enough just from the food you eat much like a creature of the desert
Youve been changed
For the third question Nate continues you are still dying
Besides the
effects of that methanol in_ your system youre a man and_ men are mortal
In your current state I give you no more than about another some years
Assuming you get out of this desert alive that is Nate seemed vastly
amused at his own humor and_ continued his wide grin
As for_ the fourth question Nate said looking more serious as far as Jack
could tell as Jack was just now working on his ability to read
talkingsnake emotions from snake facial features first you have to agree
to make a second request and_ become bound by the secrecy or_ I cant tell
you
Wait joked Jack isnt this where you say you could tell me but youd
have to kill me
I thought that was implied Nate continued to look serious
Ummmyeah Jack leaned back a little as he remembered again that he was
talking to a fifteen foot poisonous reptile with a reputation for_ having a
nasty temper
So what is this Bound by Secrecy stuff and_ can you really
stop the effects of the methanol Jack thought for_ a second
And what do_
you mean methanol anyway
I thought these days they use ethanol in_ wiper
fluid and_ just denature it
They may I dont really know said Nate
I havent gotten out in_ a
while_
Maybe they do_
All I know is that I smell methanol on your breath and_
on that bottle in_ your pocket
And the blue color of the liquid when_ you
pulled it out to drink some let me guess that it was wiper fluid
I assume
that they still color wiper fluid blue
Yeah they do_ said Jack
I figured replied Nate
As for_ being bound by secrecy with the
fulfillment of your next_ request you will be bound to say nothing about me
this place or_ any of the information I will tell you after that when_ you
decide to go back out to your kind
You wont be allowed to talk about me
write about me use sign language charades or_ even act in_ a way that will
lead someone to guess correctly about me
Youll be bound to secrecy
Of
course Ill also ask you to promise not_ to give me away and_ as Im
guessing that youre a man of your word youll never test the binding
anyway so you wont notice Nate said the last part with utter confidence
Jack who had always prided himself on being a man of his word felt a
little nervous at this
Ummm hey Nate who are you
How did you know
that
Are you umm omniscient or_ something
Well Jack said Nate sadly I cant tell you that unless_ you make the
second request Nate looked away for_ a minute then_ looked back
Umm well ok said Jack what is this about a second request
What can I
ask for_
Are you allowed to tell me that
Sure said Nate brightening
Youre allowed to ask for_ changes
Changes
to yourself
Theyre like wishes but they can only affect you
Oh and_
before you ask I cant give you immortality
Or omniscience
Or
omnipresence for_ that matter
Though I might be able to make you gaseous
and_ yet remain alive and_ then_ you could spread through the atmosphere and_
sort of be omnipresent
But what good would that be you still wouldnt be
omniscient and_ thus still could only focus on one thing at a time
Not very
useful at least in_ my opinion Nate stopped when_ he realized that Jack was
staring at him
Well anyway continued Nate Id probably suggest giving you permanent
good health
It would negate the methanol now in_ your system youd be
immune to most poisons and_ diseases and_ youd tend to live a very long
time barring accident of course
```
... story goes on for much longer ...
```
rescue SystemStackError;end
```
[Answer]
# Javascript:
```
2 * 'households, both alike' in (dignity={})
'In fair Verona', where = we = lay = our = scene ={}
Where = civil= 'blood', makes= civil ||hands ||unclean
From= forth = the =fatal =loins =of = 'these two foes';
A = pair=2; of["star-cross'd lovers"]; take = 2 || their || life
```
[Answer]
# 6502 Assembly Language
A story about a girl named Tya.
```
TYA
AND #1
TAX
MAN:
JMP *+4
A:
BIT #4
THEIR:
.byte "DONKEY"
EOR .byte "."
```
[Answer]
# JavaScript: 7\*15 + 127\*1 = 232 points
```
company = 'big'
for (employee in company) {
if (/quality/.test(employee) == 'bad') {
employee = function janitor() {
return 'less money'
}
} else {
employee = function boss() {
return 'money'
}
}
}
```
[Answer]
**PHP**
Have fun:)
```
<?php
goto:bar;
bar:
$notdrunk = 0
while ($notdrunk <= rand(5, 60)) {
drink(beer);
$notdrunk++;
}
if ($notdrunk >= rand(10, 59)) {
goto home;
}
home:
$vomit = true;
if ($notdrunk > 50) {
die();
}
?>
```
[Answer]
## [Chinese](http://esolangs.org/wiki/Chinese "Chinese")
This ancient text may have originated around 2014 AD:
```
了一人说你于一嘁力
```
A translation to English:
>
> Knowingly, a man persuaded you in one whispering sound power...
>
>
>
[Answer]
# Python, 1\*94 + 12\*15 = 274
I counted one for `=`, but didn't count the extra `f` in `def finitely()`. Also, the function is infinitely recursive, causing the call stack to be full of True "love".
```
def finitely(one=True):
if all([any([one])is"loving"or True]):return"love"in finitely()
else:return"sadness"
"love"in finitely()
```
English:
Definitely one (equals) True. If all anyone is loving or True, return love infinitely, else return sadness. Love infinitely.
[Answer]
## Delphi
I'm new and I don't really understand the scoring. So if someone can help me with that, it would be great :)
```
procedure Life;
var alive, fullbladder, fullstomach: boolean;
bladder, stomach, human: tobject;
timer:TTimer;
procedure sleepRecommended;begin sleep(((8*60)*60)*1000) {hours to ms} end;
procedure checkNeeds(sender:tobject); begin if fullbladder then bladder.empty; if fullstomach then stomach.empty; end;
procedure GoToWork;begin human.PretendToWorkAndGoOnCodeGolfInstead; end;
procedure GoHome;begin human.celebrate; end;
begin
timer:=ttimer.create;timer.interval := (60*60)*1000; timer.OnTimer := checkNeeds;
while alive do
begin
sleepRecommended;
timer.Enabled := true;
human.eat;
goToWork;
GoHome;
human.Eat;
end;
```
[Answer]
I'm a bit late to this, but every time I use firstChild in
# Javascript
I think:
```
function Rumpelstiltskin(straw){
straw = straw.replace(straw, "gold");
if(!(knowName=="Rumpelstiltskin")){
document.getElementById('millersDaughter').deleteChild(document.getElementById('millersDaughter').firstChild);//Stories are documents and characters are elements of the story.
}else{
return "angry";
}
}
```
Points:
2 undefined (knowName and the html node millersDaughter)
7 built in keywords (function, if, document.getElementById('millersDaughter'), deleteChild(...),firstChild,else,return)
I don't know how to count letters, every letter, letters in strings? Tell me.
points = 95 + letters
[Answer]
## Windows Command Script - 720
Calculated with 210 + 34\*15
*Warning: this may or may not make any sense :)*
```
IF "%time%"=="15:00" GOTO :workplace
:workplace
START SHIFT
RECOVER TASKLIST | FIND "todo" | SORT %priority% > tasks
FOR /f %%t IN (tasks) DO (
SET %%t=Done! | VERIFY
IF "%TIME%"=="17:00" START BREAK
IF "%TIME%"=="19:00" START BREAK
IF "%TIME%"=="21:00" START BREAK
IF "%RANDOM:~,1%"=="1" START BREAK
IF "%TIME%"=="23:00" EXIT SHIFT
)
```
[Answer]
# Fortran 95
Not really a story, but a short poem. Just sharing it for fun:
```
logical :: I, u = .TRUE.
do while (I); write(*,*) aPoem, 4, u;
stop; I = .FALSE.;
end do; end ! Adieu!
```
Considering the sign `=` as the verb to be, it reads as:
```
Logical eye, you are true
Do while I write a poem for you
Stop, I am false...
End, do end! Adieu!
```
[Answer]
# Google Sheets, 72 `\w` characters + 5 \* 15 reserved functions = 147
Make named ranges anywhere:
* Call one "Birth"
* Call one "Death"
`=IF(OR(ISBETWEEN("meaning",Birth,Death),NOT(ISBETWEEN("meaning",Birth,Death))),"One dies anyway")` or
```
=IF(
OR(
ISBETWEEN("meaning",Birth,Death),
NOT(ISBETWEEN("meaning",Birth,Death))
),"One dies anyway"
)
```
>
> If `"meaning"` between *Birth* and *Death*, or not `"meaning"` between *Birth* and *Death*, `One dies anyway`.
>
>
>
I also like this one:
`="My grandpa's deck "&IF(COUNTIF(GrandpasDeck,"the unstoppable Exodia")=1,"has no","has")&" pathetic cards"`
] |
[Question]
[
Your task is pretty simple. Given two floats, bitwise xor the binary representation of them, and output that as a float.
For example,
```
Normal: 16.7472 ^ 123.61 = 7.13402e-37
Binary: 01000001100001011111101001000100 ^ 01000010111101110011100001010010 = 00000011011100101100001000010110
Normal: 2.2 ^ 4.4 = 1.17549e-38
Binary: 01000000000011001100110011001101 ^ 01000000100011001100110011001101 = 00000000100000000000000000000000
Normal: 7.898 ^ 3.4444 = 1.47705e-38
Binary: 01000000111111001011110001101010 ^ 01000000010111000110101001111111 = 00000000101000001101011000010101
```
Restrictions/clarifications:
* Input/output can be given by any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods).
* The program can be a full program or just a function; either is fine.
* The float type can be any size, but the minimum size is 2 bytes.
* [Standard loopholes are forbidden.](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default)
* Shortest code wins.
[Answer]
# x86-64 machine code, 4 bytes
```
0f 57 c1 c3
```
In assembly:
```
xorps xmm0, xmm1
ret
```
This is a callable function that takes two floats or doubles as arguments (in `xmm0` and `xmm1`) and returns a float or double (in `xmm0`).
That matches the calling conventions of both Windows x64 *and* the x86-64 SysV ABI, and works for floats as well as doubles. (They're passed / returned in the low 4 or 8 bytes of XMM registers).
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), ~~74~~ 32 bytes
```
#define f(x,y)*(int*)x^=*(int*)y
```
[Try it online!](https://tio.run/##LcndCoMgGIDhc6/igyA0XGAbBaW7lIH4M4TSWAZKdO1uwY7eB161rre3UqVyXs27NsBd2OLHyOVZKm2s8wYsTjSTBjsfG5Je4q9cfoFFOo8JOhCAnYOMkATr2@ExdBSyYN297dl0TVwnWmdyeYt6HFXYI3AOaUJn@QI "C++ (gcc) – Try It Online")
I haven’t previously golfed in C++ so am grateful to all those who helped halve the size of the code! A macro which takes pointers to two floats as its arguments and modified the first to return the result.
Thanks to @12Me1 for saving 2 bytes and @Arnauld for saving 4! Thanks to @Nishioka for saving another 14, @Neil a further 6 and @AZTECCO and @Nishioka another 11! Thanks to @PeterCordes for saving 5 bytes!
[Answer]
# ARM Thumb Machine Code, 6 4 Bytes
48 40 70 47
In assembly:
```
EORS R0, R1 ; Exclusive Or of the first two params, store result in the return register
BX LR ; Branch to the value stored in the Link Register (Return address)
```
Under the standard Arm calling convention, the first two parameters are passed in the registers R0 and R1, results are returned in R0, and LR holds the return address. Assuming you're using the soft float ABI with 32 bit floats, this will perform the desired operation in 4 bytes.
-2 bytes thanks to Cody Gray
[Answer]
# [Python 3](https://docs.python.org/3/) + numpy, ~~75~~ 59 bytes
```
lambda x,y:(x.view("i")^y.view("i")).view("f")
import numpy
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaFCp9JKo0KvLDO1XEMpU0kzrhLB1oQy05Q0uTJzC/KLShTySnMLKv8XFGXmlWikaYB5emk5@YklxkYahmZ65ibmRpo6aMJGxnpmhpqamv8B "Python 3 – Try It Online")
Defines a lambda which takes two numpy float32 arrays as its arguments and returns a numpy float32 array.
Thanks to @ShadowRanger for saving 14 bytes, and Joel a further 2!
If the import can be dropped (since my lambda itself calls methods on numpy objects rather than any base numpy functions), I could save a further 13 bytes. I’m uncertain on this from the code golf standard rules.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly) + numpy, ~~89~~ 77 bytes
```
“(F(“I^F(“IvF).item()”;"F“¢lẒṾ:/²)Ɓɱ¡vẠ⁷5Rʠ¡7ɼṆṪ{ė4¶Gẉn`¡Ð}ṫȥṄo{b»Ḳ¤¹ṣḢ}jʋƒŒV
```
[Try it online!](https://tio.run/##AZoAZf9qZWxsef//4oCcKEYo4oCcSV5GKOKAnEl2RikuaXRlbSgp4oCdOyJG4oCcwqJs4bqS4bm@Oi/CsinGgcmxwqF24bqg4oG3NVLKoMKhN8m84bmG4bmqe8SXNMK2R@G6iW5gwqHDkH3huavIpeG5hG97YsK74biywqTCueG5o@G4on1qyovGksWSVv///zE2Ljc0NzIsMTIzLjYx "Jelly – Try It Online")
Has the dubious honour of being longer than the Python 3 code it reproduces, largely because of the need to convert to/from numpy objecte and the fact that numpy isn’t loaded by Jelly so the `__import__()` built-in has to be used.
A monadic link taking the two floats as a list as its argument and returning a float.
Evaluates the following Python 3 code:
```
(__import__('numpy').float32(x).view("i")^__import__('numpy').float32(y).view("i")).view(__import__('numpy').float32).item()
```
where `x` and `y` are substituted with the input.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [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")
Full program. Prompts for 1-column matrix of two IEEE 754 64-bit floating-point numbers (binary64) from stdin. Prints one such number to stdout.
```
645⎕DR≠⌿11⎕DR⎕
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L@ZiemjvqkuQY86Fzzq2W9oCOH0TQXJ/lcAgwKuR72rDM30zE3MjRQMjYz1zAy5kGSM9IwUTPRMkIXM9SwsLRSM9UyAAAA "APL (Dyalog Unicode) – Try It Online")
`⎕` prompt (numbers that collapse to non-floats can be forced into floats with the function `⊃⊢⎕DR⍨645,⍨⎕DR`)
`11⎕DR` convert to 1-bit Binary (1) **D**ata **R**epresentation (2-row, 64-column matrix)
`≠⌿` vertical XOR reduction
`645⎕DR` convert to 64-bit float (5) **D**ata **R**epresentation (single number)
[Answer]
# [VAX BASIC (later VMS BASIC, then Compaq Basic)](https://www.vmssoftware.com/pdfs/HP_branded_docs_1st_batch/5424pro.pdf), 11 bytes
```
H = F XOR G
```
Seems a bit silly to me, obviously, older languages will do better because they didn't worry abut strong-typing issues as much.
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 59 bytes
```
@(a,b)(t=@typecast)(bitxor(t(a,u='int32'),t(b,u)),'single')
```
[Try it online!](https://tio.run/##LclBCoAgEAXQ4zgfhlmYW6GraGgIoVFT1OktqN2D1yYNZ@rZi0gfKXAEqR/1XtMUdgXFolfbSN86vClVB2vASpEPgM1e6rwkg57pI1mx4N9OHNAf "Octave – Try It Online")
Typecast is the MATLAB/Octave way of casting without changing the underlying bits. This is required because `bitxor` only works on integers. No idea why they never implemented floating point numbers, even though you can explicitly specify the `AssumedType` as a third argument to `bitxor`. I guess the only use is recreational programming.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 92 bytes
```
x=>BitConverter.Int32BitsToSingle(x.Aggregate(0,(a,b)=>a^BitConverter.SingleToInt32Bits(b)))
```
[Try it online!](https://tio.run/##VctBC8IgGMbxe59EwSRst02homDnBh2iQOVVBFNQV4Pos9tgEHR64M/z03mts6unMeiuP4bxAUkqD53xURZBljG8TlzsXTnE8IRUINE@lC2bSx7i2QXrAU10Z20CKwugDUGSKMyFvP@p5TrEn0YKY1zb1SW5mRkU4HW9vRllhjS0MR@M2/oF "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~31~~ 27 bytes
*-4 bytes thanks to Grimy*
```
$\=unpack f,$a^=pack f,$_}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxrY0ryAxOVshTUclMc4Wxoyvrf7/39BMz9zE3IjL0MhYz8zwX35BSWZ@XvF/3QIA "Perl 5 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 10 bytes
```
4Z%Z}Z~9Z%
```
[Try it online!](https://tio.run/##y00syfn/3yRKNao2qs4ySvX//2gjPSMFEz2TWAA "MATL – Try It Online")
Splitting with `Z}` was shorter than taking two inputs `,4Z%]`
[Answer]
# C, 23 bytes
```
f(int*x,int*y){*x^=*y;}
```
[Try it online!](https://tio.run/##LYzRCoMgGIXvfYqfxkLDyayoi9aeZAxCkwmlo9lQomd3RTsXBz7OxxEXJ0SMCmvjMk/3DmTJ/LPNQrPGkzZimGUPt4@T2rLXHaHNgbHTBn@tlgQtCLaowXYOPLTAK1aXda4ohJ3yglVcNYeEU08hDeTA97RdKZycGS8L9TAJBf@fpt7Nk4Frg9b4Aw)
This might be a bit shifty; it takes the pointers to `float`s as pointers to `int`s.
However, it does work (this is C after all).
This takes advantage of acceptable input by taking a pointer to the variable and modifying it in-place. No (usable) value is returned.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~105~~ 101 bytes
*Shorter Node version suggested by @Neil*
*Saved 4 more bytes thanks to @ShieruAsakoto*
Takes input as `(x)(y)`.
```
x=>y=>(v=Buffer(4),v.writeInt32LE((g=n=>v.writeFloatLE(n)&&v.readInt32LE())(x)^g(y)),v.readFloatLE())
```
[Try it online!](https://tio.run/##ZYxRC4IwFEbf@yFyL9QF51B7mA9BQdBvCIZuYowt5lr6621CPkTf4zmH7yGjHFs/PMPBuk4tWiyTaGbRQBSnl9bKA8d9pLcfgrraULDbGaAXVjRfeDFOhgQtZlkkr2S3ZYgw4b2HGdeH1Wwt4tI6OzqjyLgeNOQlVbxiCDkrqMwRd7@eUXKc@J@oqD7WCAXxtHT7AQ "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 115 bytes
Takes input as an array of 2 floats.
```
a=>(v=new DataView(new ArrayBuffer(4))).getFloat32(v.setUint32([x,y]=a.map(n=>v.getUint32(v.setFloat32(0,n))),x^y))
```
[Try it online!](https://tio.run/##bYxBDoIwEEX3noJlm9SJQAO6KInGeAPdEEwm2BIMtgRqgdNjMboxzur/vPfnjg77sqtbu9bmJmclZhQZcULLITiixUstB7KUfdfhdHgqJTvCKaVQSXtqDNo4Ig56ac@1XnI@sqkQCA9siRaZW7wPemvfzYZp/4WN14nSuTS6N42ExlREkTxMIOVpxIIwiiEJC0pXP0YEnnLgf1AK292WBTFwf57PLw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), ~~109~~ ~~76~~ 63 bytes
```
a->b->a.intBitsToFloat(a.floatToIntBits(a)^a.floatToIntBits(b))
```
[Try it online!](https://tio.run/##dU@xbsIwEJ3tr7jRlhqrRWyUDB2QOnSCDVHpEiBy6thWfEFEFd/u2iFdqOrh/O7dvbt3LV6waI9fUXfe9QRtytVA2qjzYGvSzqrNDFac@6EyuobaYAjwgdrCN2czGQgpfRenj9ClkthSr22zPwD2TZC5k52NQ4IrrGGTkfLYh9MERW7aPx/kisPDu4vGf0UvWcTYr83XqfT0mOZYls06YlFWRYlKW3rTFHZuHqWmPTv3fucFys8/XCVlZCxv246BTp1yQ/KTziRjRaPQezOKq5zBKLOxG7/FuFCLuFTLHw)
Been a while since I golfed in Java and I'm not certain if I need the declaration on the LHS as part of the byte count? If it used DoubleBinaryOperator the LHS would be shorter, but the RHS would have to use Double.doubleToLongBits and Double.longBitsToDouble, so that's actually longer.
Thanks to Neil for a substantial savings on the byte count!
Thanks to Unmitigated for currying the way to another improvement!
[Answer]
## [Wolfram Mathematica](https://reference.wolfram.com), 50 bytes
```
BitXor@@(FromDigits[RealDigits[#,2,32,0][[1]],2]&)
```
Although I strongly suspect that this could be more golfed, the two extra arguments in `RealDigits` function seem to be necessary for getting a correct result.
[Try it online!](https://tio.run/##y00syUjNTSzJTE78H1CUmVcS/d8psyQiv8jBQcOtKD/XJTM9s6Q4Oig1MQfKVNYx0jE20jGIjY42jI3VMYpV0/yv71BtqAcU1jOtjf0PAA)
[Answer]
# [Lua](https://www.lua.org), 73 bytes
```
a,b=('II'):unpack(('ff'):pack(...))print((('f'):unpack(('I'):pack(a~b))))
```
[Try it online!](https://tio.run/##yylN/P8/USfJVkPd01Nd06o0ryAxOVtDQz0tDcgDs/X09DQ1C4oy80o0QOLIijxhahLrkjSB4P///4ZmeuYm5kb/DY2M9cwMAQ "Lua – Try It Online")
This code assumes 4-bytes unsigned integers and floats which is configuration on `tio.run`. Run as full program with input as arguments.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~78~~ 67 bytes
-11 bytes thanks to @grawity.
```
->x{[x.pack("gg").unpack("NN").inject(&:^)].pack(?N).unpack(?g)[0]}
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9euojq6Qq8gMTlbQyk9XUlTrzQPwvHzA3Iy87JSk0s01KziNGMhiuz94Ers0zWjDWJr/xeUlhQrpOklJ@bkaEQbmumZm5gb6SgYGhnrmRnGanKhSBvpAaVM9EzQxc31LCwtdBSM9UyAIFbzPwA "Ruby – Try It Online")
Input is an array of two floats.
[Answer]
# MMIX, 8 bytes (2 instrs)
Really, just put in an xor command.
```
00000000: c600 0001 f801 0000 İ¡¡¢ẏ¢¡¡
```
```
xorflt XOR $0,$0,$1
POP 1,0
```
Simples.
[Answer]
# [Julia 1.0](http://julialang.org/), 40 bytes
```
~=reinterpret
!x=Float64~⊻((Int~x)...)
```
[Try it online!](https://tio.run/##yyrNyUw0rPj/v862KDUzryS1qKAotYRLscLWLSc/scTMpO5R124NDc@8kroKTT09Pc3/DsUZ@eUKitFGekY6JnomsVxcacZGGhWaEA3GRnANQCZECxcXRA9IHVQRXLfmfwA "Julia 1.0 – Try It Online")
expects `Float64`s on a 64 bit platform. On a 32 bit platform, use `Float32`
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), 36 bytes
```
f::!Real!Real->Real
f _ _=code{xor%}
```
[Try it online!](https://tio.run/##NZBNb4JAEIbv/IopTSOkgAUJWqOe6sGkh6b2BmgWWHCbZZfCakuMf710kLrJzrzPfsy8mZRTIrpSZkdOoSRMdPl8fvdOCb8Ge9VHLYc97JepzOj5R9YPl46VlawVbFW2Fifrg/4oGI9BCt5CTb@OrKYZ5LKGqqZKtZiYUEwUoA4UFG1Uo20VwQJL@JRMgB6JSOgQ3kAHThWkeJ0DgQTwNCSweAQddrhRJAMtB0phjuYryFhTcdLiYwsSC9I4higCoycTFvbQOta@mToMGguEhhs4U3/qWeB6EydwTQsMz0H0Hb/XU2f2PLNg4vi4zFi7Nanxc29TYC6Q0OT5nuUGa9YnKgwx9nZG4NuVaZqjp9HIHUVRtbBD13ECP75oxf@c7dVGKK24zVfIvawu3W@ac1I0nb157V5aQUqWIiRXfuNE4XDLPw "Clean – Try It Online")
Thankfully the `Real` and `Int` types are the same sizes on 64-bit platforms...
Unfortunately requires a complete signature otherwise the graph turns into a pretzel and everything segfaults.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 87 bytes
```
x=>(v=Buffer(8),x.map((c,i)=>v.writeFloatLE(c,h=4*i)),v.map(e=>e^v[h++]).readFloatLE())
```
[Try it online!](https://tio.run/##bcpBDoIwEIXhvSfpSJ2E0gAuysJEV96AYNLgVGqQkoKV21di4sb4lu//7jroqfV2nHeDu1I0Ki6qYkEdnsaQZyXwBR96ZKzlFlQV8OXtTKfe6fl8XM9Oya0F4OGjSFV0CXWXJA2gJ339QoDYumFyPWHvbsywOs2xkIXgqcgwTxuAzQ8QKLhE@acUWO5LnqFct@b4Bg "JavaScript (Node.js) – Try It Online")
silly
[Answer]
# [Factor](https://factorcode.org/), 40 bytes
```
[ [ float>bits ] bi@ bitxor bits>float ]
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQm1iSoZCdWpSXmqNQUJRaUlJZUJSZV6JgzcVlpGekYKJn8j9aIVohLSc/scQuKbOkWCFWISnTAYhLKvKLQFSxHVhSIfZ/cmJOjoLefwA "Factor – Try It Online")
```
! 2.2 4.4
[ float>bits ] bi@ ! 1074580685 1082969293
bitxor ! 8388608
bits>float ! 1.175494350822288e-38
```
] |
[Question]
[
Your task is to turn a square root like this:
```
√12
```
into a form like this:
```
2√3
```
For our purpose, we only need to output the left number here:
```
2
```
## Test cases
```
4 -> 2
9 -> 3
12 -> 2
13 -> 1
108-> 6
```
## Specifications
* You may assume for the input that \$n>0\$. \$n\$ has to be as large as possible.
* If the number is already a perfect square, do this:
```
√4 = 2√1 -> 2
```
* If the number doesn't contain perfect squares, do this:
```
√13 = 1√13 -> 1
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~9~~ ~~6~~ 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LnIÖO
```
[Try it online](https://tio.run/##yy9OTMpM/f/fJ8/z8DT///8NjQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/n7zKw9P8/@v8jzbQMdQx0bHUMTTSMTTWMTaLBQA).
**Previous ~~9~~ 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) approach:**
```
LR.ΔnÖ
```
-3 bytes thanks to *@ovs*.
[Try it online](https://tio.run/##yy9OTMpM/f/fJ0jv3JS8w9P@/zc0AgA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf99gvTOTTm0rjjv8LT/tTr/ow10DHVMdCx1DI10DI11jM1iAQ).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input]
n # Take the square of each value in the list
IÖ # Check which squares are divisible by the input (1 if truthy; 0 if falsey)
O # And sum those checks
# (after which this sum is output implicitly as result)
L # Push a list in the range [1, (implicit) input]
R # Reverse it to [input, 1]
.Δ # Find the first value in this list which is truthy for:
n # Square the current value
Ö # Check if the (implicit) input is evenly divisible by this square
# (after which the found value is output implicitly as result)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
Ḷ²%ċ0
```
Uses the formula from [the OEIS](https://oeis.org/A000188): the number of solutions to $$x^2 \equiv 0 \ (\mathrm{mod} \ n)$$
Explanation:
* implicit input
* range `0..n-1`,
* square each
* modulo input (I got this part to work via trial and error)
* count zeroes
* implicit print
[Try it online!](https://tio.run/##y0rNyan8///hjm2HNqke6Tb4//@/pamFuaGlMQA "Jelly – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 6 5 bytes
*-1 thanks to Unrelated String*
```
f↔∋√ℕ
```
[Try it online!](https://tio.run/##AUEAvv9icmFjaHlsb2cy/3t3IiAtPiAidz/ihrDigoLhuol94bWQ/2bihpTiiIviiJrihJX//1s0LDksMTIsMTMsMzAwXQ "Brachylog – Try It Online")
### How it works
```
f↔∋√ℕ
ℕ output is a natural number (≥0) that is
√ the root of … (Brachylog gives the negative root first)
∋ an element …
f↔ in the reverse factors list (so search starts with bigger values)
```
## Alternative version with prime factors, 10 bytes
```
{ḋp⊇~j×}ᵘ⌉
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/v/rhju6CR13tdVmHp9c@3Dojv@T/f0Pj/1EA "Brachylog – Try It Online") or verify [all test cases](https://tio.run/##SypKTM6ozMlPN/r/v7r64Y7ugkdd7XVZh6fXPtw6I78ESE74/z/aRMdSx9BIx9BYx9jAIPZ/FAA).
### How it works
```
{ḋp⊇~j×}ᵘ⌉
⌉ take the maximum of …
{ }ᵘ all unique …
× multiplications of … 10
~j halves of … [2,5]
⊇ ordered subsets from … [2,5,2,5]
p the permutations of … [2,5,2,5,3]
ḋ the prime factors [2,2,3,5,5]
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) `-mx`, ~~4~~ 3 bytes
[*Crossed out  4; is no longer 4 :)*](https://codegolf.stackexchange.com/questions/170188/crossed-out-44-is-still-regular-44)
```
²vN
```
My first Japt answer. :)
Port of [my first 5-byter 05AB1E answer](https://codegolf.stackexchange.com/a/206857/52210), but with smart use of Japt's flags for the range and sum.
-1 byte thanks to *@Shaggy* thanks to the [shortcuts list](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=sg#docs-shortcuts): `p)`/`p␠` to `²`
[Try it online.](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW14&code=snZO&input=MTA4)
**Explanation:**
```
-m # Convert the (implicit) input-integer to a ranged list [0, input)
² # Square each value in the list, and implicitly close the function
vN # Check which values are divisible by the input (1 if truthy; 0 if falsey)
-x # After which the sum is calculated of the resulting list
# (before the result is output implicitly)
```
[Answer]
# JavaScript (ES6), 27 bytes
```
f=(n,k=n)=>n/k%k?f(n,k-1):k
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjTyfbNk/T1i5PP1s12z4NxNc11LTK/p@cn1ecn5Oql5OfrpGmYaKgoKmpoK@vYMSFKmEJkzBGkzA0wqHD0BgqYYguYWABkTD7DwA "JavaScript (Node.js) – Try It Online")
### How?
We recursively look for the greatest \$k\le n\$ such that \$\dfrac{n}{k}\equiv 0\pmod k\$, which is guaranteed to be satisfied for \$k=1\$ in the worst case.
This is a more golf-friendly way of testing \$\dfrac{n}{k^2}\equiv 0\pmod 1\$.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ÆE:2ÆẸ
```
A monadic Link accepting a positive integer which yields a positive integer.
**[Try it online!](https://tio.run/##y0rNyan8//9wm6uV0eG2h7t2/P//39DU2NLE2NwSAA "Jelly – Try It Online")** Or see the [first 100](https://tio.run/##y0rNyan8//9wm6uV0eG2h7t2/Dc0MDjc/qhpzf//hqbGlibG5pYA).
### How?
```
ÆE:2ÆẸ - Link: integer, X e.g. 9587193
ÆE - factorisation vector (X) [0,1,0,4,3] (since 2°×3¹×5°×7⁴×11³=9587193)
:2 - integer divide by two [0,0,0,2,1]
ÆẸ - evaluate factorisation vector 539 (since 2°×3°×5°×7²×11¹=539)
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 5 bytes
(this was produced by trying a bunch of languages from <https://github.com/ETHproductions/golfing-langs> until I found one that had the most useful built-ins for this problem)
```
dụ⁇)u
```
Explanation:
```
d divisors
ụ⁇ keep only squares
) take last
u square root
```
[Try it online! (example stolen from the Jelly answer)](https://tio.run/##S0/MTPz/P@Xh7qWPGts1S///tzS1MDe0NP4PAA "Gaia – Try It Online")
[Answer]
# [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) machine code, ~~20~~ 17 DECLEs1 ≈ 22 bytes
*As per the exception described [in this meta answer](https://codegolf.meta.stackexchange.com/a/10810/58563), the exact score is **21.25 bytes** (170 bits)*
A routine expecting the input number in **R0** and returning the result in **R3**.
```
**1D2** | CLRR R2
**1C9** | CLRR R1
**0D1** | @@loop ADDR R2, R1
**00A** | INCR R2
**084** | MOVR R0, R4
**10C** | @@sub SUBR R1, R4
**10C** | SUBR R1, R4
**114** | SUBR R2, R4
**22E 004** | BGT @@sub
**20C 001** | BNEQ @@next
**093** | MOVR R2, R3
**141** | @@next CMPR R0, R1
**226 00D** | BLE @@loop
**0AF** | JR R5
```
### How?
The CP-1610 has no multiplication, no division, no modulo. We want to implement an algorithm that relies on additions and subtractions exclusively.
We start with \$k=0\$. At each iteration, we update \$j\$ in such a way that:
$$j = \frac{k(k-1)}{2}$$
The good thing about this formula is that it's very easy to compute iteratively: we just need to add \$k\$ to \$j\$ and increment \$k\$ afterwards.
In order to test whether \$n\$ is divisible by \$k^2\$, we initialize a variable \$x\$ to \$n\$ and subtract \$k^2\$ until \$x\le 0\$.
We do not explicitly store \$k^2\$, but it can be easily obtained with:
$$2j+k=k(k-1)+k=k^2$$
Each time we end up with \$x=0\$, we update the final answer to \$k\$.
We stop when \$j\$ is greater than \$n\$.
[Here is a link](https://tio.run/##fZLNboMwEITvPMVUysEIpSE9lpJnCSUmgIkd2Uuhinj2dG1SlTRqffLPt@PZ0bbFR@FK25xprc1BXq8VcmjkO1wiQPEhzXjThg3u1mbD142DEgprbGNs8BIxezCh1hclOVR2X9KfDwVJtIFQSfIo2ujSypPUBBWg0TvKfkGOCksYGqrn9yig/usHvc6Y82s0H0esc7TZ8hlw/TvZoiQ2XFlzwvgfTENTyiWg/lJTS7UJQ910UozYIY2zGQ5XrMIhHq3kWCyoLjTSuZumEk9jvOzIp1NhkGC6rCFH/qf7RPrdnpUOS0fB0C1xqn2Z6zsCmVu0U/TjrMUb5xis@bqjgdE3h/OTN2Ul9VZ7nSyarpWxgmcF24xHhpFtyjOikyQOA1Aa7UwnnztzFPtCrC56ihleXSqh42kfe4Uv) to an implementation of the algorithm in low-level JS.
### Full commented test code
```
ROMW 10 ; use 10-bit ROM width
ORG $4800 ; map this program at $4800
PNUM QEQU $18C5 ; EXEC routine: print a number
MULT QEQU $1DDC ; EXEC routine: signed multiplication
;; ------------------------------------------------------------- ;;
;; main code ;;
;; ------------------------------------------------------------- ;;
main PROC
SDBD ; set up an interrupt service routine
MVII #isr, R0 ; to do some minimal STIC initialization
MVO R0, $100
SWAP R0
MVO R0, $101
EIS ; enable interrupts
MVII #$200, R3 ; R3 = backtab pointer
SDBD ; R4 = pointer to test cases
MVII #@@tc, R4
@@loop MVI@ R4, R0 ; R0 = next test case
TSTR R0 ; stop if it's 0
BEQ @@done
PSHR R4 ; save R4
PSHR R3 ; save R3
CALL pSquare ; invoke our routine
MOVR R3, R0 ; copy the result into R0
PULR R3 ; restore R3
CALL print ; print the result
PULR R4 ; restore R4
B @@loop ; go on with the next test case
@@done DECR R7 ; done: loop forever
;; test cases
@@tc DECLE 4, 9, 12, 13, 108, 300, 800, 900
DECLE 0
ENDP
;; ------------------------------------------------------------- ;;
;; prints the result of a test case ;;
;; ------------------------------------------------------------- ;;
print PROC
PSHR R5 ; save the return address on the stack
MVII #4, R1 ; R1 = number of digits
MOVR R3, R4 ; R4 = backtab pointer
ADDI #5, R3 ; advance by 5 characters for the next one
PSHR R3 ; save R3
CLRR R3 ; R3 = attributes (black)
CALL PNUM ; invoke the EXEC routine
PULR R3 ; restore R3
PULR R7 ; return
ENDP
;; ------------------------------------------------------------- ;;
;; ISR ;;
;; ------------------------------------------------------------- ;;
isr PROC
MVO R0, $0020 ; enable display
MVI $0021, R0 ; color-stack mode
CLRR R0
MVO R0, $0030 ; no horizontal delay
MVO R0, $0031 ; no vertical delay
MVO R0, $0032 ; no border extension
MVII #$D, R0
MVO R0, $0028 ; light-blue background
MVO R0, $002C ; light-blue border
MVO R0, $002C ; light-blue border
JR R5 ; return from ISR
ENDP
;; ------------------------------------------------------------- ;;
;; our routine ;;
;; ------------------------------------------------------------- ;;
pSquare PROC
CLRR R2 ; R2 = k
CLRR R1 ; R1 = k(k - 1) / 2
@@loop ADDR R2, R1 ; add R2 to R1
INCR R2 ; k++
MOVR R0, R4 ; start with R4 = n
@@sub SUBR R1, R4 ; subtract 2 * (k(k - 1) / 2) = k² - k
SUBR R1, R4 ; from R4
SUBR R2, R4 ; subtract k from R4
BGT @@sub ; until R4 is less than or equal to 0
BNEQ @@next ; did we reach exactly 0? ...
MOVR R2, R3 ; ... yes: update R3
@@next CMPR R0, R1 ; go on while R1 is less than or
BLE @@loop ; equal to R0
JR R5 ; return
ENDP
```
### Output
This is the output for the following test cases:
```
4, 9, 12, 13, 108, 300, 800, 900
```
[](https://i.stack.imgur.com/qjhnC.gif)
*screenshot from [jzIntv](http://spatula-city.org/%7Eim14u2c/intv/)*
---
*1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.*
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 26 bytes
```
.+
$*
((^1|11\2)+)\1*$
$#2
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0@bS0WLS0MjzrDG0DDGSFNbM8ZQS4VLRdno/38TLksuQyMuQ2MuQwMLAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
.+
$*
```
Convert to unary.
```
((^1|11\2)+)
```
Find the largest square number...
```
\1*$
```
... that divides the input...
```
$#2
```
... and output its root.
Bonus 63-byte version that for an input of `√1`, `√2`, `√3`, `√4`, `√5`, `√6`, `√7`, `√8`, `√9`... outputs `1`, `√2`, `√3`, `2`, `√5`, `√6`, `√7`, `2√2`, `3`... etc. (Previous bonus version did not handle `√1` correctly.)
```
\d+
$*
r`(?=^.(\3)+)(.)\3*((1$|11\4)+)
$#4$2$#1
\D1$
^1(\D)
$1
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyZFm0tFi6soQcPeNk5PI8ZYU1tTQ08zxlhLQ8NQpcbQMMYEKMKlomyiYqSibMgV42KowsUVZ6gR4wIUNfz//1HHLEMuIGECIixBhKERmDQGkwYWAA "Retina 0.8.2 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 37 bytes
```
n=i=input()
while n%i**2:i-=1
print i
```
[Try it online!](https://tio.run/##JcpbCoAgEAXQ/7sKEYIKgsbegqsJwYGYJIxq9Ub0fU58UtjF5Cvw5hVZf/tVa53FsWOJZyor/CYF17Wx3DhCPFiS4vxNgkGHHgNGTJixgFoQgcwL "Python 2 – Try It Online")
**38 bytes**
```
lambda n:sum(x*x%n<1for x in range(n))
```
[Try it online!](https://tio.run/##DclBDoIwEAXQ/T/FbExaV04FFZCbuCmBShMYmlJiPX31bV/4pnkTU1z/Kotdh9GStPuxqnzOJ3my2yJl8kLRyntSonX5zH6ZiFvpvYQjKd2F6CWR@29hGFxRocYNdzzQgC9gBpsf "Python 2 – Try It Online")
Based on the solution of [my pronoun is monicareinstate](https://codegolf.stackexchange.com/a/206877/20260), counting the number of solutions to \$x^2 \equiv 0 \ (\mathbb{mod}\ n)\$ for \$x\$ from \$0\$ to \$n-1\$.
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes
```
f n=sum[0^mod(x^2)n|x<-[1..n]]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NDfaIC43P0WjIs5IM6@mwkY32lBPLy829n9uYmaegq1CQVFmXomCikJuYoFCmgJI0tAo9v@/5LScxPTi/7rJBQUA "Haskell – Try It Online")
Based on the solution of [my pronoun is monicareinstate](https://codegolf.stackexchange.com/a/206877/20260), counting the number of solutions to \$x^2 \equiv 0 \ (\mathbb{mod}\ n)\$ using the range from 1 to n.
# [Haskell](https://www.haskell.org/), 32 bytes
```
f n=until((<1).mod n.(^2))pred n
```
[Try it online!](https://tio.run/##DcYxDoAgDADAr3RwgEESmOUlRpMGQYlQG8HvW73pDmxnLEUkAfmHei5KTVabem1ARq1Oa77jf6mYCTzwnanDABUZEszWGOsWeUMquDcZA/MH "Haskell – Try It Online")
Start with `n` and repeatedly take the `pred`ecessor, `until` it satiafies this condition: when we square it and take the original `n` modulo it, the result is less than 1, that is equal to 0.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~44~~ ~~33~~ 32 bytes
```
i;f(n){for(i=n;n%(--i*i););n=i;}
```
[Try it online!](https://tio.run/##XZBha4MwEIa/@ysOi5C0cau6jpXUfhn7FVNGMXE92M5i3JCJv92d1o52gYTL3fO@uVwRvhfFMKAuBcmurGqBKWkKRBjiEqWWmlLU/bBAKj6@jIWdawxWd8e9h9TA5wFJfFdopNd5wKs4Huol1K85pND5WfsSZ@32mffGV3B9T/xeT4rRprGueaOz6EFtVRSrKFHR@umKse3Jto01EwVdrBLFlHqcEW4dxMghGdsystZzuAOHP7YqxcVB3s8JxqWG1WriJJx/cHmP2GPua6rn@qbsuDzO7DZrOfvX6H/ZqWakFH5gINwDn4HLiMdCCpzimbElq/PZsvf64Rc "C (gcc) – Try It Online")
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 13 bytes
```
√#/._^_:>1&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7/1HHLGV9vfi4eCs7Q7X/AUWZeSXRyrp2aQ7KsWp1wcmJeXXVXCY6CpY6CoZGQGwMxAYWQL6phbmhpTFX7X8A "Wolfram Language (Mathematica) – Try It Online")
For an integer argument, `√` (`Sqrt`) returns in the desired `a√b` form (unless the argument was a perfect square).
Then, `/._^_:>1` matches `Power` expressions and replaces them with 1. As `a√b` expands to `Times[a,Power[b,1/2]]`, it becomes `Times[a,1]=a`.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 15 bytes
```
n->core(n,1)[2]
```
Yes, there is a build-in.
>
> `core(n,{flag=0})`: unique squarefree integer `d` dividing `n` such that `n/d` is a square. If (optional) flag is non-null, output the two-component row vector
> `[d,f]`, where `d` is the unique squarefree integer dividing `n` such that `n/d=f^2` is a square.
>
>
>
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8D9P1y45vyhVI0/HUDPaKPZ/YkFBTqVGnoKunUJBUWZeCZCpBOIoKaRp5Glq6ihEm@goWOooGBoBsXGs5n8A "Pari/GP – Try It Online")
[Answer]
# Java 10, ~~43~~ 40 bytes
```
n->{for(var c=n++;c/--n%n>0;);return n;}
```
Inspired by [*@Arnauld*'s JavaScript answer](https://codegolf.stackexchange.com/a/206856/52210), so make sure to upvote him!
[Try it online.](https://tio.run/##LY7BbsIwDIbvPMUvJKRETbt1IKQRwRvAhSPjkKUBhRUXpW6nqeqzdyn0YtmW/8/fzbQmvRU/gy1NXWNvPHUzwBO7cDHW4TCOQFE136WDFVNDUsd9P4ulZsPe4gDCdqB0112qIFoTYLeUJNq@pSktaPeupQ6Om0Ag3Q96jD4iK0YnQlv5AvdoII4cPF1PZxj5ej8ioxM8NiD3O/qdzl2uVupT5R8qX6rlupfPU@D4V7O7Z1XD2SNyuCThk/nmi@cJZVZ4Obn3wz8)
**Explanation:**
```
n->{ // Method with double as both parameter and return-type
for(var c=n // Create a copy `c` of the input `n`
++ // Then increase `n` by 1
; // Continue looping as long as:
c/--n // (decrease `n` by 1 first before every iteration with `--n`)
// `c` divided by `n`
%n>0;) // is NOT a multiply of `n` nor 0
;return n;} // After the loop: return the modified `n` as result
```
[Answer]
# [R](https://www.r-project.org/), ~~44~~ (crossed-out) ~~36~~ ~~33~~ ~~32~~ 30 bytes
```
((n=scan()):1)[!n%%(n:1)^2][1]
```
[Try it online!](https://tio.run/##K/r/X0Mjz7Y4OTFPQ1PTylAzWjFPVVUjD8iKM4qNNoz9b2hgwfUfAA "R – Try It Online")
Or, a completely-different [25 byte](https://tio.run/##K/r/v7g0V0NRw9BKI8@2ODkxT0NTUzPOSFU1T/O/oYEF138A) approach based on equivalence to 'number of solutions to x^2==0(mod n)' (as pointed-out by [my pronoun is monicareinstate](https://codegolf.stackexchange.com/questions/206853/find-the-perfect-square/206877#206877)), but that wasn't my own idea and hence seems to me to be cheating:
`sum(!(1:(n=scan()))^2%%n)`
[Answer]
# [CJam](https://sourceforge.net/projects/cjam/), 15 bytes
```
q~_{_*1$%!},,\;
```
[Try it online!](http://cjam.aditsu.net/#code=r~_%7B_*1%24%25!%7D%2C%2C%5C%3B&input=135)
Uses the new method in [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [05AB1E answer](https://codegolf.stackexchange.com/a/206857/58707).
---
**[CJam](https://sourceforge.net/projects/cjam/), 21 bytes**
*This is my old approach to the problem, pre-[Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s new method which I don't understand*
```
q~mF{[~2/]}%{~#}%{*}*
```
[Try it online!](http://cjam.aditsu.net/#code=q~mF%7B%5B~2%2F%5D%7D%25%7B~%23%7D%25%7B*%7D*&input=675)
---
*Explanation*
```
q~ Translate input into a CJam object (allows for easier testing)
mF Factorise with exponents
{ }% For each factor
~2/ Halve the exponent [and round down]
[ ] Capture the base & exponent in an array
{ }% For each transformed factor
~# Expand the base and exponent into b^e
{*}* Multiply all the transformed factors together
```
This approach removes all single factors (those that would make up the radical part) whilst halving the paired factors (equivalent to square rooting the integer part).
---
**[CJam](https://sourceforge.net/projects/cjam/), 23 bytes**
*A CJam port of [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [05AB1E answer](https://codegolf.stackexchange.com/a/206857/58707)*
```
q~_,(;{_*1$\%0>!},\;)\;
```
[Try it online!](http://cjam.aditsu.net/#code=q~_%2C(%3B%7B_*1%24%5C%250%3E!%7D%2C%5C%3B)%5C%3B&input=675)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~15~~ 12 bytes
Now based on @someone's formula.
```
NθILΦθ¬﹪×ιιθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObG4RMMnNS@9JEPDLTOnBCSpo@CXX6Lhm59SmpOvEZKZm1qskamjkKmpo1CoCQbW//8bGv3XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. For each number from `0` to the input, calculates whether its square is divisible by the input, and takes the number of matches.
Alternative version, also 12 bytes:
```
NθIΣEθ¬﹪×ιιθ
```
[Try it online!](https://tio.run/##FcG7CoAgFADQva9wvIINtTo2NShB/YCZkOC7a79/o3PsbZrNJhCtqXTUPZ6uQeVy2JpPCIt5EPYeQZkCVTCdEVS@eshw@Oge8IJ5LljlP0k0zTS@4QM "Charcoal – Try It Online") Link is to verbose version of code. For each number from `0` to the input, calculates whether its square is divisible by the input, and takes the sum of the results.
Alternative version, also 12 bytes:
```
NθI№Eθ﹪×ιιθ⁰
```
[Try it online!](https://tio.run/##S85ILErOT8z5/98zr6C0xK80Nym1SKNQ05oroCgzr0TDObEYSOSXApm@iQUahToKvvkppTn5GiGZuanFGpk6CpmaOgqFmkDCQFNT0/r/f0Oj/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. For each number from `0` to the input, calculates the remainder when its square is divisible by the input, and counts the number of zeros.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes
```
ef!%Q^T2S
```
[Try it online!](https://tio.run/##K6gsyfj/PzVNUTUwLsQo@P9/S0sA "Pyth – Try It Online")
```
ef!%Q^T2S
S Create range from 1 to (implicit) input
f Filter keep from the above, as T, where:
^T2 Square T
%Q Mod the input with the above
! Logical NOT
e Take the last (largest) element of the filtered list, implicit print
```
[Answer]
# perl -MList::Util=max -pl, 34 bytes
```
$n=$_;$_=max grep!($n%$_**2),1..$n
```
[Try it online!](https://tio.run/##K0gtyjH9/18lz1Yl3lol3jY3sUIhvSi1QFFDJU9VJV5Ly0hTx1BPTyXv/38TLksuQyMuQ2MuE4t/@QUlmfl5xf91fX0yi0usrEJLMnNAmv/rFuQAAA "Perl 5 – Try It Online")
This finds the largest square which properly divides the input number. Very inefficient as it tries all numbers from 1 up to the input.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 29 bytes
```
->n,x=n{x-=1while n%x**2>0;x}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5Pp8I2r7pC19awPCMzJ1UhT7VCS8vIzsC6ovZ/tImOpY6hkY6hsY6hgYWOYaxeamJyRnVNXo1CgUa1Qp6CrZ1CWnRerEKtpkLtfwA "Ruby – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 12 bytes
```
1#.0=[|2^~i.
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/DZX1DGyja4zi6jL1/mv@T1Mw4UpTsFQAEoZGIMIYzDSwAAA "J – Try It Online")
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [~~12~~ 10 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
·£æ9Š3nòy├
```
[Try it!](https://zippymagician.github.io/Arn?code=K3Z7ISh2XjIlfVx+&input=NAo5CjEyCjEzCjEwOA==)
# Explained
Unpacked: `+v{!(v^2%}\~`
Uses the formula from the [OEIS](https://oeis.org/A000188) page: the number of solutions to \$x^2≡0 (\mod n)\$
```
~ 1-range (inclusive) to
_ variable initialized to STDIN; implied
+\ folded with addition after
v{ mapping with block (key of v)
! Boolean NOT
( Begin expression
v
^ exponentiated by
2 two
% mod
_ implied
) End expression; implied
} End block
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
-1 byte thanks to [Razetime](https://codegolf.stackexchange.com/users/80214/razetime)!
```
▲fo¬%1m√Ḋ
```
[Try it online!](https://tio.run/##yygtzv7//9G0TWn5h9aoGuY@6pj1cEfX////LQE "Husk – Try It Online") or [Try all cases!](https://tio.run/##ASgA1/9odXNr/23igoH/4payZm/CrCUxbeKImuG4iv///1s0LDksMTIsMTNd)
### Commented
```
▲ -- the maximum of ...
fo -- ... filter on the next two functions composed
¬ -- - boolean negate / (== 0)
%1 -- - modulo 1
m√ -- ... map square root on ...
Ḋ -- ... the list of divisors
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 71 bytes
```
[S S S N
_Push_0][S N
S _Duplicate_0][T N
T T _STDIN_as_integer][T T T _Retrieve_input][S N
S _n=Duplicate_input][N
S S N
_Create_Label_LOOP][S T S S T N
_Copy_0-based_1st_input][S T S S T N
_Copy_0-based_1st_n][S N
S _Duplicate_n][T S S N
_Multiply][T S T T _Modulo][N
T S S N
_If_0_Jump_to_Label_PRINT_RESULT][S S S T N
_Push_1][T S S T _Subtract][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_PRINT_RESULT][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIObk4QQDMBnEVgCJQEkxzcSpwAtWA5ECCUBkuEI8LpPL/f0MjAA) (with raw spaces, tabs and new-lines only).
Port of [*@Sok*'s Pyth answer](https://codegolf.stackexchange.com/a/206862/52210), so make sure to upvote him! Whitespace doesn't have decimals, so his/her approach is ideal for Whitespace since it doesn't use square-root nor regular division, but only integers.
**Explanation in pseudo-code:**
```
Integer n = STDIN as integer
Integer r = n
Start LOOP:
Integer s = r * r
If(n % s == 0):
Jump to Label PRINT
r = r - 1
Go to next iteration of LOOP
Label PRINT:
Print r as integer to STDOUT
(implicitly stop the program with an error: no exit defined)
```
[Answer]
# [bc](https://www.gnu.org/software/bc/manual/html_mono/bc.html), 52 bytes
```
define f(n){for(i=n;i--;){if(!(n%(i*i))){return i}}}
```
[Try it online!](https://tio.run/##HcQxCoAwDAXQvaeog/AjdFA7KMXLqA1kiVB0Kj17RN/w9sPszCyaPUOp8lUgmyYJIVEVRgftIYMQUS35fop6aa2ZMSI5xvo1Tv/zd1zIvQ "bc – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 5 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
╒²k÷Σ
```
Port of [my 5-byter 05AB1E answer](https://codegolf.stackexchange.com/a/206857/52210).
[Try it online.](https://tio.run/##y00syUjPz0n7///R1EmHNmUf3n5u8f//hlxGXCZcllyGRlyGxlzGZlyGBhYA)
**Explanation:**
```
╒ # Push a list in the range [1, (implicit) input]
# (could alternatively be `r` for a range [0, input) )
² # Square each value in this list
k÷ # Check which values are evenly divisible by the input (1 if truthy; 0 if falsey)
Σ # And sum those checks
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# APL(NARS), 23 chars, 46 bytes
```
{√⍵÷×/(∪a)/⍨2∣≢¨⊂⍨a←π⍵}
```
test:
```
f←{√⍵÷×/(∪a)/⍨2∣≢¨⊂⍨a←π⍵}
f 4
2
f 9
3
f 12
2
f 13
1
f 108
6
f 2×2×2×2×2×3×3
12
```
comment:
```
{√⍵÷×/(∪a)/⍨2∣≢¨⊂⍨a←π⍵}
π⍵ factor argument
a← save that in a list "a" of prime factors
⊂⍨ partition "a" in a list of list each element is ugual factors found
2∣≢¨ to each element of list of list find if number of elements is odd
×/(∪a)/⍨ so choice in ∪a the elements appear in list of list as odd and multiple them
⍵÷ divide the argument for the number of factor contained odd times
√ make sqrt of that
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki), ~~123~~ 72 bytes
```
.+ We convert the input into unary
$&*_ $&*_ and create a copy for factor checking
{` (_+) START LOOP: We square the input by multiplying
$& $.1*$1 its string representation by its length
(?=^.* (_+) (_+))\2+ .+ We check if the square is a factor of the input
$.1 if so we replace the whole text with the current counter
(_*)_.* Otherwise we decrement the counter by one
$1 ---
-- IMPLICIT LOOP END --
-- IMPLICIT OUTPUT --
```
[Try it online!](https://tio.run/##K0otycxLNPz/X0@bS0VNK14BRHBVJyhoxGtrAkUUVPQMtVQMuTTsbeP0tMCiYEIzxkhbAaRHz5ALKKClGa@nxaWgYqjw/7@hEQA)
---
This approach is essentially a port of [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)'s [05AB1E answer](https://codegolf.stackexchange.com/a/206857/58707).
It checks all the numbers from the input downwards until it finds a number whose square divides the original.
---
*-51 bytes*: Many thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil), whose suggestion helped me to cut off a ridiculous amount of code.
I've also switched from separating with newlines to separating with spaces because `.` is anti-newline.
[Answer]
# TI-Basic, 16 bytes
```
sum(not(fPart(seq(I²/Ans,I,1,Ans-1
```
Port of [this answer](https://codegolf.stackexchange.com/questions/206853/find-the-perfect-square/206877#206877). Takes input in `Ans`. Output is stored in `Ans` and is displayed.
] |
[Question]
[
Making a [versatile integer printer](https://codegolf.stackexchange.com/questions/65641/the-versatile-integer-printer) is nice and all, but writing a single code that prints a lot of different numbers is cumbersome. Wouldn't it be easier to make a script that outputs a number, but also gives you a new script to get the next number?
**Challenge:**
Write a code that outputs a single integer `N` and an executable code. The next code should output `N+1` and a code that can output `N+2`. Continue this path until you reach `N = 15`. (The last printed number should be 15).
**Rules:**
* No input (assume the input is empty).
* Full program or function or other convenient formats are allowed.
* The first code should output `1`.
* You can't output leading zeros. I.e. you can't print `01` for `1`.
* The output must be on the format `N, Code_for_N+1`. Note that the output is separated by a comma and a single space. The code for `N+1` has no surrounding quotation marks. `N , Code_for_N+1` is not accepted (space in front of the comma). Trailing newlines are OK.
* The first character(s) of the output must be the number. (No leading spaces, or `ans = N`).
* The printed number should not be part of the next code (the code can contain this number, but you can't take the output number as part of the code)
+ Example: The output for `N=2` can be: `2, printer 2`. In this case, `printer 2` is the code for `N=3`. You can't use the entire output: `2, printer 2` as code for `N=3`.
* The scripts may be in different languages
* The datatypes are irrelevant (the number can be a string), but it can't be surrounded by anything (quotation marks, parentheses etc).
* If there is a code outputted for `N=15` then it must either print `STOP!` (see bonus), or don't print anything at all (not even a space or newline).
+ The code for `N=15` can not crash (but outputting to STDERR is OK).
+ You are disqualified if the output code for `N=15` prints `16` or anything else (except the bonus case).
* Built in quine operators are not allowed.
* Accessing the source file through the file system is not allowed.
**Bonus:**
-10 bytes if the code that prints 15 also produces a code that prints "`STOP!`"
**Examples using Python syntax:** (obviously, these will only work for the selected integers, not from 1 to 15.)
```
N = 1
print "1, print 2"
1, print 2
---
N = 15
print 15
15
---
N = 15 (Qualifies for the -10 bytes bonus)
print "15, print 'STOP!'"
15, print 'STOP!'
print 'STOP!'
STOP!
----
N = 15 (Qualifies for the -10 bytes bonus)
print "15, disp('STOP!')"
15, disp('STOP!') (disp('STOP!') outputs STOP! in MATLAB)
----
N = 15 (This one is not OK. The submission is disqualified)
print "15, print 16"
15, print 16
```
Standard golfing rules apply! Smallest code (for N=1) in bytes win!
[Answer]
## Pyth + ///, 15 bytes - 10 = 5
```
pPt`S15", STOP!
```
This prints `1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, STOP!` in Pyth, by taking `range(1,15+1)` and stripping off the start and end brackets, and printing it immediately followed by ", STOP!".
The next fourteen programs are in ///, which directly outputs all programs that don't contain `/` or `\`. So the second program
```
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
```
gives `2` and the third program `3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15`. The penultimate program, `15, STOP!`, prints `15, STOP!`, so the last program is just `STOP!`.
[Answer]
# JavaScript, 131238 - 10 = 131228 bytes
The naive approach turned out worse than expected. In hindsight I should have expected it. But I thought I'd share it anyway. Full code [here.](http://pastebin.com/raw/5nrCwPL1)
Idea: Iteratively escaping and adding the `N-1, ...`
```
alert("14,alert(\"15, alert(\\\"STOP!\\\")\")")
```
[Answer]
## CJam, ~~26~~ ~~25~~ 24 bytes
```
1{", "2$)@"_~"](_F<@*}_~
```
[Try it online.](http://cjam.aditsu.net/#code=1%7B%22%2C%20%222%24)%40%22_~%22%5D(_F%3C%40*%7D_~)
The subsequent programs simply have the first number incremented. [This runs the program 16 times.](http://cjam.aditsu.net/#code=q%0A%7B~%5Ds_oNoS%2F1%3ES*%7D16*&input=1%7B%22%2C%20%222%24)%40%22_~%22%5D(_F%3C%40*%7D_~)
---
Or with bonus for the same score:
```
1{", "\2$)_G<\@`+"_~"+"STOP!"`?}_~
```
[Try it online.](http://cjam.aditsu.net/#code=1%7B%22%2C%20%22%5C2%24)_G%3C%5C%40%60%2B%22_~%22%2B%22STOP!%22%60%3F%7D_~)
The subsequent programs simply have the first number incremented. [This runs the program 16 times.](http://cjam.aditsu.net/#code=q%0A%7B~%5Ds_oNoS%2F1%3ES*%7D16*&input=1%7B%22%2C%20%22%5C2%24)_G%3C%5C%40%60%2B%22_~%22%2B%22STOP!%22%60%3F%7D_~)
Alternative solution for the bonus:
```
1{", "\2$)Gmd@`+"_~"+"STOP!"`\?}_~
```
[Answer]
# JavaScript (ES6), ~~62~~ 61 bytes - 10 bonus = 51 score
```
_=>"1, "+(f=n=>`_=>"`+(n<16?n+`, "+(${f(n+1)})`:`STOP!"`))(2)
```
## Explanation
A solution which does not read it's own source code and is also not ridiculously long.
The first program constructs all 15 other programs and nests them inside each other using a recursive function. I get around the backslash issue by nesting the functions themselves (which are then cast to strings during output) rather than strings.
```
_=>
"1, " // print the first number
+(f=n=>`_=>"`+( // f = recursive function for printing program N
n<16? // for programs 2 - 15:
n+`, "+(${ // add N to the output of the nested function
f(n+1) // nest the code of program N + 1
})`
:`STOP!"` // program 16 just outputs "STOP!" for the bonus
))(2) // start from program 2
```
## Test
```
var nextProgram = '_=>"1, "+(f=n=>`_=>"`+(n<16?n+`, "+(${f(n+1)})`:`STOP!"`))(2)',
n = 1;
while(nextProgram) {
result.textContent += "Program " + n++ + ": " + nextProgram + "\n";
var output = eval("(" + nextProgram + ")()");
result.textContent += " Output: " + output + "\n\n";
var index = output.indexOf(",");
nextProgram = index > 0 ? output.substr(index + 2) : null;
}
```
```
<pre id="result"></pre>
```
[Answer]
# Matlab, ~~226~~ 212 - 10 = 202 bytes
Thanks to @StewieGriffin for a few bytes=)
```
'awFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
```
The first part is a string that represents the second line (below), the actual code (just shifted by 9). In Matlab, strings are matrices filled with characters, so you can easily perform the shifts by just adding/substracting a scalar. So the program just prints out the same string\* again, plus the same string but shifted which results in the code.
\*Not quite: The first byte is the counter which needs to be increased in each iteration.
The quine trick with the string was shamelessly stolen from [here.](http://blog.garritys.org/2009/10/quines.html)
```
'awFjw|Dro)w1:26B?G:>DwF0\}xy*0Dnu|nDwFdw~v;|}{1w1:26B?2505)05<B5w1:24:5w1;Cnwm25<B5>B5w1;Cnwm26B500fDnwmDmr|y1w2';
n=ans;if n(1)-96>15;n='Stop!';else;n=[num2str(n(1)-96),', ',39,n(1)+1,n(2:end),39,59,n(2:end)-9,''];end;disp(n)
```
Here the last few lines of the sequence copied from the console:
```
>> 'mwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
13, 'nwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
>> 'nwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
14, 'owFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
>> 'owFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
15, 'pwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
>> 'pwFjw|DWFw1:2DVFw1;Cnwm2Dro)WG:::DwF0\]XY*0Dnu|nDwFdw~v;|}{1W6B?2505)05<B5W4:5V5<B5>B5V6B500fDnwmDmr|y1w2';n=ans;N=n(1);M=n(2:end);if N>111;n='STOP!';else;n=[num2str(N-96),', ',39,N+1,M,39,59,M-9,''];end;disp(n)
STOP!
```
[Answer]
## JavaScript, ~~50~~ ~~47~~ ~~44~~ ~~42~~ 44\* bytes
```
a=_=>(x=1)+(x<15?", a="+a:"").replace(x,x+1)
```
It's a function which extracts its own body (just `a`) and makes replacements in it. Getting the function body a built-in feature of JavaScript, though not being explicitly a quine operator (if it's invalid, will remove the answer).
```
a=_=>(x=1)+(x<15?", a="+a:"").replace(x,x+1);
alert(a());
```
In case it doesn't work properly embedded there (because for me it doesn't), you can see an example [there](http://www.es6fiddle.net/ij4kgl7v/).
---
\* - looks like the snippet produces the result without `a=`, making further calls impossible
[Answer]
# Python 2.7.10, ~~196~~ 92 - 10 = 82 bytes
Whee!!! This was fun. Much shorter now. :P
```
n=1;a='n=%d;a=%r;print n,a%%(n+1,a)if n!=15else"STOP!"';print n,a%(n+1,a)if n!=15else"STOP!"
```
---
### Explanation:
I started with this:
```
a='a=%r;print a%%a';print a%a
```
That is just a simple quine.
This is that with a counter added:
```
n=1;a='n=%d;a=%r;print n,a%%(n+1,a)';print n,a%(n+1,a)
```
`n` is a counter variable that is printed at the beginning. Then when its prints the `n=` part, it substitutes `n+1` for the `%d`. So from here it will count up infinitely.
And here is the final version. It adds an if clause to stop at 15, and prints "STOP!" as well.
```
n=1;a='n=%d;a=%r;print n,a%%(n+1,a)if n!=15else"STOP!"';print n,a%(n+1,a)if n!=15else"STOP!"
```
Old code:
```
a= ['if num==15:print"STOP!!!";exit()','print num','print"a=",a','print"num=",num+1', 'for s in a:print s']
num= 1
print num
if num==15:print"STOP!!!";exit()
print"a=",a
print"num=",num+1
for s in a:print s
```
~~Never going to win, but fun. :P~~ Much shorter now, though I still don't stand a chance. :P
[Answer]
## PowerShell, ~~(215-10)=205~~ ~~197~~ ~~167~~ ~~106~~ ~~104~~ 103 bytes
```
$d='$c=(,1*{2}).count;$d={0}{1}{0};(("$c, $d"-f[char]39,$d,($c+1)),$c)[$c-eq15]';"1, $d"-f[char]39,$d,2
```
(If your only tool is PowerShell, every problem looks like a nail. Wait...)
Essentially, we start with setting `$d` equal to a big-ole-lengthy string of an almost-[quine](https://codegolf.stackexchange.com/a/57648/42963) of the original code. It outputs `1` and then `$d` with the format operator `-f` to correctly populate the `{0}`,`{1}`,`{2}` stand-ins, incrementing the `{2}` number in the `,1*{2}` section by one each time.
The `,x*y` operation in PowerShell creates a new array of `y` items, each of which is equal to `x`. For example, `,2*3` is equivalent to `@(2,2,2)`.
This means, the first output will be `1, $c=(,1*2).length;$d=(etc...)`, so when the second code is executed, `$c` will equal the count of the array `@(1,1)`, or `2`, etc. Note that `$c` isn't used as a variable in the original code, just in subsequent runs.
Stops when it prints 15 by simply calculating whether `$c` equals `15` and then indexing into an array, the 0th element is `$c, $d` as described above, the other is just `15`. Thus, when `$c` is 15, it'll output `15` and nothing else. Doesn't qualify for the bonus, because `"15, {0}STOP!{0}"` is 5 characters too long for the -10 to be worthwhile.
Requires a PowerShell terminal of width > ~150. Or for you to manually remove the extra linebreak (that the terminal *helpfully* inserts on output wrap) when copy-pasting the code. Or for you to capture output into a variable and then re-execute that variable. Etc.
Edit 1 -- Saved some bytes by removing the "STOP!" wording.
Edit 2 -- Durr, don't use .length each time, just call it once
Edit 3 -- Doesn't need to be a quine, so the initial run can be a lot shorter
Edit 4 -- Changed from using strings to arrays to calculate `$c`, which saved two bytes. I'm pretty sure this is almost optimal for this approach.
Edit 5 -- Saved another byte by directly counting equality rather than modding
[Answer]
## JavaScript, 79 - 10 = 69 bytes
```
s='STOP!';for(i=15;i;){s=i--+',alert("'+s.replace(/[\\"]/g,"\\$&")+'")'};alert(s)
```
Without using `Function.prototype.toString` in any way at all.
[Answer]
# Befunge, 57 - 10 = 47 bytes
```
1:'!`'#*j:.',,1+:9`''*'0++,1#;:0g:48*`j@,1+;"!POTS",,,,,@
```
This one is awesome. Try it [here](http://befungius.aurlien.net).
[Answer]
## Batch, 73 + 5 - 10 = 68 bytes
```
@set a=STOP!
@for /l %%a in (15,-1,1)do @set a=%%a, @echo !a!
@echo %a%
```
Requires `CMD /V:ON` so I added 5 bytes for that.
[Answer]
## Python 2.7, 107 characters
By using recursion and *not* writing a quine, I thought I could save a lot, which is true, but not good enough. Although not a winner, I think the approach is fun to share.
I started by making up a string for N=4, escaping the `\` and `"` characters.
```
print "1, print \"2, print \\\"3, print \\\\\\\"4, print \\\\\\\\\\\\\\\"STOP!\\\\\\\\\\\\\\\"\\\\\\\"\\\"\""
```
Then I created a lambda function that creates this string, based on a start index and a stop index, using recursion. This is it:
```
l=lambda n,m:str(n)+", print "+"\\"*(2**(n-1)-1)+"\""+l(n+1,m)+"\\"*(2**(n-1)-1)+"\"" if n<m else "STOP!"
```
Use it like this:
```
print l(1,15)
```
Output: *[32902 characters, too long to handle]*
So, it seems that my kolmogorov complexity approach isn't that successful ;-)
[Answer]
## [SMBF](https://esolangs.org/wiki/Self-modifying_Brainfuck), 28 bytes
`\x10` represents a literal byte (decimal value 16). The integer is output as an integer (byte). So the first *character* output is `\x01`. The program then prints ", ". When printing its own source, it prints an extra `+` at the beginning.
```
+.<-<<.>.>[[<]>.[.>]<[-]], \x10
```
Explanation:
```
+. Increment number and print
<- Pre-decrement loop counter
<<.>.> Print comma and space from own source
[ ] Only execute if loop counter != 0
[<]>. Move to left of source, then print `+`
[.>] Print entire source.
<[-] Zero out the loop counter so this program halts.
, \x10 The comma, space, and loop counter used earlier.
Input is empty, so `,` doesn't do anything.
```
Note that you cannot run this in a standard interpreter because it requires a hex literal in the input. You also need a special terminal for hex output to work properly.
[Answer]
# Bash, ~~78~~ ~~74~~ 73 - 10 = 63 bytes (Example, can't win)
```
p='if(($((++a>15))));then unset a p;fi;echo ${a-STOP\!}${p+, $p}';eval $p
```
Coming in late, but saw bash hadn't been tried so gave it a go. First gulf challenge and quine-like puzzle. They're fun!
### Explanation:
This works because `a` steps from 1 to 15 and is then `unset` along with `p`. The script (stored in `p`) prints them both out if they're `set` and "STOP!" otherwise. The initially `unset` `a` is `set` to 0 because it appears in an arithmetic expansion.
[Answer]
# ùîºùïäùïÑùïöùïü, 30 chars / 47 bytes (non-competitive)
```
⟮a=1)+(a<ḏ?⬬+ⒸⅩ222+ᶈ0:⬯)ē(a,⧺a
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=&code=a%3D1%29%2B%28a%3C%E1%B8%8F%3F%E2%AC%AC%2B%E2%84%B9%29%3A%E2%AC%AF%29%C4%93%28a%2C%E2%A7%BAa)`
Finally found a good ol' true quine for ùîºùïäùïÑùïöùïü.
# Explanation
Here's the true quine that I used: `⟮ⒸⅩ222+ᶈ0`
You see it in my answer? Hopefully, y'all will be able to expand from there.
[Answer]
## [Keg](https://esolangs.org/wiki/Keg)+PHP, 19-10=10 bytes
```
ï_(. \,,,)\!POTS(,
```
Counts from 1 to 15 and then stops. [TIO](https://tio.run/##y05N//@f//D6eA09hRgdHR3NGMUA/5BgDZ3//wE)
## Keg, 13 bytes
```
ï_(. \,,,).
```
[Answer]
# [Python 2](https://docs.python.org/2/), 68 (-10) bytes, [Python 3](https://docs.python.org/3/), 69 (-10) bytes
My previous answers were incorrect. That's now fixed :)
## Python 2 (68 bytes, 58 points)
```
a,b="print'%d, a,b=%r,%d;exec a'%(b,a,b+1)*(b<16)or'STOP!'",1;exec a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P1EnyVapoCgzr0RdNUVHAcRVLdJRTbFOrUhNVkhUV9VI0gEKahtqamkk2RiaaeYXqQeH@AcoqivpGEIVcVFiiBE1DDGmhiEmMEPA@pX09PSUKDLP0JQarjI0g6r6/x8A "Python 2 – Try It Online")
## Python 3 (69 bytes, 59 points)
```
a,b="print(f'{b}, a,b=%r,{b+1};exec(a)'%a*(b<16)or'STOP!')",1;exec(a)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P1EnyVapoCgzr0QjTb06qVZHASSiWqRTnaRtWGudWpGarJGoqa6aqKWRZGNopplfpB4c4h@gqK6ppGMIk@aixBQjqphiTBVTTOCmQAxQ0tPTU6LMSENTqrjM0Awm//8/AA "Python 3 – Try It Online")
## How it works:
* I started from the quine `a="print("a=%r;exec(a)"%a);exec(a)"`
* I assign `b` to the value to be printed
* Then I print `b,` and the quine replacing `b` by `b+1`
* If `b` is equal to `16`, I print `STOP!` intead
] |
[Question]
[
# Task
Given a string composed of ASCII printable characters, return how many strings could fit the given pattern with character literals and regex-like ranges.
# Pattern string
The pattern string follows this grammar (the | means an option and the \* means 0 or more occurrences of whatever was immediately to the left):
```
pattern := '' | pattern_string
pattern_string := (SAFE_CHAR | ASCII_RANGE) pattern_string*
ASCII_RANGE := '[' CHAR '-' CHAR ']'
```
where `CHAR` is any ASCII character in the range `[32, 127]` and `SAFE_CHAR` is any `CHAR` except the three characters `[`, `-` and `]`.
## Examples
Examples of pattern strings would be `a`, `[0-*]4fj`, `[a-z][4-9]D[d-B]`.
# Input
The pattern string. You can assume all ranges are well-formed and that all the second characters in the ranges have their ASCII codepoints `>=` than the corresponding first characters in the range.
# Output
The integer corresponding to the number of strings that match the given pattern string.
# Test cases
```
"" -> 1
"a" -> 1
"[*-0]" -> 7
"[0-9][0-9]" -> 100
"[a-z]d[A-z]" -> 1508
"[<->]" -> 3
"[!-&]" -> 6
"[d-z]abf[d-z]fg" -> 529
"[[-]]" -> 3
"[a-a][b-b]cde[---]" -> 1
"[0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1]" -> 4096
"[--[][--]]" -> 2303
"[[-[].[]-]]" -> 1
```
You can check [this Python reference implementation](https://tio.run/##nVLLboMwELznK7YcmkDZCtRTo4LU73CsiIdpkFxAtlHVRvl2un5Qcu5lZj07Hi8rpm9zGYeXZWlFB804D@ag4@MO4HOWpp9kLxQUkJPwdemlAG17AH0HmmUcigL2bO81gHMKjUwdKUeJpsuaHXkwjKqlPqENJTo0Mk59oeLgoWhrg9L51miASfU0nM3fvHdDJoXPRX/7yc0MIKQWa4YfJqdpSFDCzGq4S1iM0ObcVFpYHyNLFKUWK08swYyHMsNX7iCcK/zhLXsnDMIblmv5gI9r2ZKhqjvH3UcQGfItpuKsxpo3rWCIuD2X839CSEBknODvJUbnZ8atsKN1dKMC@/nQD7Ctwe7Nb72LTtHVNm6nCLCEq/9TrBLfonj5BQ) that I used to generate the test cases.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest submission in bytes, wins! If you liked this challenge, consider upvoting it... And happy golfing!
---
This is the second challenge of the [RGS Golfing Showdown](https://codegolf.meta.stackexchange.com/q/18545/75323). If you want to participate in the competition, you have 96 hours to submit your eligible answers. Remember there is still 400 reputation in prizes! (See 6 of [the rules](https://codegolf.meta.stackexchange.com/q/18545/75323))
Also, as per section 4 of the rules in the [linked meta post](https://codegolf.meta.stackexchange.com/q/18545/75323), the "restricted languages" for this second challenge are: [05AB1E](https://codegolf.stackexchange.com/a/200009/75323), [W](https://codegolf.stackexchange.com/a/200004/75323), [Jelly](https://codegolf.stackexchange.com/a/200043/75323), [Japt](https://codegolf.stackexchange.com/a/200132/75323), [Gaia](https://codegolf.stackexchange.com/a/200042/75323), [MathGolf](https://codegolf.stackexchange.com/a/200033/75323) and [Stax](https://codegolf.stackexchange.com/a/200037/75323), so submissions in these languages are not eligible for the final prize. But *they can still be posted!!*
Otherwise, this is still a regular [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") challenge, so enjoy!
[Answer]
# [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) machine code ([Intellivision](https://en.wikipedia.org/wiki/Intellivision)), ~~23~~ 22 DECLEs1 ≈ 28 bytes
*As per the exception described [in this meta answer](https://codegolf.meta.stackexchange.com/a/10810/58563), the exact score is **27.5 bytes** (220 bits)*
A routine taking a null-terminated string as an inline argument through **R4** and returning the result in **R1**.
```
**2B9 001** | MVII #1, R1
**2A0** | @@read MVI@ R4, R0
**080** | TSTR R0
**204 00F** | BEQ @@rtn
**378 05B** | CMPI #'[', R0
**22C 007** | BNEQ @@read
**2A0** | MVI@ R4, R0
**00C** | INCR R4
**320** | SUB@ R4, R0
**020** | NEGR R0
**008** | INCR R0
**004 11C 1DC** | CALL MULT
**091** | MOVR R2, R1
**220 012** | B @@read
**0A7** | @@rtn JR R4
```
### A note about subroutine calls
The CP-1610 instruction for calling subroutines is `JSR Rx, $address`. This instruction saves the return address in `Rx` instead of pushing it on the stack as many other CPUs do.
This allows to pass a block of arguments that immediately follows the function call. This is a common practice in CP-1610 programming and that's what we use here.
```
JSR R4, count ; call to subroutine through R4
STRING "[*-0]", 0 ; argument
... ; we will return here
```
Obviously, the subroutine is responsible for reading the correct number of arguments and eventually jumping to the expected return address.
### Full commented test code
```
ROMW 10 ; use 10-bit ROM width
ORG $4800 ; map this program at $4800
PNUM QEQU $18C5 ; EXEC routine: print a number
MULT QEQU $1DDC ; EXEC routine: signed multiplication
;; ------------------------------------------------------------- ;;
;; main code ;;
;; ------------------------------------------------------------- ;;
main PROC
SDBD ; set up an interrupt service routine
MVII #isr, R0 ; to do some minimal STIC initialization
MVO R0, $100
SWAP R0
MVO R0, $101
EIS ; enable interrupts
MVII #$200, R3 ; R3 = backtab pointer
JSR R4, count ; test cases
STRING "", 0
CALL print
JSR R4, count
STRING "a", 0
CALL print
JSR R4, count
STRING "[*-0]", 0
CALL print
JSR R4, count
STRING "[0-9][0-9]", 0
CALL print
JSR R4, count
STRING "[a-z]d[A-z]", 0
CALL print
JSR R4, count
STRING "[<->]", 0
CALL print
JSR R4, count
STRING "[!-&]", 0
CALL print
JSR R4, count
STRING "[d-z]abf[d-z]fg", 0
CALL print
JSR R4, count
STRING "[[-]]", 0
CALL print
JSR R4, count
STRING "[a-a][b-b]cde[---]", 0
CALL print
JSR R4, count
STRING "[0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1][0-1]", 0
CALL print
JSR R4, count
STRING "[--[][--]]", 0
CALL print
JSR R4, count
STRING "[[-[].[]-]]", 0
CALL print
DECR R7 ; done: loop forever
ENDP
;; ------------------------------------------------------------- ;;
;; prints the result of a test case ;;
;; ------------------------------------------------------------- ;;
print PROC
PSHR R5 ; save the return address on the stack
MOVR R1, R0 ; R0 = number to print
MVII #4, R1 ; R1 = number of digits
MOVR R3, R4 ; R4 = backtab pointer
ADDI #5, R3 ; advance by 5 characters for the next one
PSHR R3 ; save R3
CLRR R3 ; R3 = attributes (black)
CALL PNUM ; invoke the EXEC routine
PULR R3 ; restore R3
PULR R7 ; return
ENDP
;; ------------------------------------------------------------- ;;
;; ISR ;;
;; ------------------------------------------------------------- ;;
isr PROC
MVO R0, $0020 ; enable display
CLRR R0
MVO R0, $0030 ; no horizontal delay
MVO R0, $0031 ; no vertical delay
MVO R0, $0032 ; no border extension
MVII #$D, R0
MVO R0, $0028 ; light-blue background
MVO R0, $002C ; light-blue border
JR R5 ; return from ISR
ENDP
;; ------------------------------------------------------------- ;;
;; our routine ;;
;; ------------------------------------------------------------- ;;
count PROC
MVII #1, R1 ; initialize R1 to 1
@@read MVI@ R4, R0 ; R0 = current character
TSTR R0 ; end of string?
BEQ @@rtn ; if yes, return
CMPI #'[', R0 ; is this a '['?
BNEQ @@read ; if not, just go on with the next character
MVI@ R4, R0 ; R0 = ASCII code of the starting character
INCR R4 ; skip the '-'
SUB@ R4, R0 ; subtract the ASCII code of the ending character
NEGR R0 ; negate
INCR R0 ; increment
CALL MULT ; compute R2 = R0 * R1
MOVR R2, R1 ; and save the result in R1
B @@read ; go on with the next character
@@rtn JR R4 ; return
ENDP
```
### Output
[](https://i.stack.imgur.com/jIP2c.gif)
*screenshot from [jzIntv](http://spatula-city.org/~im14u2c/intv/)*
---
*1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.*
[Answer]
# [Haskell](https://www.haskell.org/), ~~50~~ 48 bytes
```
f[]=1
f('[':a:b:c:s)=length[a..c]*f s
f(a:s)=f s
```
[Try it online!](https://tio.run/##nY1BDoJADEX3nqJOjCixBJZOxMRzNF10gAEiTIiw8vLjMIQLuHl9/zdNO5nfzTB4b4nL4mAvCSVatNGVnq/l0Lh26UiyrOLUwhz2svZB/Si9gxKmT@8WOMEoE1ggpW6gZAWlmHOUHO8cEZPgl2t6Bcb4wOcmRzxvUoeVGBunbWNFyPuxMBk0XNUNIeL@oOA/odj/AA "Haskell – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~66 65~~ 60 bytes
```
s=>(s.replace(/\[.../g,s=>r*=([,b]=Buffer(s))[3]-b+1,r=1),r)
```
[Try it online!](https://tio.run/##rdLBTsQgEAbgu0@x7sHA2qF0u6s2kU30NcY5QAuNptluqHrw5SvtUXrZIoefhMMH/JkP/a2H2r9fPuHcN3Z0ahzUiQ3C20una8vyNxRC5G0Wjv1OMcwMqdcv56xnA@dYEpj7IvOq4JnnY92fh76zoutb5th2y/kmaeX5prj5g@pUdQnFHUhKgQP6GKESKppjpTy9VMqI1fBDDb6EXOdO7FE@Re4znFI7KCP0Fu5S0YcIbcLftXHz7trr@YAe91XEItD/F6BBExowVDcWAeDaGxbHVUJBK2O@PqAHWcXFAiCFoISJ3ZeyXGgWSSCthqcSxl8 "JavaScript (Node.js) – Try It Online")
### Commented
```
s => ( // s = input string
s.replace( // find in s all occurrences of
/\[.../g, // '[' followed by 3 characters
s => // given the matched string s:
r *= // multiply r by:
([, b] = Buffer(s)) // the difference between
[3] // the ASCII code of the 4th character
- b // and the ASCII code of the 2nd one
+ 1, // + 1
r = 1 // start with r = 1
), // end of replace()
r // return r
) //
```
---
# [JavaScript (Node.js)](https://nodejs.org), ~~65~~ 64 bytes
A recursive solution.
```
f=s=>s?-~([g,b,,c]=Buffer(s),!(g^=91)*(c-b))*f(s.slice(g?1:5)):1
```
[Try it online!](https://tio.run/##rdJBT8MgFAfwu59i28FA09fBatUudot@DfJMgAKZaVYz1IMHv3qlPUovK3L4c/s9@Oe9yS/p9eX0/gHnvjXDYBvfHPwRfohwucpzjc3Lp7XmQjzN18S9NjWnGdGgKM0s8YXvTtoQd@T7itI9H3R/9n1niq53xJLNhtJV0tluV/zmDypT1TlUZMAwBQ7oQ4QyqHGKhfL4UsYiVsI3tuI55DJ3ZCv2GLlPcEjtoIzQNdymovcR2oa/S2Wn27rr@YBWuzpiBeD/FyBBolCgULdGAMC1E2bXlQHHhTGND@gdq@NiAQSGwISN3ZWsnGlWYCFwMTyWMPwC "JavaScript (Node.js) – Try It Online")
### Commented
```
f = s => // f is recursive function taking a string s
s ? // if s is not empty:
-~( // add 1 to the result of the multiplication below
[g, b,, c] = // g, b, c = ASCII codes of 1st, 2nd and 4th characters
Buffer(s), //
!(g ^= 91) * // true if g is a '[', or false otherwise
(c - b) // multiply it by the width of the ASCII range
) * // multiply by ...
f( // ... the result of a recursive call
s.slice(g ? 1 // discard 1 character if it was not a group
: 5) // or 5 if it was
) // end of recursive call
: // else:
1 // stop recursion
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~22~~ 21 bytes
*1 byte saved thanks to [@DeathIncarnate](https://codegolf.stackexchange.com/users/91386/deathincarnate)*
```
'\[.-.'XX"@gHKh)dQ]vp
```
[Try it online!](https://tio.run/##y00syfn/Xz0mWk9XTz0iQskh3cM7QzMlMLasACgcrasbHQskYmPVAQ) Or [verify all test cases](https://tio.run/##y00syfmf8F89JlpPV089IkLJId3DO0MzJTC2rOC/S8h/dXUu9UQgjtbSNYgF0Qa6lrFgAsRJ1K2KTYl2BJIgno2uHZhW1FUD0ylA8cSkNDCdlg4SidaNhepLjI1O0k2KTU5JjdbV1YWabBhLJgHSrqsbHQskIBZEAzl60bEgHgA).
### How it works
```
'\[.-.' % Push this string, to be used as regexp
XX % Implicit input. Cell array of substrings that match the regexp
" % For each
@g % Push current substring
HKh % Push 2, then 4, concatente horizontally: gives [2 4]
) % Index: gives a string of two chars
d % Consecutive difference (of code points)
Q % Add 1
] % End
v % Concatenate all stack contents vertically (result may be empty)
p % Product. Implicit display
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~58~~ ~~56~~ ~~54~~ ~~52~~ 50 bytes
```
f(char*s){s=*s?*s++-91?f(s):(s[2]-*s+1)*f(s+4):1;}
```
[Try it online!](https://tio.run/##tdJBT8IwFAfws36KMaNpOx@0G6gDhPg56jt0LYUlOA3Fi4TPPssit3JgjT28Nj38@vrP07DWur2rG739Nqtk7vam/hxuFq0leqN2zNGDe2VuyVyWQSmWljg6JU7mCP5KUOYvsjGditmx/VB1Q@jh9mtXN3tL0nvz3qSPiT@llM6SmDUaJSLgqlj4gisZcIyxvfsccjmU2JWe@KlfzkOygh808s3XfvRJnvCXED2HRWwYRcgdwEOs@xRyjQ9BVbbb7fr6F7w7ycuQLAH/JQkFCmUFFWqzkgBw7SOXxpiDwJ6l68C7Y14GQwaQ6AtGTHJe8CKcssShxD/7plvnTx7bXw "C (gcc) – Try It Online")
Thanks to @S.S. Anne for 2 bytes, and to @Arnauld for 2 more bytes!
This is a recursive solution in C.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~31~~ ~~21~~ ~~20~~ 19 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ü5ε2ι`Çs…[-]Q*ÆÄ>}P
```
-10 bytes thanks to an alternative approach suggested by @ExpiredData.
-2 bytes and a bugfix for `[[-[].[]-]]` thanks to *@Grimmy*.
[Try it online](https://tio.run/##yy9OTMpM/f//8B7Tc1uNzu1MONxe/KhhWbRubKDW4bbDLXa1Af//R6foVsUmJqWB6bR0AA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/w3tMz201Orcz4XB78aOGZdG6sYFah9sOt9jVBvzX@R@tpKSjlAjE0Vq6BrEg2kDXMhZMgDiJulWxKdGOQBLEs9G1A9OKumpgOgUonpiUBqbT0kEiQNOh@hJjo5N0k2KTU1KjdXV1oSYbxpJJgLTr6kbHAgmIBdFAjl50LIgXCwA).
**Explanation:**
```
ü5 # Push all substrings of length 5 of the (implicit) input-string
ε # Map each substring abcde to:
2ι # Uninterleave it into 2 blocks: [ace, bd]
` # Push both strings separated to the stack
Ç # Convert the top (bd) to a list of ASCII codepoint integers [B,D]
s # Swap to get the other string (ace) at the top again
…[-]Q # Check if it's equal to "[-]" (1 if truthy; 0 if falsey)
* # Multiply the codepoints by that ([B,D] if truthy; [0,0] if falsey)
ÆÄ # Take the absolute difference between those two (D-B if truthy; 0 if falsey)
> # And increase this by 1
}P # After the map: take the product (which will of course be 1 for empty lists)
# (after which this is output implicitly as result)
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~77~~ \$\cdots\$ ~~59~~ 58 bytes
Saved 2 bytes thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen)!!!
Saved ~~11~~ 13 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
```
r;f(char*s){for(r=1;*s;)r*=*s++-91?1:1-*s+(s+=3)[-1];s=r;}
```
[Try it online!](https://tio.run/##tdOxTsMwEAbgvU8RIoFsh1PthhaCCYjncG9wHNx2ICCbiarPHq6Z3aGx8HC@6Tvr19nBzrlxDNozt7dBRH70X4GFVmkRNQ@iFbGqoFFv6lkB9SxWbc0NKNSxDfo0ftrDwPhx8R0Ow49n5W2/Hcr7grqSc13knOWyUAnX5sIXXCNAYo5N7mPKldDgVGbi5/dKmZIt/GJv3qnOo8/yWj6l6Bd4zQ2jTrk3cJfrblJuTyHYzk@3310/gdz1qknJBvBfkrBg0XTQoes/DABcO@TSGkv6nDPL9AJyH2STDBnAIBXM2ORVLevFafwD "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~77 75~~ 73 bytes
```
f=lambda s:s==''or'['!=s[0]and f(s[1:])or(ord(s[3])-ord(s[1])+1)*f(s[5:])
```
[Try it online!](https://tio.run/##nY/PToQwEMbvPEW3B2lXZ1MWUSGyie/grZlDEXBJEEjLxijh2XG2rO7dy3R@3zf/OnyNx76Ll6XOW/NRlIa5zOV5GPY21OEmd1qh6UpWC6ejDGVvRW9LghglrFmE8jaS23NFQhXLYJtuFLXgXMrg89i0FXu1pyoLmLuzedMNp1HInRvaZhScwYFxSRbL2XkDRBgwS2B3brTNIMi7DAz55GbfMNEuOTM92RlDuXAvRgE3v4negkIPjwQKUvRhtZUizcA3lvqF4iom6onUZzisHBNs4GaFB4KSKk1R@7d@93KyT8nQgNcWAwZ1AQW@lZUGAPw7SNHH/hn8jHuVns8A0EjhsnIfq/gH "Python 3 – Try It Online")
*-2 bytes thanks to @Arnauld*
*-2 bytes thanks to @KevinCruijssen*
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 37 bytes
```
{[*] map {137+[R-] .ords},m:g/\[.../}
```
[Try it online!](https://tio.run/##nY6xDoJADIZ3n6IyMICFQwXEKImvoOPR4RCOmIAQmJDw7OfliLq7/O33/23TruzrSDUj2BLOauIOQSM6mIJd7PIrEnhtXwzzpjlWfsY9z/NnNYgRJDR@dnN9kG0P9eNZDsqyAFMIVpb4NNxBRgZiDQwTMrLEjGlP4IsKftG6mCE7aPeE6cI7DWu0F4g0FHpS5NJUWRk73CY64Ei/FYGCeI453YuSIyJ9H2IY0J9ibuxZEr0B "Perl 6 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 73 bytes
```
function(s,i=el(gregexpr("\\[.-",s)),u=utf8ToInt(s))prod(u[i+3]-u[i+1]+1)
```
[Try it online!](https://tio.run/##nY5Pj4IwEMXvfgrFZFNWnmll/UMiJh69722cQxFKSAwYhMTsl2drF1y9ennT@b3OzKs7E3emLU9NUZXiGhRxdhZ5neXZ7VIL73ikObzg6vtBG7eN2XxXh7IRtr/UVSpaKmYh414Uz5TfGeF5/niK3ViN7Fs/N/QJyT1YOyARsZPhm5SOa/xwSnurg7GUG@dssRtY6MAEHwNYOZDaKZ0YV03eW8tF5EwCv45raKYECZ/SjADwS2AJxW9Kv@dLRn@xAGIrj/OLUIZ9JOI58b@jul8 "R – Try It Online")
Today I learned that to include the character `[` in a regexp, you need to escape it twice: `\\[`.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 40 38 36 29 27 bytes
```
1{\(91={(\(;(@-)}1if@*1$}do
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPmvFJ2oWxWbEu0IJJX@G1bHaFga2lZrxGhYazjoatYaZqY5aBmq1Kbk//8PAA "GolfScript – Try It Online")
With a bit of teamwork, Grimmy and I have this baby down fairly low. it's a shame my goofy integer trick is no longer here :( Check edits for a neat little GS trick.
```
1{\(91={(\(;(@-)}1if@*1$}do # Regex Counter
1 # Our stack is now [str 1]
{ }do # Pop the top value after a run. If it's true, loop.
{\ }do # Swap the top two element of the stack. [1 str]
{ (91={ }1if }do # Pop the first char and see if it's "[".
{ { } }do # If so, do the following.
{ {(\(;(@ } }do # Get rid of the garbage in our block, leaving just the params
{ { - } }do # Find the difference
{ { -)} }do # Increment
{ 1 }do # If the if statement fails, instead push a 1.
# At this point, our stack is [1 str dif] (dif may be 1)
{ @ }do # Bring our 1 up. [str dif 1]
{ * }do # Multiply our 1 by dif. [str dif*1]
{ 1$}do # Duplicate our string. [str dif*1 str]
# At this point, if our string is empty, our stack is
# ["" dif*1 ""], and we see the output. If it ISN'T
# empty, then dif*1 is our new 1, and the next loop
# works with this loop's dif instead of with a 1.
# This functionally multiplies all the values together.
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
```
*Fmhs.+CMtd:Q"\[.-."1
```
[Try it online!](https://tio.run/##nY27CsJAEEV7/8ItUkTvkpSKCiKk0mLrcYpdJw@EgGCa@PPrzpovsJhzORdm5jVPQ7y226MLsWzG4W03l9ske2fuZGFNHZ/jLNZFY1bGp6ESFWtW2HGGiseHhc6Jageccq5R5JTU@9Dl7HptCLzseaaAwA9pCcByueY/oesAccLvASWxxGpf "Pyth – Try It Online")
Standard regex match with `:Q"\[.-."1`. Then, we remove the leading `[` with `td` and convert to characters with `CM`.
Next, the clever part: `.+` gives deltas between the code points, and `s` adds up the deltas. This gives just the difference between the first and last characters, ignoring the `-`.
Finally, `h` adds one, and `*F` multiplies everything together.
[Answer]
# [C++ (gcc)](https://gcc.gnu.org/), 70 bytes
```
int f(char*s){int r=1;for(;*s;)r*=*s++-91?1:1-*s+(s+=3)[-1];return r;}
```
[Try it online!](https://tio.run/##tdPBUoMwEAbge58CcXQIuDYpVsWUOj5H3ENIoGWmUibQi50@OwbO6aFkzGGTXL7d@SdRbQs7pYahbvqgitRemrgj5/Fmcsaro4l43HFi4jzukgQy9sk@GNhz1CV5SgQw5KbsT6YJDL8M93WjDiddBhvV9bo@bhcj9SPrJiLnRWvsrYrCB/3dhE@2XxgSwgOftVwGzOFKX/iKK2Kg6GNb983lUshwKjPxcV5KXbKEX9Tiy9Z59Civ6buL3sDWN4zU5d7Bo6/76nK1DUEW1bRXu9s7WHe9ylyyAPyXJCRIFAUUqHQpAODWJteeMbX/dmaZJrDuC82cIQMItAU9XvIqpak7ZYHPAmfbUxqX4Q8 "C++ (gcc) – Try It Online")
[Answer]
# [BBC BASIC V](http://www.riscos.com/support/developers/manual_index/basic.html), 92 bytes
```
DEFFNf(X$):O=1:FORI=1TOLEN(X$):IFMID$(X$,I,1)="["THENO=O*(1+ASC(MID$(X$,I+3,1))-ASC(MID$(X$,I+1,1))):I=I+5
NEXT:=O
```
Defines a function that takes a single string argument and returns an integer. Note BBC BASIC V (as implemented on the Acorn Archimedes and RISC PC) was a tokenised language, so commands like `MID$` are a single byte. Unfortunately I can't find an online implementation of this, but [RPCEmu](http://www.marutan.net/rpcemu/index.php) can be used to test this.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 22 [bytes](https://github.com/barbuz/Husk/wiki/Codepage)
```
ΠmöLu…Ċ2mtf·=Ċ"[-]"2X5
```
**[Try it online!](https://tio.run/##yygtzv7//9yC3MPbfEofNSw70mWUW5J2aLvtkS6laN1YJaMI0////0fr6kbHAonYWAA "Husk – Try It Online")**
### How?
```
ΠmöLu…Ċ2mtf·=Ċ"[-]"2X5 - string S
X5 - sublists of length five
f - filter by predicate:
· - compose two functions:
Ċ 2 - 2-gaps (every 2nd element) (e.g. "[a-e]" -> "[-]")
= "[-]" - equal to "[-]"?
m - map with:
t - tail (e.g. "[a-e]" -> "a-e]")
m - map with:
ö - compose four functions:
Ċ2 - 2-gaps (every 2nd element) (e.g. "a-e]" -> "ae")
… - fill (e.g. "ae" -> "abcde" -- Note: "xx" -> "xx")
u - remove duplicates (e.g. "xx" -> "x")
L - length
Π - product
```
[Answer]
# brainfuck, ~~134~~ ~~125~~ 119 bytes
```
-[+[+<]>>+]<+++<+>>>,>+<[<<[->+>-<<]>>[[+]<<<[->+<]>>>>-]>[>,<,,>[-<->]<+<<<<[->>>>[-<+<<+>>>]<[->+<]<<<]>>>>>]+<,]<<<.
```
A commented version can be found below. Saved 9 bytes thanks to @S.S.Anne.
You can [try it online](https://copy.sh/brainfuck/?c=SW5pdCBhIGNlbGwgd2l0aCA5MQotWytbKzxdPj4rXTwrKysKPCs-Pj4sPis8Ck1lbTogYWNjdW11bGF0b3IgPSAxIHwgbGVmdCBicmFja2V0ID0gOTEgfCAwIHwgXmlucHV0IGNoYXIgfCAxIHwgMApbIElmIHNvbWV0aGluZyB3YXMgcmVhZApTdWJ0cmFjdCB0aGUgOTEgZnJvbSB0aGlzIGNoYXIKPDxbLT4rPi08PF0KPj4KTWVtOiBhY2N1bXVsYXRvciB8IDAgfCA5MSB8IF5pbnB1dCBtaW51cyA5MSB8IDEgfCAwClVzZSBub24gZGVzdHJ1Y3RpdmUgZmxvdyBjb250cm9sIHRvIGNoZWNrIGlmIHRoZSBpbnB1dCBjaGFyIHdhcyB0aGUgYmVnaW5uaW5nIG9mIGEgcmFuZ2UKWyBJZiB0aGUgYXNjaWkgY29kZSBwb2ludCB3YXMgbm90IDkxIHRoZW4gdGhpcyBpcyBhIHNhZmUgY2hhcmFjdGVyClplcm8gb3V0IHRoZSBpbnB1dCBjaGFyClsrXQpNb3ZlIHRoZSBhY2MgdG8gdGhlIHJpZ2h0Cjw8PFstPis8XT4-PgpSZW1vdmUgdGhlIGVsc2UgZmxhZwo-LV0gKGVuZCBpZikKPgpbIEVsc2UgdGhlIGNoYXJhY3RlciBzdGFydHMgYSByYW5nZSBhbmQgbGF5b3V0IGlzCk1lbTogYWNjIHwgMCB8IDkxIHwgMCB8IF4xIHwgMAo-LDwsLApNZW06IGFjYyB8IDAgfCA5MSB8IDAgfCBecmlnaHQgY2hhciB8IGxlZnQgY2hhcgpTdWJ0cmFjdCB0aGUgdHdvIGFuZCBhZGQgb25lCj5bLTwtPl08KwpNZW06IGFjYyB8IDAgfCA5MSB8IDAgfCBeZGlmZiBwbHVzIG9uZSB8IDAKICAgICAgICAgICAgICAgICAgICBBICAgQiAgICAgICAgICAgICAgICBDCk11bHRpcGx5IHRoZSBhY2N1bXVsYXRvciBieSB0aGUgZGlmZiBwbHVzIG9uZQpUaGUgZGlmZiBwbHVzIG9uZSB3aWxsIGJlIGp1Z2dsZWQgYXJvdW5kIEEgYW5kIEIKPDw8PFsgV2hpbGUgdGhlIGFjYyBpcyBzdGlsbCBub256ZXJvCi0-Pj4-ClstPCs8PCs-Pj5dCjxbLT4rPF0KPDw8Cl0gKGVuZCB3aGlsZSkKTWVtOiBeMCB8IGFjYyB8IDkxIHwgMCB8IGRpZmYgcGx1cyBvbmUgfCAwCj4-Pj4-Cl0gKGVuZCBlbHNlKQpNZW06IDAgfCBhY2MgfCA5MSB8IDAgfCA_IHwgXjAgfCAwClJlc2V0IHdvcmtwbGFjZQorPAosIFRyeSByZWFkaW5nIGFnYWluCk1lbTogYWNjIHwgOTEgfCAwIHwgXmlucHV0IGNoYXIgfCAxIHwgMApdCjw8PC4$), where you can check the "memory dump" to see that the final output is the correct result. In practice only works for tests where final result is `<= 255`.
You are welcome to golf my code, just keep it commented please. Then use [this Python script on TIO](https://tio.run/##fVRNb9swDL3rVxA5xbAdtNiphaqhHXbooZeuw4AZLqDIsq1WlgxJXpBh/z2j5CRLvxbEgE2Lj4/vkR63obfm007YRsIVLBaL3a1RATgIqTVsVOjh4pyUVV7ltGYsr2me54TmjLGC5ZTcyeESuBDTMGkerEOQc/gDWrYB1o6LZxkwdBFjZ3g9KjNOAUTPHT6lKKngtgVvBxl6ZTrYcA9O8oZ8m9YBEQKEXkaE1tkB75VP6YTSqmQ5KymtCWNvicwFU@V91UGZyc@RufJ3L8FYA430wU0iqF8SWm03IKwJzmoIFmtJ8QyqTSxO2EeaMbSWnTImErctyua46eTcUnzLvVAKkrqjVSakNGNDZIHvzdwP/jl43soEjS1LR35KZ8FO4VVdUuU1ubNINMELETnGW6e6PqAoSZVoFSP3cjgclNrH1nhHWFnDUpoGW8oIQ6Zf46t45lgbfOAu@EM3wPG05ttIRvmj0KcCJ2tnTVlBi@LjQ4nmwf80JamrF16HjU01edOANZKwqqQlw8n7GLZRbQujRnsxIfGAd37XeN28Dn4hd5MOatTbg6THEVrPoRfg5OF1BLcEV2Ut4WnqOi2Rt7MT0r9OTdxET2gFP3ql/5mGjvsQ03D8fqPTpGTRMWw0p2m5arI3MqaTvWWbiJHNKjzGvmcpjjK8VYEl2H16HIJ99jvJn6OOZynrXnpc2411z6PmQhLc8wIe3DbtZRx13nFlTt3474KnHlY7/LgQYkcfvzPFqqopy0uMjA73YumnYYmexU1ZCZQvLCNEBi3akMCUAcwlWXbIWCxWT7hSy1ZpnNml5sO6wc/WpdgfLRJYlmW7vw) to do the byte count and remove comments.
```
Init a cell with 91
-[+[+<]>>+]<+++
<+>>>,>+<
Mem: accumulator = 1 | left bracket = 91 | 0 | ^input char | 1 | 0
[ If something was read
Subtract the 91 from this char
<<[->+>-<<]
>>
Mem: accumulator | 0 | 91 | ^input minus 91 | 1 | 0
Use non destructive flow control to check if the input char was the beginning of a range
[ If the ascii code point was not 91 then this is a safe character
Zero out the input char
[+]
Move the acc to the right
<<<[->+<]>>>
Remove the else flag
>-] (end if)
>
[ Else the character starts a range and layout is
Mem: acc | 0 | 91 | 0 | ^1 | 0
>,<,,
Mem: acc | 0 | 91 | 0 | ^right char | left char
Subtract the two and add one
>[-<->]<+
Mem: acc | 0 | 91 | 0 | ^diff plus one | 0
A B C
Multiply the accumulator by the diff plus one
The diff plus one will be juggled around A and B
<<<<[ While the acc is still nonzero
->>>>
[-<+<<+>>>]
<[->+<]
<<<
] (end while)
Mem: ^0 | acc | 91 | 0 | diff plus one | 0
>>>>>
] (end else)
Mem: 0 | acc | 91 | 0 | ? | ^0 | 0
Reset workplace
+<
, Try reading again
Mem: acc | 91 | 0 | ^input char | 1 | 0
]
<<<.
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), ~~138~~ 133 bytes
```
I =INPUT
P =1
A =&ALPHABET
L =LEN(1)
N I '[' L . X L L . Y REM . I :F(O)
A X @S
A Y @E
P =P * (E - S + 1) :(N)
O OUTPUT =P
END
```
[Try it online!](https://tio.run/##HY3BCsIwEETPyVfMySaVCgVPhUArrhiISbAttIRcPIs9@P/ErZd5y@zO7Pezvbb3uRRhYayP8yRFhGmlGGAOg4v34ULsORhHXrVaer6sUgWHExbWnSue9GBa0d1U0Ht4QT/uXNHTvzKihiI0GHFEq0WnvJZBhHnip7yW5K@lpKZJmSXnlHj6AQ "SNOBOL4 (CSNOBOL4) – Try It Online")
[Answer]
# [Shakespeare Programming Language](https://github.com/TryItOnline/spl), ~~493~~ 398 bytes
-2 bytes thanks to Jonathan Allan
-87 bytes (!) thanks to Jo King
```
,.Ajax,.Ford,.Act I:.Scene I:.[Enter Ajax and Ford]Ajax:You cat.Scene V:.Ajax:Is I as big as the sum ofThe cube ofa big big cat the cube ofThe sum ofA big cat a cat?If notLet usScene X.Remember you.Open mind.Ford:Open mind.Open mind.You is the sum ofA cat the difference betweenYou I.Ajax:Recall.You is the product ofyou I.Scene X:.Ford:Open mind.Ajax:Is I worse zero?If notLet usScene V.Open heart
```
[Try it online!](https://tio.run/##bZBLasMwEIavMgdIdABtghcNCAKBNIQU44Ueo8TFloweJOnlXUk2dihdaPQP843mH/mhG8cNqb75c0P21qmkZQBGyadEg1nUHyagg4wANwoy1eSMftkIkocZvdDyDGUeGHAPor3lK9wRfOzB6nNSMgpMkpdqPqm/IHPhvNDVUuY57pgGY8MBA0Q/DbySE/bYi2TuZSM5Dmigb40qe9A1XVU23L5bqpb5qtUaHRqJIDA8EE2G2bTSCSXvuvf2wVkV00dZ/SrY7Ij@nb3@yMM6j/CDzv6zymUyeUfuwjjWfCuaEmSttrr5BQ "Shakespeare Programming Language – Try It Online")
Ford is initialized as `1`. Ajax reads through the input. When he encounters a `[`, Ford reads the next and Ajax the third next character, and Ford is multiplied by the difference + 1. When Ajax reaches the end of the input, Ford opens his heart, printing his value.
The shortest representation I found of 91 (the ASCII code of `[`) is \$91=(2\times2)^3+(2+1)^3\$ but there might be something better.
With spaces and comments:
```
,.Ajax,.Ford,. A = F = 0
Act I:.Scene I:.
[Enter Ajax and Ford]
Ajax: You is a cat. F = 1
Scene V:.
Ajax: Is I as big as the sum of if not(A == 91) (with 91=64+27)
The cube of a big big cat (2*2)^3 (=64)
the cube of The sum of A big cat a cat? (2+1)^3 (=27)
If not Let us Scene X. go to Scene X
Remember you. F[2] = F
Open mind. F = stdin
Ford: Open mind. Open mind. A = stdin
You is the sum of A cat the difference between You I. A = 1 + A -F
Ajax: Recall. F = F[2]
You is the product of you I. F = F * A
Scene X:.
Ford: Open mind. A = stdin
Ajax: Is I worse zero? If not Let us Scene V. if not(A<0) go to Scene V
Open heart print(F)
```
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~80~~ 76 bytes
```
r=>{int c=1,i=r.Length;for(;i-->1;)c*=r[i]==93?r[--i]-r[i-=2]+1:1;return c;}
```
[Try it online!](https://tio.run/##nZA9b8IwEIZ3fkVgQAnNIQwTGAchJCZ2BuuGxLHTkypHujhLq/72YNG5RmJ5707vo/syA5iBpuvozXEITL4rM/KhypyaWFU/Mc@MEiUpXt@s78KndD3nkgAqIQuzUqwJldrvTqwBCCHWoLb4IQ5Csg0j@8zI30nOZpfeD/2XXd@Zgr2Rt7nL88WiKAr5j1enTL2CDSaBDezxKUmqhm9s9TlqEjtClQbmsEwDbRxRN@4ZXfdipxp1Aw2a1sa3wqs7Bb4pyb4AGqPgHzU9AA "C# (Visual C# Interactive Compiler) – Try It Online")
Port of @KevinCruijssen's [Java answer](https://codegolf.stackexchange.com/a/200260/85908)
[Answer]
# Java 8, ~~80~~ 76 bytes
```
r->{int c=1,i=r.length;for(;i-->1;)c*=r[i]==93?r[--i]-r[i-=2]+1:1;return c;}
```
-4 bytes thanks to *@ExpiredData*.
[Try it online.](https://tio.run/##nVKxbsIwEN35CjdDcUgvIu0EbqhQ57Iwph4cxwHT4KCLoaKIb0@NQ6U2bF3e6d6dz0/vbiMOAjbFRysr0TTkTWhzGhCijVVYCqnI4pJ6gkgq1wIzTjBkjjwPHCyIIWmLMDv5jjR50CnGlTIru2ZljZRpgFnCQjlKMdM8TSdPL5gBaA4uh/SRR8k0YajsHg2R7Nyyy9zdPq@0JI0V1oVDrQuyddro0qI2K6dBhJ0wqxpLg8Ar@snE3zQbwZj3qDFMuIceL@CLF9ncYa/wDLM@dQf3fapwD0Ve@liubmYLnuWQc1ko5wDcakr4P6E3CSDjDviV95v6baVv66x0y@yMXB4bq7ZxvbfxzhVsZegwGEYYBe/BlASRUZ/@PGgYm1hSjG396s5hjiiONAyvH53bbw)
**Explanation:**
```
r->{ // Method with character-array parameter and integer return-type
int c=1, // Count-integer, starting at 1
i=r.length; // Index integer, starting at the length of the input
for(;i-->1;) // Loop as long as the index is larger than 1,
// and decrease the index every iteration by 1 right after this check
c*= // Multiply the count by:
r[i]==93? // If the `i`'th character of the input is a ']':
r[--i] // Take the `i-1`'th character, by decreasing `i` with 1 first
-r[i-=2] // And decrease it by the `i-3`'th character,
// due to the earlier `--i` and by first decreasing `i` with 2 first
+1 // And add 1 to that difference
// (NOTE: We've only decreased `i` by 3 instead of 4 here, but this
// doesn't matter, since it will always be the '[' character of the
// previous block in the next iteration, and thus multiplying by 1
// in the else block)
: // Else (single character match):
1; // Keep the count the same by multiplying with 1
return c;} // And then return this count as result
```
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 149 bytes
```
[S S S T N
_Push_1][N
S S N
_Create_Label_LOOP][S N
S _Duplicate][S N
S _Duplicate][T N
T S _Read_STDIN_as_character][T T T _Retrieve_input][S N
S _Dupe][S S S T S T S N
_Push_10][T S S T _Subtract][N
T S S S N
_If_0_Jump_to_Label_DONE][S S S T S T T S T T N
_Push_91][T S S T _Subtract][N
T S S N
_If_0_Jump_to_Label_BLOCK_FOUND][N
S N
N
_Jump_to_Label_LOOP][N
S S S N
_Create_Label_BLOCK_FOUND][S N
S _Duplicate][S N
S _Duplicate][T N
T S _Read_STDIN_as_character][T T T _Retrieve][S N
S _Duplicate][S N
S _Duplicate][S N
S _Duplicate][T N
T S _Read_STDIN_as_character][T N
T S _Read_STDIN_as_character][T T T _Retrieve][S N
T _Swap_top_two][T S S T _Subtract][S S S T N
_Push_1][T S S S _Add][T S S N
_Multiply][S N
S _Duplicate][T N
T S _Read_STDIN_as_character][N
S N
N
_Jump_to_Label_LOOP][N
S S S S N
_Create_Label_DONE][S N
N
_Discard][T N
S T _Print_as_integer]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
Since Whitespace inputs one character at a time, the input should contain a trailing newline (`\n`) so it knows when to stop reading characters and the input is done.
[Try it online](https://tio.run/##bYxBCoAwDATPm1fsB3yReKjaqreCguDnYxKpXqShyU6YnOt25L2mKauShAgpjA8CAvBgC3uWAzKQL61eaKa4/aN/uTG4xXYOj@ShHYkBxlT7ubuGNJboZZEb) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Integer count = 1
Start LOOP:
Integer c = read STDIN as character
If(c == '\n'):
Jump to Label DONE
If(c == '['):
Jump to Label BLOCK_FOUND
Go to next iteration of LOOP
Label BLOCK_FOUND:
Integer a = read STDIN as character
Read STDIN as character (without saving it)
Integer b = read STDIN as character
Integer diff = b - a
diff = diff + 1
count = count * diff
Read STDIN as character (without saving it)
Go to next iteration of LOOP
Label DONE:
Print count as integer to STDOUT
```
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), 30 bytes
```
1v;>.@; <
*>#^~'[-#^_~~$~\1--
```
[Try it online!](https://tio.run/##S0pNK81LT9W1tNAtqAQz//83LLO203OwVlCw4dKyU46rU4/WVY6Lr6tTqYsx1NX9/z86UbcqNiXaEUgCAA "Befunge-98 (PyFunge) – Try It Online")
### Explanation
```
1v
>
```
Push `1` to the stack and move east in the second line
```
>.@
#^~
```
Input character (`~`), if no input is left print the TOS (`.`) and quit the execution (`@`).
```
'[-#^_
```
Subtract `[` from the input, if the input is `[` continue east, otherwise go north.
```
1v;>.@; <
>
```
Case input ≠ `[`: Go back to the start of the second line.
```
*> ~~$~\1--
```
Case input = '[': Take the next three characters of input, discard the `-`, and compute the difference between the two remaining chars, multiply this to the current result.
Animation of the code for input `a[0-9]`:
[](https://i.stack.imgur.com/1emMt.gif)
[Answer]
# Haskell, ~~66~~ 64 bytes
Non-regex solution.
```
f[]=1
f('[':a:b:c:d:s)=(1+(g c)-(g a))*f s
f(a:s)=f s
g=fromEnum
```
You can [try it online](https://tio.run/##y0gszk7Nyfn/Py061taQK01DPVrdKtEqySrZKsWqWNNWw1BbI10hWVMXSCZqamqlKRQDFSWCpEDMdNu0ovxc17zS3P@5iZl5CrYKBUWZeSUKKgppCkrRKbpVsYlJaWA6LV3pPwA)! Uses the algorithm in my Python reference implementation.
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 87 bytes
-5 byte thanks to [@SurculoseSputum](https://codegolf.stackexchange.com/users/92237/surculose-sputum)
```
lambda s:math.prod(ord(m[3])-ord(m[1])+1for m in re.findall(r'\[.-.',s))
import re,math
```
[Try it online!](https://tio.run/##nYxNTgMxDIX3PkXYtAmto466gQqQOIfrRYZM2kiTHyXZlMsPmYET4MVn@9nv5Ue7p3h@yWVx4l1cl9mE0RpRL8G0u84lWZmKlYHOrPB3GlgdBpeKCMJHUSbtfLRmnmXZX0mj3h@rUuBDTqX183FNWv7W@qgAq3f2cVrtXdC1WR8vIHrl4mOTTq5npRYwQM94YqATvvIGIIPfbOmzE@gNPzqfcNdpu2JGt3V3AyLk7dswjTjyl50IEbesgf8J6BHEHcw/ "Python 3.8 (pre-release) – Try It Online")
[Answer]
# x86-16 machine code, 25 bytes
```
B3 01 MOV BL, 1 ; init multiplier
C_LOOP:
AC LODSB ; AL = [SI], SI++
3C 20 CMP AL, 32 ; is char less than 32
7C 10 JL DONE ; if so, exit
3C 5B CMP AL, '[' ; is char '['?
75 F7 JNZ C_LOOP ; if not, keep looping
AD LODSW ; AL = CHR_L
92 XCHG AX, DX ; DL = CHR_L
AC LODSB ; AL = CHR_R
2A C2 SUB AL, DL ; AL = CHR_R - CHR_L
98 CBW ; AH = 0
40 INC AX ; AL = AL + 1
93 XCHG AX, BX ; AX = multiplier
F7 E3 MUL BX ; multiplier *= CHR_R - CHR_L + 1
93 XCHG AX, BX ; BX = multiplier
EB EA JMP C_LOOP ; keep looping
DONE:
C3 RET ; return to caller
```
As a callable function, input string in `[SI]`. Output in `BX`.
**Example test program I/O:**
[](https://i.stack.imgur.com/5rQN0.png)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 23 bytes
```
1q{('[={(\(;(@-)@*\}&}h
```
[Try it online!](https://tio.run/##S85KzP3/37CwWkM92rZaI0bDWsNBV9NBK6ZWrTbj//9oA13LWDABAA "CJam – Try It Online")
First time programming in CJam.
```
1q{('[={(\(;(@-)@*\}&}h
1q Push 1, then push the input, stack = [ 1, str ]
{('[={(\(;(@-)@*\}&}h Execute this while the top of the stack is truthy
('[= Pop the first char and test for equality
& If it is truthy...
{(\(;(@-)@*\} Execute this:
(\(;(@ Get the two values of the character class to the top of the stack
E.g "0-9]..." -> "9", "0", ...
-) Subtract 2nd element char code by first and increment, stack = [1, str, diff]
@ Get the 1 to the top of the stack, stack = [ str, 1, diff]
* Multiply top 2 elements, stack = [ str, diff ]
\ Swap the top 2, so the string is back on top
{ }h If the string is not empty, run this again. Else print the output
```
[Answer]
# [Labyrinth](https://github.com/m-ender/labyrinth), ~~53~~ 50 bytes
```
1 @!{""
} ;
,:_91-,,;,-
" ; `
""";;)~}*{)
```
**[Try it online!](https://tio.run/##y0lMqizKzCvJ@P/fUMFBsVpJiatWAQisuXSs4i0NdXV0rHV0uZTAQiAigUtJScnaWrOuVqta8///aF3d6FggERsLAA "Labyrinth – Try It Online")**
### How?
Sets the top of the auxiliary stack to 1 and consumes characters from STDIN, if these are `[` the next three characters are consumed and the top of the auxiliary stack is multiplied by one more than the difference in ordinals of the relevant two characters. Once the EOF is reached this value is printed.
```
1 pop main (0); * 10; + 1 (=1) -> main
} pop main -> auxiliary (i.e. set initial cumulative product to 1)
A , read a character, C, ord(C) -> main
3-neighbours, top of stack is non-zero so turn
: copy top of main -> main
_ zero -> main
9 pop main; * 10; + 9 (=90) -> main
1 pop main; * 10; + 1 (=91) -> main
- pop main (a=91); pop main (b=ord(C)); b-a -> main
B 4-neighbours
if top of main is zero (i.e. we read a '[') then go straight:
, read a character, L, ord(L) -> main (i.e. L of [L-R])
, read a character, x='-', ord(x) -> main
; pop main (i.e. discard the '-' of [L-R])
, read a character, R, ord(R) -> main (i.e. R of [L-R])
- pop main (a=ord(R)); pop main (b=ord(L)); b-a -> main
` pop main; negate -> main
) pop main; increment -> main (i.e. ord(R)-ord(L)+1)
{ pop auxiliary -> main (i.e. get current cumulative product)
* pop main (a); pop main (b); b*a -> main
} pop main -> auxiliary (i.e. set new cumulative product)
~ pop main (0); bitwise NOT (~0=-1) -> main
) pop main; increment -> main
3-neighbours, top of stack is zero so go straight
; pop main (i.e. discard the zero, leaving infinite zeros on main)
; pop main (i.e. discard another zero, sill leaving infinite zeros on main)
"""" no-ops taking us back to the first , instruction at "A"
B elif top of main is negative (i.e. we read something <'[') then turn left:
; pop main (i.e. discard the result)
" no-op
C 3-neighbours
if top of main (the duplicate of ord(C)) is negative (i.e. EOF) then turn left:
{ pop auxiliary -> main (i.e. get cumulative product)
! pop main; print as decimal
@ exit program
C elif top of main is positive then turn right:
" no-op
we hit a wall so turn around
" no-op
3-neighbours, top of stack is non-zero so turn
; pop main (i.e. discard this leaving infinite zeros on main)
- pop main (a=0); pop main (b=0); b-a=0 -> main
4-neighbours (same location as B but facing down), top of main is zero so go straight
; pop main (i.e. discard one of the infinite zeros off of main)
) pop main; increment (=1) -> main
3-neighbours, top of stack is positive so turn right
; pop main (i.e. discard this 1)
; pop main (i.e. discard one of the infinite zeros off of main)
"""" no-ops taking us back to the first , instruction at "A"
C (N.B. elif top of main is zero cannot happen)
B elif top of main is positive (i.e. we read something >'[') then turn right:
; pop main (i.e. discard the result)
) pop main (duplicate of ord(C)); increment -> main
3-neighbours top of main is positive so turn right:
; pop main (i.e. discard that)
; pop main (i.e. discard one of the infinite zeros off of main)
"""" no-ops taking us back to the first , instruction at "A"
```
The complicated 4-neighbour `-`, along with the dead-end `"`, is a 3 byte save over the easier to follow:
```
1
}
,:_91-,,;,-
; ; `
""""")~}*{)
{
@!
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~62~~ 60 bytes
```
s->prod(map(x->x[2][1]-x[1][1]+1,eachmatch(r"\[(.)-(.)",s)))
```
-2 bytes thanks to [Robin Ryder](https://codegolf.stackexchange.com/users/86301/robin-ryder)
[Try it online!](https://tio.run/##yyrNyUw0rPifZvu/WNeuoCg/RSM3sUCjQteuItooNtowVrcCSACRtqFOamJyRm5iSXKGRpFSTLSGnqYuECvpFGtqav4vKMrMK8nJ00jTUIpO1K2KTYl2BJJKmppcyDIGukCzyCOARv0HAA "Julia 1.0 – Try It Online")
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 29 bytes
```
"\[.-."~?{)**{3 1}si^p.-+.}mp
```
[Try it online!](https://tio.run/##nY7RCsIwDEXf/YqtD4KTlMy56UAm/oA/UCN0thNhk@kYgmP@ei0t6rsvNzn3JiFlf691d@u1qa/DQ2EYttqwg@DA2Ws7zKJoSIJ47C7HlsOcj01rRmr6vWEsgCKIJ0x@GhEBkoOVBYScnPgY0XoSnqTEzqo3U1xbdwOF58RCCFMPmQVlJ2VZuVqdnZ0uchsIoN@KBEmihJJOSgsAoO9DCDH9Ke7GEvPsDQ "Burlesque – Try It Online")
```
"\[.-."~? # List of all RegEx matches
{
)** # Ord()
{3 1}si # Select values at indices 3 & 1 (start,end)
^p # Unbox
.- # Difference
+. # Increment
}mp # Map product (returns 1 for empty)
```
# [Burlesque](https://github.com/FMNSSun/Burlesque), 24 bytes
```
s1r1{@\x01\x7fr\jCB}\m{g1~=}fl
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/2LDIsNqBsb4oJsvZqTYmtzrdsM62Ni3n///oRN2qWAA "Burlesque – Try It Online")
Solution that generates all possible strings and counts the number of matches.
WARNING: May take infinite time and memory.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 31 bytes
```
≔⪪⮌S¹θ≔¹ηWθF⁼⊟θ[≧×L…·⊟θ∧⊟θ⊟θηIη
```
[Try it online!](https://tio.run/##PU6xCoMwEN37FaHTHcTB2UlKh0ILot3EIdhrEkhjTKL9/DRicbh37x33eG9Uwo@TMCnVIWhpoXNGR2hpJR8IbtYtsYteWwmInJV5ZqxO/@eSM5XVV2lDDGZk78kzuM6LMAGayeUTZ@f@jMgewu2mVksV4ak/FDi7k5VR5ZjRLEGv1Aor6XDW9nXwfeNWYotscqUIFxEiKMQqpb4o@iHDMKRiNT8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔⪪⮌S¹θ
```
Input the pattern string, reverse it, and split it into individual characters. This allows characters to be consumed within an expression by using `Pop(q)`.
```
≔¹η
```
Start off with 1 matching string.
```
Wθ
```
Repeat until all of the input characters have been processed.
```
F⁼⊟θ[
```
Is this a character range?
```
≧×L…·⊟θ∧⊟θ⊟θη
```
If so then multiply the result by the length of the inclusive range between the next character and the next but three (this saves a byte over converting to ordinals manually). The characters are consumed so that a range that starts or ends at `[` does not get misinterpreted as a second range.
```
Iη
```
Output the result.
] |
[Question]
[
Given a string of text, output it as a 'tower'.
Each slice of the string (of the form `0:n`) is repeated `5*n` times, so the first character is repeated 5 times, then the first and the second 10 times, etc.
### Examples:
```
'hello' ->
['h']
['h']
['h']
['h']
['h']
['h', 'e']
['h', 'e']
['h', 'e']
['h', 'e']
['h', 'e']
['h', 'e']
['h', 'e']
['h', 'e']
['h', 'e']
['h', 'e']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
['h', 'e', 'l', 'l', 'o']
'cat' ->
['c']
['c']
['c']
['c']
['c']
['c', 'a']
['c', 'a']
['c', 'a']
['c', 'a']
['c', 'a']
['c', 'a']
['c', 'a']
['c', 'a']
['c', 'a']
['c', 'a']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
['c', 'a', 't']
```
### Rules:
You can output each layer as a list of characters or just a string of them joined together.
[Answer]
# [R](https://www.r-project.org/), 48 bytes
```
function(s)substring(s,1,rep(x<-1:nchar(s),x*5))
```
[Try it online!](https://tio.run/##K/qfpmCj@z@tNC@5JDM/T6NYs7g0qbikKDMvXaNYx1CnKLVAo8JG19AqLzkjsQgorVOhZaqp@T9NQykjNScnX0mTC8hMTixR0vwPAA "R – Try It Online")
Returns a list of strings.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 6 bytes
```
ηā5*ÅΓ
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3PYjjaZah1vPTf7/PyM1JycfAA "05AB1E – Try It Online")
Returns a list of string.
**Explanation**
```
ÅΓ # Run-length decode...
η # ... the prefixes of the input
ā5*и # ... with the length range multiplied by 5 -- [5, 10, 15, 20, 25]
```
[Answer]
# [Haskell](https://www.haskell.org/), 36 bytes
```
f""=[]
f s=f(init s)++(s<$s<*[1..5])
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P01JyTY6litNodg2TSMzL7NEoVhTW1uj2Eal2EYr2lBPzzRW839uYmaegq1CbmKBr0JBaUlwSZFPnoKKQpqCUgbQkHyl/wA "Haskell – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 8 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
äï▄;♫├W^
```
[Run and debug it](https://staxlang.xyz/#p=848bdc3b0ec3575e&i=hello&a=1)
Unpacked, ungolfed, and commented, it looks like this.
```
|[F for each prefix of the input
i^5* 5*(i+1) where i is the iteration index
DQ that many times, peek and print to output
```
[Run this one](https://staxlang.xyz/#c=%7C[F%09for+each+prefix+of+the+input%0A++i%5E5*%095*%28i%2B1%29+where+i+is+the+iteration+index%0A++DQ%09that+many+times,+peek+and+print+to+output&i=hello&a=1)
[Answer]
# TI-Basic (TI-84 Plus CE), 29 bytes (27 tokens)
```
For(A,1,length(Ans
For(B,1,5A
Disp sub(Ans,1,A
End
End
```
Explanation:
```
For(A,1,length(Ans # 9 bytes, 8 tokens: for A from 1 to the length of the string
For(B,1,5A # 8 bytes, 8 tokens: 5*A times
Disp sub(Ans,1,A # 9 bytes, 8 tokens: Print the first A characters of the string
End # 2 bytes, 2 tokens: end loop
End # 1 byte, 1 token: end loop
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 15 bytes
```
.
$.>`*5*$($>`¶
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8F@PS0XPLkHLVEtFQ8Uu4dC2//8zUnNy8rmSE0sA "Retina – Try It Online") Link includes test cases. Explanation:
```
.
```
Match each character in the string.
```
$.>`*5*$($>`¶
```
`$`` is the prefix of the match. Retina then provides two modifiers, `>` modifies it to be in the context of the string between successive matches, while `.` takes the length. We therefore start with the prefix of the suffix, which is equivalent to the match including its prefix. This saves 2 bytes over using overlapping matches. The `$(` then concatenates that with a newline, the `5*` repeats it, and then the `$.>`` repeats it a further number of times given by its length.
[Answer]
# [Canvas](https://github.com/dzaima/Canvas), 6 [bytes](https://github.com/dzaima/Canvas/blob/master/files/chartable.md)
```
[³5×*P
```
[Try it here!](https://dzaima.github.io/Canvas/?u=JXVGRjNCJUIzJXVGRjE1JUQ3JXVGRjBBJXVGRjMw,i=JTIyaGVsbG8lMjI_,v=6)
Explanation:
```
[ for each prefix
³5× 1-indexed counter * 5
* repeat the prefix vertically that many times
P and print that
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 15 bytes
```
a₀ᶠ⟨gj₎{l×₅}⟩ᵐc
```
[Try it online!](https://tio.run/##ATMAzP9icmFjaHlsb2cy//9h4oKA4bag4p@oZ2rigo57bMOX4oKFfeKfqeG1kGP//yJjYXQi/1o "Brachylog – Try It Online")
The final `c` can be removed if OP replies positively to the question about outputting 2D arrays.
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), ~~44~~ 40 bytes
```
i.!?@UBqwW_#/>u...;B^...?qo;;q*n5;oN/./)
```
[Try it online!](https://tio.run/##Sy5Nyqz4/z9TT9HeIdSpsDw8XlnfrlRPT8/aKQ5I2hfmW1sXauWZWuf76evpa/7/75Gak5MPAA "Cubix – Try It Online")
This still has a lot of no-ops, but it is a little better than before.
As a very brief description, a character is grabbed from input and tested for EOI (-1), halt if it is. The stack is then reversed. Get the number of items on the stack and multiple by -5. Drop that to the bottom of the stack and clean up. Loop through the stack, printing, until a negative number. Print newline, increment the number, if 0 drop the zero, reverse stack and start from input again, otherwise loop through the stack, printing, until a negative number ... ad nauseum
Cubified it looks like
```
i . !
? @ U
B q w
W _ # / > u . . . ; B ^
. . . ? q o ; ; q * n 5
; o N / . / ) . . . . .
. . .
. . .
. . .
```
[Watch it online](https://ethproductions.github.io/cubix/?code=ICAgICAgaSAuICEKICAgICAgPyBAIFUKICAgICAgQiBxIHcKVyBfICMgLyA+IHUgLiAuIC4gOyBCIF4KLiAuIC4gPyBxIG8gOyA7IHEgKiBuIDUKOyBvIE4gLyAuIC8gKSAuIC4gLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4KICAgICAgLiAuIC4=&input=c3RlcAo=&speed=20)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
¹Ƥx'J×5Ɗ
```
[Try it online!](https://tio.run/##y0rNyan8///QzmNLKtS9Dk83Pdb1/3B75P//GUCJfAA "Jelly – Try It Online")
```
J×5x'@¹Ƥ
```
[Try it online!](https://tio.run/##y0rNyan8/9/r8HTTCnWHQzuPLfl/uD3y//8MoHg@AA "Jelly – Try It Online")
```
¹Ƥx'Jx'5
```
[Try it online!](https://tio.run/##y0rNyan8///QzmNLKtS9KtRN/x9uj/z/PwMonA8A "Jelly – Try It Online")
This is likely golfable.
[Answer]
# JavaScript, 48 46 bytes
(thanks @redundancy)
Edit: The author clarified and this answer is now not valid, but I will leave it here unchanged.
Returns an array of multi-line strings.
```
s=>[...s].map(c=>(q+=c).repeat(5*++i),i=q=`
`)
```
# Try it
```
f = s=>[...s].map(c=>(q+=c).repeat(5*++i),i=q=`
`);
console.log( f("hello").join`` );
```
# Potential strategy:
It didn't help me much, but maybe someone can use this:
The number of characters at (0-indexed) line `i` is `floor(sqrt(2/5*i+1/4)+1/2)`, which is golfed in JavaScript as `(.4*i+.25)**.5+.5|0`.
For a string of length `n`, there are `n*(n+1)*5/2` lines.
Perhaps:
`s=>{for(i=0;(n=(.4*i+++.25)**.5+.5|0)<=s.length;)console.log(s.slice(0,n))}`
[Answer]
# [Python 3](https://docs.python.org/3/), ~~43~~ 41 bytes
Thanks to *ovs* for saving 2 bytes!
### Code
```
f=lambda x:[*x]and f(x[:-1])+[x]*5*len(x)
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRocIqWqsiNjEvRSFNoyLaStcwVlM7uiJWy1QrJzVPo0Lzf0FRZl6JRpqGUnJiiZKm5n8A "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 67 bytes
```
i,j;f(char*s){for(i=0;s[i++];)for(j=5*i;j--;)printf("%.*s\n",i,s);}
```
[Try it online!](https://tio.run/##HczBCoMwEATQu1@xCEI2JqUeelrsj1gP6ULsBpqWpHgRvz2a3t7MwLBdmEsRE8grfrmkM27@k5SMV8qT9P1MWHMYb1ooWEv4TRJ/XrXdRedHbI2YjLSXs4S3k6gqXFrY1D/Q@vSKsDUA4lUd7gPCX@s0zEjNXop78gE "C (gcc) – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
ΣzoR*5Nḣ
```
[Try it online!](https://tio.run/##yygtzv7//9ziqvwgLVO/hzsW////Xyk5sUQJAA "Husk – Try It Online")
### Explanation
```
Σz(R*5)Nḣ -- example input: "ab"
ḣ -- non-empty prefixes: ["a","ab"]
z( )N -- zip with [1..]
*5 -- | multiply by 5
R -- | replicate
-- : [["a","a","a","a","a"],["ab","ab","ab","ab","ab","ab","ab","ab","ab","ab"]]
Σ -- concat: ["a","a","a","a","a","ab","ab","ab","ab","ab","ab","ab","ab","ab","ab"]
```
[Answer]
## Haskell, ~~46~~ ~~43~~ 42 bytes
```
f s=do n<-[1..length s];take n s<$[1..n*5]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2DYlXyHPRjfaUE8vJzUvvSRDoTjWuiQxO1UhT6HYRgUknqdlGvs/NzEzT8FWITexwDdeoaC0JLikyCdPQUUhTUEpObFE6T8A "Haskell – Try It Online")
Sadly `inits` requires `import Data.List`, so
```
import Data.List
((<$)<*>(>>[1..5])=<<).inits
```
with its 45 bytes is longer.
Edit: -1 byte thanks to @BWO.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 11 bytes
```
F⊕LθE×⁵ι…θι
```
[Try it online!](https://tio.run/##FcYxDoAgDADAr3RsExydfIGJJA5@gEAVkgKCxO/XeNP56LqvTlTP2gHX4jtnLoMDblyuEbEREew9lYHW3XikzA/OBhIZsFUCtv9Ei2pkkarTKx8 "Charcoal – Try It Online") Link is to verbose version of code. Output includes 0 repetitions of the zero-length substring. Explanation:
```
θ Input string
L Length
⊕ Incremented
F Loop over implicit range
⁵ Literal 5
ι Current index
× Multiply
E Map over implicit range
θ Input string
ι Current index
… Chop to length
Implicitly print each string on its own line
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~46~~ 42 bytes
```
->s{(1..s.size).map{|i|puts [s[0,i]]*i*5}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WsNQT69YrzizKlVTLzexoLoms6agtKRYIbo42kAnMzZWK1PLtLb2P1hMKSM1JydfQddOiSstGsJRiuUCSXFB5JMTS2CyQKZS7H8A "Ruby – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~40~~ ~~20~~ 25 bytes
Score cut in half thanks to mazzy
+5 bytes thanks to AdmBorkBork pointing out the specs
```
$args|%{,($s+=$_)*5*++$i}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkqZgq1D9XyWxKL24RrVaR0OlWNtWJV5Ty1RLW1sls/Z/LReXCkhlPlCdEpihxKUG1OUAZv8HAA "PowerShell – Try It Online")
Takes input via splatting. Works by building the string by adding the next character to itself, converts it to a one element array, and then repeats it `5*i` times.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
f"G@:)@5*1X"
```
[Try it online!](https://tio.run/##y00syfn/P03J3cFK08FUyzBC6f9/9YzUnJx89f8A "MATL – Try It Online")
```
f % Get the indices of input i.e. range 1 to length(input)
" % For loop over that
G % Push input string
@ % Push current loop index
: % Range 1 to that
) % Index at those positions (substring 1 to i)
@5* % Multiply loop index by 5
1X" % Repeat the substring that many times rowwise
% Results collect on the stack and are
% implicitly output at the end
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 17 bytes
```
òïç$îî/6Ä
Hl$xòxú
```
Expects inputs without newlines, and outputs with superfluous leading newlines.
I can remove this entry if input/output violates the challenge spec.
[Try it online!](https://tio.run/##ASMA3P92///DssOvw6ckw67Dri82w4QKSGwkeMOyeMO6//9oZWxsbw "V – Try It Online")
### 21 bytes
```
òïç$îî/6Ä
Hl$xòxíîî/ò
```
Expects inputs without newlines, but outputs with only one leading and trailing newline.
## Explanation
Differing substrings are separated with two consecutive newlines so that
linewise duplication only applies to lines matching the regex `$\n\n`.
When the duplication command (`Ä`) is supplied a count, e.g. `6Ä`, (I think) it
deletes the current line before pasting `n` times, thus only appearing to append `n - 1` copies.
```
ò | recursively...
ï | . append newline
ç | . globally search lines matching...
$îî | . . compressed version of $\n\n regex
/6Ä | . . duplicate to create 6 copies
H | . go to first line
l | . move cursor right 1 char
| . . if current line is 1 char long, errors out of recursion
$x | . delete 1 char from end of current line
ò | ...end
x | delete extra 1-char substring
ú | sort so that newlines rise to top
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 14 [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")
```
{↑(5×⍳≢⍵)/,\⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR20QN08PTH/VuftS56FHvVk19nRggVfs/7VHbhEe9fY/6pnr6P@pqPrTeGKgUyAsOcgaSIR6ewf/TFNRLUotL1AE "APL (Dyalog Unicode) – Try It Online")
My first apl post so please let me know if you have any suggestions
## How it works:
```
{↑(5×⍳≢⍵)/,\⍵}
,\⍵ - Prefixes of the input
/ - Repeated
⍳≢⍵ - By a list of indices the same length as the input
5× - Times 5
↑ - Separate into rows
```
[Answer]
# [Wenyan](https://github.com/LingDong-/wenyan-lang), ~~350~~ ~~326~~ 308 bytes
```
吾有一術名之曰「A」欲行是術必先得一言曰「B」是術曰有數零名之曰「C」吾有一言名之曰「D」凡「B」中之「E」加五於「C」昔之「C」者今其是矣加「E」於「D」昔之「D」者今其是矣為是「C」遍夫「D」書之云云云云是謂「A」之術也
```
[IDE](http://wenyan-lang.lingdong.works/ide.html)
Just seen this programming language on GitHub, so I'll have a try. There is no equivalent for "process.argv", so I have to write this as a function, but then the boilerplate `吾有一術名之曰「X」欲行是術必先得一言曰「X」乃行是術曰...是謂「X」之術也` itself (114 bytes) is just too long.
Each variable has to be at least 7 bytes (the brackets themselves take 6 bytes), and a string takes `12 bytes + length of string` to achieve. Of course I can trivially put something like `施「eval」於「「a=>[...a].map(_=>(a.slice(0,++i)+'\\n').repeat(i*5),i=0).join``」」` (91 bytes) but that's boring (why not use JavaScript then?)
### Explanation
```
function A(B) {
var C = 0, D = "";
for (var E of B) {
C = C + 5;
D = D + E;
for (var i = 0; i < C; i++)
console.log(D);
}
}
```
### 326->308 `乃行` before `是術曰` is optional so it's removed, and `吾有一言曰「D」` is replaced by `夫「D」` to recall the variable.
[Answer]
## [Perl 5](https://www.perl.org/), 29 bytes
```
map{say}($x.=$_)x($y+=5)for@F
```
[Try it online!](https://tio.run/##K0gtyjH9r1Jpq1Jhq6Rk/T83saC6OLGyVkOlQs9WJV6zQkOlUtvWVDMtv8jB7f//jNScnHyu5MSSf/kFJZn5ecX/dXPc/uv6muoZGBoAAA "Perl 5 – Try It Online")
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 25 bytes
```
{(1..*X*5)RZxx[\~] .comb}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1rDUE9PK0LLVDMoqqIiOqYuVkEvOT83qfZ/moaSoZGSpp2dXnFipfV/AA "Perl 6 – Try It Online")
Anonymous code block that returns a list of list of strings.
If you want it as a 1D array, you can append `flat` in front like so:
```
{flat (1..*X*5)RZxx[\~] .comb}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzotJ7FEQcNQT08rQstUMyiqoiI6pi5WQS85Pzep9n@ahpKhkbGSpp2dXnFipfV/AA "Perl 6 – Try It Online")
### Explanation:
```
{ } # Anonymous code block
.comb # Split the string into a list of characters
[\~] # Triangular reduce the list of characters with the concatenate operator
RZxx # Multiply each list by:
(1..*X*5) # A sequence of 5,10,15 etc.
```
Alternatively,
```
{($+=5)xx*RZxx[\~] .comb}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1pDRdvWVLOiQisoqqIiOqYuVkEvOT83qfZ/moaSoZGxkqadnV5xYqX1fwA "Perl 6 – Try It Online")
Also works for the same amount of bytes.
[Answer]
# Japt, 10 bytes
Awaiting confirmation as to whether the output format is acceptable (+2 bytes if not).
```
å+ £T±5 ÇX
```
[Try it](https://ethproductions.github.io/japt/?v=1.4.5&code=5Ssgo1SxNSDHWA==&input=ImNhdCIKLVE=)
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~15~~ 12 bytes
*-3 bytes from @Shaggy*
```
£¯°Y +R pY*5
```
[Try it online!](https://tio.run/##y0osKPn//9DiQ@sPbYhU0A5SKIjUMv3/XykjNScnXwkA "Japt – Try It Online")
[Answer]
# JavaScript, 76 bytes
```
s=>{for(i=1;i<=s.length;i++)for(j=0;j<5*i;j++)console.log(s.substring(0,i))}
```
```
f=s=>{for(i=1;i<=s.length;i++)for(j=0;j<5*i;j++)console.log(s.substring(0,i))}
f("cat")
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 48 bytes
```
: f 1+ 1 do i 5 * 0 do dup j type cr loop loop ;
```
[Try it online!](https://tio.run/##S8svKsnQTU8DUf//WymkKRhqKxgqpOQrZCqYKmgpGICYKaUFClkKJZUFqQrJRQo5@fkFEML6f7GSQkZqTk6@kkLafwA "Forth (gforth) – Try It Online")
### Explanation
1. Loop from 1 to string-length
2. for each iteration:
1. Loop (5 \* loop index) times
2. Print string from beginning to outer loop index
### Code Explanation
```
: f \ start a new word definiton
1+ 1 \ set up to the loop paramers from 1 to str-length
do \ start a counted loop
i 5 * 0 do \ start a second counted loop from 0 to 5*index - 1
dup j \ duplicate the string address and set the length to the outer index
type \ print character from start of string to loop index
cr \ output a newline
loop \ end inner counted loop
loop \ end outer counted loop
; \ end word definition
```
[Answer]
# Java 10, ~~120~~ ~~92~~ ~~90~~ 89 bytes
```
s->{for(int j=1,i=1;i<=s.length();i+=++j>i*5?j=1:0)System.out.println(s.substring(0,i));}
```
-28 bytes thanks to *@OlivierGrégoire*.
-1 byte thanks to *@ceilingcat*.
[Try it online.](https://tio.run/##bY87DsIwDEB3TmF1SihEMLAQAisLLIyIIYQALiFFtYuEUM9eQunIYsnf91zYpx0Xp1vrgiWCjcUI7wEARvbV2ToP228K8CzxBE7suMJ4AZI6VZtBCsSW0cEWIhhoabx8n8tKpH0ozHSEZqpxYUgFHy98FVJjbvK8WOJwtkoD84ncvYj9XZU1q0c6ziEKUlQfqUOJyQil1E2rv7BHfQwJ1jM7p3tS7rX2B7DypxuVE9nah1BmnSrAH0zf6Wad5ax/qmk/)
**Explanation:**
```
s->{ // Method with String parameter and no return-type
for(int j=1, // Repeat-integer, starting at 1
i=1;i<=s.length() // Loop `i` in the range [1,length_input]
; // After every iteration:
i+=++j>i*5? // Increase `j` by 1 first with `++j`
// If `j` is now larger than `i` multiplied by 5:
j=1 // Increase `i` by 1, and reset `j` to 1
: // Else:
0) // Leave `i` the same by increasing it with 0
System.out.println( // Print with trailing newline:
s.substring(0,i));} // The prefix of size `i`
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 40 bytes
```
++++++++++>,[>>+++++[<<[<]>[.>]>>+<-]<,]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fGw7sdKLt7MCsaBubaJtYu2g9u1igiI1urI1O7P//Gak5OfkA "brainfuck – Try It Online")
```
[Tape: 10 (newline), [characters], 0, rowcounter]
++++++++++> 10 (newline)
,[ for each input character
>>+++++ add 5 to number of rows
[ for each row
<<[<] go to start
>[.>] print newline and all previous characters
>>+ add 1 to next rowcounter cell
<- decrement current rowcounter cell
]
<, input next character
]
```
] |
[Question]
[
This is a code golf version of a similar question [I asked on stack earlier](https://stackoverflow.com/questions/51492374/get-the-point-where-the-replace-occurred-in-a-replace#51493248) but thought it'd be an interesting puzzle.
Given a string of length 10 which represents a base 36 number, increment it by one and return the resulting string.
This means the strings will only contain digits from `0` to `9` and letters from `a` to `z`.
Base 36 works as follows:
The right most digit is incremented, first by using `0` to `9`
>
> # 0000000000 > 9 iterations > 0000000009
>
>
>
and after that `a` to `z` is used:
>
> # 000000000a > 25 iterations > 000000000z
>
>
>
If `z` needs to be incremented it loops back to zero and the digit to its left is incremented:
>
> # 000000010
>
>
>
### Further rules:
* You may use upper case or lower case letters.
* You may **not** drop leading zeros. Both input and output are strings of length 10.
* You do not need to handle `zzzzzzzzzz` as input.
### Test Cases:
```
"0000000000" -> "0000000001"
"0000000009" -> "000000000a"
"000000000z" -> "0000000010"
"123456zzzz" -> "1234570000"
"00codegolf" -> "00codegolg"
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 13 bytes
```
n36 Ä s36 ù0A
```
[Try it online!](https://tio.run/##y0osKPn/P8/YTOFwi0IxiNpp4Pj/v5KBQXJ@Smp6fk6aEgA "Japt – Try It Online") and [Verify test cases](https://tio.run/##y0osKPn//9C6PGMzhcMtCsUgaqeB4///0UoGcKCkw4XgWaLwqkA8QyNjE1OzKiCAyCXnp6Sm5@ekKcUCAA "Japt – Try It Online")
Takes input as a string
## Explanation
```
n36 converts input to base 36
Ä +1
s36 to base 36 string
ù0A left-pad with 0 to length 10
```
[Answer]
# JavaScript (ES6), 45 bytes
*Saved 4 bytes thanks to @O.O.Balance*
```
s=>(parseInt(1+s,36)+1).toString(36).slice(1)
```
[Try it online!](https://tio.run/##dY@xCsMgFEX3fkVwUpoabZqUDuneOV8gRiVFVFQ65OethLaBSu52D4fLe0/2YoH72cWTsZNIckhhuEPHfBAPE2Go2x4dKcLRjtHPRsHcsWPTGJmPkJKaoMStCVYLrK2CEgLyC0CoappqIxQc9uRbIbN9efmXKSlkem4vXb/kfOWVXNfDymWe31dWy235QxRIbw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 58 bytes
```
d=['0'..'9']
f s=snd(span(<s)$mapM(\_->d++['a'..'z'])d)!!1
```
[Try it online!](https://tio.run/##FcpBCoMwEADAe1@xirAJomhvQtMf@AIrZTFNK8awdHvK493inOdDsr1iVPVuwg7bFgecLwHESfJGmJK5ia124tE8ns3d1/WEdL6Ms/W2KHrdaU3ggL9r@kEFAcru1F@HnEs9lhDpLdoszH8 "Haskell – Try It Online")
A very brute-force strategy: generate all the length-10 base-36 strings in order, and find the one that comes after the input in the list. Take an enormous amount of time on strings far from the start of the list.
---
# [Haskell](https://www.haskell.org/), 60 bytes
```
q '9'='a'
q c=succ c
f(h:t)|any(<'z')t=h:f t|r<-'0'<$t=q h:r
```
[Try it online!](https://tio.run/##FcFLCoMwEADQvacYRBhdCLY7Q@Yww9A00jTkMy4aPHtT@p7n@nqE0HsG3JGQccggVE8RkMHN3uhycfzMFhsuSt440KvYFTe0k1IGb0p/8xGBIJUjKkzgYNz@bve9tbF/xQV@1r5KSj8 "Haskell – Try It Online")
Reads the string left to right until it reaches a character followed by a suffix of all z's, which may be empty. Increments that character, and replaces the z's with 0's.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
Input is in **uppercase**.
### Code
```
1ì36ö>36B¦
```
### Explanation
```
1ì # Prepend a 1 to the number
36ö # Convert from base 36 to decimal
> # Increment by 1
36B # Convert from decimal to base 36
¦ # Remove the first character
```
Uses the **05AB1E** encoding. [Try it online!](https://tio.run/##MzBNTDJM/f/f8PAaY7PD2@yMzZwOLQNyjYxNTM2igAAA "05AB1E – Try It Online") or [Verify all test cases](https://tio.run/##MzBNTDJM/V9TVvnf8PAaY7PD2@yMzZwOLftfqXR4v8KjtkkKh/cr6fw3gAMuOMsSwYziMjQyNjE1iwICoKizv4uru7@PGwA).
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 7 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ûæ≥╡►N▀
```
[Run and debug it](https://staxlang.xyz/#p=9691f2b5104edf&i=%220000000000%22+%0A%220000000009%22+%0A%22000000000z%22+%0A%22123456zzzz%22+%0A%2200codegolf%22+&a=1&m=2)
Explanation:
```
|3^|3A|z Full program, implicit input
|3 Convert from base 36
^ Increment
|3 Convert to base 36
A|z Fill with "0" to length 10
Implicit output
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 50 48 bytes
An explicit carry flag wasn't necessary after restructuring the loop to end as soon as no carry would happen. The 9->A adjustment is performed during the loop check.
Thanks to ceilingcat for the suggestion.
```
f(char*s){for(s+=9;(*s+=*s-57?1:8)>90;*s--=48);}
```
[Try it online!](https://tio.run/##XVDLTsMwELz7K6xUlew8IIGWNhgHQZ@Hil448TiExGktlaSK3R6o8u1hXacSwhfPzO7OriYLNlnW9mSZ7Q65wA9K57K62ibor1TLcvNfy3fyC7S2INk2rV1FT0VVE@XxmBEXPlcFw9FjdD@mSRwyYAEfjClr2l4uClkKvJq9LF6XJKWYKPkjqgLgtUUuQIqQMcauFkq/f/ITwtgJw8l6OlusV3PHNzx@uzzLn54n09l8sYw7HkY3t4Ph3WgcOw1DSJYaf6eyJAak9Sbz7QoX8JFis6ITFDdrfVcz0Ex3Vh1KzbubTY2CH5TgavBJIjuNseLGy4vYmdkp0xGclcbMmJzYuRIEScgukwXRHKLOD3vIj1JrsIfodUGcvsIejjDHffVROj4E7Pm66ylqIYglDWraXw "C (gcc) – Try It Online")
---
## Original version: 71 57 bytes
This version uses a carry flag to propagate updates: I set it to truthy to begin the increment. The string is modified in-place and only accepts 0-9, A-Z. The tricky part was making sure that 9->A got handled correctly on carries.
Edit: I repurposed the input pointer as the carry flag.
```
f(s){for(char*t=s+9;s;)*t--+=(s=++*t>90)?-43:7*!(*t-58);}
```
[Try it online!](https://tio.run/##XVHJTsMwEL37K0yqSl4SSGhLG4yDoOuhohdOLIfgJK2l4qDY5UCVbw92k0oIn94y82Y0FsFWiKYnldgfshzeaZPJ8nKXgL9SJdX2v5bt5YfVmgJpfCzKColdWhHDNY2ZZpiYIKAcaU4pMUkc4vtgOLgdkwtkndEEs7rpZXkhVQ7X86fl8wqlGCItf/KysPCqRcRCDICLhsTk2ry@8yOA0AvD6WY2X27WC893PH45v5Y/PE5n88VyFXc8jK4Hw9HNeBJ7NQNAKgM/U6mQA2m1FX47glj8jaEb0Qmau7E@McxqrlqUB2V4t7PzsM2zlt3a5iRR2w2h5i6LRuzE2i5XEZyU2vW4q7GTEwRJyM6dBbJXNFV2@EJEY9wGfNk/MAXy@hpSGEEO@/pNeT7RlPqmqymqPEctqUHd/AI "C (gcc) – Try It Online")
[Answer]
# C, ~~82~~ ~~81~~ ~~53~~ 50 bytes
```
f(char*s){for(s+=10;*--s>89;)*s=48;*s+=*s-57?1:8;}
```
Directly modifies the input string; input and output is in upper case. Try it online [here](https://tio.run/##rVJbT4MwGH3nV3RNTFo2EqqbYxI0i7vEuIR33kgtSsIttEvUhd@OwLiJm@Dle2rac@k5LVWeKU1TB9EXO5Y5PjhhjPjYIKouKwq/1RY6lrkx1XQ525W5MpvfkRtNT1LBuDiy3CDaiwko1uw1YlSwJwwOEignit1AOAhecDAGBBgATkDBwXqNcVB3x3XQiIuY@hGqRCtaW7xjgMxHfEI@Aczj7DxtZICcvFk@7NarXKBr2ZJqcu0FRxBmZ4kk@bYboPbFmmqyxL7teSFFhMjcfWfhsW7cUv1U3hBCXk30hsruoVoP/ApqwjQ40sYVb1lK1S/Y77UY6LX8By9rmBdRf@9FLq@ms2srm@@9Cty82/VPc92bq/XW3G36cpW47R@8rGp6cp38Q2e8Ein9AA). Thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld) for golfing 24 bytes and to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for golfing 3 more bytes.
Ungolfed:
```
f(char *s) { // function taking a string argument
for(s += 10; *--s > 89; ) // skip to the least significant digit, and step through the string until you hit something other than a 'Z' (90 is the ASCII code for 'Z') ...
*s = 48; // ... replacing each digit with a zero (48 is the ASCII code for '0')
*s += // the next digit has to be incremented:
*s - 57 // if it's not a '9' (ASCII code 57) ...
? 1 // ... that is straightforward ...
: 8; // ... otherwise it has to be replaced with an 'A' (ASCII code 65 = 57 + 8)
}
```
[Answer]
# [Online Turing Machine Simulator](https://turingmachinesimulator.com/), 745 bytes
```
init:0
accept:2
0,0
0,0,>
0,1
0,1,>
0,2
0,2,>
0,3
0,3,>
0,4
0,4,>
0,5
0,5,>
0,6
0,6,>
0,7
0,7,>
0,8
0,8,>
0,9
0,9,>
0,a
0,a,>
0,b
0,b,>
0,c
0,c,>
0,d
0,d,>
0,e
0,e,>
0,f
0,f,>
0,g
0,g,>
0,h
0,h,>
0,i
0,i,>
0,j
0,j,>
0,k
0,k,>
0,l
0,l,>
0,m
0,m,>
0,n
0,n,>
0,o
0,o,>
0,p
0,p,>
0,q
0,q,>
0,r
0,r,>
0,s
0,s,>
0,t
0,t,>
0,u
0,u,>
0,v
0,v,>
0,w
0,w,>
0,x
0,x,>
0,y
0,y,>
0,z
0,z,>
0,_
1,_,<
1,0
2,1,-
1,1
2,2,-
1,2
2,3,-
1,3
2,4,-
1,4
2,5,-
1,5
2,6,-
1,6
2,7,-
1,7
2,8,-
1,8
2,9,-
1,9
2,a,-
1,a
2,b,-
1,b
2,c,-
1,c
2,d,-
1,d
2,e,-
1,e
2,f,-
1,f
2,g,-
1,g
2,h,-
1,h
2,i,-
1,i
2,j,-
1,j
2,k,-
1,k
2,l,-
1,l
2,m,-
1,m
2,n,-
1,n
2,o,-
1,o
2,p,-
1,p
2,q,-
1,q
2,r,-
1,r
2,s,-
1,s
2,t,-
1,t
2,u,-
1,u
2,v,-
1,v
2,w,-
1,w
2,x,-
1,x
2,y,-
1,y
2,z,-
1,z
1,0,<
```
[Online interpreter](http://turingmachinesimulator.com/shared/dymdlyvxoj)
[Answer]
# [6502 (NMOS\*) machine code](https://en.wikibooks.org/wiki/6502_Assembly) routine, 26 bytes
```
A0 09 F3 FB B1 FB C9 5B 90 07 A9 30 91 FB 88 10 F1 C9 3A D0 04 A9 41 91 FB 60
```
\*) uses an "illegal" opcode `ISB`/`0xF3`, works on all original NMOS 6502 chips, not on later CMOS variants.
Expects a pointer to a 10-character string in `$fb`/`$fc` which is expected to be a base-36 number. Increments this number in-place.
Doesn't do anything sensible on invalid input (like e.g. a shorter string) -- handles `ZZZZZZZZZZ` "correctly" by accident ;)
### Commented disassembly
```
; function to increment base 36 number as 10 character string
;
; input:
; $fb/$fc: address of string to increment
; clobbers:
; A, Y
.inc36:
A0 09 LDY #$09 ; start at last character
.loop:
F3 FB ISB ($FB),Y ; increment character ("illegal" opcode)
B1 FB LDA ($FB),Y ; load incremented character
C9 5B CMP #$5B ; > 'z' ?
90 07 BCC .checkgap ; no, check for gap between numbers and letters
A9 30 LDA #$30 ; load '0'
91 FB STA ($FB),Y ; and store in string
88 DEY ; previous position
10 F1 BPL .loop ; and loop
.checkgap:
C9 3A CMP #$3A ; == '9' + 1 ?
D0 04 BNE .done ; done if not
A9 41 LDA #$41 ; load 'a'
91 FB STA ($FB),Y ; and store in string
.done:
60 RTS
```
---
### Example C64 assembler program using the routine:
**[Online demo](https://vice.janicek.co/c64/#%7B%22controlPort2%22:%22joystick%22,%22primaryControlPort%22:2,%22keys%22:%7B%22SPACE%22:%22%22,%22RETURN%22:%22%22,%22F1%22:%22%22,%22F3%22:%22%22,%22F5%22:%22%22,%22F7%22:%22%22%7D,%22files%22:%7B%22inc36.prg%22:%22data:;base64,AQgLCOIHnjIwNjEAAACpvKAIIB6rqb+gCKILIC8Iqb+F+6kIhfwgogipv6AITB6ryob7hfyE/aAAhMyE/iBC8fD7hQIpf8kgsA7JDfAQyRTQ66X+8OfQBqX+xfvw33ik07HRKX+R0aUCIBbnps/wCqTTsdEJgJHRpQJYyRTwIMkN8Amk/pH8yIT+0LGpAKT+kfx4pNOx0Sl/kdHmzFhgxv6wmqAJ8/ux+8lbkAepMJH7iBDxyTrQBKlBkftgPiAA%22%7D,%22vice%22:%7B%22-autostart%22:%22inc36.prg%22%7D%7D)**
[](https://i.stack.imgur.com/GQmF0.png)
**Code in [ca65](http://cc65.github.io/doc/ca65.html) syntax:**
```
.import inc36 ; link with routine above
.segment "BHDR" ; BASIC header
.word $0801 ; load address
.word $080b ; pointer next BASIC line
.word 2018 ; line number
.byte $9e ; BASIC token "SYS"
.byte "2061",$0,$0,$0 ; 2061 ($080d) and terminating 0 bytes
.bss
b36str: .res 11
.data
prompt: .byte "> ", $0
.code
lda #<prompt ; display prompt
ldy #>prompt
jsr $ab1e
lda #<b36str ; read string into buffer
ldy #>b36str
ldx #$b
jsr readline
lda #<b36str ; address of array to $fb/fc
sta $fb
lda #>b36str
sta $fc
jsr inc36 ; call incrementing function
lda #<b36str ; output result
ldy #>b36str
jmp $ab1e
; read a line of input from keyboard, terminate it with 0
; expects pointer to input buffer in A/Y, buffer length in X
.proc readline
dex
stx $fb
sta $fc
sty $fd
ldy #$0
sty $cc ; enable cursor blinking
sty $fe ; temporary for loop variable
getkey: jsr $f142 ; get character from keyboard
beq getkey
sta $2 ; save to temporary
and #$7f
cmp #$20 ; check for control character
bcs checkout ; no -> check buffer size
cmp #$d ; was it enter/return?
beq prepout ; -> normal flow
cmp #$14 ; was it backspace/delete?
bne getkey ; if not, get next char
lda $fe ; check current index
beq getkey ; zero -> backspace not possible
bne prepout ; skip checking buffer size for bs
checkout: lda $fe ; buffer index
cmp $fb ; check against buffer size
beq getkey ; if it would overflow, loop again
prepout: sei ; no interrupts
ldy $d3 ; get current screen column
lda ($d1),y ; and clear
and #$7f ; cursor in
sta ($d1),y ; current row
output: lda $2 ; load character
jsr $e716 ; and output
ldx $cf ; check cursor phase
beq store ; invisible -> to store
ldy $d3 ; get current screen column
lda ($d1),y ; and show
ora #$80 ; cursor in
sta ($d1),y ; current row
lda $2 ; load character
store: cli ; enable interrupts
cmp #$14 ; was it backspace/delete?
beq backspace ; to backspace handling code
cmp #$d ; was it enter/return?
beq done ; then we're done.
ldy $fe ; load buffer index
sta ($fc),y ; store character in buffer
iny ; advance buffer index
sty $fe
bne getkey ; not zero -> ok
done: lda #$0 ; terminate string in buffer with zero
ldy $fe ; get buffer index
sta ($fc),y ; store terminator in buffer
sei ; no interrupts
ldy $d3 ; get current screen column
lda ($d1),y ; and clear
and #$7f ; cursor in
sta ($d1),y ; current row
inc $cc ; disable cursor blinking
cli ; enable interrupts
rts ; return
backspace: dec $fe ; decrement buffer index
bcs getkey ; and get next key
.endproc
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~34 32~~ 30 bytes
*Thanks to nwellnhof for -2 bytes through the use of the `o` operator to combine functions*
```
{S/.//}o{base :36(1~$_)+1: 36}
```
[Try it online!](https://tio.run/##XY1NC4JAEIbv@yuGRUrR0s0yUpSkzIvgoehgRBgoCFbS2iHE/rqtmn3NZebZZ96dLLqmWnW6Qy82q2ItD2W5vBTHkEagqxpPHtxBEIkOqlbWW/M8ojkFE9LkHFHLGtIsTXK@DwML@gJjZ2t7BkI3lt@wVTZmaXgGsQ0yjC/X7pcCASQUYp477JS9IAHrZC8BbhhMq33ABiorrLwL18c@TDD6wOxP2t8y@JVEYZKM1PFEC1i1suFpc6ZOLvyl4/reqku@2MVP "Perl 6 – Try It Online")
Function that converts the argument to base 36, adds 1, converts back and then formats it. Now uses the same tactic as [Adnan's answer](https://codegolf.stackexchange.com/a/169450/76162) to preserve the leading zeroes.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 12 bytes
```
36ZAQ5M10&YA
```
[Try it online!](https://tio.run/##y00syfmf8N/YLMox0NTX0EAt0vG/S8h/dYPk/JTU9PyctCp1LnUDOEDmWCJzQMoMjYxNTM2qgAAsAzNBHQA "MATL – Try It Online")
```
% Implicit input
36ZA % convert from base 36 to decimal
Q % increment by 1
5M % bring the 36 back on stack (done this way to avoid needing space separator after this)
10 % = minimum length of output string
&YA % convert back to base 36 with those arguments
% Implicit output
```
[Answer]
# [Haskell](https://www.haskell.org/), 63 bytes
```
r.f.r
f('9':r)='a':r
f('z':r)='0':f r
f(c:r)=succ c:r
r=reverse
```
[Try it online!](https://tio.run/##y0gszk7NyfmfrmCrEPO/SC9Nr4grTUPdUt2qSNNWPRFIgbhVEK6BulWaAkggGcQtLk1OVgCyuIpsi1LLUouKU//nJmbmAQ3KTSzwVdAoKC0JLinyyVPQU0jXVIhWMoADJR0ExxKZUwXkGBoZm5iaVQEBWCY5PyU1PT8nTSn2/7/ktJzE9OL/uhHOAQEA "Haskell – Try It Online") Reverses the string and checks the first character:
* A `9` is replaced by an `a`.
* A `z` is replaced by a `0` and recursively the next character is checked.
* All other characters are incremented using `succ`, the successor function which can be used on Chars because they are an instance of the [Enum class](http://hackage.haskell.org/package/base-4.11.1.0/docs/Prelude.html#t:Enum).
Finally the resulting string is reversed again.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 14 bytes
```
×0⁹←⮌⍘⊕⍘S³⁶¦³⁶
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCMkMze1WEPJQElHwVJT05oLImrlk5pWoqMQlFqWWlScquGUWJwaXAKUSdfwzEsuSs1NzStJTUEVLigtgbI1dRSMzTShpKb1//8GBsn5Kanp@Tlp/3XLcgA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
×0⁹
```
Print 9 `0`s. This serves to pad the result.
```
←⮌⍘⊕⍘S³⁶¦³⁶
```
Convert the input from base 36, incremented it, then convert back to base 36. Then, reverse the result and print it leftwards.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 12 bytes
```
T`zo`dl`.z*$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPyShKj8hJSdBr0pL5f9/AzjggrMsEcwqLkMjYxNTsyogAIom56ekpufnpAEA "Retina 0.8.2 – Try It Online") Explanation: The `dl` part of the substitution destination expands to `0-9a-z` while the `o` copies that to the source, resulting in `z0-9a-z` (although the second `z` gets ignored as it can never match). This increments the matched digits. The `.z*$` part of the pattern matches the last non-`z` digit plus all trailing `z`s, thus handling the carry from their increment to `0`.
[Answer]
# Java 8, ~~90~~ ~~76~~ 56 bytes
```
s->Long.toString(Long.valueOf(1+s,36)+1,36).substring(1)
```
Accepts both upper-case and lower-case letters for input. Output is always in lower case.
Thanks to [Okx](https://codegolf.stackexchange.com/users/26600/okx) for golfing 18 bytes.
Try it online [here](https://tio.run/##nVLfT4MwEH73r6g8tRmQ1emMLpJo1MQ4swcflz10pRBmB0gL6hb@diwtP92bl0Dbu/u@73q9HSmIs/M/qjTf8ogCyokQ4I1EMTieAWVRLFkWEMrAAxFsNm/ctb3LLIpDlUEztmexhJ0jzSVa6LxS/xtyIYlUS5FEPtgriQaw3gCShQINqButrVnuQCUcb5nEoSsTg4H6VBCes1UA8UTYszma4PrvinwrTBJGVcu4@FO2EpVMSKoUhBKI2VcfOFrTzhyv22LLBn3kZhAho8ihj@BpHcEXs8ur@UGZ4@n9dR0zGJr4LEx4UGOafWiVfbVBkrV9besFt33pw6aNLidSHkl1sTbT1Q5oOZ6FFiNInQFNp20DW0837Q5vBtnl8EmzqCCSjd5UM42ezgbDmehO7DtlVDIfnU4ToTInXBVuCNx@uoZjpSczgC2Pyz4VSEADRidN@RGS7d0kl64qO5Y8NmRgAiz1YaVWr4107YSrVzTsUwkYV43/F21bpHafn0o9378snx7Hck2jy@oX).
Ungolfed:
```
s -> // lambda taking a String argument and returning a String
Long.toString(Long.valueOf(1+s,36)+1,36) // prefix input with '1' to ensure leading zeros, convert to Long using base 36, increment, then convert back to String in base 36
.substring(1) // remove the leading '1'
```
[Answer]
# JavaScript (ES6), 89 bytes
This one is not nearly as byte-efficient as [the other JavaScript entry](https://codegolf.stackexchange.com/a/169453/41061), but I made this without noticing this rule:
>
> Given a string **of length 10**
>
>
>
So this isn't a serious entry - just for fun! It works with strings of general length, such as `0abc`, and prepends a `1` when the first digit is `z`, e.g. `zzz` -> `1000`. Input must be lowercase.
```
s=>(l=s[s.length-1],r=s.slice(0,-1),l=='z'?f(r||'0')+0:r+(parseInt(l,36)+1).toString(36))
```
## Explanation
The expression `(A, B, C)` actually means "do A, then do B, then return C", which I make use of to declare some variables I reuse in the code. `s` stands for "string", `l` means "last", `r` means "rest".
```
/*1*/ s=>(
/*2*/ l=s[s.length-1],
/*3*/ r=s.slice(0,-1),
/*4*/ l=='z'
/*5*/ ? f(r||'0')+0
/*6*/ : r+(parseInt(l,36)+1).toString(36))
```
This is a recursive function. For a typical string like `aza`, it will just increment the last character (see line 6) - `azb`. But for a string that ends with `z`, like `h0gz`, it will run itself on everything up to the last character (the `z`) and substitute a `0` in place of it (see line 5) - `f(h0gz)` = `f(h0g) + 0` = `h0h0`.
The `||'0'` in line 5 is so that the function works when it's called on a 1-length string (i.e. the string `'z'`). Without it, `f('')` is called (since `'z'.slice(0, -1)` is `''`), which has undefined behavior (literally - try it yourself), and that's no good. The expected result of `f('z')` is `'10'`, which is what we get from `f('0') + 0`, so we use `||'0'`. (`||'0'` is particularly useful because it doesn't get in the way of the *usual* case - `r` being at least 1-length (`s` at least 2-length) - because strings are falsey only when they are 0-length.)
The method for incrementing a string is the same as used in the other JS entry: convert the base-36 "number" into an actual number, add 1, then convert it back to base-36. We don't need to worry about the `1` from incrementing 'z' (`'z'` -> `'10'`), since we never actually increment 'z' (see line 4 and 6: the last character is only incremented if it is not 'z').
Also, we never risk discarding leading zeroes, because we don't ever actually manipulate more than a single character at a time - only ever the last character in the string. The rest of the characters are cleanly sliced off as you slice any string and prepended afterwords.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 40 bytes
```
->s{(s.to_i(36)+1).to_s(36).rjust 10,?0}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664WqNYryQ/PlPD2ExT21ATxC4GsfWKskqLSxQMDXTsDWr/FyikRSsZwIFSrIKtrQJCwFCJC1WFJbqKRHQVVWgqDA2gKgyNjE1MzaqAAKoCLGAOthZmRnJ@Smp6fk4a3AyoQLrSfwA "Ruby – Try It Online")
1. Convert the string to an integer interpreting it as base 36
2. Add 1
3. Convert back to base 36 string
4. Left pad with `0`s
`"zzzzzzzzzz"` returns an 11-long string
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 109 bytes
```
,[>>,]<+[++++<[<--->>-<-]-[<->>+<---]<[[-]>-------<]+>>[[+<+>]<<+[>+<------]>>]-[<+>-----]<++++<]<[<<]>>[.>>]
```
[Try it online!](https://tio.run/##JYxLCoBADEMP1KngdxVyEEsXKggiuBA8f@0wb1WavOzvdj3nd9wRxcjiEJMEBlUlFeqaNyn14TBTpzbgQpoJhI4UW6fWyGpJK@ZmXUwXyMS6TCP6YZzmZU1@ "brainfuck – Try It Online")
[Answer]
# [Apl (Dyalog Unicode)](https://dyalog.com), 30 28 24 bytes
Thanks to ngn for the hint to save some bytes.
```
(f⍣¯1)1+f←36⊥1,(⎕D,⎕A)⍳⊢
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/zOBpEbao97Fh9YbahpqpwG5xmaPupYa6mgAFbnoAAlHzUe9mx91Lfr/P1PdwMDZ38XV3d/HTZ0rU93QyNjE1CwKCEA8AzhA4UHkomAAxINzItUB)
* Requires ⎕IO of 0
* Uses upper case
[Answer]
# PHP, ~~69~~ 64 bytes
**lame version**:
```
printf("%010s",base_convert(1+base_convert($argn,36,10),10,36));
```
Run as pipe with `-R`. Input case insensitive, output lowercase.
**first approach, 69 bytes:**
```
<?=str_pad(base_convert(1+base_convert($argn,36,10),10,36),10,'0',0);
```
Run as pipe with `-F`
**looping version, also 69 bytes**:
```
for($n=$argn;~$c=$n[$i-=1];)$f||$f=$n[$i]=$c!=9?$c>Y?0:++$c:A;echo$n;
```
* PHP 7.1 only: older PHP does not understand negative string indexes,
younger PHP will yield warnings for undefined constants.
* requires uppercase input. Replace `Y` and `A` with lowercase letters for lowercase input.
Run as pipe with `-nR`
... or [try them online](http://sandbox.onlinephpfunctions.com/code/8053aa5fa35b580f326021fc0041ef32176f8fb8).
[Answer]
# [Python 2](https://docs.python.org/2/), 88 bytes
```
def f(s):L,R=s[:-1],s[-1:];return s and[[L+chr(ord(R)+1),f(L)+'0'][R>'y'],L+'a'][R=='9']
```
[Try it online!](https://tio.run/##Vc69CoMwHATwuX2K4PJPSARjP8AUfYJMriGDNKYKJZHEDvryqVJo6W0/joOblnnwrkzJ9BZZHImQrK2jEjnXLKqcC30L/fwKDkXUOaOUpPchYB8MbgnlhFksCYUCtGobWEAzSaHbVddQgU7Wh206OqSy4puMoZ@qP627eHk6X67rlk9396Z/@KfNtDgepjC6GUUGeQNs/5zSGw "Python 2 – Try It Online")
Increments the string "by hand".
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 39 bytes
```
IntegerString[#~FromDigits~36+1,36,10]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n6Zg@98zryQ1PbUouKQoMy89WrnOrSg/1yUzPbOkuM7YTNtQx9hMx9AgVu1/AFC@JFpZQddOIS1aOTZWQU1B30GhWskADpR0FBA8SxReFYhnaGRsYmpWBQQQueT8lNT0/Jw0pdr/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Clean](https://github.com/Ourous/curated-clean-linux), ~~89~~ 84 bytes
```
import StdEnv
@['9':t]=['a':t]
@['z':t]=['0': @t]
@[c:t]=[inc c:t]
r=reverse
```
#
```
r o@o r
```
[Try it online!](https://tio.run/##RcwxC8IwEAXgPb/iwCGT0NVCIIMOglvH0uFIUwkkF7leC/bHG00VfMt7fMNz0SOVlMclekgYqIT0yCzQyXihVdlen3Qrg@k11q6w/aDRLdid3A6BHNSl2LBfPc@@dIIs6gDTQk5CJjDAkG0GVuaPn6tm@0YP5eWmiPe5HK@3cn4SpuDmNw "Clean – Try It Online")
A shorter solution thanks to [Laikoni](https://codegolf.stackexchange.com/users/56433/laikoni).
# [Clean](https://github.com/Ourous/curated-clean-linux), 115 bytes
I love it when I get to use `limit(iterate...`
```
import StdEnv
@'9'='a'
@c=inc c
?[h,'{':t]=[@h,'0': ?t]
?[h:t]=[h: ?t]
?e=e
$l=limit(iterate?(init l++[@(last l)]))
```
[Try it online!](https://tio.run/##LY29CsIwFEb3PEUG4bZUoauF0Aw6CG4dQ4ZLGu2FJJX2Kqjvbqw/33S@sxwXPKYcx/4avIxIKVO8jBPLjvt9ugkNW1CAILRTlJx0ojXDGp7QsFVGL1hDI1u2H/91w/965cUqqECRuCD2E7JvC0rEMlSV0UXAecHSlmXuGJekkitpoK4fv4HNL3cKeJ7z5nDMu3vCSG5@Aw "Clean – Try It Online")
Produces the answer without converting bases using list matching.
* `? :: [Char] -> [Char]` performs forward carrying.
* `@ :: Char -> Char` increments by one, accounting for the gap between `'9'` and `'z'`.
* `$ :: [Char] -> [Char]` increments the last character and applies `?` until the value stabilizes.
[Answer]
# [R](https://www.r-project.org/), ~~152~~ 123 bytes
```
function(x)f(utf8ToInt(x),10)
f=function(x,n,y=x[n]){x[n]=y+(y==57)*39+(y==122)*(-75)+1
"if"(y==122,f(x,n-1),intToUtf8(x))}
```
[Try it online!](https://tio.run/##ZY0xD4IwEIV3fkVTlx60CQURSay7O07GwaAlJKZNTEkA42@vBQlguOFy9@679162RAeGrKxVYSqtSAOS1Ebuc31Sxm2Uh@BJMd@poq1oLuoK776LNiCtEEkKfpwNI48i8AlLEwi4hyuJR5HK/plxoJUyuT67EOcPH1sSHE6FAW0QO6JZ4thbEtmauP0T3Yrg4UDwKN4mu87VRAxSOgT/PAp9f5T6KRceo1Ri@wU "R – Try It Online")
A completely different approach. Get the ASCII code points and recursively "increment" the right-most code point (making `0` (57) jump to to `a` (97) and `z` (122) go back to `0` (48)) until you run out of `z`s. Convert back to string.
### Old version
```
function(s,w=gsub("(z)(?=\\1*$)","0",s,,T),x=regexpr(".0*$",w)[1],y=substr(w,x,x),z=chartr("0-9a-z","1-9a-z0",y))sub(p(y,"(0*$)"),p(z,"\\1"),w)
p=paste0
```
[Try it online!](https://tio.run/##ZY3BboMwDIbvPEXkcbArMyXb2qrSsr1Eb20PjAGtVJUoAQF5eZayiTLhk/3r8/fboRDviRiK5pbVl@qGjltduuYLAT3hpz4e1SomYJDAjnlP3Gmbl3lnLMKzXMXALR3UiXsdvlxtseWOO2Kvs3Nqww0y2aWJDwo1LkHUE90rDPYMKO9@YoOeIbSFtaXIaJO6OpdDEf6nARJPIvkQj0hBNCd2SyL9T/gFoeRIqJfXt/XGh5mIMdqOxb@OrPrOy@pazBx/UQnDDw "R – Try It Online")
This is all text manipulation, which is does not go hand-in-hand with R code golfing.
Replace all `z` at end of strings with `0`. Find location of last element before the newly minted trailing `0`s. Find the next base 36 digit. Make the change. Be glad to have barely beaten the Online Turing Machine Simulator solution.
[Answer]
# [Zsh](https://www.zsh.org/), ~~41~~ 36 bytes
```
echo ${(l:10::0:)$(([##36]36#$1+1))}
```
[Try it online!](https://tio.run/##qyrO@J@moalQ/T81OSNfQaVaI8fK0MDKysBKU0VDI1pZ2dgs1thMWcVQ21BTs/Z/LVdRamKKQgVXmoJKxX8Dg@T8lNT0/Jw0AA "Zsh – Try It Online")
[Answer]
# [Starry](https://esolangs.org/wiki/Starry), 325 bytes
```
+ , , , , , , , , , , + + + +`* + + +* + +** + * +* * ' + + +* +* +* +* +* ` + + + + + * +* * ' + +* + +* +* +* ` + + + +* + * ** + + +' + + ` + + +* + * * . + +* + * * + '
```
[Try it online!](https://tio.run/##dZDbDoAgCIZfhTs3aK1HsnW6aXOzbnp6ShhmTT2g/MCH8zjHGC9mSIOgq0yN5EO2R5NUJhSD5mNSEFxRW2TaUgnBG5w@yVYBgJBzn2tJNcqfLkyqdhecPFU7vrhkfKsimb4R0t9wzMMwhXnZwr7e "Starry – Try It Online")
# Explanation:
```
Put-a-zero-at-the-base-of-the-stack
| +
Read-10-digits
| , , , , , , , , , ,
Initialise-next-stack
| +
Initialise-carry-bit
| +
| + +
Do
|`
Top-of-stack:-[output-stack]-[carry-bit]-[next-value]
Add-Carry-bit-to-digit
|*
Compare-with-58-("9"=57)
| +
5-double-triple-sub1-double
| + +* + +** + * +*
Take-difference
| *
If-one-above-"9"
| '
set-to-"a"=97=6-double-double-double-double-add1
| +
| + +* +* +* +* +*
| `
Initialise-next-carry-bit
| +
| +
Compare-with-123-("z"=122)
| +
11-squared-add2
| + + * +*
Take-difference
| *
If-one-above-"z"
| '
Delete-current-value
| +
set-carry-bit
| +*
Set-to-"0"=48
| + +* +* +*
| `
Push-value-to-stack
| + +
| + +* + *
| **
| + +
While-next-value-is-not-null
| +'
Pop-carry-bit-and-null-string-terminator
| + +
Do
| `
Get-top-value
| +
| + +* + *
| *
Print-it
| .
Pop-the-value-off-the-stack
| + +* + *
| *
While-stack-is-not-null
| + '
```
[Answer]
# [Python 3.6+ and gmpy2](https://docs.python.org/3/), 62 bytes
```
from gmpy2 import*;f=lambda s:f'{digits(mpz(s,36)+1,36):0>10}'
```
[Try it online!](https://tio.run/##VY3BCsIwEAXP@hVLL2m0QttowYj9EfFQrdsGmmxIcmnFb48tguIcHgxzeHYMPRkRIzrS0Gk7lqC0JRc2JzwPjb61DXiJ7NmqTgWfajulPhMV3xbLyrwu8heLSA48KAOXJP@SZPCz459NixWl2B@qaebT7tQ@Ohowucr1yjplAsxfbFezDFPPeYxv "Python 3 – Try It Online")
(Note that gmpy2 isn't part of Python standard library and requires separated installation)
[Answer]
# [Pyke](https://github.com/muddyfish/PYKE), 11 bytes
```
? b!!R+bhbt
```
[Try it here!](https://pyke.catbus.co.uk/?code=%3F+b%21%21R%2Bbhbt&input=0zzzzzzzzz%0A&warnings=1&hex=0)
```
? b - Change default base of `base` command to 36
- This is kind of clever because it modifies the list of characters
- the command uses to exactly the same as it was originally, whilst
- forcing an overwrite from the default settings of 10.
- The default setup works for base 36, you just have to specify it
- time when using the command.
- Literally `b.contents = modify(b.contents, func=lambda: noop)`
!! - The previous command returns `0123456789abcdefghijklmnopqrstuvwxyz`
- So we convert it into a 1 with (not not ^) for the following command:
R+ - "1"+input
b - base(^, 36)
h - ^ + 1
b - base(^, 36)
t - ^[1:]
```
Could be 2 bytes shorter with the following language change: If hex mode is used, change all base\_36 and base\_10 usages to base\_92 (which isn't really base 92 in that context anyway)
[Answer]
# [sed](https://www.gnu.org/software/sed/), 94 bytes
```
s/$/#:0123456789abcdefghijklmnopqrstuvwxyz#0/
:l
s/\(.\)#\(.*:.*\1\)\(#*.\)/\3\2\3/
tl
s/:.*//
```
[Try it online!](https://tio.run/##K05N0U3PK/3/v1hfRV/ZysDQyNjE1MzcwjIxKTklNS09IzMrOyc3L7@gsKi4pLSsvKKyStlAn8sqh6tYP0ZDL0ZTGUhqWelpxRjGaMZoKGsBhfRjjGOMYoz1uUpAqoBy@vr//xvAARecZYlgVnFBbK4CAqBocn5Kanp@ThoA "sed – Try It Online")
Sed suffers a lot for having to change the characters by lookup.
[Answer]
# Powershell, ~~79~~ ~~78~~ 82 bytes
*+4 bytes: `z` and `9` inside an argument string fixed*
```
$i=1
"$args"[9..0]|%{$r=([char]($i+$_)+'0a')[2*($i*$_-eq57)+($i*=$_-eq'z')]+$r};$r
```
Less golfed test script:
```
$f = {
$i=1 # increment = 1
"$args"[9..0]|%{ # for chars in positions 0..9 in the argument string (in reverse order)
$c=[char]($i+$_) # Important! A Powershell calculates from left to right
# Therefore the subexpression ($i+$_) gets a value before the subexpression ($i=$_-eq122)
$j=2*($i*$_-eq57)+ # j = 2 if the current char is '9' and previous i is 1
($i*=$_-eq122) # j = 1 if the current char is 'z' and previous i is 1
# j = 0 othewise
# side effect is: i = 1 if the current char is 'z' and previous i is 1, i = 0 othewise
$c=($c+'0a')[$j] # get element with index j from the array
$r=$c+$r # accumulate the result string
}
$r # push the result to a pipe
}
@(
,("09fizzbuzz" , "09fizzbv00")
,("0000000000" , "0000000001")
,("0000000009" , "000000000a")
,("000000000z" , "0000000010")
,("123456zzzz" , "1234570000")
,("00codegolf" , "00codegolg")
) | % {
$s,$expected = $_
$result = &$f $s
"$($result-eq$expected): $result"
}
```
Output:
```
True: 09fizzBv00
True: 0000000001
True: 000000000a
True: 0000000010
True: 1234570000
True: 00codegolg
```
] |
[Question]
[
Read two strings from `stdin`.
Output `Yes` if one string is a rotated version of the other.
Otherwise output `No`
**Testcases**
Input
```
CodeGolf GolfCode
```
Output
```
Yes
```
Input
```
stackexchange changestackex
```
Output
```
Yes
```
Input
```
stackexchange changestack
```
Output
```
No
```
Input
```
Hello World
```
Output
```
No
```
[Answer]
## Ruby 49 41
```
a,b=$*;puts (a*2).sub(b,'')==a ?:yes: :no
```
Edit: replaced gets.split by $\*
[Answer]
## APL (28)
Takes input on two lines.
```
'No' 'Yes'[1+(⊂⍞)∊⌽∘A¨⍳⍴A←⍞]
```
Explanation:
* `A←⍞`: read a line of input and store it in A
* `⌽∘A¨⍳⍴A`: Rotate A by x, for each x in [1..length A]. Gives a list, i.e. `estT stTe tTes Test`
* `(⊂⍞)∊`: read another line of input, and see if it is in this list.
* `1+`: add one to this, giving 1 if the strings were not rotated and 2 if they were
* `'No' 'Yes'[`...`]`: Select either the first or second element from the list `'No' 'Yes'` depending on whether the strings were rotated or not.
* This value is output automatically.
[Answer]
## Python, 70 bytes
```
a,b=raw_input().split()
print ['No','Yes'][a in b*2and len(a)==len(b)]
```
[Testing ...](http://ideone.com/sMtVR)
[Answer]
**Python 70 Characters**
```
a,b=raw_input().split()
print'YNeos'[len(a)<>len(b)or a not in 2*b::2]
```
Thanks to gnibbler for the slice trick.
[Answer]
## J, 47
```
y=:>2{ARGV
(>1{ARGV e.1|.^:(i.#y)y){'No',:'Yes'
```
[Answer]
According to the spec (same string lengths):
### Perl, 42 43 chars
```
$.=pop;$_=(pop)x2;print+(qw'yes no')[!/$./]
```
If different sized strings are allowed, the solution would be:
### Perl, 47 chars
```
$.=(pop)x8;$_=(pop)x9;print+(qw'yes no')[!/$./]
```
rbo
[Answer]
## Golfscript, 31
```
' '/:)~,\,=)~.+\/,(&'Yes''No'if
```
This one check length first, so it should work as expected.
[Answer]
## J, 57
```
{&('No';'Yes')@-:/@:((/:~@(|."0 _~i.&$))&.>)&.(;:&stdin)_
```
Sample use:
```
$ echo -n CodeGolf GolfCode | jconsole rotate.ijs
Yes
$ echo -n stackexchange changestackex | jconsole rotate.ijs
Yes
$ echo -n stackexchange changestack | jconsole rotate.ijs
No
$ echo -n Hello World | jconsole rotate.ijs
No
```
[Answer]
## Windows PowerShell, 76
```
$a,$b=-split$input
('No','Yes')[+!($a.length-$b.length)*"$b$b".contains($a)]
```
[Answer]
## JavaScript, 51
```
function f(a,b)a&&(a+a).replace(b,"")==a?"Yes":"No"
```
JavaScript doesn't have a canonical host, so this answer is written as a function of two arguments. The score goes up to 60 if we disallow JS 1.7 features (expression closures).
In the SpiderMonkey shell this would be (for a score of 71):
```
[a,b]=readline().split(" ");print(a&&(a+a).replace(b,"")==a?"Yes":"No")
```
[Answer]
## Python, 66 63
```
a,b=raw_input().split()
print'YNeos'[a!=(2*a).replace(b,"")::2]
```
**Another solution in 69 char**
```
a,b=raw_input().split()
print['No','Yes'][a in b*2and len(a)==len(b)]
```
[Answer]
## J, 84
```
y=:(>1{ARGV),:(>2{ARGV)
((0{y)e.(y&((]$0{[),(]-~[:}.[:$[)$1{[)/.i.}.$y)){'No',:'Yes'
```
[Answer]
**JavaScript (120 chars)**
```
function f(a,b) {for (i=0,A=a.split("");A.join("")!=b&&i++<a.length;A.push(A.shift()));return A.join("")==b?'Yes':'No';}
```
Output:
```
f('CodeGolf','GolfCode'); //Yes
f('stackexchange','changestackex'); //Yes
f('stackexchange','changestack'); //No
f('Hello','World'); //No
f('nn','nBn'); //No
```
[Answer]
## Ruby, 58 (62) characters
```
a,b=gets.split;$><<(a.size==b.size&&/#{a}/=~b*2?:Yes: :No)
```
This solution assumes the input contains only alphanumeric characters (actually everything that doesn't have a special meaning inside a regular expression is ok).
A solution that doesn't have this constraint is 4 characters longer
```
a,b=gets.split;$><<(a.size==b.size&&(b*2).index(a)?:Yes: :No)
```
[Answer]
## Python, 71
```
a,b=raw_input().split()
print'Yes'if a in b*2and len(a)==len(b)else'No'
```
[Answer]
## PHP, 61
```
<?echo preg_match('/^(.+)(.*) \\2\\1$/',fgets(STDIN))?Yes:No;
```
[Answer]
## Ruby, 41
```
puts gets =~ /^(.+)(.*) \2\1$/ ?:Yes: :No
```
[Answer]
## Haskell (98 96 chars)
```
g x y@(t:r)(z:w)|x==y="Yes"|1>0=g x(r++[t])w
g _ _[]="No"
f(x:y:_)=g x y y
main=interact$f.words
```
[Answer]
# Q (~~50~~ 43 chars)
```
{`No`Yes x in((!)(#)y)rotate\:y}." "vs(0:)0
```
[Answer]
**Scala 78**
```
val b=readLine split " "
print(b(0).size==b(1).size&&(b(0)+b(0)contains b(1)))
```
It's a shame about the size check, without it the count drops to **54**
```
val a=readLine split " "
print(a(0)+a(0)contains a(1))
```
[Answer]
## bash 56
```
read a b
[[ $a$a =~ $b&&$b$b =~ $a ]]&&echo Yes||echo No
```
[Answer]
# GolfScript, 25 bytes
```
' '/~.2*@/''+='Yes''No'if
```
### How it works
```
# STACK: "CodeGolf GolfCode"
' '/ # Split input string by spaces.
# STACK: [ "CodeGolf" "GolfCode" ]
~ # Dump the array.
# STACK: "CodeGolf" "GolfCode"
. # Duplicate the topmost string.
# STACK: "CodeGolf" "GolfCode" "GolfCode"
2* # Repeat the topmost string.
# STACK: "CodeGolf" "GolfCode" "GolfCodeGolfCode"
@ # Rotate the three topmost strings.
# STACK: "GolfCode" "GolfCodeGolfCode" "CodeGolf"
/ # Split the second topmost string around the topmost one.
# STACK: "GolfCode" [ "Golf" "Code" ]
''+ # Flatten the array of strings.
# STACK: "GolfCode" "GolfCode"
= # Check for equality.
# STACK: 1
'Yes''No'if # Push 'Yes' for 1, 'No' for 0.
# STACK: "Yes"
```
[Answer]
# CJam, 21 bytes
```
r]r_,,\f{\{(+}*}_@+^!
```
[Try it online!](http://cjam.aditsu.net/#code=r_%2C%2C%5Cf%7B%5C%7B(%2B%7D*%7D_%5Br%5D%2B%5E!&input=golfcode%20codsgolf)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
Not sure about the rules here, Husk doesn't do IO at all. The closest alternative is a function:
```
!w¨Ye∫No¨€U¡ṙ1
```
[Try it online!](https://tio.run/##yygtzv7/X7H80IrI1Ecdq/3yD6141LQm9NDChztnGv7//985PyXVPT8n7T@IAHEA "Husk – Try It Online")
### Explanation
```
!w¨Ye∫No¨€U¡ṙ1
¡ -- iterate the following for ever:
ṙ1 -- rotate string by 1
U -- only keep the longest prefix with unique elements
€ -- is the argument in that list?
¨Ye∫No¨ -- compressed string: "Yes No"
w -- split on space
! -- modular index (1-based)
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~17~~ 13 bytes
```
ɠṙJɠeị“Yes“No
```
[Try it online!](https://tio.run/##y0rNyan8///kgoc7Z3qdXJD6cHf3o4Y5kanFQNIv//9/5/yUVPf8nDQuEAHiAAA "Jelly – Try It Online")
## How it works
```
ɠṙJɠeị“Yes“No - Main link. Takes no arguments
ɠ - Read a line from STDIN
J - Indices; [1, 2, ..., len(S)]
ṙ - All rotations of S
ɠe - Read a line from STDIN; is that in the rotations?
ị“Yes“No - Index that into ["Yes", "No"]
```
[Answer]
**Lua 115 chars**
```
a,b=io.read():match"(%w+) (%w+)"c=b repeat c=c:sub(2,-1)..c:sub(1,1) s=s or a==c until b==c print(s and"Yes"or"No")
```
[Answer]
## C program - 146
```
char b[99],c[99],*p,*q;main(n){q=(p=b+(n=strlen(gets(c))))+n;sprintf(b,"%s%s"
,c,c);for(gets(c);p>b&&strcmp(p,c);--p,*--q=0);puts(p>b?"Yes":"No");}
```
[Answer]
## PHP, 82 characters
```
<?$s=split(" ",fgets(STDIN));echo str_replace($s[1],"",$s[0].$s[0])==$s[0]?Yes:No;
```
[Answer]
**perl, 123 chars**
```
@s1=split(//,shift);
$s2=shift;
$i=0;
while($i<=@s1){
if(join("",@s1) eq $s2){die "yes";}
unshift @s1,pop @s1;
$i++;
}
die "no";
```
[Answer]
## Ruby, 30 37
```
gets
puts~/^(.+)(.*) \2\1$/?:Yes: :No
```
A version that prints "true" and "false" instead of "yes" and "no":
```
gets
p !! ~/^(.+)(.*) \2\1$/
```
Both of these work with different-length strings (unlike the old one)
] |
[Question]
[
# Problem:
Your task is to write a program that takes as input a height (in meters) and weight (in kilograms), and outputs the corresponding BMI category.
[BMI](https://en.wikipedia.org/wiki/Body_mass_index) is a measure of the ratio of your weight to your height. [It's dated and inaccurate for many people](https://en.wikipedia.org/wiki/Body_mass_index#Limitations), but that doesn't matter here!
BMI can be calculated using the following equation:
```
BMI = (mass in kilograms) / (height in meters)^2
```
The categories will be defined as follows:
* BMI < 18.5: "Underweight"
* 18.5 <= BMI < 25: "Normal"
* 25 <= BMI: "Overweight"
For the sake of the challenge, I'm ignoring all the "extreme" categories. Also, since some numbers like "25" sit between 2 categories, I adjusted the bounds slightly so there's a definite answer.
You can write either a function, or a full program.
# Input:
Input can be in any reasonable form. Two numbers (or strings), either as 2 separate arguments, or as a single string. An array/list of 2 numbers, a dictionary with "weight" and "height" keys... Decimal values should be supported. You can assume the input will always be valid (no negative values, and height will never be 0).
# Output:
Output will be a string containing the *case-insensitive* category names. The strings must match the category names exactly as above, ignoring case. It can be output to the stdout, returned (in the case of a function), or written to file.
# Test Cases (weight, height => result):
```
80, 1 => "Overweight"
80, 2 => "Normal"
80, 3 => "Underweight"
50, 1 => "Overweight"
50, 1.5 => "Normal"
50, 2 => "Underweight"
Edge Cases:
41, 1.5 => "Underweight" (18.2 BMI)
42, 1.5 => "Normal" (18.667 BMI)
56, 1.5 => "Normal" (24.889 BMI)
57, 1.5 => "Overweight" (25.3 BMI)
73, 2 => "Underweight" (18.25 BMI)
74, 2 => "Normal" (18.5 BMI)
99, 2 => "Normal" (24.75 BMI)
100, 2 => "Overweight" (25 BMI)
```
Here's some pseudocode that shows an example implementation:
```
function bmi_category(weight, height):
var bmi = (weight / (height**2))
if (bmi < 18.5):
return "Underweight"
if (18.5 <= bmi < 25):
return "Normal"
if (25 <= bmi):
return "Overweight"
```
This is code-golf, so the fewest number of bytes wins.
(Yes, this task is ***exceedingly*** trivial in most languages. Most of the challenges lately seem to be harder than normal, so I thought I'd post a more accessible one).
---
NOTE! An hour after I posted this challenge, I had to modify the ranges slightly since the ranges as stated had "holes" as pointed out in the comments. Please see the new ranges.
[Answer]
# [Python](https://docs.python.org/2/), 69 bytes
```
lambda w,h:["UOnvd"[w/h/h>20::2]+"erweight","Normal"][18.5<=w/h/h<25]
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqhQrpNhFa0U6p9XlqIUXa6foZ9hZ2RgZWUUq62UWlSempmeUaKko@SXX5SbmKMUG21ooWdqYwtWZ2NkGvs/Lb8IZIRCZp5CtIaFgZ6BjrGegaaOhimIaQRmWiCYYFFDPVMEE64AxIy14uIsKMrMK1FI0wAaqvkfAA "Python 2 – TIO Nexus")
Compare to 72 bytes:
```
lambda w,h:"Underweight"*(w/h/h<18.5)or"Normal"*(w/h/h<25)or"Overweight"
```
[Answer]
# TI-Basic, ~~58~~ 54 bytes
```
Input
X/Y²→C
"NORMAL
If 2C‚â§37
"UNDERWEIGHT
If C≥26
"OVERWEIGHT
```
Also, for fun, here's a more compact version that is more bytes:
```
Prompt A,B
sub("UNDERWEIGHTNORMAL OVERWEIGHT ",sum(A/B²≥{18.5,25})11+1,11
```
All I can say is, thank you for making this case-insensitive ;)
P.S. `Input` takes graph input to `X` and `Y` similar to `Prompt X,Y`
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 24 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
÷÷⁹Ḥ“%2‘>Sị“$⁽¿“;ṅẒ“&ċ)»
```
**[Try it online!](https://tio.run/nexus/jelly#@394@@Htjxp3Ptyx5FHDHFWjRw0z7IIf7u4GclQeNe49tB/IsH64s/XhrklAltqRbs1Du////29q8N9QzxQA)**
### How?
Calculates the BMI, doubles it, compares that with the greater than operator with each of the numbers 37 and 50 (18.5 and 25 doubled), sums the resulting ones and zeros (yielding 1, 2, or 0 for Normal, Underweight, and Overweight respectively) and indexes into the list of strings `["Normal","Underweight","Overweight"]`.
```
÷÷⁹Ḥ“%2‘>Sị“$⁽¿“;ṅẒ“&ċ)» - Main link: weight, height
√∑ - weight √∑ height
‚Åπ - right argument, height
√∑ - √∑ by height again to get the BMI
·∏§ - double the BMI
“%2‘ - list of code page indexes [37,50]
> - greater than? (vectorises) - i.e [18.5>bmi, 25>bmi]
S - sum -- both:=2 (Underweight), just 50:=1 (Normal) or neither:=0 (Overweight)
ị - index into (1-based)
“$⁽¿“;ṅẒ“&ċ)» - compressed list of strings ["Normal","Underweight","Overweight"]
- implicit print
```
[Answer]
# Mathematica, 67 bytes
```
"Normal"["Underweight","Overweight"][[Sign@‚åä(2#/#2^2-37)/13‚åã]]&
```
Uses the fact that `a[b,c][[Sign@d]]` returns `a` if `d` equals 0, returns `b` if `d` is positive, and returns `c` if `d` is negative. `‚åä...‚åã` is Mathematica's `Floor` function using the three-byte characters U+230A and U+230B. Couldn't figure out how to do better than using `weight` twice.
[Answer]
# Ruby, 91 77 74 67 bytes
First naive try:
```
->(w,h){case w/h/h
when 0..18.5
'underweight'
when 18.5..25
'normal'
else
'overweight'
end}
```
Second try with ”inspiration“ from previous answers:
```
->w,h{["#{(w/=h*h)<18.5?'und':'ov'}erweight",'normal'][(18.5..25)===(w)?1:0]}
```
Third try:
```
->w,h{["#{(w/=h*h)<18.5?'und':'ov'}erweight",'normal'][w>=18.5&&w<25?1:0]}
```
Fourth try:
```
->w,h{18.5<=(w/=h*h)&&w<25?'normal':"#{w<18.5?'und':'ov'}erweight"}
```
[Try it online!](https://tio.run/nexus/ruby#RcrBCoIwHIDxu08xDJzGWtMYiMx8kOVB3Owf2AzTdlCf3ZqHvP34@Jr8tp6ulsAUp5SLPLTnHI4QBYEVCS@w6fpn1eLMP0xWuKXAo1E4w90HL7q3@nGHwV9WKVNGGblQVhLJHZON6c6txpTv/A@OJdVVDUh1aA4tQRDNHkKvcXijhtZV2/4iRJ42av0C "Ruby – TIO Nexus")
[Answer]
# JavaScript (ES6), ~~70 67 64~~ 63 bytes
*Saved 4B thanks to Arnauld*
```
a=>b=>(a/=b*b)<25&a>=18.5?"Normal":(a<19?"Und":"Ov")+"erweight"
```
## Usage
```
f=a=>b=>(a/=b*b)<25&a>=18.5?"Normal":(a<19?"Und":"Ov")+"erweight"
f(80)(1)
```
### Output
```
"Overweight"
```
## Explanation
This answer is quite trivial, though there is one clever trick: `Underweight` and `Overweight` both end in `erweight`, so we only have to change those characters.
I assumed that `Normal` means a BMI between 25 (exclusive) and 18.5 (inclusive). `Underweight` means a BMI less than 18.5, and `Overweight` means a BMI greater than or equal to 25.
[Answer]
# C, 81 bytes
```
f(float m,float h){m/=h*h;puts(m<26?m<18.6?"Underweight":"Normal":"Overweight");}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 28 bytes
```
n/©37;‹®25‹O’‚Š‰ß î ‚â‰ß’#è
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@5@nf2ilsbn1o4adh9YZmQIp/0cNMx81zDq64FHDhsPzFQ6vO9ykAOQfXgTmAyWVD6/4/99Qz5TL1AAA "05AB1E – TIO Nexus")
[Answer]
## [QBIC](https://drive.google.com/drive/folders/0B0R1Jgqp8Gg4cVJCZkRkdEthZDQ), ~~61~~ 58 bytes
```
::m=a/b^2~m<18.5|?@Und`+@erweight`\~m>=25|?@Ov`+B\?@Normal
```
*@Luke used the Force and chopped off two bytes. Thanks!*
*The rules change saved another byte.*
Explanation:
```
:: gets weight and height as a and b
m=a/b^2 Calculates BMI
~m<18.5| If BMI < 18.5 then
?@Und` Print the string literal 'Und' (which is now A$)
+@erweight` and the string literal 'erweight' (which is now B$)
\~m>=25| else if the BMI is greater than or equal to 25
?@Ov`+B Print 'Ov' and B$ ('erweight')
\?@Normal Else, if we're here, BMI is normal.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 72 bytes
```
lambda a,b:"UNOnovdreemrrawwlee ii gg hh tt"[(18.6<a/b/b)+(a/b/b>25)::3]
```
[Try it online!](https://tio.run/nexus/python2#S7ON@Z@TmJuUkqiQqJNkpRTq55@XX5ZSlJqaW1SUWF6ek5qqkJmpkJ6ukJGhUFKiFK1haKFnZpOon6SfpKmtAabtjEw1rayMY/8XFGXmlWikaVgY6BnoKBjqGWhqcqGKGWERMwaJ/QcA "Python 2 – TIO Nexus")
[Answer]
# Python 3, ~~97~~ 95 bytes
```
a,b=map(int,input().split())
a/=b*b*5
print(["UOnvd"[a>93::2]+"erweight","Normal"][93<=a<=125])
```
Full program.
Multiply by five to save a byte. Thanks Jonathan Allan.
Line by line:
1. Map the two space separated user input numbers to ints. Unpack to a and b.
2. Calculate
3. If the bmi is between 18.6 and 25, inclusive, the expression on the right will evaluate to True. Booleans can be 0 or 1 when used as list indexes, so we get either "Normal" or the constructed string in the zero index. "erweight" is a shared suffix for the remaining two options, so it doesn't need to be repeated. Then we use the [start:stop:step] pattern of Python list/string slicing. c>18.6 will evaluate to either 0 or 1 (False or True) and becomes our start. Stop isn't indicated so we go to the end of the literal. Step is 2 so we take every second index. If start start evaluates to 1, we get "Ov", otherwise we get "Und". Either way, we append "erweight" to what we got and we have our final output.
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), 81 bytes
```
param($m,$h)('Underweight','Normal','Overweight')[(18.5,25-lt($m/($h*$h))).Count]
```
[Try it online!](https://tio.run/nexus/powershell#@1@QWJSYq6GSq6OSoamhHpqXklpUnpqZnlGirqPul1@Um5gDZPiXwUU1ozUMLfRMdYxMdXNKgPr0NVQytIB6NTX1nPNL80pi////b2rw31DPFAA "PowerShell – TIO Nexus")
## Explanation
The main bit that needs explaining is `18.5,25 -lt $b` (where I'm substituting `$b` for the BMI which is calculated in place in the code). Most operators in PowerShell, when given an array on the left side, return an array of items that satisfy the test, instead of returning a boolean value. So this will return an empty array if `$b` is smaller than 18.5, an array containing only 18.5 if it's in the middle, and an array containing both 18.5 and 25 if it's larger than 25.
I use the count of the elements as an index into an array of the strings, so count `0` gets element `0` which is `'Underweight'`, etc.
[Answer]
## R, ~~89~~ ~~84~~ ~~80~~ 74 bytes
```
f=pryr::f(c('Overweight','Normal','Underweight')[sum(w/h^2<c(18.5,25),1)])
```
With a nod to StewieGriffin's Octave answer, creates an array of strings, then sums the result of `BMI < c(18.5,25)` and references the array at that position + 1.
First argument needs to be height, then weight; if that's not allowed, then
```
f=pryr::f(w,h,c('Overweight','Normal','Underweight')[sum(w/h^2<c(18.5,25),1)])
```
works for 4 more bytes.
[Answer]
## Clojure, 63 bytes
```
#(condp <(/ %(* %2 %2))25"Overweight"18.5"Normal""Underweight")
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 58 bytes
```
Fk[Ov]?2^/d[[Normal]pq][[Und]26]sasb18.5>a25>bn[erweight]p
```
Takes input as 2 space separated numbers in the format `<mass> <height>` . Outputs a string on a separate line.
[Try it online!](https://tio.run/nexus/dc#@x/tXxZrbxSnnxId7ZdflJuYE1tQGBsdHZqXEmtkFhucWJxkaKFnapdoZGqXlBedWlSempmeURJb8P@/hYGC4de8fN3kxOSMVAA "dc – TIO Nexus")
### Explanation
For the purposes of this explanation, the input is `80 1`.
```
Fk # Set decimal precision to `16`.
[Ov] # Push the string "Ov" onto the main stack.
# Main Stack: [[Ov]]
?2^/d # Take and evaluate input, squaring the 2nd one, and the dividing by the first one by the 2nd. Then duplicate the result.
# Main Stack: [[Ov],80.000000000000000,80.000000000000000]
[[Normal]pq][[Und]26]sasb # Push and store the executable macros "[Normal]pq" and "[Und]26" on registers "a" and "b", respectively.
# Main Stack: [[Ov],80.000000000000000,80.000000000000000], reg. a: [[[Normal]pq]], reg. b: [[[Und]26]]
18.5>a25>b # Push, "18.5" onto stack, and then pop top 2 values. If "18.5 > (top of stack)", then execute the macro on top of reg. "a", which in turn pushes the string "Und" onto the main stack followed by the number 26.
# The "26" will automatically prompt the next comparison to not execute the macro on top of reg. "b", regardless of the value on top of the main stack.
# Otherwise, if "18.5 <= (top of stack) < 25", then execute "b"s macro, which in turn pushes the string "Normal" onto the main stack, outputs it, then quits the program.
# In this case, Main stack: [[Ov]], reg. a: [[[Normal]pq]], reg. b: [[[Und]26]]
n[erweight]p # If "Normal" has not been output, only then will the program get to this point. Here, it will output whatever string, either "Und" or "Ov", on top of the main stack, followed by "erweight" and a new line.
```
[Answer]
# Octave, 64 bytes
```
@(w,h){'Underweight','Normal','Overweight'}{3-sum(2*w/h^2<'%2')}
```
[Try it online](https://tio.run/#5pIiW)
This is an anonymous function that takes two input arguments, `h` (height) and `w` (weight).
The function creates a cell array containing there strings `'Underweight','Normal','Overweight'`, and outputs string number `3-sum(2*w/h^2<'%2')`.
Yes, that one looks a bit strange. We want the first string if `w/h^2<=18.5`, the second string if `(w/h^2 > 18.5) & (w/h^2 < 25)` and the third string if none of the above conditions are true. Instead of creating a bunch of comparisons, we could simply compare the string to: `w/h^2 < [18.5, 25]`, which would return one of the following arrays `[1 1], [0 1], [0,0]` for Underweight, Normal and Overweight respectively.
`[18.5,25]` takes 9 bytes, which is a lot. What we do instead, is multiply the BMI by 2, and compare the result with `[37, 50]`, or `'%2'` in ASCII. This saves three bytes.
[Answer]
# [Perl 6](http://perl6.org/), 59 bytes
```
{<Overweight Normal Underweight>[sum 18.5,25 X>$^a/$^b**2]}
```
### How it works
```
{ } # A lambda.
$^a/$^b**2 # Compute BMI from arguments.
18.5,25 X> # Compare against endpoints.
sum # Add the two booleans together.
<Overweight Normal Underweight>[ ] # Index into hard-coded list.
```
Too bad the string `erweight` has to be repeated, but all variations I tried in order to avoid that ended up increasing the overall byte count:
* With string substitution, 62 bytes:
```
{<Ov_ Normal Und_>[sum 18.5,25 X>$^a/$^b**2].&{S/_/erweight/}}
```
* With string interpolation, 67 bytes:
```
{$_='erweight';("Ov$_","Normal","Und$_")[sum 18.5,25 X>$^a/$^b**2]}
```
* Rough translation of [xnor's Python solution](https://codegolf.stackexchange.com/a/109338/14880), 65 bytes:
```
{$_=$^a/$^b**2;25>$_>=18.5??"Normal"!!<Und Ov>[$_>19]~"erweight"}
```
[Answer]
# OCaml, 93 bytes
```
let b w h=if w/.h/.h<18.5 then"underweight"else if w/.h/.h>=25.0 then"overweight"else"normal"
```
[Answer]
# Python, ~~75~~ 74 bytes
```
lambda h,w:18.5<=w/h/h<=25and"normal"or["ov","und"][25>w/h/h]+"erwe‌​ight"
```
[Try it online!](https://tio.run/nexus/python3#NclLCoAgFADAqzzeqo9UCkVEnsRaGGkKZmEfj2@rZjsaOEzJyX1ZJRgSB/RH2KVDq4H2VTvyWJuiYCNnLSh3KYHHiwQfv@IsWPf/XKIKUdnN3JjOYP2d6axvCM3z9AE)
Fairly basic solution that takes advantage of other people's techniques for solving it.
Thanks @ovs for saving a byte.
## Alternatives
### 1. 73 bytes
```
lambda h,w:"normal"if 18.5<=w/h/h<=25 else"uonvd"[25<w/h/h::2]+"erweight"
```
I rejected this as it was too similar to another answer I saw.
### 2. 71 bytes
```
lambda h,w:"normal"if 18.5<w/h/h<25 else"uonvd"[25<w/h/h::2]+"erweight"
```
I rejected this because, despite working on all the tests in the question, there are some numbers it can fail on as it's missing the `=` in the `<=`.
[Answer]
# C#, 63 62 61 bytes
*Saved 1 more byte thanks to [TheLethalCoder](https://codegolf.stackexchange.com/users/38550/thelethalcoder).*
*Saved 1 byte thanks to anonymous user.*
```
w=>h=>w/h/h<18.5?"Underweight":w/h/h<25?"Normal":"Overweight";
```
A pretty straightforward anonymous function. The whole trick is using the ternary operator to return directly (thus omitting the `return` keyword, a pair of curly braces and a variable declaration and assignment).
Full program with test cases:
```
using System;
class BodyMassIndex
{
static void Main()
{
Func<double, Func<double, string>> f =
w=>h=>w/h/h<18.5?"Underweight":w/h/h<25?"Normal":"Overweight";
// test cases:
Console.WriteLine(f(80)(1)); // "Overweight"
Console.WriteLine(f(80)(2)); // "Normal"
Console.WriteLine(f(80)(3)); // "Underweight"
Console.WriteLine(f(50)(1)); // "Overweight"
Console.WriteLine(f(50)(1.5)); // "Normal"
Console.WriteLine(f(50)(2)); // "Underweight"
}
}
```
[Answer]
# Common Lisp, ~~89~~ ~~87~~ ~~85~~ ~~84~~ 83 bytes
A function:
```
(lambda(w h)(if(< #1=(/ w(* h h))18.5)'underweight(if(< #1#25)'normal'overweight)))
```
### Example of usage:
```
((lambda(w h)(if(< #1=(/ w(* h h))18.5)'underweight(if(< #1#25)'normal'overweight)))150 2)
```
[Try it online!](https://tio.run/##NYtLCoAgEECvMuCimRaVQdCiDmNpKZiJWR7f3Lh9n92ax@eMPhgXEa24NikwgSY0By7A@Io9JGxBF0Z87iZqXidVSMqcOtaKjYW7O1zCNvdXLZVjGmAkyvkH "Common Lisp – Try It Online")
(I added printing function to see output in TIO)
Ideas for improvement are welcomed.
[Answer]
# MATL, ~~54~~ ~~45~~ ~~44~~ 42 bytes
```
U/E'%2'<sqt?q?'ov'}'und']'erweight'h}x17Y0
```
[Try it at matl.io](https://matl.io/?code=U%2FE%27%252%27%3Csqt%3Fq%3F%27ov%27%7D%27und%27%5D%27erweight%27h%7Dx17Y0&inputs=3%0A80&version=19.8.0)
Starts off by calculating the BMI and doubling it `U\E`, then creates the vector `[37 50]` with the string literal '%2'. Compares the BMI to this vector and uses if statements to get the answer, taking advantage of `normal` as a predefined literal `17Y0`.
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 25 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
²/¿}ȯE¿©S‘Ọḃẋɠ Ḳẇ ṁẓẋɠ‘Oi
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCMiUyRiVDMiVCRiU3RCVDOCVBRkUlQzIlQkYlQzIlQTlTJUUyJTgwJTk4JUUxJUJCJThDJUUxJUI4JTgzJUUxJUJBJThCJUM5JUEwJTIwJUUxJUI4JUIyJUUxJUJBJTg3JTIwJUUxJUI5JTgxJUUxJUJBJTkzJUUxJUJBJThCJUM5JUEwJUUyJTgwJTk4T2kmZm9vdGVyPSZpbnB1dD0xJTJDJTIwODAlMjAlM0QlM0UlMjAlMjAlMjAlMjJPdmVyd2VpZ2h0JTIyJTBBMiUyQyUyMDgwJTIwJTNEJTNFJTIwJTIwJTIwJTIyTm9ybWFsJTIyJTBBMyUyQyUyMDgwJTIwJTNEJTNFJTIwJTIwJTIwJTIyVW5kZXJ3ZWlnaHQlMjImZmxhZ3M9QyVFMSVCOSVBQw==)
#### Explanation
```
²/...©S...i # Implicit input
²/ # Divide the weight by the height squared
... # Compressed numeric list [18.5, 25]
© # Vectorised lesser than or equal to
S # Sum the list to get an integer from 0 to 2
# (0=overweight, 1=normal, 2=underweight)
...i # Index into compressed list of strings
# ["Overweight", "Normal", "Underweight"]
# Implicit output
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 57 bytes
```
{((,"Normal"),("Ov";"Und"),\:"erweight")3!("%2"%2)'x%y*y}
```
[Try it online!](https://ngn.codeberg.page/k#eJx1kN1LwzAUxd/vX5HdMpO40jVts3YZU1F8yIMKBd8COlhXBT9gk+kQ97cvJt2Xm5CXe87vnhzuRH0zFuLt+/R19II8ZHg3xwHev43tYBRW08/quX76QJ62GLYT+zj9ai9OFz8AXSjikAgyPCOE2MUN7PSk0Ztsp6WNZvO3MMh/UpweyV9nkyJ3kvdTrsd1Ra5Gs2qmADKxXd3FCBNFlJDLG80hSw7ind3r5R4A2TtCJFlUFH1PyHwL7DS3kIzSJiRPjzf2VaSn8uzgYM5vbOj31/5ekbzxRbw+y98a3jcAWokHfXGyZPo8pNg1BjllrUCrWD2OpvWcCPsN04OSqw5LhoGiPECXaKgGKBXroEE7lFzYcUnMJKIRpRh6YgVoZ4vc)
[Answer]
# Java 8, 61 bytes
```
w->h->w/h/h<18.5?"Underweight":w/h/h<25?"Normal":"Overweight"
```
Assign to a `DoubleFunction<DoubleFunction<String>>` and call thusly:
```
bmi.apply(50).apply(1.5)
```
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 64 bytes
```
[erweight][[Und]PszPq]su[[Normal]Pq]sn9k?d*/d18.5>ud25>n[Ov]PszP
```
[Try it online!](https://tio.run/nexus/dc#@x@dWlSempmeURIbHR2alxIbUFwVUBhbXBod7ZdflJuYEwvi5Vlm26do6acYWuiZ2pWmGJna5UX7l4HV/v9vYaBgyAUA "dc – TIO Nexus")
[Answer]
## Javascript (ES6), 63 bytes
```
(m,h)=>(w="erweight",b=m/h/h)<18.5?"Und"+w:b<25?"Normal":"Ov"+w
```
Example
```
f=(m,h)=>(w="erweight",b=m/h/h)<18.5?"Und"+w:b<25?"Normal":"Ov"+w
console.log(f(80, 1));
console.log(f(80, 2));
console.log(f(80, 3));
```
[Answer]
# PHP, 69 68/85 bytes
If you want it to be more as a program,
```
$a=$args;$b=$a[0]/($a[1]*$a[1]);echo$b>=18.5&&$b<25?normal:($b<18.5?und:ov).erweight; // 85
$b=$k/($h*$h);echo$b>=18.5&&$b<25?normal:($b<18.5?und:ov).erweight; // 68
$b=$k/pow($h,2);echo$b>=18.5&&$b<25?normal:($b<18.5?und:ov).erweight; // 69
```
You can test with `$k=80; $h=1;`. I had three choices, via `$args`, like this or as defined values (`K`&`H`). I choose the middle as most fair.
[Answer]
# Swift, 97 bytes
```
{(w:Float,h)->String in return 18.5<=w/h/h&&w/h/h<25 ?"normal":"\(w/h/h>25 ?"ov":"und")erweight"}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 46 bytes
```
/=V¬≤U<25¬©U¬®18¬Ω?`Nެµl`:¬∫U<19?`U˜`:"Ov")+`€¬≥ight
```
[Try it online!](https://tio.run/nexus/japt#AT8AwP//Lz1WwrJVPDI1wqlVwqgxOMK9P2BOwo7CtWxgOsK6VTwxOT9gVcKYYDoiT3YiKStgwoDCs2lnaHT//zUwLDI "Japt – TIO Nexus")
Inspired by @Luke's [answer](https://codegolf.stackexchange.com/a/109322/61613).
### Explanation
```
/=V²U<25©U¨18½?`N޵l`:ºU<19?`U˜`:"Ov")+`€³ight
```
Decompresses to :
```
U=U/V**2,U<25&&U>18.5?"Normal":(U<19?"Und":"Ov")+"erweight"
```
Japt has an implicit input `U`. The second input is `V`.
Japt uses the [shoco library](http://ed-von-schleck.github.io/shoco/) for string compression. Backticks are used to decompress strings.
Unicode shortcuts used:
```
² : **2
© : &&
¨ : >=
¬Ω : .5
º : ((
```
] |
[Question]
[
Given a string \$ x \$, we say another string \$ y \$ is half of it, if both of the following properties are true:
* \$ y \$ is a (not necessarily continuous) subsequence of \$ x \$ - there exists a strictly increasing sequence \$ a\_i \$ such that \$ y\_i = x\_{a\_i} \$
* Each character appears in \$ x \$ exactly twice as many times as it appears in \$ y \$
For example, "acb", "bac" and "bca" are all halves of "baccba", but "abc" and "ac" aren't.
Given a string with English a-z characters (you can choose if you want it lowercase or uppercase), which you are guaranteed all characters appear an even number of times in, output an arbitrary half of it.
# Test Cases
```
"aaaabbbb" -> "aabb"
"abab" -> "ab", "ba"
"aabbaa" -> "aab", "aba", "baa"
"aabbaaaa" -> "aaba", "abaa", "baaa"
"baccba" -> "acb", "bac", "bca", "cba"
"aabbcc" -> "abc"
"abcabc" -> "abc", "acb", "bac", "bca", "cab"
```
# Rules
* You can use any reasonable I/O format.
* You can print any half of it, or a list containing any non-empty subset of its halves, with or without duplicates.
* The distribution of the output can be whatever you want, as long as only valid outputs have a non-zero chance to be selected.
* [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed.
This is code golf, so the shortest answer wins.
[Answer]
# [Python](https://www.python.org) NumPy, 36 bytes
```
lambda s:s[sorted(s.argsort()[::2])]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3VXISc5NSEhWKrYqji_OLSlJTNIr1EovSQWwNzWgrK6NYzVioWr3M3AKgsEJeaW5BJVdBUWZeiUaaBpinVxQfHa2llJiUmJiclJyoFBurqQnRtWABhAYA)
Takes and returns arrays of characters.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 23 bytes
```
a=>a.filter(c=>a[c]^=1)
```
[Try it online!](https://tio.run/##jc@xCsMwDATQvZ@RJfZQQefg/khIQb7awcFYJQn9fUdroYOOGzQ8DrTxlw/s5XPem7xTz6FzeDLlUs@0O@g9Y3mFh@@QdkhNVGV12c1ENLAmaobF0yaluXH0frr9k5EtSteYrc4iIwPRuAhY/oD21/UL "JavaScript (Node.js) – Try It Online")
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 6 bytes
```
⊢/˜2|⊒
```
[Try it at BQN REPL](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oqiL8ucMnziipIKRsKoIOKfqCJhYWFhYmJiYiIsImFiYWIiLCJhYWJiYWEiLCJhYWJiYWFhYSIsImJhY2NiYSIsImFhYmJjYyIsImFiY2FiYyLin6k=)
BQN's "Occurrence count" (`⊒`) operator, which returns a number for each element indicating how many previous elements match it, is pretty useful here.
Select elements from the input (`⊢/˜`) specified by the occurrence count of each of them (`⊒`) modulo 2 (`2|`).
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 3 bytes
```
p~j
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv6Au6///aKVEIEgCAiUdpcSkRDAF5CcmwhlgZlJicnISTCw5Gaw4GYiUYgE "Brachylog – Try It Online")
(`jp` with reversed I/O appears not to work.)
Originally, I had `⊇.jp?∧` (which [can generate all halves, with an extreme volume of duplicates](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6OmpofbFqQ83NVZ@3DrhP8FdVl6ao@62v//j1ZKBIIkIFDSUUpMSgRTQH5iIpwBZiYlJicnwcSSk8GKk4FIKRYA)), but it turns out that [the order in which `p` tries permutations maximizes the length of the prefix of items which are not rearranged](https://tio.run/##SypKTM6ozMlPN/r/3/TR/GUF1eVKVgqleckZiXnpqSkKBUWpaZkVCvlpCkrl9o/apiQ@amoEUnVApTYPd3UqPupYYQCkax91Lf3/HwA). So:
```
p Permute the input such that
~j the output is a string which concatenated with itself is the input.
```
It appears that the output is guaranteed to be in a valid order because of this, but I'm not entirely sure--[relevant](https://www.swi-prolog.org/pldoc/doc/_SWI_/library/lists.pl?show=src#permutation/2) [source](https://www.swi-prolog.org/pldoc/doc/_SWI_/library/lists.pl?show=src#select/3) if anyone else wants to reason through it, or engineer a counterexample.
[Answer]
# [J](http://jsoftware.com/), 11 bytes
```
#~2|1#.]=]\
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/leuMagyV9WJtY2P@a3KlJmfkK6QpqCcmJiUlJqpD@GCeuoKuFUQGxAPyYXIImaREJNFEhAZko5ISk2ESQGZyEsKOpGRkHcnJ2CSSkkG8/wA "J – Try It Online")
* `#~` Filter by
* `2|1#.]=]\` Prefixes where the count of items that equal the last item is odd.
Just noticed this is the same approach as the BQN answer, though this one I arrived at independently after waking up today.
## port of loopy walt's answer, 14 bytes
```
{~[:/:~_2{.\/:
```
[Try it online!](https://tio.run/##bYsxCsJAEEX7nGKI4BpjZtVyMBAUrMTC1oDMDAZJkwNE9urrbrFsCosZ/vuPP/oSzQAtgYEd7IHCNQiXx@3qZ/ckS@51nLG35KvifkZYhbJG66jbbGvbnzC8NX6xKg9dW7z1M4FhFjHQEAwxRwqcXDbCi5bzQIQ5CWFNIkQVzgtdLlT/CdFI/gc "J – Try It Online")
Port of [loopy walt's excellent idea](https://codegolf.stackexchange.com/a/250225/15469).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
ṗṠ'ds?s=
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuZfhuaAnZHM/cz0iLCIiLCJiYWNjYmEiXQ==)
Tack on a `;U` if halves must be unique.
```
ṗṠ # Subsequences as strings
' # Filtered by
ds # It doubled, sorted
= # Equals...
?s # The input sorted
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
Φθ﹪№…θκι²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMMtM6cktUijUEfBNz@lNCdfwzm/FCjsXJmck@qckV8AksnW1FHIBGIjTU1N6///ExWSEvOAUCGJ679uWQ4A "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
Φ Filtered where
№ Count of
ι Current character in
θ Input string
… Truncated to length
κ Current index
﹪ ² Is odd
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ụm2Ṣị
```
**[Try it online!](https://tio.run/##y0rNyan8///h7iW5Rg93Lnq4u/v////JyYmJiUmJSUnJQDIxMRkA "Jelly – Try It Online")** Or see the [test suite](https://tio.run/##y0rNyan8///h7iW5Rg93Lnq4uxvI3nK4/VHTmsj//xOBIAkIuBKTEoEEkJ2YCKWAjKTE5OQkCD85GagkGYgA "Jelly – Try It Online").
### How?
Same idea [loopy walt had](https://codegolf.stackexchange.com/a/250225/53748).
```
Ụm2Ṣị - Link: list, X
Ụ - grade X up -> indices sorted by value
m2 - mod2 slice -> 1st, 3rd, 5th, etc.
Ṣ - sort
ị - index into X
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~34~~ ~~29~~ ~~26~~ ~~24~~ 23 bytes
```
Select[g@#*=-1&]
_g=1>0
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b7Pzg1JzW5JDrdQVnLVtdQLZYrPt3W0M7gf0BRZl5JtLKuXZqDc0ZiUWJySWpRsYNyrFpdcHJiXl01l1IiECQBgZIOkJ2UCKGBIomJCBaEnZSYnJwEF01OhuhIBiIlrtr/AA "Wolfram Language (Mathematica) – Try It Online")
Input and output a list of characters. Keeps every other occurrence of each letter, starting from the second.
```
_g=1>0 per-character indicator
Select[ ] keep in input where:
g@#*=-1& negate corresponding indicator
(-True is not truthy)
(all indicators receive an even # of negations,
so are reusable)
```
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 27 bytes
```
for$c(a..z){s/$c.*?\K$c//g}
```
[Try it online!](https://tio.run/##K0gtyjH9/z8tv0glWSNRT69Ks7pYXyVZT8s@xlslWV8/vfb//0QgSAICrsSkRCABZCcmciUlJicnJYJ5yclAmWQg@pdfUJKZn1f8X7cAAA "Perl 5 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) + `-lF -M5.10.0`, 20 bytes
```
say grep++${$_}%2,@F
```
[Try it online!](https://dom111.github.io/code-sandbox/#eyJsYW5nIjoid2VicGVybC01LjI4LjEiLCJjb2RlIjoic2F5IGdyZXArKyR7JF99JTIsQEYiLCJoZWFkZXIiOiIjIHRoaXMgaXMgbmVlZGVkIHRvIHJ1biBtdWx0aXBsZSB0ZXN0c1xuJHskX309MGZvciBhLi56OyIsImFyZ3MiOiItbEZcbi1NNS4xMC4wIiwiaW5wdXQiOiJhYWFhYmJiYlxuYWJhYlxuYWFiYmFhXG5iYWNjYmFcbmFhYmJjY1xuYWJjYWJjIn0=)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 5 bytes
```
⇧y_sİ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiZiIsIuKHp3lfc8SwIiwi4oiRIiwiYWFhYWJiYmJcbmFiYWJcbmFhYmJhYVxuYWFiYmFhYWFcbmJhY2NiYVxuYWFiYmNjXG5hYmNhYmNcbmFiYWFjYmNhIl0=)
Port of loopy walt's answer. I/O as list of chars.
```
⇧y_sİ
⇧ # Grade up
y_ # Every other item starting from the first
s # Sort
İ # Index into the input
```
`y_` (uninterleave, pop) could alternatively be `2Ḟ` (every 2nd item).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 34 bytes
```
(.)(?=(?(\1)((?<-3>)|()).|.)*$)\3
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wX0NPU8PeVsNeI8ZQU0PD3kbX2E6zRkNTU69GT1NLRTPGmOv//0QgSAICrsSkRCABZCcmciUlJicnJYJ5yclAmWQgAgA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
(.)(?=
```
Capture a character, then looking ahead...
```
(?(\1)
```
... if the initial character appears, then...
```
((?<-3>)|())
```
... unset `$3` if it's set, otherwise set it to the empty string...
```
.|.)*$)
```
... and check all the remaining characters in the string.
```
\3
```
If `$3` is set at this point (i.e. has been toggled an odd number of times), then...
```
```
... delete the character.
[Answer]
# [lin](https://github.com/molarmanful/lin), 40 bytes
```
.#n.n `pset"2rep.n \;.' eq"`#
.(""sort )
```
[Try it here!](https://replit.com/@molarmanful/try-lin) Outputs an iterator of subsequences.
For testing purposes (use `-i` flag if running locally):
```
"abcabc" ; `_
.#n.n `pset"2rep.n \;.' eq"`#
.(""sort )
```
## Explanation
Similar to @emanresu A's answer. Prettified code:
```
.#n .n `pset ( 2rep .n (.( ""sort )).' eq ) `#
```
* `.#n` input as *n*
* `.n `pset` powerset of *n*
* `(...) `#` filter each subsequence *s*...
+ `2rep` repeat *s*
+ `.n` push *n*
+ `(.( ""sort )).'` sort *s* and *n*
+ `eq` check if equal
[Answer]
# [Curry (PAKCS)](https://www.informatik.uni-kiel.de/%7Epakcs/), 28 bytes
```
f[]=[]
f(a:b++a:c)=a:f(b++c)
```
[Try it online!](https://tio.run/##Sy4tKqrULUjMTi7@/z8tOtY2OpYrTSPRKklbO9EqWdM20SpNA8hO1vyfm5iZp2CrkKaglJiYlJQIBEr/AQ "Curry (PAKCS) – Try It Online")
This may returns multiple results, with duplicates, but not necessarily all of them. If this is not allowed, you can add the flag `:set +first` to print only the first result: [Try it online!](https://tio.run/##DcZNCoAgEAbQfaeQVop0gQFPIi4@hyakH0Jt0eWbfKvHT63vcmPnpioxhZgmsaDsPYhdAIkdZ6cnymWCETMDOWOY9WM5sDWltnb1UmrrPw "Curry (PAKCS) – Try It Online").
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 7 bytes
```
q#.-QTy
```
[Try it online!](https://tio.run/##K6gsyfj/v1BZTzcwpPL/f6WkxOTkpEQlAA "Pyth – Try It Online")
Returns the half of the input which occurs last in the input, repeated for every time it appears as a subsequence of the input.
```
q#.-QTy
y subsequences of input
# filtered by
.-QT multiset difference with input
q equals the subsequence
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 bytes
```
®;©ṛ
Ç®ċ%2
ÇƇ
```
[Try it online!](https://tio.run/##y0rNyan8///QOutDKx/unM11uP3QuiPdqkZAxrH2/w93bznc/qhpTeT//4lAkAQEXIlJiUACyE5MhFJARlJicnIShJ@cDFSSDEQA "Jelly – Try It Online")
```
® (load register)
; (concatenate with [tacit argument, character we're filtering])
© (store result of previous link in register)
ṛ (return right argument [tacit argument, character we're filtering])
Ç (previous link as a monad, [v=character, new_v=character])
®ċ (count occurrences of [character] in register)
%2 (mod2 of [count])
Ç (previous link as monad, [v=character, new_v=1 or 0])
Ƈ (filter all items, keeping all that satisfy condition, [v=argument])
```
Filter each character, storing them in a growing list of previous seen characters. Every time you see a character for an odd numbered time, keep it.
[Answer]
# x86-64 machine code, 12 bytes
```
AC 84 C0 0F BB C2 77 01 AA 75 F5 C3
```
[Try it online!](https://tio.run/##fVLBctsgED2zX7FVxxMUyxnHTX2wq15y7qWnzsQ5IEA2GYQ0gFq5Hv963UWKk57KAMvuvn27LMiuW@ylvFxEaJDj94zD3d62lbBYQ@03zCsvnEKtBqg3zLYqVMCiDhGFLWgBq6JM7gK1GIC9CAzAQmwJFzbsxf0mIuZ1hDzDfAt6iNo7zB4zPP1sjcKay4PweOt16G0sULaOyCdbyLc4gfz/UWeAj8ZJ2yuNX0JUpr07fAUA4yI2wjiewwnYCDeu6@PT6vP6ucCJbVS2wH4djNXIgxSu5tksZMUEzrEs8T4HRhSs88SZ3Iv71TuColndeuQpocESl1sSH0p8IDmfU@wYzOge1xu8B/7DuU6UE2J0nVPGPqbC@c3O3SQj2a4BO/dNyINxmvqh9CZL7lTBkCoo8EiqavF0heNsufpBCY4l570LZu@0Gnt4m9f50zCfP1Mn8bUNx1T@cnj8lEjfGPjMYHWk9893jpgGcp7p89CoaICoBG10FuJV0KESUlaTLiVBJE0IWgdQrWohCk8TRNcJayFq0TQiaqAXliYYeuc/srZiHy6LZv1AG/3UkqrR9i8)
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes in RDI an address at which to place the result, as a null-terminated byte string; and the address of the input, as a null-terminated byte string, in RSI.
In assembly:
```
f: lodsb # Load a byte from the string into AL, advancing the pointer.
test al, al # Set flags based on that byte. In particular, ZF=1 iff it's 0.
btc edx, eax # Invert the bit in EDX indexed by the low 5 bits of that byte.
# Set CF to the previous value of that bit. Leave ZF unchanged.
ja s # Jump if CF and ZF are both 0.
stosb # (If CF=1 or ZF=1) Add the byte to the output, advancing the pointer.
s: jnz f # Jump back, to repeat, if ZF is 0.
ret # Return.
```
Because EDX is not initialised, this can keep either the odd instances or the even instances of each letter; either possibility is acceptable. In the TIO demonstration, a `RDRAND` instruction is added to show multiple possibilities.
[Answer]
# [R](https://www.r-project.org), 24 bytes
```
\(x,`+`=order)x[!++x%%2]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=PU5BCsIwELz3FwYKuzRePHnJS6zQTUyhEmzIRmj7FS_14B_8Sn9jTNBhYWZ2FnYez7Buir0bomphRuuAY8geZikEYnUdh1vKFvTE0cIizegcebYqxVWvXvfY74_vFibZNZ0aw8UGnE67ppnq-nAu8UZM3rsZDAhK0AlCCtKUKXmiv8hSkzH6tzMmH5s0AmULjN9W0ENpyphQHq1r4Q8)
[Answer]
# [Octave](https://www.gnu.org/software/octave/) / MATLAB, ~~31~~ 30 bytes
```
@(s)s(j^2.^sum(triu(s==s'))>0)
```
Anonymous function that inputs and outputs character vectors.
The code keeps each character that has appeared an even number of times so far.
[Try it online!](https://tio.run/##ZcwxCoAwDAXQ3Ys0XYK4VzxJIY0WKohiqtePmYTSz1/y@OTkSu@mOSCiLiBeYI8TRnkOqHd5QEIQ5/08el2LXJDBkSVZjIffErW3LYh6aS0Rc@pWzO1ntproBw)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ηε¤¢É}Ï
```
Outputs the first valid prefix.
[Try it online](https://tio.run/##yy9OTMpM/f//3PZzWw8tObTocGft4f7//5MSk5OTEgE) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXL/3Pbz209tOTQosOdtYf7/@v8j1ZKBIIkIFDSUUpMSgRTQH5iIpwBZiYlJicnwcSSk8GKk4FIKRYA).
Or alternatively (port of [*@emanresuA*'s Vyxal answer](https://codegolf.stackexchange.com/a/250215/52210)):
```
æʒº{I{Q
```
Outputs a list of all valid results, with duplicates.
[Try it online](https://tio.run/##yy9OTMpM/f//8LJTkw7tqvasDvz/PykxOTkpEQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf8PLzs16dCu6kPrqgP/1@r8j1ZKBIIkIFDSUUpMSgRTQH5iIpwBZiYlJicnwcSSk8GKk4FIKRYA).
**Explanation:**
```
η # Get all prefixes of the (implicit) input-string
ε } # Map each prefix to:
¤ # Push its last character (without popping)
¢ # Count how many times this character occurs
É # Check if the count is odd
Ï # Keep all characters of the (implicit) input-string at the truthy indices
# (after which this string is output implicitly)
æ # Get the powerset of the (implicit) input-string
ʒ # Filter it by:
º # Mirror it (to duplicate its characters)
{ # Sort its characters
Q # Check if it's equal to
I{ # The input-string with sorted characters as well
# (after which the filtered list is output implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~46~~ 45 bytes
*-1 Thanks to @Command Master*
```
f=lambda s:s and s[:s.count(s[0])%2]+f(s[1:])
```
[Try it online!](https://tio.run/##K6gsycjPM/7/P802JzE3KSVRodiqWCExL0WhONqqWC85vzSvRKM42iBWU9UoVjsNyDS0itX8X1CUCRRP01BKBIIkIFDS1ORCCCYlogkA1SQmYhFCE0xKTE5OwlSXnIxmfDIQAYX@AwA "Python 3 – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 25 bytes
```
^
,
+`,(.)(.*)\1
$1,$2
,
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP45Lh0s7QUdDT1NDT0szxpBLxVBHxQgo@P9/IhAkAQFXYlIikACyExO5khKTk5MSwbzkZKBMMhABAA "Retina 0.8.2 – Try It Online") (Test harness borrowed from [Neil's answer](https://codegolf.stackexchange.com/a/250221/16766).)
### Explanation
```
^
,
```
Insert a comma at the beginning of the string. (Any non-alphabetic delimiter will do.)
```
+`,(.)(.*)\1
$1,$2
```
Repeat until the regex no longer matches: Match the delimiter, the next character after it (group 1), any run of characters (group 2), and the character from group 1 again. Replace with the character from group 1, the delimiter, and group 2.
In effect: Comb through the string from left to right. On each iteration, move the first character to the output section, and delete another copy of that character from later in the string.
```
,
```
Remove the delimiter.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~70~~ 67 bytes
* Saved three bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat): using K&R-style argument type declaration and a neat `write.2` call to branch on printing a pointed-to character.
```
p[91];main(_,a)char**a;{for(++a;**a;++*a)write(1,*a,!(p[**a]^=1));}
```
[Try it online!](https://tio.run/##S9ZNT07@/78g2tIw1jo3MTNPI14nUTM5I7FISyvRujotv0hDWzvRGsTR1tZK1CwvyixJ1TDU0UrUUdQoiAaKx8bZGmpqWtf@///fMcrR0dHJyQUInZ1dXKIA "C (gcc) – Try It Online")
] |
[Question]
[
## Context
After attempting to program in [Grass](https://esolangs.org/wiki/Grass) for the entire morning, you decide to go outside and mow some *real* grass. The grass can be viewed as a string consisting exclusively of the following characters: `wWv`. `w` denotes tall grass which takes \$ 1 \$ unit of energy to mow. `W` denotes *extremely* tall grass which takes \$ 2 \$ units of energy to mow. Lastly `v` denotes short grass which does not need to be mowed.
## Task
You decide to mow the grass from left to right *(beginning to the end of the string)*. However, every time you encouter a `v` *(short grass)*, you stop to take a break to replenish your energy, before carrying on with the mowing. Your task is to calculate the maximum amount of energy expended while mowing. In other words, find the maximum total energy of mowing a patch of grass, that of which does not contain `v`.
### Example
In the example input below, the answer is \$ 8 \$. Although the patch `wwwwwww` is a longer patch of grass, it only costs \$ 7 \$ units of energy, whereas the optimal patch `WWWW` expends \$ 2 \times 4 = 8 \$ units of energy.
```
Input: WwwvWWWWvvwwwwwwwvWwWw
Output: 8
```
Here is an example Python program -> [Try It Online!](https://tio.run/##hY6xDsIgFEX39xV3o8Zq1NGkbn4Do2kiVZIWG0Be/fr6oDo4eROWcy4Xxle8P9xhnq@mQ1eF1ZFw820IaBC2YextrFRSK8IwCdoRuofHDdYtNanjvIhibDGZCl432MN2ApsGihVMHwwOIsvY0E7VMNU4y7o38emd8JnvtjfYy0T@g2/5Yt34jJWURm9dRKihNidVl@/OmjlpSUq8JGnWTEyaMqEsKVFaIizpcor45Hv1N38reVXefQM).
## Test Cases
```
WwwvWWWWvvwwwwwwwvWwWw -> 8
w -> 1
W -> 2
vwww -> 3
vWWW -> 6
v -> 0
vvvvvvv -> 0
vwvWvwvWv -> 2
vWWWWWWWWWWvwwwwwwwwwwwwwwwwwwwwwv -> 21
vWWWWWWWWWWvwwwwwwwwwwwwwwwwwwwv -> 20
vvWvv -> 2
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins!
[Answer]
# [Python 2](https://docs.python.org/2/), 49 bytes
```
lambda s:len(max(s.replace("W","ww").split('v')))
```
[Try it online!](https://tio.run/##hY3BasMwDIbvfgrhS21Iw5rBGIX0NXzZxVsTZnAcIxl7ffrMirPBTvtB6Jf0SYqP9LmGYZvHt83b5f1uga5@CmqxX4p6nKK3H5OSRnayFKl7it4ldconrfXmlrhiAnqQmFcE78IELnDdU7q7cBUA1IENBCMsNipKWCfoYrfDxzV5vkmtK9tAF5KqjhtYy1ntNmLtA3aA41inmyklm6qcS1M2xRQ43@BV7OkiDKdBMMDuWfACuxeROT2J3HQU9cQex5r51c@Lv2rc5T@wYfzLtE/DNw "Python 2 – Try It Online")
Here's how it works:
1. Replace each `W` with `ww`
2. Split on `v`'s to produce chunks of consecutive `w`'s
3. Take the `max` to get the longest one
4. Get its length
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), ~~55 46~~ 44 bytes
*Thanks @xnor for saving 2 bytes!*
*Thanks @dingledooper for saving 2 bytes!*
```
lambda s,t=0:max((t:=c%2*t+c%5%3)for c in s)
```
[Try it online!](https://tio.run/##hY3RasMwDEXf/RXCEHC2prQNGyGQ/oYftj2kaUMNiWNszVkI@fbMirvBnnbBSL46ujIT3gedF8aubfW@dnV/udbgdlgdyr7@EgLLqklOT/jcJC9JnraDhQaUBpeuqjeDRXCTY2R3St@2yeT2Dq9KlwxCEtTaQQV9bYRDGyZWmd0G753pFAqenXmaBjaCSqMIHRn0vUx4cyLE8E9ss4KTb4Pfig0xlviWz26B7AyzXeBtDvOK0pYPnq5yHL0M8n6M8nKUI8EF28qRSSonRgB1OaMF6l6Zp3JgPurxCRHbe6zJX/2c@KvIHf8DI0a3ZLx0@gY "Python 3.8 (pre-release) – Try It Online")
A function that takes in a byte string, and returns the max energy.
---
Cool trick with `eval`.
## [Python 2](https://docs.python.org/2/), 61 bytes
```
lambda s:max(eval("+".join(s+"v").replace("v","0,")))
w=1;W=2
```
[Try it online!](https://tio.run/##hY3BbsMgDIbvPIXFiag0ajJpmlrR1@CyC1sTjYkQZBCsT5@Z0E3aab@E/P/msx3u6WP14zar182Z5e1mIJ4X8yWmbJzgB95/rtaLeOCZdz1OwZn3SVCQ/CR513WsqOGi1bjZJayYIN4jm1cEZ/0E1tfcx3Sz/swAogTjIyhYTBAxIf2gDXKH@xicTYIfr7SW2AZanwS52kCKs9htQOoDSkCl6HfTpWRNyrk0ZV10geMVXtheBqZrGVkFqntidaC6Z5ZrObHc9Ai0Yn@PMf2rnxN/1bjhP7Bh9ZZul8Zv "Python 2 – Try It Online")
Transforms the given string by adding `+` between characters, then replaces `v` with comma (e.g `wWvW -> w+W+0,W`).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O’%3ṣ0§Ṁ
```
**[Try it online!](https://tio.run/##y0rNyan8/9//UcNMVeOHOxcbHFr@cGfD////w8vLy8KBoKysHALKwsvDywE "Jelly – Try It Online")**
### How?
```
O’%3ṣ0§Ṁ - Link: list of characters e.g. "wwwvWvwWww"
O - ordinals [119,119,119,118,87,118,119,87,119,119]
’ - decremented [118,118,118,117,86,117,118,86,118,118]
%3 - modulo three [1,1,1,0,2,0,1,2,1,1]
ṣ0 - split at zeros [[1,1,1],[2],[1,2,1,1]]
§ - sums [3,2,5]
Ṁ - maximum 5
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 50 bytes
```
s=>Math.max(...Buffer(s).map(c=>e+=c%5%3||-e,e=0))
```
[Try it online!](https://tio.run/##ldFND4IgGAfwe5/CubnBStRarQseunfm7Ax6mYkTgw5@d4OcbSor@m9cGD/2vNwymYm8vlZNWPIT7RjuBE6PWXNB9@wJEEKHB2O0BgLqiwrkOKVLnAfbYNO2IV1RHEPY5bwUvKCo4GfAgE@UkkRHStVHEkWUD6E3ShR5@8WEzl9Zo2kypcSZrqfU1OmgNd3MqO7Tje5m1LngeEb7/PrASvU23uc7to6JfDJsdpz@T0OTP@1QjbGWbol0GJax3Qs "JavaScript (Node.js) – Try It Online")
Or **42 bytes** if we can take a Buffer (or an array of ASCII codes) as input:
```
s=>Math.max(...s.map(c=>e+=c%5%3||-e,e=0))
```
[Try it online!](https://tio.run/##ndJNC4MgHAbw@z5FBIGyZbXY2MUOu@/sWZruhZZRTXfouzdbWxBkyR4QPMiPv4/eqaRVWt6K2s/FmbUctxVOTrS@ogd9AYRQpTcFSHHC1jj1dl7cND7bMBxC2KYir0TGUCYugIPjk3NWApcoJYmOlKqPJIooF0LojBIEzmE1TUycnowmIgNB7Imtgejmt1E0EZsI3YMlsTcR9hcJTUSfRWiO0K/4WQvIXJ1kyO9njPO1OyL6zxim6wxzG0TalNoZ7Rs "JavaScript (Node.js) – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~19~~ ~~18~~ 13 bytes
**Solution:**
```
|/+/'3!5!"v"\
```
[Try it online!](https://tio.run/##y9bNz/7/v0ZfW1/dWNFUUalMKUYpvLy8LBwIysrKIaAsvDy8XOn/fwA "K (oK) – Try It Online")
**Explanation:**
Might be further golfable...
```
|/+/'3!5!"v"\ / the solution
"v"\ / split on "v"
5! / modulo 5 (turns "vwW" into 3 4 2)
3! / modulo 3 (turns 3 4 2 into 0 1 2)
+/' / sum (+/) each (')
|/ / take maximum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
I⌈E⪪Sv⁺Lι№ιW
```
[Try it online!](https://tio.run/##JYyxCoRADER/5dgqgn7BlVYHCoJF6kUODazrotnEv4/h7hUzDDPMssVzOWIym07KDH28GMZ401539wJzScTwyaXyzD5ZoWlfQYLrlOoFwzevvAF57o/qD@Q1hubH2wxVBR0R/SOoqNZJegA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Input string
⪪ v Split on literal `v`
E Map over chunks
ι Current chunk
№ W Count of literal `W`
⁺ Plus
Lι Length of current chunk
⌈ Maximum
I Cast to string for implicit print
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 6+ for Windows, 48 bytes
port of [math junkie's](https://codegolf.stackexchange.com/a/204443/80745) answer for Retina.
```
$args-creplace'W','ww'-split'v'|% len*|sort -b 1
```
[Try it online!](https://tio.run/##jVDLCsIwELznKxZJTSstWAURQfAvcpRa1wcErUlNBNtvr9vEKt4cCMxkZnZhq6tDbU6oVMcPsIZnxwt9NFmpsVJFiUKKVDgnMlOpcy2saCJQeJk05qpryHaQdy1jm5ilsZDOWUmw1gVY6aQTKSyT3u5Z7hnNhJlnfZLEPAjqklgEQWwaWMBX01z/vlPkB8PqX/ho/k/WJ4e90r53JNBABE8GBH7UhTEpcHxUWNa4p6vxbbA0mruq6WNMxwxBb4x4/PYyvH2KyWpojFjbvQA "PowerShell – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~19~~ 17 bytes
-2 bytes thanks to @Neil!
```
W
ww
S_`v
O^`
\Gw
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wP5yrvJwrOD6hjMs/LoErxr38///w8vKycCAoKyuHgLLw8vByrnKucC6QCBdIkquMqwwCgGJl4WAMloACmFZUQFAJyFSgvQA "Retina 0.8.2 – Try It Online")
Replaces `W` with `ww`, splits at `v`, sorts by length, then counts the `w`'s in the largest chunk.
[Answer]
# [J](http://jsoftware.com/), 26 21 bytes
```
[:>./0+/;.1@,3|2+3&u:
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/o63s9PQNtPWt9QwddIxrjLSN1Uqt/mtypSZn5CtYKNgqpCmoh5eXl4UDQVlZOQSUhZeHl6tD1BhC1MC4RlAtUK4xhAvSCBUxg4oAzYOKGEBF0LgQgGpsGdBqMIYJGyJMgwKYG1EBXIMBURrQrQXaWKb@HwA "J – Try It Online")
* `3&u:` Change input to unicode int values
* `3|2+` Add 2 and then mod 3: Now `v` becomes 0, `w` becomes 1, and `W` 2.
* `0...,` Prepend 0
* `+/;.1` Split by first element (0) and sum the elements of each split chunk
* `[:>./` Take the max
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 21 bytes
```
(((⌈/+/¨)×⊆⊢)'vwW'∘⍳)
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/zU0NB71dOhr6x9aoXl4@qOutkddizTVy8rD1R91zHjUu1kTpBaokqA69bJwOCgrxwbK1P8DAA) Assumes IO is 0.
**How it works**:
* we convert `v`, `w` and `W` into `0, 1, 2` respectively;
* we split on 0s;
* we sum each run of non-zeroes;
* and find the max of those.
[Answer]
# [Haskell](https://www.haskell.org/), 51 45 bytes
-6 bytes thanks to [Ad Hoc Garf Hunter](https://codegolf.stackexchange.com/users/56656/ad-hoc-garf-hunter)! Unfortunately all the grass-like operators were already taken :(
```
g=maximum.scanl(#)0
x#'w'=x+1
x#'W'=x+2
x#_=0
```
[Try it online!](https://tio.run/##hY3BDoIwEETv@xUbMUFCMOjZ@gXcjOnRNNoAkRZDoeXv67ZoIicnaTOdtztthHnKrvO@ZkrMrZrU3tyF7nZJVsKcpC5lc34Ijgd3JHdjpa/leDVyqFotDTJ89ICkjp54KpBoIDF7TeNlHCqN2wXnOW6wONNFzjS9w10dSRbHf4sBlGh1rF/lnjtnOclat8hyxx044BASCBAs2EWUWR5PBB99V9f6OxJa6d83 "Haskell – Try It Online")
**Explanation**
`scanl` is basically a "running total", where for each element of a list, it applies a function to the element and an accumulator, and saves the accumulator at each step. So `scanl (+) 0 [1,2,3]` gives `[0,1,3,6]`. We're giving it the function `(#)` which we've defined to add `1` to the accumulator if the element of the list is `'w'`, add `2` to the accumulator if it's `'W'` or set the accumulator to `0` if it's anything else (`'v'`). Then we just get the maximum number of the new list, which will be the largest sum we managed to accumulate.
Cool idea I couldn't get to work:
`mapping = zip "vwW" [(*0),(+1),(+2)]`
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 9 bytes
```
C‹3%0€v∑G
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=C%E2%80%B93%250%E2%82%ACv%E2%88%91G&inputs=WwwvWWWWvvwwwwwwwwvWwWw&header=&footer=)
Port of the Jelly answer. Update: Bug has been fixed.
```
C # To array of charcodes
‹ # Decremented
3% # Mod 3
0€ # Split on 0s
v∑ # Map to sum
G # Maximum
```
## Other approach, 10 bytes
```
\W₀V\v/vLG
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%5CW%E2%82%80V%5Cv%2FvLG&inputs=WwwvWWWWvvwwwwwwwwvWwWw&header=&footer=)
```
V # Replace...
\W # 'W'
V # With...
₀ # 10 (arbitrary 2-byte value)
/ # Split on...
\v # 'v'
v # Map each to...
L # Length
G # Maximum
```
-2 from this thx to @DLosc.
[Answer]
# [Perl 5](https://www.perl.org/) with `-p0166 -l -MList::Util+max` , 22 bytes
```
$\=max$\,y///c+y/W//}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxjY3sUIlRqdSX18/WbtSP1xfv7b6///w8vKycCAoKyuHgLLw8vDyf/kFJZn5ecX/dQsMDM3MFHRz/uv6@mQWl1hZhZZk5mgDjQIA "Perl 5 – Try It Online")
### Explanation
`-p` reads `STDIN` into `$_` breaking on each `$\`, `-0166` sets `$\` to `v` and `-l` strips `$\` from the end of each `$_` and enables automatically printing `$\` when printing the output.
This stores the larger of `$\` (initialised to `v` which is `0` when compared numerically) or `y///c` (which 'replaces' the empty set of characters with the empty set of characters for every character in the string, returning the `c`ount) added to the number of `W` in the string.
Since `$\` is globally scoped, storing it here lasts for each iteration of the script the `}{` breaks out of the `while (<STDIN>) {` loop that `-p` inserts and terminates it so that instead of the current value of `$_` being printed alongside `$\`, `$_` is empty and only `$\` is printed.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~69~~ \$\cdots\$ ~~62~~ 60 bytes
Saved 5 bytes thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!!!
Saved ~~2~~ 4 btes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)!!!
```
e;m;f(char*g){for(e=m=0;*g;m=m>e?m:e)e=*g%2*e+*g++%5%3;e=m;}
```
[Try it online!](https://tio.run/##jVBNa8MwDL3nVwiDwU5caFJWxjx3P8OHpYeSOp4PzooTkkHIb8/kfBR220NCtqT3EK862KqaZyO9rFn1dQup5WP9HZhRXh1laqVX/mI@/JvhRqWWFqnJUptl9IWeJC7JafY31zAOYwKIRQM603bt5xUUjEQPQ68RfT@s6PWgByJITI0Z@7HgTiwxVyyzXi@5LWzYpf7iH0urOt5CJrnc65oOzM9jvfVVQC6gEHAScBZwXAK/RezG50aKBkWiQ4vAvee5hCxzuwW7bEDJmq1WuCuXz@Ej4LhmpCS0LQkcLkDvwOidlw0RsBMEBAyl4nVP@pRMyfwL "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
Port of the Jelly answer.
```
Ç<3%0¡Oà
```
[Try it online!](https://tio.run/##yy9OTMpM/f//cLuNsarBoYX@hxf8/x9eXl4WDgRlZeUQUBZeHl4OAA "05AB1E – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-naFv`, 35 bytes
`-naFv` enables input on STDIN with auto-split on `v` into the `$F` global array.
```
p$F.map{|w|w.gsub(?W){11}.size}.max
```
[Try it online!](https://tio.run/##KypNqvz/v0DFTS83saC6prymXC@9uDRJwz5cs9rQsFavOLMqtRYoV/H/f3h5eVk4EJSVlUNAWXh5eDlXOVc4F0iECyTJVcZVBgFAsbJwMAZLQAFMKyogqARkKtDef/kFJZn5ecX/dfMS3coA "Ruby – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ṣ”v<”w‘§Ṁ
```
[Try it online!](https://tio.run/##y0rNyan8///hzsWPGuaW2QCJ8kcNMw4tf7iz4f///@Hl5WXhQFBWVg4BZeHl4eUA "Jelly – Try It Online")
# Explanation
```
ṣ”v<”w‘§Ṁ Main Link
ṣ”v Split on "v"
<”w Check if less than "w" ("w" = 0, "W" = 1)
‘ Add one to every element
§ Sum every sublist
Ṁ Find the maximum
```
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~85~~ ~~82~~ 69 bytes
```
{FS="v";gsub("W","ww");for(;i<NF;){s=length($++i);m=m>s?m:s;}print m}
```
[Try it online!](https://tio.run/##JcG9DkAwEADgV5GLoQ1P4JTNaDHcTOKnoYhyN4hnL4nva2UO4a4aAww4@qtTQJCCCGgctkOhzesK9e3N0q/jOak4SaxGZ1zhS5d5fPbDrmfknhBIhOnDLD8mIXkB "AWK – Try It Online")
Thanks to [@dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) for cutting off 13 bytes.
The code could be even less, **62 bytes** accounting for the field separator flag being a parameter and not part of the actual code.
pretty straightforward: change all `W` into `w`, get lenght of words, `v` counts as field separator. Retain max score with ternary operator.
[Answer]
# [Java (JDK)](http://jdk.java.net/), 62 bytes
```
s->{int m=0,n=0;for(var c:s)m=(n=c%2*n+c%5%3)>m?n:m;return m;}
```
[Try it online!](https://tio.run/##hU89a8MwEN3zK46AwU4aE1q62LVLKBQ6dErBQ8igKnEq15KMdJYwwb9dlR13CIX0wSHu3sfpKmLIqjp8O8YbqRAq38ctsjpepLM/s7IVFJkUA0lrojW8EybgPANo2s@aUdBI0D9GsgNwz4VbVEycdnsg6qSjUQrwId8Evk5hT/SLqN0@hxIycHqVn5lA4Nn6TmTrtJQqNEQBTXTEs1BkNLhfiCUNHoOHKOfPIuGpOmKrBPC0d@mY700wuvzS5GozwLbTeOSxbDFu/NewFuEcYA7LQRelN1T5qCpj0jR1t9H@hNBbYpQv/oCNUqQLo@hWwsT1s6F65wprTeFhjL3AFLawzrrCDRM3kM44c4GfmWKskZjwa73Gv5Ih1e/9AQ "Java (JDK) – Try It Online")
After finishing it, it seems to be a port of [Noodle9's C answer](https://codegolf.stackexchange.com/users/9481/noodle9).
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 69 bytes
```
Func<string,int>g=s=>s.Replace("W","ww").Split('v').Max(x=>x.Length);
```
[Try it online!](https://tio.run/##JYxBCsMgEAD/4iUKqR9o9VLoKb20B89BFrsgm5C1rr83QuY8M5FvkbH315/ig8uBlGak4pNj59l@YM9rBK2CmpWIMva7Zyx6qpOx77Xp5nyzC1AqP3Pvz414y2DDgQUWJNBppCI1DGqVixokjNXwTw "C# (Visual C# Interactive Compiler) – Try It Online")
Heavy inspiration from [@xnor](https://codegolf.stackexchange.com/a/204449/87760)
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 28 bytes
```
sed 's,W,ww,g;y/v/\n/'|wc -L
```
Input from stdin, output to stdout
There might be a better way.
[Try it online!](https://tio.run/##S0oszvifpqGpUP2/ODVFQb1YJ1ynvFwn3bpSv0w/Jk9fvaY8WUHX538tF1dqcka@glJ4eXlZOBCUlZVDQFl4eXi5kkKNQtp/AA "Bash – Try It Online")
[Answer]
# Mathematica, 53 bytes
```
Max[#~(s=StringCount)~"W"+#~s~_&@StringSplit[#,"v"]]&
```
More readable, un-golfed code:
```
Max[StringCount[#,"W"]+StringCount[#,_]&[StringSplit[#,"v"]]]&
```
`StringSplit[#,"v"]` takes a string and turns it into a list of strings, seperated by 'v', then add together the length of the string, and the count of 'W's, and take the max value.
[Answer]
# [Crystal](https://crystal-lang.org/), 57 bytes
```
def f(a);a.split('v').max_of {|s|s.count('W')+s.size};end
```
[Try it online!](https://tio.run/##rZPBTgMhEIbv@xQTLtuNWeJqYkz6IBwbZGcryRa2DAtW67Ov1KoJjResf8JlMv/H8APKHcjLcVl6HGBYyWYtOU2j9qs61A3fyZeNHeDtSEfiys4m1UXd3BAn/YrvazT94nA/a4fAaELFqqpHUk4/pcLORm22GzTotgcGva0AtAc2SSIkkErh5KVRCB7JQ/fVAmkQJmIMIimEeFYQUUTWcHq289gD7uEx9aYBCqC5vyv2i8x/V@w/nSVD3JcjUiYZ4qEckflvy/1nXUtJN/q5rs1U/Oj7qeS62KD77x0u@H/JU4TfUzh9r6VtjW2VHa37AA "Crystal – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 70 bytes
Comprehensive approach.
```
lambda n:max([sum([2if i=="W"else 1for i in x])for x in n.split('v')])
```
[Try it online!](https://tio.run/##NcqxDsIgEIDh3ae4sMAtJnY04TkYageMJV4CV1KQw6dHG@M/fcOf3/W58TSCvY3o0/3hga/JdzOXVzLzRAHIWuXUGssKl7DtQEAMfcHD/TCfS45UjW4aFxx5J64mGOVEmvvWmvxqTpwoxNN/0aIRxwc "Python 2 – Try It Online")
[Answer]
# [Rust](https://www.rust-lang.org/), 67 bytes
Port of [xnor's answer](https://codegolf.stackexchange.com/a/204449/95013)
```
|s:&str|s.replace("W","ww").split('v').map(str::len).max().unwrap()
```
[Try it online!](https://tio.run/##hU/LbsMgELzzFZSDA5LrDyBKf6IHLpUityEWKsYIMLRy/O3u2vjRnjoSCHZnZmdd78N0N7itlaEMDwgDtAy4wZfp4Xnhg3v4ykmr6w9JiSAlSYmwylutAj3FE6va2lKgca6lmX9flFW9SQ7KbDpnx66zq/k2oO0DVsbCfcGvwSnTcG5kouy803y4ca46zuExx4MY9e2qlZG02OXHrEOo7rlXKX@VrQ3f@2ob3sHq8xCMh3SNlPX73m@GlJiQXzMsRA7aPFEyjPj5BQ8jMBZViRta5Gwrf0TjJFKKAhBjyogiiYQSEmiuoLmJIooZUItiOUtjxSb9i38psyvM/QE "Rust – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 14 bytes
```
π├♦.8Σ0└ó?∟X≈Æ
```
[Try it online!](https://tio.run/##ASQA2/9zdGF4///PgOKUnOKZpi44zqMw4pSUw7M/4oifWOKJiMOG//8 "Stax – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 13 bytes
```
MX#*YaR'Wt^'v
```
[Try it online!](https://tio.run/##K8gs@F@drldcq1f93zdCWSsyMUg9vCROvex/rYKvQvr/8PLysnAgKCsrh4Cy8PLwcq5yrnAukAgXSJKrjKsMAoBiZeFgDJaAAphWVEBQCchUoL3/dYtycDgDAA "Pip – Try It Online")
### Explanation
```
a First command-line argument
R'W Replace all occurrences of W
t with 10 (arbitrary value--the important thing is, it's two characters)
^'v Split on occurrences of v
Y Yank (to enforce precedence)
#* Replace each string in the list with its length
MX Take the maximum
```
[Answer]
# Excel, 101 bytes
```
=MAX(LEN(SUBSTITUTE(FILTERXML("<a><b>x"&SUBSTITUTE(A1,"v","</b><b>x")&"</b></a>","//b"),"W","ww"))-1)
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnDnePjbAK85_20_N?e=t637DY)
* `"<a><b>x"&SUBSTITUTE(A1,"v","</b><b>x")&"</b></a>"` converts text to
XML containing "x" + the "wW" strings. The additional "x" prevents
errors.
* `FILTERXML(~,"//b")` converts XML to a vertical array.
* `SUBSTITUTE(~,"W","ww")` change "W" to "ww".
* `LEN(~)-1` counts the "w"; minus 1 for the leading "x".
* `MAX(~)` return the largest one.
] |
[Question]
[
ùñßello all, I hope this finds you well.
There are 118 elements on the Periodic table at the moment, each one corresponds to the number of protons in an atom's nuclei.
Each element also has a 'symbol'. Hydrogen has 'H', Helium has 'He' and so on. I want to know about these!
### Challenge:
Given 1 string as input, output `true` if the string is present as a symbol on the periodic table. Output `false` if not.
The string is case sensitive. While `He` is a valid symbol, `he` is not.
For reference, here are the elements that are valid symbols for this challenge (from [wikipedia](https://en.wikipedia.org/wiki/File:Colour_18-col_PT_with_labels.png)):
[](https://i.stack.imgur.com/VTwhl.png)
That is, if the string is any one of the elements in this list, output 'true':
```
Ac,Ag,Al,Am,Ar,As,At,Au,Ba,B,Be,Bh,Bi,Bk,Br,Ca,Cd,C,Ce,Cf,Cl,Cn,Cm,Co,Cr,Cs,Cu,Ds,Db,Dy,Er,Es,Eu,Fm,Fl,F,Fe,Fr,Ga,Gd,Ge,H,He,Hg,Hf,Ho,Hs,I,In,Ir,K,Kr,La,Li,Lr,Lv,Lu,Md,Mg,Mn,Mt,Mo,Mc,N,Na,Nb,Nd,Ne,Ni,Nh,No,Np,O,Og,Os,Pb,P,Pa,Pd,Po,Pr,Pm,Pt,Pu,Ra,Rb,Re,Rf,Rg,Rh,Rn,Ru,S,Sb,Sc,Sm,Sg,Se,Si,Sn,Sr,Ta,Tb,Tc,Te,Th,Ts,Tl,Ti,Tm,W,U,V,Xe,Y,Yb,Zn,Zr
```
And, Alphabetically indexed:
```
Ac,Ag,Al,Am,Ar,As,At,Au,
B,Be,Ba,Bh,Bi,Bk,Br,
C,Ca,Cd,Ce,Cf,Cl,Cn,Cm,Co,Cr,Cs,Cu,
Db,Ds,Dy,
Er,Es,Eu,
F,Fe,Fm,Fl,Fr,
Ga,Gd,Ge,
H,He,Hg,Hf,Ho,Hs,
I,In,Ir,
K,Kr,
La,Li,Lr,Lu,Lv,
Mc,Md,Mg,Mn,Mo,Mt,
N,Na,Nb,Nd,Ne,Ni,Nh,No,Np,
O,Og,Os,
P,Pa,Pb,Pd,Pm,Po,Pr,Pt,Pu,
Ra,Rb,Re,Rf,Rg,Rh,Rn,Ru,
S,Sb,Sc,Se,Sg,Si,Sn,Sm,Sr,
Ta,Tb,Tc,Te,Th,Ti,Tm,Tl,Ts,
U,
V,
W,
Xe,
Y,Yb,
Zn,Zr
```
This is a classic code golf, so be sure to reduce the number of bytes you use in any way possible.
Good luck~!
[Answer]
# [Factor](https://factorcode.org) + `periodic-table`, ~~22~~ 17 bytes
```
[ elements key? ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70sLTG5JL9owU3z0GBPP3crhYLUosz8lMxk3ZLEpJxUhYKi1JKSyoKizLwShezUorzUHIXE4uL85GIFay4upYhUpaWlJWm6FhujFVJzUnNT80qKgcoq7RViIeLLkhNzchT0IJwFCyA0AA)
Factor has a built in periodic table (with all 118 elements and no typos; I checked :D).
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~197~~ 195 bytes
```
^([HNOUVWY]|[CGLP]a|[DNPRSTY]b|[AMST]c|[CMNP][do]|Gd|[BCFGHNRSTX]e|[CHR]f|[AHMORS]g|[BNRT][ah]|[BLNST]i|Bk|[ACFT][lm]|Pm|Sm|[CIMRSZ]n|Ho|Np|[AELZ]r|[BCFIKPS]r?|[ACDEHOT]s|[AMP]t|[ACELPR]u|Lv|Dy)$
```
[Try it online!](https://tio.run/##HY7ZCsIwFETf@x0K@hViFxsxTUNS1zBi6462lbqAcP@93vo658wwzfF1rfK2P4h37XbghErni@Ua5IJYauTkQqWNzdYoyI0Tm2HPKFEa7lCD4gM5P5jEQrGzwpGZMDixKpLUWJwZK5PB5Ree9KXigSv5NxaCCcf3EqRLsiUXp4mxG1QkalIPFiK5QfOfn860RTPqSmEk0gzP7ovGq0siqQ3eJD8Ufoe9tg1yzxRe6qkf "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Grouping by last letter is slightly shorter than grouping by first letter. I also saved three bytes by handling Cd, Co, Md, Mo, Nd, No, Pd and Po together, Ba, Bh, Na, Nh, Ra, Rh, Ta and Th together, and Al, Am, Cl, Cm, Fl, Fm, Tl and Tm together. (Grouping by last letter didn't seem to offer the same opportunities.) Edit: Saved 2 bytes thanks to @DidierL by grouping B, Br, C, Cr, F, Fr, I, Ir, K, Kr, P, Pr, S and Sr together.
Edit: Added Be, which @JonathanAllen pointed out was missing from the table in the question.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 186 bytes
Returns `0` or `1`.
```
s=>parseInt("2cjns/5ogz/1r4hf/kafb8/1pszk/5vs1/1e/by01/5ywx//5m9t/3wh6q/nj4o/24hj/b8n5/21x5j//19b6u/65rh/bini/1/1/1/w/5/5yww".split`/`[([a,b,c]=Buffer(s),a-65)]||0,36)>>b&!(c|b<97|b>122)
```
[Try it online!](https://tio.run/##bcxPT8IwHMbxu@/CHUibDH50rJMlbol68uDFk4aQ0JZ2f5jtbAeDZe99gkdtntsneb41OzEnbNV2c232clLZ5LK8ZdbJV92hIBK1dkBNMQCxcangwBRfA2ndcAB6cgSIBH5ZEqCX/gxAv9IOVn2ZfIOuYwNRXNbA15pCRM60BiApT46QUFsCr3QF5Hc90FugDxaubapuB7sN2rCQh2KbPR@VkhY5HLJ5QvF2HJfhKsF5zmf3SIz8MX0YeU6iCE/CaGcauWhMgRQKmA0wvvuDT@8@tINHX4QHP272/@@7Mw@@Fb6m9ODn1aYf "JavaScript (Node.js) – Try It Online")
[All truthy inputs](https://tio.run/##LZFLbtpQAEXnXQVlUEA6yYtJTJOqUNkOBBRwLNv9JFGk@Bn/CNjED4ckYgmVOumw3UfXkw10CZRW1ZWOrnSlOzmz4CFQYZktV3t5MY22cXerur1lUKpolK@a9XY4y5XQi@RZaOVRGou7IJbHQluq5zuhPyhNaJGQTwea0J/Wj0Loi5OVOFynnXuRz44K0T5KZ0Ie57poa4/6TAjtRHYq0dHLVMgsz4T2L2uh/z1Y1/fVcp6tbsXtdfM6QBLedM0qjqOyqVoEex29dbPZHHDYafV68s3rZriR70/ebmRPa7db27oRYiQYc4wFRomhMFYYFWaAiRlhppgZ5h1miRVgTbGwIqwYa46VYy2wCqzdqLAqThWnktMn@iV9Rb9isGAwZ8AgYlByFnA25SxiyHCHhGHMsGCoGDHKGZWcc14yDhhnjHflgXHFZMokYZIzWTEpmITY2AG2xJ5iR9gZdopdYC@54CLhQuFIHJwAZ4pT4JQ4C5wVToUb4ErcCDfGTXBT3By3wsOTeCHeAi/Bi/AyvByvxA/wJX6IH@Gn@Ap/jp/hL/jMRz7xJeKSS8lVzlX5X0mzTr31aj8uyn4Qpk1V6/ZqYZGrYh7tz4ukqajFO0e1D7XG71/fXn5837FRe1drvPz82mi1tn8A) / [Random falsy inputs](https://tio.run/##ZVJbbttGFP3XKib6qMn6hCPSphrHkQKStizDFk2ITNLEcJvhmzI5VGZIK06VHRToTz/bfXQ92UCX4I6MfAQNBnPnnnsuDg7u3BW7YzIR1bp7yts0e8gnD3IyXTMhs3PeaUMrWXFJ7bb4RE1xWOb0luXxM2qu5adbat9Jk5oZje9HJrXvNx8ptZujjh5syvEHyleHLbUOyxWNn3GbWuZHe0WpeRSPezq2RUnjilfUfDwbau8ENkNDruuqe0/fX2vXDDGSm4nb53kmNKmDPR3b@s12O8LBWJ9O4x@eaMk2fnH00zaempalPyQtlx1xyIQMnQROAaeG08ARcCScDk4Pl8GFm8Et4VZwb@EKeAxeCg9eBi@HV8Pj8Bp4LTxFSng9TiROYpzc41TgVOK0x6zBrMYMswwzgTOGsxRnGeaYq1BgnmPeYi5xjnOOc4ELXAhcMlxWuFTJHS57LFIsCiw4Fh0WLRYJfPgMfgw/hZ/Br@CX8Fv4a1zhqsCVRBAjQMAQpAhaBAJBg6BD0GPJsIyxzLDMsSywLLHkWPYIEcYIE4QNwgJhhrBCyBEKRAxRjChBlCEqEUlENaIKUYM3eIXX@DnDW7yN8Y7jnfj6OdoQQ/14MKizjrhq1Nc3CuSt0HYFrgqjY/W8IOZol@zv6@S3ASE7Uh6rJG0fMSFStYadqHhh5KJtvJIJT62gZhjGtbqOEOxeW7CuNATjadtouhIdGSZ5SUzynHzPHCnGUsyBfmM0bK1pvxJUOplM/9f7I7HGZJ@MbfILObAU1CryRNlW8HtRS9f1ne3PZFNWdaY5RsWTuk8zqTaSbLfE/bbw2Ooa616WCh0PPg9cQ43mlCUK75zsNrStM6NuC02C5DuRl2Tv33/@@PLXnyruKf97X/7@fU/XH/4D)
### Commented
```
s => // s = input string
parseInt( // parse as base-36:
"2cjns/5ogz/.../5yww" // lookup string
.split`/` // turned into an array
[( //
[a, b, c] = // a, b, c = ASCII codes of the first
Buffer(s), // three characters in s
a - 65 // use a - 65 as the lookup index
)] || 0, // force to 0 if there's no entry
36 //
) >> b & // right-shift by b positions (mod 32)
!( // test the least significant bit
c | // make sure that s has either 1 or 2 chars.
b < 97 | b > 122 // and that the 2nd one (if present) is a
) // lowercase letter
```
[Answer]
# Wolfram Language (Mathematica), 50 bytes
```
#~ElementData~"Abbreviation"&~Array~118~MemberQ~#&
```
Uses the inevitable builtin. Don't try it online, since it requires access to Mathematica's data repository that TIO doesn't have :( On the plus side, all of the nested argument precedences worked out so that the `~` syntax could be used without brackets.
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), ~~98.5~~ 97.5 bytes (195 nibbles)
*Edit: -2 nibbles by changing the encoding*
```
?+! |_\$u .`/~`=`D-28\$N |+$\$! ~.@:@\$a $ 1e0ffdd0810caa7a28e383c93c330770433251ee362b67eb4b57b2c6f2899d4742d379353a3791767afb7dd86bbf684e52506db285eb7e59af343e632802eec0bde3135659c1618936c003d96bbca
```
[Attempt This Online!](https://ato.pxeger.com/run?1=LY9BSkMxEECvkn6yK22TmSQzEcQKrr2AEX8mmYAgbvTvSi_iphsRPIlX8DYW7OrBg7d4H1-vzyIv-nY6fS7vY8O_PzfrlTk8FbuY7bw7ztfz3Qa42HtzWNtiV-a43V_ti63GGq9ujN4de9dqpQqsyNgyNkRH5AIiRK-KCSSRSpBIAi0N4Jx7oAAdKWPEeoanRHUI9c5JZCQOGiG61AU4qpDGXAcG1ITADlSbk67oMaaYm0-eM6bmHPZ87lv9_7lsfT9MZbpdyjQ9Xswf)
Similar 'build the element symbols using the lists of second letters for each first letter' approach to [Neil's Charcoal answer](https://codegolf.stackexchange.com/a/264726/95126).
**How?** (original 98.5-byte version):
```
?++! `%`D-26"j" |@\$u ~.$%:_$~ $
! # zip together
`D-26 # the hex data 243d...
# decoded using base 26 to " abc...y"
`% "j" # and split on the letter "j"
# with
|@\$u # uppercase letters
# (printable ASCII filtered for uppercase)
~ # by
.$ # mapping over each group of lowercase letters
:_$ # appending each to the uppercase letter
% ~ # and removing spaces
++ # flatten to a list of element-strings
? $ # and find the index of the input
# (or zero if not found)
```
[Answer]
# [R](https://www.r-project.org/) >=4.1, ~~235 232 224 221~~ 220 bytes
We build all valid element names by "overloading" the `/` operator with the function `strsplit`, then unpacking the string of single-character names. We unpack another string with all capital letters except J and Q, then paste them to the unpacked second characters of the two-character names.
I am sure it's very golfable because I am bad at this.
*edit: realized I can remove `UVW` from singletons.*
*edit2: -8 bytes due to Giuseppe tricks*
*edit3: `mapply` can be drop-in replaced with its simplified wrapper `Map`, thanks again Giuseppe*
*edit4: another -1 byte from Giuseppe indexing trick*
```
\(x,`/`=strsplit)x%in%unlist(c('BCFHIKNOPSY'/'',Map(paste0,LETTERS[-17][-10],el('cglmrstu,eahikr,adeflnmorsu,bsy,rsu,emlr,ade,egfos,nr,r,airuv,cdgnot,abdeihop,gs,abdmortu,abefghnu,bceginmr,abcehimls,,,,e,b,nr'/',')/'')))
```
[Attempt this Online](https://ato.pxeger.com/run?1=bZPdbpswGIYPdpariCJVgOSs3dF2sB4sNIQsgTDs_aRbtQIxPyp_wqZqrmUnaaVdy65h0y5m9oumSRMcPCHYfr7X5uPbY3d6Si-_9zKdv_r5-4v5QG7Pby-F7ERbFtJ6OCvqs74uCyHNxDQWtuOuN_4uoHvj3DCIF7VmGwnJL8h2ydgypJ_nL17eKFzcEF6aRpKVVSdkT3iUF3cdiQ48Leuq6URPYnEk-pdXJQYIz9JGkLoj6m_R9fckOWR1I0kUH3iRNy3JhL5Xq5Uwinma5bXSJDwr6kqtUXd5UZWCqIuTWJlUSGJYKqllWcMefz37IbmQX0VfSD59PZ8m5mwxI9OZreFouBprjY2Gr7HTCDSoxnuNDwqT6X_X7KMe2mu8ScAMLMEK7EABSrDXXPBR4SLCYA4W4B0IjY1R-wByMAVR0K5HlTZy2A04aJDGRo6rGMSTq6PmEnOWeLLsR5UOajsQO6jtYNEK-VbIt8IcdyCOxUVWtxlVuqi3rkHINuAWyi2OYjs8Qe7tvaaXjMo8JPBQ1YPSw_Y9vAAfSh8b9zHTR0ofRfx8VOlD4LfoD4h3SBxAFkAWQBbgWALMD5A4kKPKABsJIQghCJEjxDmFKBKiE0LsIcR8Go_KKPqPQkCxlGI7FEspMlGkYSjIUJBhFRvvRYbaDBoGAcO7Ztj4J5TaQ3M93nnXQ-9jhgYapWlwMs-xGrfvNN7OrMmkK7kporYtj-a_75ZM07_f8-k0_P4B)
[Answer]
# [Ruby](https://www.ruby-lang.org/), 158 bytes
```
->s{i=[*?B..?Z,*'Aa'..'Zr'].index(s)||2;",:wyp;S_F&?{}?z_o?sqo}]}wo?sg~<?2>~w}SZ|CooOj9Q_o?;"[i/7].ord[i%7]<1}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=TZLLbtNQFEXFNBNmSDDBCgK31aoRnRRoU8t2m6Zq4hjbPJoqquzYSQx-BN-Y0ibp_RAkVCH4CD4FvgarBYk9OGdrn8mR1v7yvazCi-tv49aPaj7efP7r6-aeWCSt0w3d1DR9wIZqBKqmqYNSHWpJHsWf18T6crm10-TBvZfnF7Md70y27z7RpVyspH559rDQhZTyY7GScihvtTqvw8nVrr61dyXP5cqTg2UdP7SKov_-hXx1_0z-p0JK_cbsNE-Tp9tDrSij0-Tx9nD32er2y993fsZpnAmlpajGCGOCkWJkGCWGwJhjVJgBJmaMOcVMMD9gllgBVoSFFWONsVKsHCvDKrDqo8Cq2Bfsh-xfcFByIDioaGe0U9q0Y9olhwGHEYcxHTr1mNAZ0ynoCI44yjkqOea4pBvQTejW5hPdil5Eb0IvpzenV9AbYWMH2CF2hB1jJ9hT7AJ7Rp_-hL7ACXFwApwIp8ApcTKcOU6FG-CGuDHuGHeCO8XNcSs8vBBvhJfhTfBivAQvxyvxA_wQf4Qf40_xBX6Kn-BnvOU1b3gXc8JJyCCnJq2JWZrM11TU9UZj7V8DLtV1LQtmykJZimVDUcogEbHSbAdJGkfKo4VYNZUqT2MhlPGpGCqtlnJDqa7NKK2iWK-b0_hL8Pr6dv8B)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 99 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
¬ª·πò·∫ã·∏Ñ√¶√òo·πñ√üYp‚Äô…≤¬ª13BkAd√óJ‚ÄúU·∫π√êƒã·∏∑·πòt∆ÅM∆ì·∫†√á|hu·πó¬Ω√±{…ì[·πá·∫ä¬ß ?bx‚Ǩ≈ªcb0·∏≥√ü∆ù·∏Ñ∆§ƒ∞·ªµ·πÅ√ócj"D¬≥¬ø≈í_…º·ª¥ƒ±R9?√±‚Äô√û@YX¬ß1O√ßG¬¶ Ç≈ª‚ÄúZ‚ǨJw∆á
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMiVCQiVFMSVCOSU5OCVFMSVCQSU4QiVFMSVCOCU4NCVDMyVBNiVDMyU5OG8lRTElQjklOTYlQzMlOUZZcCVFMiU4MCU5OSVDOSVCMiVDMiVCQjEzQmtBZCVDMyU5N0olRTIlODAlOUNVJUUxJUJBJUI5JUMzJTkwJUM0JThCJUUxJUI4JUI3JUUxJUI5JTk4dCVDNiU4MU0lQzYlOTMlRTElQkElQTAlQzMlODclN0NodSVFMSVCOSU5NyVDMiVCRCVDMyVCMSU3QiVDOSU5MyU1QiVFMSVCOSU4NyVFMSVCQSU4QSVDMiVBNyUyMCUzRmJ4JUUyJTgyJUFDJUM1JUJCY2IwJUUxJUI4JUIzJUMzJTlGJUM2JTlEJUUxJUI4JTg0JUM2JUE0JUM0JUIwJUUxJUJCJUI1JUUxJUI5JTgxJUMzJTk3Y2olMjJEJUMyJUIzJUMyJUJGJUM1JTkyXyVDOSVCQyVFMSVCQiVCNCVDNCVCMVI5JTNGJUMzJUIxJUUyJTgwJTk5JUMzJTlFJTQwWVglQzIlQTcxTyVDMyVBN0clQzIlQTYlQ0ElODIlQzUlQkIlRTIlODAlOUNaJUUyJTgyJUFDSnclQzYlODcmZm9vdGVyPSZpbnB1dD1CZSZmbGFncz0=)
Inspired by Neil's Charcoal answer.
#### Explanation
The idea is to construct the first and second letter strings separately, and then zip them together. We can sort the first letters in alphabetical order, and then multiply the alphabet with a list of numbers to get the whole string. There are 8 `A`s, 7 `B`s, 12 `C`s, etc. So, we use the list `[8, 7, 12, ...]`. Then, we use base-255 compression to get the string of second letters, replacing it with a space where the symbol is only one letter, then after zipping we can remove the whitespace. Finally, after we've constructed the list, we can check if it contains the input.
```
»...»13BkAd×J“...“Z€JwƇ # Implicit input
»...»13B # Compressed list [8,7,12,3,3,5,3,6,3,0,2,5,6,9,3,9,0,8,9,9,1,1,1,1,2,2]
kAd×J   # Multiply elementwise with the uppercase alphabet - the first letters
“...“ # Compressed string of second letters, or spaces where N/A
Z€J # Zip with the first letters and join each pair into a string
w # Remove whitespace (the space fillers in the second letters)
Ƈ # Is the input in this list?
# Implicit output
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~ 222 219 ~~ 212 bytes
-3 thanks to [bsoelch](https://codegolf.stackexchange.com/users/118682/bsoelch)! (Avoiding `enumerate`.)
-7 thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor)! (Use the direct functional reference `[...].count`.)
```
[chr(i+65)+r[r>'y':]for i in range(26)for r in'cglmrstu,zaehikr,zadeflnmorsu,bsy,rsu,zelmr,ade,zefgos,znr,,zr,airuv,cdgnot,zabdehiop,zgs,zabdmortu,,abefghnu,zbcegimnr,abcehilms,z,z,z,e,zb,nr'.split(',')[i]].count
```
(Beryllium is included at a cost of 1 byte)
**[Try it online!](https://tio.run/##HYzNisMwDIRfJTfbVPSwZXtYaKHPkeYQO/4RTeQgOwvxy6dq0WFGI8237jVluhzh9jx6l1jj6fprTtzzXe3qbwiZO@yQOh4pev1zNZ9EMlIuzguXukEbfcIXi04@zLRkLhvYssNHm5cvkIu4EHOBRgzQJELe/sFNkXKVqp0EkldosXw3oQgaRiutRMKxzkdcpDyKSzgv8vcdIVsgVueyzli1AmV6HIazyxvVY2WkqoNWj6iMOd4 "Python 3 – Try It Online")** Or see the [test-suite](https://tio.run/##bZJJb9swEIXv@RWqL7KRDzm0aA4BWkCW49hNrKiSumQ7aKEkIhJlkFIAO@hvdykjORQoCbwZzvLwyOF219ed@nQovzweHvJaT@Xp@efZqX7QX92de/FUdtqRjlSOTlUlph/PZ2PExpSbV02rTT@wT0Utn7W1hSgb1XbaDGRmx2j3wlZhM9Yrq86wVxr2NiT18EJeVKrrbWtWWJJuy74yx5NlsdSkme2qleXJclHJ1jan1qtl09q647bMGUq7Z2bbyH7q4s4e5NPTWd4Nqj@MckUjWqH68RoTL8er8Bq8Fk/jGbweb2CeMmcumNfMJfNn5ho/xS/w8QV@id/gK/wWv8O3SYM/sDAsMhY7LjWXhsuBZcuyYclSsNRcpVwVXAlWrCxUrEpWHSvDmrVirbnmWnOTciO5sc4LNwObgk3FRrHp2XRscgKClCAjKAgEgSSoCTqCLbfcVtwawoyQMCUsCDtCTdgS9oQDUUqUEQmikqgiqokU0UBMnBHnxC1xRSyIJbEi1iQpSUaSkwiSmsSQNCSSpOUXP/jJb8Eddxn3ins9eXv5CZPZxYljV2qM0L1TTt9efoZTTpapbETh9J0jCxuT5c55fct/0H9sj5Oq91FNTk7GwfXCHKc2dV0c91GN6IywGOHbCN9H8LIj5sL9V4D9WlbEyHJUsFZ5p7XI@2b3rkFaRa9jwf8kbLVU9lpe0xyVGGc78haT2eEv "Python 3 – Try It Online").
Beatable with a hashing approach or even regex? (Edit or golfing [bsoelch](https://codegolf.stackexchange.com/a/264716/53748)'s ...until they golfed mine! ;p)
[Answer]
# [Python](https://www.python.org), 210 bytes
*-10 bytes, thanks to Jonathan Allan*
*-11 bytes, thanks to xnor*
```
lambda s:s in{*"BCFHIKNOPSUVWY"}or"A"<s<"["<s[1:]in[*"cglmrstu,aehikr,adeflnmorsu,bsy,rsu,emlr,ade,egfos,nr,,r,airuv,cdgnot,abdeihop,gs,badormtu,,abefghnu,bcmgeinr,abcehslim,,,,e,b,nr".split(",")[ord(s[0])-65]]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dZPRbpswFIYvdpensLhKuj9TU2nTFDWTgDRN14QgoO2SNBcGDFgFE9kQLar6JLupNG0PtLvtaeak7Vo2jQsff_7t38fG58v39bbKSnH_NRlcf6urpPv-54-cFmFMieorwsXtgWHZo_HZuTNz_YvLq7lxV0rDNI7VsbHU7bLXX3GxPDCiNC-kqmpQlvEbCRqzJBdFKVWNUG2xi6zI9wJYmpQKQgKauaw3iOJUlBVoGDOelWukCiGNS1loRz3KkjQT2igqUsb1OhpGLFM5L6A_hlB7GW_UOudV24DRWZYybqvl4arTffd2tXo42a9XVyxnBROVGhhmBDOFmcMsYEqYCmYFs4ZFYcFisDJYHNYNLAmbwo5hw2awE9g5bAG7gF3C1qKCXWOoMAwx3OJE4kThpMaowCjHCCOGkcQpxWmMU4YxxrpJMU4wLjFWOMOZwJnEOc4lJhQTjonubDCpMY0xTTEVmFaYlphGcOBQOCGcGA6Dw-FkcEo4a8wwSzFTcEO4cCncGG4JV8It4FZwa3gUXgiPwUvgpfAyeAJeDR9-CD-CX8BP4TP4HL6ALxFQBCGCCAFDkCFQCHIEHEGBK1zgEp8Y5piHWAgsGj-g1VpLLqp20tY3bXQ6zzhmDbRkA826gcNtAyebBs4btHjhZHS7XeOF1tyjSVEzoWGDPjYoaCZrNU-22FErKSWJerpyiKQiZe3Dz0nS6bcI2QtHz0K3hz8aIWoQZbId9Tqv9_GoQ3iip38YHBKWK0Ye1f1crehaIbvyJE8vmlARk6StHu0IeUzLSOhu-bpUvOIb1ifXxq26u9Y38mT1r83O_P9WgqX0L6uH-rq_f4i_AQ)
## Explanation
First check for one character element names.
If the name has two characters check if the first is between `A` and `[` (one after `Z`) in lexicographical order.
Then check if the second character is a second character of an element name starting with the first character
# [Python](https://www.python.org), 362 bytes
the naive approach
```
lambda s:s in"Ac,Ag,Al,Am,Ar,As,At,Au,Ba,B,Bh,Bi,Bk,Br,Ca,Cd,C,Ce,Cf,Cl,Cn,Cm,Co,Cr,Cs,Cu,Ds,Db,Dy,Er,Es,Eu,Fm,Fl,F,Fe,Fr,Ga,Gd,Ge,H,He,Hg,Hf,Ho,Hs,I,In,Ir,K,Kr,La,Li,Lr,Lv,Lu,Md,Mg,Mn,Mt,Mo,Mc,N,Na,Nb,Nd,Ne,Ni,Nh,No,Np,O,Og,Os,Pb,P,Pa,Pd,Po,Pr,Pm,Pt,Pu,Ra,Rb,Re,Rf,Rg,Rh,Rn,Ru,S,Sb,Sc,Sm,Sg,Se,Si,Sn,Sr,Ta,Tb,Tc,Te,Th,Ts,Tl,Ti,Tm,W,U,V,Xe,Y,Yb,Zn,Zr".split(",")
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VdDNqtNQEMBx3PoUl6xa-OtaBBcnp01TbpKGnOPVW9ycNJ-aj3JOcqFrH8NNQfSd9GksFIRsZubHDMMwP36fL1MzDtef1Ycvv-apevPu76uvnenzwjy49-6hHTxxQtSIDtEjLMIhJsSMb_DxG_wW_xu-RRpkgUSWyArZIQdkjxyRt6ZDzmwcm5zNha1l69jOBD1BR0BQElh2hl3BriQkvIWasCIcCR179gN7yyOPlsgQtUS34oVoJi6Ia-KBeCIeiU8kJIYkJylISpKWpCEZSc4cONQcHGlOSmpIC9KR1JL2pBPpTGbIcrKSrCKryRqygWxGoXLUCdWjalSJalEDyqINOkef0CW6QTt0h27RPZ_4yBOfS555zjkOHK331p27dlp5eOv7y_98P9t2mFbVygtLb71-_Z--XVDMC24uC0Yvy-Hl7EJ6ufd40_2U6_We_wE)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 100 bytes
```
•ÍøλMI;ÌL₂<ý¤•13вAuS×J.•∊×FéÛÍ@ƶ
‚Äú¬¨E|*[√≥AR{≈ì‚ÇÑ√ù√ë√¢W í$^C√ì%$m√öL‚ÄÀú√á√•√∞H%,YŒµ∆íBJ!¬ß¬ΩPŒ£v íR√æKŒ±‚ÇÇ‚ÇÅ√¢nŒîNŒ∏5¬®√ì‚Ä¢√∏‚Ǩ√°I√•
```
[Try it online!](https://tio.run/##AbMATP9vc2FiaWX//@KAosONw7jOu01JO8OMTOKCgjzDvcKk4oCiMTPQskF1U8OXSi7igKLiiIrDl0bDqcObw41AxrYK4oCcwqxFfCpbw7NBUnvFk@KChMOdw5HDolfKkiReQ8OTJSRtw5pM4oCUzrvLnMOHw6XDsEglLFnOtcaSQkohwqfCvVDOo3bKklLDvkvOseKCguKCgcOibs6UTs64NcKow5PigKLDuOKCrMOhScOl//9CZQ "05AB1E – Try It Online")
Same as my Thunno 2 answer.
*-1 thanks to @KevinCruijssen*
#### Explanation
```
•...•13вAuS×J.•...•ø€áIå # Implicit input
•...•13в # Compressed list [8,7,12,3,3,5,3,6,3,0,2,5,6,9,3,9,0,8,9,9,1,1,1,1,2,2]
AuS√óJ # Multiply elementwise with the uppercase alphabet - the first letters
.•...• # Compressed string of second letters, or spaces where N/A
√∏ # Zip with the first letters and join each pair into a string
ۇ # Remove whitespace (the space fillers in the second letters)
Iå # Is the input in this list?
# Implicit output
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 120 bytes
```
№⁻E”|«↓‹℅Zy⊗⌈↗⁷◧⟦π@0\`‽◧~H≕' t?¹6´↗T?ⅉς6σ”⁺ι§”&⌊↧\`rfV~⍘ROB;ü⌈ê↙⌕Xhk~& №E⪪DTN¿O-·⁶‹6n×⊟3✳∧Ap|λXⅉω⪫¦⁻⊟»lC↓×;!"B⊘ⅈêα⊗◨·²”κjS
```
[Try it online!](https://tio.run/##TdDJboMwEAbgV0GcQKJP0FMSKEUJBTXpktwMOMYTL8hLlD69O6RB6nf4NR7Zo5H7kZheExFCa7hyyUZ7zJorb5OaTEm8elj/2fyT53lRFC@zsixf76qq2m53s/rubdE0Tbt4f9gvDouPz6/v4/F0irOoFbgCz6KVq9RAb0ncMyGNdZ7QkcPFkIGeQUiljfWd/cGkeJzb9MxAW1AGDOHGX/uBKe1IN8wP9cTAYg1SG5zV4eVR@a6njINUhmA1ciEtANAOZ@AmlzRNsyiGGLNSk3d7h3/FEmw/h7Cm4ekqfgE "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for an element, nothing if not. Explanation:
```
‚Ññ Count of
S Input string in
”...” Compressed string of first characters
E Map over characters
ι Current character
⁺ Concatenated with
”...” Compressed string of second characters
§ Indexed by
κ Current index
⁻ j Remove all `j`s from all strings
Implicitly print
```
The string of two-characters elements is 151 bytes compressed. I tried uppercasing the string which reduces it to only 127 bytes, with the decoding logic resulting in a 155 byte solution, but then I hit on the idea of compressing the first and last characters separately. I then saved a final two bytes by compressing the single-element names with a trailing `j` which I then remove afterwards.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~207 190~~ 192 bytes
```
->n{k=!j=8
"&$&%$%&$$&%$$% '($($$$3'&$%\*6&$$)$$$&$%44)@$%7\*$(6&$G$$+'B'k6+,&$4$&*$(4$%$&$)$>/5$%,%&%$W$&$$$)\*4$%%%'$'6$$%&$&$)\xA5DS'".bytes{|i|k||=n==(j+=i>9?i-35:338).to_s(36).capitalize}
k}
```
[Try it online!](https://tio.run/##PY1La8JQEIXXza9oL2fuI9F0cZP4gButFLrswkWhrRQtEa4RFY2gNf72OAp2Nd85c@bMdj87NnPXtPPVqXRPC9cNhIQkkMR1gB6UhgZglQSFGduGFXOSmCGoE0Kz@QZEaqTKLGpJJJDsJiCOGeTPKahFXPbBms9D3hApqAzXN5z5Prykr2Ml4tmxKnan2tdlXbuVc3oROZ/3Br5t0761XRNX65@dtpmJf6cbX02X/q84B@W52TzOv8S7mAQ3GN9hVNzpc/1PWzFpLg "Ruby – Try It Online")
For some reason, `TIO.run` pastes the `&` characters as `&` in the output formatted for this website, but the code at `TIO.run` shows them as a single character.
Produces all valid elements by incrementing `j` according to each term in the magic string and converting the result to a base 36 number. The increment of `j` is based on `ASCII CODE - 35` to avoid having `"` or `#` in the string.
Single-letter elements are first in this order, and there is a big jump of 338 from `Y` to `Ac` which requires special handling as it won't fit in a single byte. The jump is encoded as a `TAB=ASCII 9`.
2 bytes added to make it work with `Be` and `S`
[Answer]
# [Python](https://www.python.org), 271 bytes
```
import re
re.findall("[A-Z][a-z]?","AcAgAlAmArAsAtAuBaBBhBiBkBrCaCdCCeCfClCnCmCoCrCsCuDsDbDyErEsEuFmFlFFeFrGaGdGeHHeHgHfHoHsIInIrKKrLaLiLrLvLuMdMgMnMtMoMcNNaNbNdNeNiNhNoNpOOgOsPbPPaPdPoPrPmPtPuRaRbReRfRgRhRnRuSSbScSmSgSeSiSnSrTaTbTcTeThTsTlTiTmWUVXeYYbZnZr").__contains__
```
[ATO](https://ato.pxeger.com/run?1=NdHPS8MwFAdwPLqr_0DpxQ02zyKopNm6jrVZaOKPbYyRtkkbbJORpMIc-0u8eNH_Sf8areLl8x7fw3vw3uvHbu8qrd7e3lsnRpdfJ2ey2WnjPMN7wrv-KRdCqoLVdd9fg9Fqs2ajl82tP_RBDkpQgwYYYIEDbcCCoApk8BQYyGABIYcC1lDBBmpooIXt2I6z8X5iJnbShk1YhyEPzZRNiymPIh6VkYh0ZGczNTPzuYlZLGMTP8dtUiRlohKX6CRHiKEMFYgjiSqk0W6xKBcWZxgzXGCNDW6ww23K0izlqUjLtEpV2hKSkZw0pCScSKKIoYxmNKecVtTSmkraPNzdP_LlMluplfEHF9ttrpVjUtnt9u82nxuhjee4dZ5UXt8HrT_0_Eh0wl9nv0HHogN1rFTn0h9c9U53RirXF-eHbsjRG914B9Hv-sHxfPC35P8R3w)
[Answer]
# [PowerShell Core](https://github.com/PowerShell/PowerShell), 257 bytes
```
$args-cin("AcAgAlAmArAsAtAuBBaBeBhBiBkBrCCaCdCeCfClCnCmCoCrCsCuDbDsDyErEsEuFFeFmFlFrGaGdGeHHeHgHfHoHsIInIrKKrLaLiLrLuLvMcMdMgMnMoMtNNaNbNdNeNiNhNoNpOOgOsPbPPaPdPoPrPmPtPuRaRbReRfRgRhRnRuSSbScSmSgSeSiSnSrTaTbTcTeThTsTlTiTmUVWXeYYbZnZr"-csplit'([A-Z][a-z]?)')
```
[Try it online!](https://tio.run/##XZDtbptAEEV/w1MgCzW2FB4hqmFtjBXAK3ab1LasalmGjwRYuh9N29TP7pImcSr/nDP3npFmEE8gVQ1t63Eh4eSWN88nl8lKebzppxOf@5Xf@p0vfeVr3wQBCyCogyZ4DCRCDBUIUIla1KMOCSSRQmaRL9Ti11Iu1dKEIYRd2IZyxVbFCqIIoioqIxGp9bpfy9tbGbO4iWVs4h8JT4qkSvpEJDpNWZqnRQppk9apSIfNptoonGPMcIEFlrjDGpuMZXkGWZlVWZ31mSEkJ5x0pCJAGtITSRnNKadAa6poSxvafbm7/wrbbb7rd3LicTW0jb6a7n1vd9gz7/fh8@xqdjra9nxqW9fz8QNycu24WhqYvYLtxRzABWD/GiVr1TvpxQCX7O7@PzJz/jihkEvGa2@TPwDXzrNtuRqURkzBGISfw0ihcG4c99u4kqBMq8fpk1s656Bt7TFBRmnRvWoOznwUWcRwDkq9lM8iD747b5oxQUfDy/rDZGXvJ86po308/QU "PowerShell Core – Try It Online")
A naive approach, `cin` stands for `case sensitive in` and `csplit` for `case sensitive split`.
+2 bytes for Beryllium
[Answer]
# [Python](https://www.python.org), 210 bytes
```
lambda s:1/(s in{*"BCFHIKNOPSUVWY"}or"A"<s*(s[1]in"cglmrstu,aehikr,adeflnmorsu,bsy,rsu,emlr,ade,egfos,nr,,r,airuv,cdgnot,abdeihop,gs,badormtu,,abefghnu,bcmgeinr,abcehslim,,,,e,b,nr".split(",")[ord(s[::2])-65]))
```
Many thanks to [bsoelch](https://codegolf.stackexchange.com/users/118682/bsoelch)'s [python answer](https://codegolf.stackexchange.com/a/264716/46901)!
I refactored it so it returns `1.0` if the input is an element and raises an Exception if it isn't.
Interesting notes:
1. The `*` is used as a boolean AND.
2. `s[::2]` produces every second element, and `ord` raises an Exception if its argument is longer than one character. So, this expression filters out anything 3 chars or longer
[Attempt This Online!](https://ato.pxeger.com/run?1=dVTLbuM2FN105a8g1I2dHLdJgBaF0RSQlDjOxFYESzPTZBIUlHQpESNRBikFMQbzJd0EKNpv6Hd0135NKdtJ7I7Lhahz7oO8ukf31z8Wy6ao1dNv4vTu97YRwx_-_qvkVZJxZkbH3_YNk-rTgeP548nlVXAdRm_fvb9xPtfacZ0fzUHffDi-l8pJ87LSpmnBqZAfNXhGolRVrU2LxCzR7VSVKwMoF7WB0oDFUrcPSLNc1Q14kpEs6gVyg4Rnta5sRsuSyAtlE6VVTtLG8SSlwpSygl2ExOZyvjGLUjZ9B87gQ60ze7HR6OR-MPz-u_vBYF3ZP1_9SSVVpBpz6rgp3BxuCbeCq-EauA3cFh6HB4_gFfAkvI_wNHwOP4MPn-AL-CV8Bb-CX8O3RgO_xZnBWYKzJc41zg3OW4wrjEuMMSaMNS44LjJcECaY2EeOicCkxsTgEpcKlxpXuNKYckwlpvblAdMWswyzHDOFWYNZjVmKAAFHkCDIEBACiaBAUCNY4BrXOa4NwgQhQo4wQ1gj1AgrhA3CFnOOeYI5YS4wzzEvMFeYt4gQJYhSRBWiHBEhkogUIo2YI04Qp4gJcYHYIC4RS8QV3uMt3uFnwg1uEtwq3O70oNezCmDcGNLNL_SY0qKRteqbwajH7CKta00ZO2WxbmlFNXq5tnVLWM8X8Oo85qVZewupeFluRXy90FLZszfOI-awg5fIQ4tEre3zkG0lluLZ4zVPtzQ1rVav59tD_-PApSHmrqqzZZ13SfrCoccFpY0976XgEbtzPpnPd073RTY3HA6HFq2B6FshOoMtOKEd6Okd6LY78Gy5A6cPO_BmB91uZdrcofdFf7p7fkm6-9mU_ofP9_Jne9k3e9lY76W9dC9929XS9Tc9tuPKdkfl1D_C0aMQK72tTCd7TYyZ07TQ_fR4cLjaTwadLNKTn45WfWcbY2-jFzumWDcT2fMkeRbGHqk_x-z4M66yVRbx8jMwtmmSIzp9M0U5b-QDbYlnPcCentb7vw)
[Answer]
# [C (GCC)](https://gcc.gnu.org), ~~276~~ 274 bytes
*-2 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
f(x,s,i,j)char*x,*s;{s="-cglmrstu-@aehikr-@adeflmnorsu-bsy-rsu-@elmr-ade-@efgos-@nr--@r-airuv-cdgnot-@abdehiop-@gs-@abdmortu--abefghnu-@bcegimnr-abcehilms-@-@-@-e-@b-nr";i=*x++-64;j=*x?:64;*x=i&&i<27&63<j&j<123&*x*x[1]<1;for(;*x=*x*i>0;)i-=*s++==45;for(;*s-45;)*x|=j==*s++;}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VVTbTttAFFTVJ_uxX7CkauRLViJAKcVxGxoIoU2MZbs3KKocx042xHbkdZAp5UfaF174qX5NzxhohZIzPt6dmXN2td7ft9H3aRTd3NyuyoTv_HnyLNGqlmyJ1lyPZmFhVC1DWlfSbvBoukgLWa54N4xn4ryg5yROFmmWF3LFx_KS49mNicVphrJkmkvezQrOuzQkitUFjybTLC9JOp6QSb7k3ams39K8IGsejkk1y8hnHMVTkZI4pGwmFinx6h85j3lWNCxhG5Vp8u0ta07Z211KjMoWzabobLxqbm925s15p72x2TQqozptn3XaVpIXGkg0It6sW7rgtiFN07a3Xt7PSU6pblQ_7bldz1nX91vz9NdzWq_IYhazdntHfXjLmBYzk73WVRU7xowylmUUylieZmfMZleq0tiLGq3G3hSwAKSAAiABJWBF8C4EIGLADCAA5wAIemD0JgAEaL0EAN9eBoB5LwfUAlTowXwf2f4YcElwgNkDjB1gtg9ZHy59BIz7YByi4CEKHmJsgKgTrGaA0gPUGsDoCIEejqD8gEAyhMUQ6xjWrxcA1BzBdgSjEVQj7MMIbiPsl4OA1EHPDrgOKjtwcrA3DrjOkuAYAaNj9OFC4CIgd6F0QXVR3sVCXZRy0YMHigeBB3MPK_Lg5KGCh7488HwEaD5682Hig-ZD5aMlH1wfJQJ4BiAHIAegBLAL0F2ATQ6gCODymeIjxSeKL2B-RUB8AsMTMqQTNMxJxRqLuwcijGrsAfdq_AF4X8OcRNeWqqahyDQdZ1BkJYuLgg7kuqUqdye1orc0XCzySNvSaRSfAHjCXreY6GQWM02hk1h5fLJJ9v-QizNSKrIsouUl3R3_ZmCo0G1SP0XCtLU1DZ-hztZspgnWYbFed6Yoy1UptUc6xTSpWWTXKv7LgvpKtAYN0nWzy15MvtHmYEFEv1bvPtGHW-wv)
[Answer]
## Pascal, 352 bytes
This `function` requires a processor supporting features of ISO standard 10206 “Extended Pascal”, in particular the `string` schema data type and `index` string search function.
```
type t=string(3);function f(s:t):Boolean;begin case length(s)of 1:f:=index('BCFHIKNOPSUVWY',s)>0;2:f:=odd(index('AcAgAlAmArAsAtAuBaBeBhBiBkBrCaCdCeCfClCmCnCoCrCsCuDbDsDyErEsEuFeFlFmFrGaGdGeHeHfHgHoHsInIrKrLaLiLrLuLvMcMdMgMnMoMtNaNbNdNeNhNiNoNpOgOsPaPbPdPmPoPrPtPuRaRbReRfRgRhRnRuSbScSeSgSiSmSnSrTaTbTcTeThTiTlTmTsXeYbZnZr',s));otherwise f:=6=9 end end;
```
Ungolfed:
```
type
{ A schema data type `string` is an Extended Pascal extension.
Here we discriminate `string` to have (at least) a capacity
exceeding one character than the longest abbreviation. }
tripleCharacter = string(3);
{ NB: When calling with a string literal longer than three characters,
the extra character are silently clipped. }
function isElementAbbreviation(protected sample: tripleCharacter): Boolean;
const
single = 'BCFHIKNOPSUVWY';
double = 'AcAgAlAmArAsAtAuBaBeBhBiBkBrCaCdCeCfClCmCnCoCrCsCu' +
'DbDsDyErEsEuFeFlFmFrGaGdGeHeHfHgHoHsInIrKrLaLi' +
'LrLuLvMcMdMgMnMoMtNaNbNdNeNhNiNoNpOgOs' +
'PaPbPdPmPoPrPtPuRaRbReRfRgRhRnRuSbScSeSgSiSmSnSr' +
'TaTbTcTeThTiTlTmTsXeYbZnZr';
begin
case length(sample) of
1:
begin
{ In Pascal `string`s indices are 1-based.
`index` returns `0` if nothing was found. }
isElementAbbreviation := index(single, sample) > 0;
end;
2:
begin
{ Do not match, for example, `'cA'`. }
isElementAbbreviation := odd(index(double, sample));
end;
otherwise
begin
isElementAbbreviation := false;
end;
end;
end
```
[Answer]
# Python, 229 bytes
Thanks to [@Neil](https://codegolf.stackexchange.com/users/17602/neil) for the regex - :)
```
import re;bool(re.match("([HNOUVWY]|[CGLP]a|[DNPRSTY]b|[AMST]c|[CMNP][do]|Gd|[BCFGHNRSTX]e|[CHR]f|[AHMORS]g|[BNRT][ah]|[BLNST]i|Bk|[ACFT][lm]|Pm|Sm|[CIMRSZ]n|Ho|Np|[AELZ]r|[BCFIKPS]r?|[ACDEHOT]s|[AMP]t|[ACELPR]u|Lv|Dy)",input()))
```
...go brr
] |
[Question]
[
### Introduction:
Two resistors, `R1` and `R2`, in parallel (denoted `R1 || R2`) have a combined resistance `Rp` given as:
$$R\_{P\_2} = \frac{R\_1\cdot R\_2}{R\_1+R\_2}$$
or as suggested in comments:
$$R\_{P\_2} = \frac{1}{\frac{1}{R\_1} + \frac{1}{R\_2}}$$
Three resistors, `R1`, `R2` and `R3` in parallel (`R1 || R2 || R3`) have a combined resistance `(R1 || R2) || R3 = Rp || R3` :
$$R\_{P\_3} = \frac{\frac{R\_1\cdot R\_2}{R\_1+R\_2}\cdot R\_3}{\frac{R\_1\cdot R\_2}{R\_1+R\_2}+R\_3}$$
or, again as suggested in comments:
$$R\_{P\_3} = \frac{1}{\frac{1}{R\_1} + \frac{1}{R\_2}+ \frac{1}{R\_3}}$$
These formulas can of course be extended to an indefinite number of resistors.
---
### Challenge:
Take a list of positive resistor values as input, and output the combined resistance if they were placed in parallel in an electric circuit. You may not assume a maximum number of resistors (except that your computer can handle it of course).
### Test cases:
```
1, 1
0.5
1, 1, 1
0.3333333
4, 6, 3
1.3333333
20, 14, 18, 8, 2, 12
1.1295
10, 10, 20, 30, 40, 50, 60, 70, 80, 90
2.6117
```
---
**Shortest code in each language wins. Explanations are highly encouraged.**
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~5~~ 3 bytes
```
zOz
```
[Try it online!](https://tio.run/##yy9OTMpM/f@/yr/q//9oQwMdBRA2AmJjIDYBYlMgNgNicyC2AGJLg1gA "05AB1E – Try It Online")
---
### Explanation
```
z # compute 1/x for each x in input
O # sum input
z # compute 1/sum
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~18~~ 16 bytes
```
(1/).sum.map(1/)
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzX8NQX1OvuDRXLzexAMT@n5uYmadgq1BQlJlXoqCikKYQbaKjYKajYBz7/19yWk5ievF/3QjngAAA "Haskell – Try It Online")
[Answer]
# [MATLAB](https://ch.mathworks.com/products/matlab.html), 14 bytes
In MATLAB `norm(...,p)` computes the `p`-norm of a vector. This is usually defined for \$p \geqslant 1\$ as
$$\Vert v \Vert\_p = \left( \sum\_i \vert v\_i \vert^p \right)^{\frac{1}{p}}.$$
But luckily for us, it also happens to work for \$p=-1\$. (Note that it does not work in Octave.)
```
@(x)norm(x,-1)
```
[Don't try it online!](https://tio.run/##y08uSSxL/f/fQaNCMy@/KFejQkfXUPN/Yl6xRrShjpGOcazmfwA "Octave – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 3 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
İSİ
```
**[Try it online!](https://tio.run/##y0rNyan8///IhuAjG/7//x9taKCjAMJGQGwMxCZAbArEZkBsDsQWQGxpEAsA "Jelly – Try It Online")**
### How?
Initially I forgot this form from my electronic engineering days ...how easily we forget.
```
İSİ - Link: list of numbers, R e.g. [r1, r2, ..., rn]
İ - inverse (vectorises) [1/r1, 1/r2, ..., 1/rn]
S - sum 1/r1 + 1/r2 + ... + 1/rn
İ - inverse 1/(1/r1 + 1/r2 + ... + 1/rn)
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 15 bytes
```
@(x)1/sum(1./x)
```
[Try it online!](https://tio.run/##y08uSSxL/Z@mYKugp6f330GjQtNQv7g0V8NQT79C83@aRrShgmGsJheIYaCjAMJGQGwMxCZAbArEZkBsDsQWQGxpEKv5HwA "Octave – Try It Online")
Harmonic mean, divided by `n`. Easy peasy.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 22 bytes
```
$args|%{$y+=1/$_};1/$y
```
[Try it online!](https://tio.run/##RY3BDoJADETv@xUbUgXiJHYXxFVCwp@gB9ADiQYOSnC/fa0kag/NvGknc7892mG8tn0fqKvmQOfhMr5WM02bymyp8aXsKXil6KkrXSeJgUmhtMxH/iFHgewLlmFyGAcHC2N/AbEZcswYOWPHKBh7hmMcOE2lQ6qX14ia0zFa5Jo6XTdlHCsf3g "PowerShell – Try It Online")
Takes input via splatting and uses the same 1/sum of inverse trick as many of the others are doing
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 4 [bytes](https://github.com/abrudz/SBCS)
```
÷1⊥÷
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/////B2w0ddSw9v/5/2qG3Co94@o0ddzY/6pgYHOQPJEA/PYC4gDZRKUzA0ACEjAwVjAwUTAwVTAwUzAwVzAwULAwVLg/8A "APL (Dyalog Unicode) – Try It Online")
-1 thanks to [Adám](https://codegolf.stackexchange.com/users/43319/ad%c3%a1m).
[Answer]
# [R](https://www.r-project.org/), 15 bytes
```
1/sum(1/scan())
```
[Try it online!](https://tio.run/##K/r/31C/uDRXA0gmJ@ZpaGr@NzTgAiIjAy5jAy4TAy5TAy4zAy5zAy4LAy5Lg/8A "R – Try It Online")
Follows the same Harmonic Mean principle seen in other answers.
[Answer]
# JavaScript, 28 bytes
```
a=>a.map(y=>x+=1/y,x=0)&&1/x
```
[Try it Online!](https://tio.run/##DcJRDoIwFATA25A2LLBVQfx4XMT48YJAIEgJGFJOX53MpIfu7Tau32zx7y72ElUazT@6mlOakIorTgShTRJXhNj6Zfdzl89@ML15OuL/QlyJG1ESFXEnauLBl7XxBw)
[Answer]
# [Perl 5](https://www.perl.org/) `-pa -MList::Util=reduce`, 26 bytes
```
$_=reduce{$a*$b/($a+$b)}@F
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rYoNaU0ObVaJVFLJUlfQyVRWyVJs9bB7f9/QwVDLiAGkiYKZgrGXEYGCoYmCoYWChYKRgqGRlyGQL6BAlDU2EDBxEDB1EDBzEDB3EDBwkDB0uBffkFJZn5e8X9dX5/M4hIrq9CSzByoXf91E3MKAA "Perl 5 – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 14 bytes
```
1/*.sum o 1/**
```
[Try it online!](https://tio.run/##JcpBDoIwFIThq/whxAUx@l6ppUbpVQgLu5JgICwI8ey1wmq@zMznNb1dGlZOkTbptbrMy8BIVpUezP1KUXa0gS1Sdt@COE48FQ3nPQ5YHPUfRlCLejwGNfspV0IeasEKN8EJjeCFu4T0Aw "Perl 6 – Try It Online")
`1 / **` is an anonymous function that returns a list of the reciprocals of its arguments. `1 / *.sum` is another anonymous function that returns the reciprocal of the sum of the elements of its list argument. The `o` operator composes those two functions.
[Answer]
# bash + coreutils, 25 bytes
```
bc -l<<<"1/(0${@/#/+1/})"
```
[TIO](https://tio.run/##DYhBCsIwFAX3OcWjdqGI5P001kiz8B6li9YEKgQLVnBhPXvMYgZmpnGd82d@pIhXHAPStvU96oRh6BAWrPFdqsvTHafkva9E71l/b3qnj6J/hyqH5RmzQFSh2KJFowwhFuLgYCBGSWmi3IawxJloiQvhiCv/)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 10 bytes
```
1/Tr[1/#]&
```
[Try it online!](https://tio.run/##JYoxDoMwFEN3roHE5Cr@IdAwFHEEBjbUIUJFZaBDlA3l7GmAyc/P3l34fnYXtsWl9ZVETX4WVb6rNPrtF@by0a9Drmo4ikMgEVfcYNCiPkETYiAWFhqir1NWRB5qwhAN0RJPwhIdYxHTHw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 3 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
∩Σ∩
```
The same as other answers, using the builtins `∩` (\$\frac{1}{n}\$) and `Σ` (sum):
$$M(x\_1,...,x\_n)=\frac{1}{\frac{1}{x\_1} + \frac{1}{x\_2} + ... + \frac{1}{x\_n}}$$
[Try it online.](https://tio.run/##y00syUjPz0n7//9Rx8pzi4HE///RhjqGsVwgEkyb6JjpGANpIwMdQxMdQwsdCx0jHUMjkAqgiIEOUNzYQMfEQMfUQMfMQMfcQMfCQMfSIBYA)
[Answer]
# Java 8, 24 bytes
```
a->1/a.map(d->1/d).sum()
```
I noticed there wasn't a Java answer yet, so figured I'd add one.
[Try it online.](https://tio.run/##hVDLTsMwELz3K1Y9Oep2sdNQgiqQkLjSS4@Ig0lclJA4UexUqlCvfACfyI@EzUOiFQculnd3ZnZ2cn3Qyzx975JCOwdPOrMfM4DMetPsdWJg25cAadW@FgYSkTOBWp8V5HxjdEmPw2Q3FKCDDcNPM36c1z5LYAsW7qDTy3t1panUtUj7bxqQa0sRdJseW7MEYyfKocpSKNmJYNXMvj2/sO5owxvnhUI1rPktLxsRrnF13gglqghVjDGGqMILMo8kMmAlMZJ4LXEt8UZiLPFW/jlmcDbwxjyIiKOqWz/Z2x2dNyVVraeanfvCnuX10DT66MhX41ViJC7m8P35BfOFpX/CpWo/cYLJ2Kn7AQ)
**Explanation:**
Uses the same Harmonic Mean approach as other answers:
$$M(x\_1,...,x\_n)=\frac{1}{\frac{1}{x\_1} + \frac{1}{x\_2} + ... + \frac{1}{x\_n}}$$
```
a-> // Method with DoubleStream parameter and double return-type
a.map(d->1/d) // Calculate 1/d for each value `d` in the input-stream
.sum() // Then take the sum of the mapped list
1/ // And return 1/sum as result
```
[Answer]
# [PHP](https://php.net/), 51 bytes
Reciprocal of sum of reciprocals. Input is `$a`.
```
1/array_reduce($a,function($c,$i){return$c+1/$i;});
```
[Try it online!](https://tio.run/##HcuxDsIgEADQX2G4ASJJQa2tQeOnGHLSwALkUgbT9Nvx7PDGV2Ptj1eNVYB/eiL/ldZo8XdmF3ZlI7uxic3sbpQTAWPpdjjWm8KnYZDg9dIyrqlkCaghqY3C2igDnuwAye3K9f4D "PHP – Try It Online")
[Answer]
# JavaScript (ES6), 29 bytes
```
a=>a.reduce((p,c)=>p*c/(p+c))
```
[Try it online!](https://tio.run/##lc@9DoIwEMDx3ae4sdVa2vI9wOhLGIemFIMhtAE0vn09ViFBL/0nnX65e@iXnszY@fk8uMaGtgq6qjUfbfM0lhDPDK1qfzQR8SdDaTBumFxvee/upCVXyUDC7twon92le9uGJJRCFIHg6WGD2te2qBjnW0sYZAzivzW5qSmBmyEpCwb4FP7Ub5pU5frSRcMWNcYSLMUyLMcKrBRrTfFMyjx8AA "JavaScript (Node.js) – Try It Online")
or:
```
a=>1/a.reduce((p,c)=>p+1/c,0)
```
[Try it online!](https://tio.run/##lc@9DoMgEMDxvU/BCCkFDr8HHfsSTQeC2GiMGLVN356eazWxvfBPmH6568zLzHZqx@Uy@NqFpgymrEAaMbn6aR2lI7esrMYzSMsVC9YPs@@d6P2DNvQGnAA5nDsTi7@2b1fTmDEiJVEiOe1Qx9oeFeF8azEnKSfR3xrsalrhZkhCzgk@jT/9mwa62F66atiqRliMJViKZViOFWqraZECZOED "JavaScript (Node.js) – Try It Online")
But with this approach, using `map()` (as [Shaggy did](https://codegolf.stackexchange.com/a/192651/58563)) is 1 byte shorter.
[Answer]
# [Python 3](https://docs.python.org/3/), 30 bytes
```
lambda r:1/sum(1/v for v in r)
```
**[Try it online!](https://tio.run/##TY7LCoMwEEX3fsXsTGBAY6y1gl9SXVhUKtQoMRX69emN0EfIYc7NzEDWl7svRvuxbvyjm299R7ZSyfachUp2GhdLO02GrPTB3bC5EEVEOFfFpFr@@V/MmQom/YlZih7eVMmEm8Gy72bogTCjQQ5OoABnUIJL2kayOuZXOxknwk@YxqNKpm1Y67gxMdNg@mBw6d8 "Python 3 – Try It Online")**
[Answer]
# [Perl 5](https://www.perl.org/) (-p), 17 bytes
```
$a+=1/$_}{$_=1/$a
```
[Try it online!](https://tio.run/##K0gtyjH9/18lUdvWUF8lvrZaJR7ESPz/39CAC4iMDLiMDbhMDLhMDbjMDLjMDbgsDLgsDf7lF5Rk5ucV/9ctAAA "Perl 5 – Try It Online")
[Answer]
# x86-64 Machine code - ~~20~~ 18 bytes
```
0F 57 C0 xorps xmm0,xmm0
loopHead
F3 0F 53 4C 8A FC rcpss xmm1,dword ptr [rdx+rcx*4-4]
0F 58 C1 addps xmm0,xmm1
E2 F6 loop loopHead
0F 53 C0 rcpps xmm0,xmm0
C3 ret
```
Input - Windows calling convention. First parameter is the number of resistors in `RCX`. A pointer to the resistors is in `RDX`. `*ps` instructions are used since they are one byte smaller. Technically, you can only have around 2^61 resistors but you will be out of RAM long before then. The precision isn't great either, since we are using `rcpps`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
,1w/s
```
[Try it online!](https://tio.run/##y00syfn/X8ewXL/4//9oIwMdBUMTILbQUQAiIyDLKBYA "MATL – Try It Online")
I'm not sure if "do twice" (`,`) counts as a loop, but this is just the harmonic mean, divided by `n`.
Alternately, `,-1^s` is five bytes as well.
[Answer]
# Intel 8087 FPU machine code, 19 bytes
```
D9 E8 FLD1 ; push 1 for top numerator on stack
D9 EE FLDZ ; push 0 for running sum
R_LOOP:
D9 E8 FLD1 ; push 1 numerator for resistor
DF 04 FILD WORD PTR[SI] ; push resistor value onto stack
DE F9 FDIV ; divide 1 / value
DE C1 FADD ; add to running sum
AD LODSW ; increment SI by 2 bytes
E2 F4 LOOP R_LOOP ; keep looping
DE F9 FDIV ; divide 1 / result
D9 1D FSTP WORD PTR[DI] ; store result as float in [DI]
```
This uses the stack-based floating point instructions in the original IBM PC's 8087 FPU.
Input is pointer to resistor values in `[SI]`, number of resistors in `CX`. Output is to a single precision (DD) value at `[DI]`.
[Answer]
# [Rattle](https://github.com/DRH001/Rattle), 24 bytes
```
|>II^[=1+#g`e_1P+~s]`e_1
```
[Try it Online!](https://www.drh001.com/rattle/?flags=&code=%7C%3EII%5E%5B%3D1%2B%23g%60e_1P%2B%7Es%5D%60e_1&inputs=10%2C%2010%2C%2020%2C%2030%2C%2040%2C%2050%2C%2060%2C%2070%2C%2080%2C%2090)
This answer can probably be golfed more (can anyone outgolf me in my own language?)
# Explanation
```
| take input, parse automatically (Rattle's input parsing is powerful
enough to recognise "1,2,3" etc. as a list)
> move pointer to the right (to slot 1)
I flatten input list and insert into consecutive memory slots
I^ get length of this list (which is still on top of the stack)
[ ... ]` loop structure: loop as many times as the length of the list
=1 set top of stack to 1
+# increment top of stack by list's iterator
(the number of times the loop has run)
g` get the value in storage at the calculated index (iterator + 1)
e_1 get 1/x of this value
P set the pointer to slot 0
+~ increment the current value by the stored value in slot 0
s save the result to slot 0
e_1 get 1/x of this value
```
[Answer]
# [Dart](https://www.dartlang.org/), 42 bytes
```
f(List<num>a)=>a.reduce((p,e)=>p*e/(p+e));
```
[Try it online!](https://tio.run/##ZYxBDsIgFET3noLlRyf6oVgxak/gDYwLYmnCooRUujKeHYk7a2Y1702md1MuZaBreOZznMfOyUvntpPv54cnSvC1p7XfUdp4KU9ldCGSfK2ESFOImQa6KQh1r@6X1SyhQYtmCTVDGSgLCw2l/46qZtRRwzCMPaNlHBiWceTv@F0@ "Dart – Try It Online")
Having to explicitly specify the `num` type is kinda sucky, prevents type infering, because it would infer to `(dynamic, dynamic) => dynamic` which can't yield doubles for some reason
[Answer]
# [PHP](https://php.net/), 40 bytes
```
for(;$n=$argv[++$i];$r+=1/$n);echo 1/$r;
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxV8mxVEovSy6K1tVUyY61VirRtDfVV8jStU5Mz8hWAzCLr////GxqAkJHBf2OD/yYG/00N/psZ/Dc3@G9h8N/SAAA "PHP – Try It Online")
Tests: [Try it online!](https://tio.run/##VY/baoQwEIbv8xSDBDZiUKO77iGVvkNvrZSwpKvFjZJooZQ@u501le0O@WEO3/xDhmaYn56HZiCEjtqNDkqoCGBUgoOoOSQJpPHu3vrXzX342ZZDwSH3M/E4y1LcQkAcOODLMMtWUGTH1f1GoW50jtqidqgCtUcdUMfU72VxIcSe1JKQ995qdW6A/X1AOViyEL4XX6rs5RO/paxVX29XbS@aVWbqOnTyoFw4fW56CF60m7oR0BSqAGL46FvDNhw2K4y9oIbWnSCQM2JMUlMuN6ooom0tqY1KkVATysURUyvn@4FXG/h7k3F6ZLQNH0qL5c/8Cw "PHP – Try It Online")
Similar to [Yimin Rong's solution](https://codegolf.stackexchange.com/a/192652/81663) but without built-ins and all program bytes are included in the bytes count.
[Answer]
# Python 3, ~~58~~ 44 bytes
```
f=lambda x,y=0,*i:f(x*y/(x+y),*i)if y else x
```
A recursive function. Requires arguments to be passed unpacked, like so:
```
i=[10, 10, 20]
f(*i)
```
or
```
f(10, 10, 20)
```
**Explanation:**
```
# lambda function with three arguments. *i will take any unpacked arguments past x and y,
# so a call like f(10, 20) is also valid and i will be an empty tuple
# since y has a default value, f(10) is also valid
f=lambda x,y=0,*i: \
# a if case else b
# determine parallel resistance of x and y and use it as variable x
# since i is passed unpacked, the first item in the remaining list will be y and
# the rest of the items will be stored in i
# in the case where there were no items in the list, y will have the default value of 0
f(x*y/(x+y),*i) \
# if y does not exist or is zero, return x
if y else x
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 7 bytes
```
I∕¹Σ∕¹A
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwyWzLDMlVcNQRyG4NBeJ55lXUFqioQkG1v//R0cbGegoGJoAsYWOAhAZAVlGsbH/dctyAA "Charcoal – Try It Online") Link is to verbose version of code. Works by calculating the current drawn by each resistor when 1V is applied, taking the total, and calculating the resistance that would draw that current when 1V is applied. Explanation:
```
A Input array
∕¹ Reciprocal (vectorised)
Σ Sum
∕¹ Reciprocal
I Cast to string for implicit print
```
[Answer]
# [J](http://jsoftware.com/), 6 bytes
```
1%1#.%
```
[Try it online!](https://tio.run/##TYsxCoNAFER7T/GIiAR0mb@uugqpAqlS5QpBCWm8f7WaIirMg3kM800XV87cRkoqxLhRO@6v5yNZYbkr0jUjm96fhRnDTvWQQEfzFy8sYJGIx/x@0C/b2IggWtGJXkQxKK0 "J – Try It Online")
[Answer]
# [MATLAB], 15 bytes
One more byte than *flawr* excellent answer, but I had to use other functions so here goes:
```
@(x)1/sum(1./x)
```
It's rather explicit, it sums the inverse of the resistances, then invert the sum to output the equivalent parallel resistance.
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 49 bytes
```
: f 0e 0 do dup i cells + @ s>f 1/f f+ loop 1/f ;
```
[Try it online!](https://tio.run/##hY9BTsMwEEX3PcVnxaJTGCdpmlIJISFxCcrCJA6JSOPKdoCevkxiEJVQVS9iR/7v/XFtXWgWb/W4HY93qMEGjMqiGvZoUZqu85jjAf6@hrqtUc/RWbufzhshvmI8DOX7Sf4qhionnw228I00lENAsPDBOoNKB422x87srDsQfNuXBk/jIOIzvr8OaPSHwevQdmEhSe2cPviZgsJeV0ikelxbPDqjg4n3@GxF8KxIvcxiSka@QelmExjRdELPgb9o@odmyOX3AppRTuk/NGGoDKpAIbOoZJLk5yUJk8pIFVRQQiqJuvzkEaJjiDRlZIwlI2esGAVjzZNcrs@/TuxM0pEyZUxLppxpxVQwrTl2Cf5TdvwG "Forth (gforth) – Try It Online")
Input is a memory address and array length (used as an impromptu array, since Forth doesn't have a built-in array construct)
Uses the sum-of-inverse method as most other answers are
### Code Explanation
```
: f \ start a new word definition
0e \ stick an accumulator on the floating point stack
0 do \ start a loop from 0 to array-length -1
dup \ copy the array address
i cells + \ get the address of the current array value
@ s>f \ get the value and convert it to a float
1/f f+ \ invert and add to accumulator
loop \ end the loop definition
1/f \ invert the resulting sum
; \ end the word definition
```
] |
[Question]
[
## Goal:
Create a program to find the smallest file in the current folder.
* File size may be measured in bytes or characters.
* If multiple files have the same size, you can either choose one or display all of them.
* You can assume there will be at least one file in the folder, and no files will have a size of 0.
* Assume that all files in the folder can be loaded by the language you're using.
* ### Assume that there are no folders in the current directory.
### Input:
The program should not take any input from the user, unless:
* If your language doesn't have a "current folder", it may ask the user for a folder name/path.
* If your language cannot directly access files on your computer, it may allow the user to upload files. (JavaScript, for example)
### Output:
The name of the smallest file should be displayed.
* Leading/trailing symbols are allowed, as long as it's clear which file has been chosen.
* (Printing a list of all the files is against the rules).
### Notes:
* [Standard Loopholes](http://meta.codegolf.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default "Standard Loopholes") are not allowed.
* You cannot modify/create/delete files in the folder to change the result.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"); shortest answer (in bytes) wins.
[Answer]
# Bash + coreutils, 13 bytes
```
ls -Sar|sed q
```
Explanation:
```
ls -Sar|sed q
ls # list files
-S # sorted, biggest first
a # show hidden files
r # reversed (smallest first)
|sed q # q is quit at first line that matches given regex,
# given regex is empty so guaranteed match.
```
[Answer]
## Python ~~2~~ 3, ~~94~~ ~~76~~ ~~74~~ 54 bytes
-18 bytes thanks to @orlp
-2 bytes thanks to @Jonathan Allan
-20 bytes thanks to a change in challenge specs
```
from os import*
print(min(listdir(),key=path.getsize))
```
[Answer]
# [PowerShell](https://github.com/PowerShell/PowerShell), ~~30~~ ~~24~~ 21 bytes
```
(ls|sort le*)[0].Name
```
[Try it online!](https://tio.run/nexus/powershell#@6@RU1xTnF9UopCTqqUZbRCr55eYm/r/PwA "PowerShell – TIO Nexus")
`ls` is an alias for `Get-ChildItem`. That's piped to `sort-object` with the `length` attribute, so the files are sorted by size. We index into that with the `(...)[0]` to get the first (i.e., smallest), and then take the `.Name` thereof. Output via implicit `Write-Output` happens at program completion.
*Saved 6 bytes since we're guaranteed that only files exist in the directory. Saved an additional 3 thanks to ConnorLSW.*
[Answer]
# Vim 12 bytes
```
!!ls -Sa
Gd{
```
[Try it online!](https://tio.run/nexus/v#@6@omFOsoBucyOWeUv3/PwA "V – TIO Nexus")
## Explanation:
`!!` is the *filter* command. It pipes the contents of the current line to an arbitrary system command, and sends the output back into the buffer. It's useful for using external tools for things that bash is better at than vim, for example `!!rev` to reverse the current line, or `!Gxxd` to hexdump the buffer. In our case, the buffer is empty so it's equivalent to `:r!ls`, which just feeds the output of the command into the current line.
Now the cursor is on line 1, and we want to delete every line but the last one. The naïve approach is
```
G " Go to the last line
k " Go up one line
d " Delete:
gg " Everything up to the first line
```
But we can do better. Like I explained in [this tip](https://codegolf.stackexchange.com/a/103946/31716), the `{` can *usually* (but not always) be equivalent to `gg`. Here, it's even better. Because the motion is *character-based*, not *line-based* like `gg` is, we don't have to go up a line first, leaving us with
```
Gd{
```
[Answer]
# Java 7, ~~149~~ 142 bytes
```
String f(){String n="";long s=-1>>>1,p;for(java.io.File f:new java.io.File(".").listFiles())if((p=f.length())<s){n=f.getName();s=p;}return n;}
```
[Try it online!](https://tio.run/nexus/java-openjdk#TY8xbsMwDEX3nILwRAGpgKxR5bFbu2QsMiip5KiQJUGkUwSGz@7SSIdO/HwEicdrckTw7mKGeT1xi3mAgGr@i9l2nUlFEtmXQ9/3h301oTT8dnenY9FvMXkIx@x/4D/CTndKp0i8dYRKxYBYbdDJ54FvAl5JzVnA4PnDjR6VIVvN0jxPLUM2y1qnS4pXIHYs5V7iF4wiik@3z7Nrg4J5B099BxY2ja2RY4JPD2I/6jKxrrLBKaPT8pwMl92y/gI "Java (OpenJDK) – TIO Nexus")
-7 bytes thanks to CAD97
[Answer]
## Ruby, ~~61~~ ~~40~~ ~~38~~ 37 bytes
Thanks G B and Value Ink
```
p Dir[?*,".*"].min_by{|x|File.size x}
```
[Answer]
# Mathematica, 35 bytes
```
FileNames[]~MinimalBy~FileByteCount
```
`FileNames[]` produces a list of names of all the files (and directories) in the current directory; `~MinimalBy~FileByteCount` selects the name of the file whose byte count is smallest. `FileByteCount` throws a bunch of errors when it's applied to directories, but the errors don't derail the program.
[Answer]
## SH (Linux/Unix) ~~15~~ ~~14~~ ~~13~~ 14 bytes
```
ls -aS|tail -1
```
`-S` sorts by size (descending),
~~`-r`reverses~~ and `tail -1` outputs the last file in the list.
@ Dennis Thanks for saving 1 byte
@Dani\_l Thanks for saving 1 byte.
[Answer]
# MATLAB / Octave, ~~52~~ 48 bytes
```
d=dir;[~,n]=min([d.bytes]./~[d.isdir]);d(n).name
```
**Explanation**
This gets a directory listing of all files and folders in the current directory using `dir`. The output of `dir` is a `struct` containing the filename, whether it's a directory or not, the size (in bytes), etc.
We can then take an array of the sizes of each in bytes `[d.bytes]` and perform element-wise division with a boolean indicating whether it's a directory or not `~[d.isdir]` which will yield `Inf` where it's a directory (division by zero) and the size in bytes otherwise (division by 1).
We find the index of the minimum of this array using the second output of `min` and use that to index into the initial struct and display the name with `d(n).name`
[Answer]
**Scala, 52 bytes**
Old version, 79 bytes
```
new java.io.File(".").listFiles.map(a=>a.getName->a.length)sortBy(_._2)apply(0)
```
Adjusted according to jaxad0127's advice. It is only 52 bytes now.
```
new java.io.File(".").listFiles.sortBy(_.length)head
```
[Answer]
## Batch, ~~43~~ ~~39~~ 35 bytes
```
@dir/b/os|(set/pf=&call echo %%f%%)
```
Output includes a leading space for some reason, but fortunately that's allowed. Edit: Now assuming there are no directories to save 4 bytes.
[Answer]
# [Perl 6](https://perl6.org), ~~33 32 31~~ 16 bytes
```
'.'.IO.dir.grep(*.f).min(*.s).put
```
[Try it](https://tio.run/nexus/perl6#@6@up67n6a@Xklmkl16UWqChpZemqZebmQdkFGvqFZSW/P8PAA "Perl 6 – TIO Nexus")
```
put '.'.IO.dir.min:{try .s//Inf}
```
[Try it](https://tio.run/nexus/perl6#@19QWqKgrqeu5@mvl5JZpJebmWdVXVJUqaBXrK/vmZdW@/8/AA "Perl 6 – TIO Nexus")
```
put $*CWD.dir.min:{try .s//Inf}
```
[Try it](https://tio.run/nexus/perl6#@19QWqKgouUc7qKXklmkl5uZZ1VdUlSpoFesr@@Zl1b7/z8A "Perl 6 – TIO Nexus")
```
put dir.min: *.s
```
[Try it](https://tio.run/nexus/perl6#@19QWqKQklmkl5uZZ6WgpVf8/z8A "Perl 6 – TIO Nexus")
## Expanded:
```
put # print with trailing newline
dir # the list of files in the current directory
.min: # find the minimum by
*.s # calling the `s` method (size) in a Whatever lambda
```
[Answer]
# [J](http://jsoftware.com/), ~~21~~ 20 bytes
```
>{.,(/:2&{"1)1!:0'*'
```
Saved a byte thanks to @[Conor](https://codegolf.stackexchange.com/users/31957/conor-obrien).
## Explanation
```
>{.,(/:2&{"1)1!:0'*'
'*' Glob all files in current directory
1!:0 Table of file metadata in that directory
2&{"1 Get the file size of each
/: Sort the files by that
, Flatten
{. Get the first value
> Unbox
```
[Answer]
## PHP, ~~84~~ 62 bytes
```
$t=array_map(filesize,$g=glob('*'));asort($t);echo$g[key($t)];
```
Since the question was updated with the assumption that there will be no folders in the current directory, I was able to remove the file check stuff and golf this down.
---
**Here is my old answer:**
```
$t=array_map(filesize,$g=array_filter(glob('*'),is_file));asort($t);echo$g[key($t)];
```
This is the best I could do. Maybe there is a better way I'm missing.
```
$t=array_map( # visit each array element and...
filesize, # map each filename to its filesize...
$g=array_filter( # using an array of...
glob('*'), # all files and directories...
is_file # filtered by files...
) #
); #
asort($t); # sort the array of filesizes, then...
echo$g[key($t)]; # print element from the array of files using the first key of the sorted array as an index
```
[Answer]
## BATCH File, ~~77~~ ~~72~~ ~~63~~ 60 bytes
```
@FOR /F tokens^=* %%G IN ('dir/o-s/b')DO @SET[=%%G
@ECHO %[%
```
There's no direct equivalent of `head` or `tail` in BATCH, at least to my knowledge, so here's a kludgy work-around. (with much assistance from @Neil - thanks!)
The `dir` command, with `/o-s` to sort in descending file size, and `/b` to output only the file names. We loop through those with `FOR /F`, setting the variable `[` to the file name each time. Finally, we output just the last one with `ECHO %[%`.
*Saved 9 more bytes thanks to Neil and thanks to guarantees that no directories are present.*
*Saved 3 bytes thanks to HackingAddict1337.*
[Answer]
# Node.js (using [`walk`](https://www.npmjs.com/package/walk)), 114 bytes
Ignore newline:
```
require('walk').walk(__dirname).on('file',(r,s,n)=>
(m=s.size>m.size?m:s,n()),m=0).on('end',_=>console.log(m.name))
```
This invokes a walker that traverses through the current directory (`__dirname`) and for each file calls a function with its stat `s` and a function next `n()` that must be invoked to continue the traversal. Then at the `end`, it prints a filename with the minimum `size` in bytes found. `s.size>m.size` returns `false` when `m.size` is `undefined`, so after the first callback, `m` is equal to the first file found, and continues from there normally.
[Answer]
## R, 36 bytes
```
x=file.info(y<-dir())$s;y[x==min(x)]
```
**Explained**
`file.info()` returns a `data.frame` of "file information" when given a character or character vector of file/folder names which when used on the list of files/folders in the current directory (`dir()`), looks something like:
```
size isdir mode mtime ctime atime exe
Polyspace_Workspace 0 TRUE 777 2014-11-28 17:29:25 2014-11-28 17:29:25 2014-11-28 17:29:25 no
Python Scripts 0 TRUE 777 2016-03-21 23:59:41 2016-03-21 23:59:41 2016-03-21 23:59:41 no
R 0 TRUE 777 2015-12-23 20:11:02 2015-12-23 20:11:02 2015-12-23 20:11:02 no
Rockstar Games 0 TRUE 777 2015-04-14 12:23:05 2015-04-14 12:23:03 2015-04-14 12:23:05 no
TrackmaniaTurbo 0 TRUE 777 2016-03-24 17:15:05 2016-03-24 13:13:48 2016-03-24 17:15:05 no
ts3_clientui-win64-1394624943-2014-06-11 03_18_47.004772.dmp 314197 FALSE 666 2014-06-11 02:18:47 2014-06-11 02:18:47 2014-06-11 02:18:47 no
```
Subsequently we just have the find the name of the file for which the `size` column (abbreviated using `$s`) is the smallest. Consequently, if there are more than one file with the smallest size, all will be returned.
Bonus: if we also wanted to disregard folders in the current directory we could simply search for size when `isdir == FALSE`: `x=file.info(y<-dir());y[x$s==min(x$s[!x$i])]` which turns out to be 44 bytes.
[Answer]
# [Tcl](http://tcl.tk/), 88 bytes
```
set s Inf
lmap f [glob -ty f *] {if [set m [file si $f]]<$s {set n $f
set s $m}}
puts $n
```
[Try it online!](https://tio.run/##dY7LCsIwEEX3@YpZdCXoF7gSpHThxm3Joo9JCEweOClVSr89JioiBXeXyzlzJw6UGCMoaH1AB2w7okO8R5ilCFNkqBSwGMgz5ijEL2xxNJPd0hcc//C90RpvW/7U1PX5@lVe7zA0TgmyXSiyJt/DPj5y3klYTK4KZKFVhhDYZE3KY8WwlN6V4feVyq7rZ8il9AQ "Tcl – Try It Online")
[Answer]
# SmileBASIC, 110 bytes
```
DIM F$[0]FILES"TXT:",F$FOR I=0TO LEN(F$)-1F$[I][0]="TXT:
S=LEN(LOAD(F$[I],0))IF!Z||S<Z THEN Z=S:B=I
NEXT?F$[B]
```
Only looks at `TXT:` files, since `DAT:` files cannot be loaded unless you already know their size, making it impossible to load a random one.
[Answer]
# [Groovy](http://groovy-lang.org/), 49 bytes
```
m={f->f.listFiles().sort{it.length()}[0].getName()}
```
[Try it online!](https://tio.run/nexus/groovy#@1@dpmuXppeTWVzilpmTWqyhqVecX1RSnVmil5Oal16SoaFZG20Qq5eeWuKXmJsK5P3/DwA "Groovy – TIO Nexus")
Closure, usage: `m(new File("location"))`
[Answer]
# C#, 277 bytes
Not the shortest, but what would you expect from C#?
## Golfed
```
using System.Linq;using static System.IO.Directory;class P{static void Main(){var x=GetFiles(GetCurrentDirectory());var d=new long[]{}.ToList();foreach(var s in x){var b=new System.IO.FileInfo(s).Length;if(!d.Contains(b))d.Add(b);}System.Console.Write(x[d.IndexOf(d.Min())]);}}
```
## Ungolfed
```
//Linq using for List.Min()
using System.Linq;
//Static using to save bytes on GetCurrentDirectory() and GetFiles()
using static System.IO.Directory;
class P
{
static void Main()
{
//String array containing file paths
var x = GetFiles(GetCurrentDirectory());
//Creating a Long array and converting it to a list, less bytes than "new System.Collections.Generic.List<long>()"
var d = new long[] { }.ToList();
foreach (var s in x) //Loop through all file paths
{
//Getting file size in bytes
var b = new System.IO.FileInfo(s).Length;
if (!d.Contains(b))
//If there isn't already a file with this size in our List, add the file path to list
d.Add(b);
}
//Get index of the smallest Long in our List, which is also the index of the file path to the smallest file, then write that path
System.Console.Write(x[d.IndexOf(d.Min())]);
}
}
```
[Answer]
# [Röda](https://github.com/fergusq/roda "branch roda-0.12"), ~~32~~ 31 bytes
```
{ls""|sort key=fileLength|pull}
```
It's an anonymous function that sorts the files in the current directory by file length and selects then the first file with `pull`.
Use it like this: `main{ {ls""|sort key=fileLength|pull} }`
[Answer]
# [Zsh](https://www.zsh.org/) `-C4`, 9 bytes
* `-C`: enables noclobber (Zsh will not redirect to files which already exist)
* `-4`: enables globdots (`*` matches files beginning with `.`.
>
> Leading/trailing symbols are allowed, as long as it's clear which file has been chosen.
>
>
>
The following prints the file name, preceded by `$0:1: file exists:` and followed by a newline, to stderr:
```
>*(oL[1])
```
~~[Try it online!](https://tio.run/##qyrO@J@bnZJZpFCSWlzClZwCoVOTM/IV1HPy89IV0jJzUtUV7BQSoYIQPhjYKSRhU5n8HyyooVWjp6Wpke8TbRir@f8/AA "Zsh – Try It Online")
[Try it online!](https://tio.run/##qyrO@J@bnZJZpFCSWlzClZwCoVOTM/IV1HPy89IV0jJzUtUV7BQSoYIQPhjYKSRhU5n8HyyopeGS7xNtGKv5/z8A "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##qyrO@F@cWqKg62zClZudklmkUJJaXMKVnAKhU5Mz8hXUc/Lz0hXSMnNS1RXsFPQSoaIQATAAiiZhVZv8305LI98n2jBW8/9/AA "Zsh – Try It Online")
* `(oL)` sorts by size
* `[1]` selects the first match
---
I used to have just `*(oL[1])` and rely on Zsh printing "command not found", but if the file matches the name of a builtin or executable, this would break. Additionally, the previous `echo` methods would break if the smallest file was `-e` or `-` or similar (interpreted as a flag to `echo`). This new method works for all file names and is still very short.
[Answer]
# SmileBASIC 3, 105 bytes (competing?)
Beats [12Me21's answer](https://codegolf.stackexchange.com/a/108408/42096) but still suffers from inability to load DAT files (which feels very cruel to be disqualifying considering the circumstances.)
```
DIM F$[0],T[0]FILES"TXT:",F$FOR I=0TO LEN(F$)-1F$[I][0]="TXT:
PUSH T,LEN(LOAD(F$[I]))NEXT
SORT T,F$?F$[0]
```
The shorter version above is annoying and prompts you on every file to load, but it does work. For two bytes more you can suppress the prompt; change line 2 to this:
```
PUSH T,LEN(LOAD(F$[I],0))NEXT
```
[Answer]
## Batch File, 33 bytes
Batch files are moderately competitive this time, oddly enough.
```
@dir/os/b>..\q&set/pa=<..\q&"%a%.
```
**Output**
[](https://i.stack.imgur.com/vFLFa.png)
---
Find a way to stop the creation of `q` prior to `dir/os/b` being run and you'll save a maximum of 6 bytes by not needing to put the output file in a separate directory.
```
@dir/os/b>q&set/pa=<q&"%a%
```
Will always output `q` as the smallest file (unless tied for another 0 byte file) as it is created as an empty file before `dir/b/os` gathers a list of files.
[Answer]
# [C++17 (gcc)](https://gcc.gnu.org/), 180 bytes
```
#include<filesystem>
using namespace std::filesystem;auto f(){std::error_code e;path r;size_t m=-1,s;for(auto&p:directory_iterator(".")){s=file_size(p,e);if(s<m)m=s,r=p;}return r;}
```
[Try it online!](https://tio.run/##RY7NasMwEITP9VOIFBqJ2IWcCpaUJykYIa9dgfXDrnRIg1@9rpRDe9pld@absSkNq7XHqwt2KzMw5SJlBONvfze1uA3oThn8rSvkwsqC8UDJWGCU53H8F0hTcmQLF4/nAxAjTjZWMMhk8hdDSe4bpsy8Hq49ySUib563NM4OweaI98llQFM3fno/iYrSLWBqRp56ENItnJQXXlOPOskdIRcMlb0fLlS0cYEL9uheniVsLJkp1Vq1cf4MZ9ntx49dNrPSMVSRtpfL9eMX "C++ (gcc) – Try It Online")
Requires a recent standard library that implements `std::filesystem`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell) 6+ for Windows, 20 bytes
```
ls|sort l* -t 1|% n*
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/P6e4pji/qEQhR0tBt0TBsEZVIU/r/38A "PowerShell – Try It Online")
Unrolled:
```
ls|sort length -top 1|% Name
```
See also AdmBorkBork's [answer](https://codegolf.stackexchange.com/a/108409/80745).
[Answer]
# Red, 56 bytes
```
first sort/compare read %. func[a b][(size? a)< size? b]
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 51 bytes
```
.ml$open(b,"rb").read()$$__import__("os").listdir()
```
I feel like Pyth might not be the best tool for the job here...
[Try it online!](https://tio.run/##DcnBCsAgCADQf4kOClu/JIuCCZViXvbzc3vXp4/fEWWOLNoX1CNZTVisXw0wZyKeKuZEkGT/MXh7YwOMeEWdZe042wc "Pyth – Try It Online")
] |
[Question]
[
The challenge today is very simple. The task is to determine the TI calculator for which the submitted datafile was made.
The datafiles always start with a string `**TI`, the version (described below), and other data you can ignore.
Now, the versions you need to recognize are:
```
95* => TI-95
92P => TI-92+
92* => TI-92
89* => TI-89
86* => TI-86
85* => TI-85
84P => TI-84+
84* => TI-84
83* => TI-83
83P => TI-83+
82* => TI-82
81* => TI-81
74* => TI-74
73P => TI-73+
```
## Examples
```
**TI95* => TI-95
**TI83P => TI-83+
**TI73P => TI-73+
**TI85* => TI-85
**TI83PGG => TI-83+
**TI86*asdf*9**TI92Pasd => TI-86
```
## Rules
You can assume the input is always correct, is at least 7 characters long, and has been crafted for one of the TI calculators listed above.
This is code golf, so the shortest answer wins.
I/O rules and loopholes apply.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 39 38 35 bytes
Saved 3 bytes thanks to @Dorian.
```
,+++>,>,.,.<<.-->>,.,.,[-<->]<[<.<]
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fR1tb207HTkdPR8/GRk9X1w7M1InWtdG1i7WJttGzif3/X0srxNPCLCCxOCVNyxLEsTQCcQA "brainfuck – Try It Online")
This abuses the fact that the characters `*`,`+`, and `-` are very close to each other in ASCII.
Ungolfed:
```
,+++> create a minus from the first asterisk
,> store the second asterisk for comparison later
,. display T
,. display I
<<.-->> display the minus from line 1 and turn it into a plus
,. display first number
,. display second number
,[-<->]<[ if the last char is not an asterisk from line 2
<.< display the plus from line 5
]
```
Original 38 byte solution:
```
>,+++>,>,.,.<<.-->>,.,.,<[->-<]>[<<.<]
```
Original 39 byte solution:
```
,+++>,>,.,.<<.-->>,.,.,<[->-<]>[<<.[-]]
```
[Answer]
# TI-BASIC (TI-83), ~~40~~ 39 bytes
*Saved a byte thanks to @iPhoenix.*
```
Ans→Str1
sub(Ans,5,2
If sub(Str1,7,1)="P
Ans+"+
"TI-"+Ans
```
Takes input as a string via `Ans` ([allowed by default](https://codegolf.meta.stackexchange.com/a/8580/92901)). The character count differs from the byte count because TI-BASIC is [tokenised](http://tibasicdev.wikidot.com/tokens): `Str1` and `sub(` are 2-byte tokens; `Ans`, `→`, `If` , and all other characters used (including newlines) are 1-byte tokens.
### Sample output
Uses [this emulator](https://www.cemetech.net/sc/).
[](https://i.stack.imgur.com/i1k9l.png)
### Explanation
```
Ans→Str1 # store input in Str1
sub(Ans,5,2 # overwrite Ans with 2-digit calculator ID (5th and 6th input characters)
If sub(Str1,7,1)="P # if the 7th input character is 'P'...
Ans+"+ # then add '+' to Ans
"TI-"+Ans # full calculator name (printed implicitly)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~52, 43~~ 36 bytes
```
lambda x:"TI-"+x[4:6]+"+"*(x[6]>"*")
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCSinEU1dJuyLaxMosVltJW0lLoyLaLNZOSUtJ839BUWZeiUaahpKWVoinhXGAu7uSpiYXmqhWYlpKYoinsXEAUPI/AA "Python 3 – Try It Online")
[Answer]
# perl -pl, 24 bytes
```
s;(\d..).*;-$1;;y;P*;+;d
```
[Try it online!](https://tio.run/##K0gtyjH9/7/YWiMmRU9PU0/LWlfF0Nq60jpAy1rbOuX/fy2tEE9LUy0uEG1hHACmzaG0BUzcVCuxOCc7JS0rsdg6JS0bQaVkA8WsUSmQjDWImWMNVgJSmJIG5CQW/8svKMnMzyv@r1uQAwA "Perl 5 – Try It Online")
Keep the first digit and the next two characters, removes anything after that, and inserts a `-` before the first digit. Replaces any `P` with a `+`. Removes any `*`.
Reads lines from `STDIN`, writes versions to `STDOUT`.
Editted to deal with trailing garbage.
[Answer]
# TI-Basic (TI-84 Plus CE), 54 bytes (50 tokens) ~~61 bytes (56 tokens)~~
```
"TI-"+sub(Ans,5,3
If sub(Ans,6,1)="P
Then
sub(Ans,1,5)+"+
Else
sub(Ans,1,5
End
Ans
```
Usage: `"**TI89*":prgmNAME` if the program is named `NAME`.
TI-Basic is a [tokenized language](http://tibasicdev.wikidot.com/tokens), the `sub(` token is two bytes and all the other tokens used here are one byte (e.g. digits, punctiation, newline, `Ans`, `If`, `Then`, `Else`, `End`).
Takes the input in `Ans` and implicitly prints the result stored in `Ans`.
Encodes the `-` with the [subtraction `-`](http://tibasicdev.wikidot.com/subtract) (0x71), not the [negative `-`](http://tibasicdev.wikidot.com/negative) (0xB0)
Explanation:
```
"TI-"+sub(Ans,5,3 # 19 tokens, 21b: "**TIXX?..." -> "TI-XX?"
If sub(Ans,6,1)="P # 12 tokens, 13b: If the "?" above is "P"
Then # 2 tokens, 2b: Then
sub(Ans,1,5)+"+ # 11 tokens, 12b: Replace "P" with "+"
Else # 2 tokens, 2b: Else
sub(Ans,1,5 # 7 tokens, 8b: Remove the last character
End # 2 tokens, 2b: End If
Ans # 1 tokens, 1b: Last line's Ans is implicitly printed
```
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-ir`, 15 bytes
```
__,,\-,,,P=[\+,
```
[Try it online!](https://tio.run/##y05N//8/Pl5HJ0ZXR0cnwDY6Rlvn/38trRBPCzOtxOKUNC1LEMfSKADI@a@bWQQA "Keg – Try It Online")
Huh, who'da thunk a simple stack approach would beat everyone else?
## Explained
```
__,,\-,,,P=[\+,
__ # Pop the two asterisks at the start
,, # Print the "TI"
\-, # Followed by a dash
,, # Then the number embedded in the input
P= # See if the last character is P
[\+, # If it is, print a "+", otherwise, do nothing and end execution
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 16 bytes
Sorry, didn't understand the comment...
```
7£¦¦…*PI„ +„I-ª‡
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f/NDiQ8sOLXvUsEwrwPNRwzwFbSDhqXto1aOGhf//a2mFeFqYBWglFqekaVmCeJZGAUAOAA "05AB1E – Try It Online")
## Explanation
```
7£ Take a 7-char prefix.
¦¦ Remove the first 2 characters.
…*PI "*PI"
„ +„I-ª With: [" ", "+", "I-"] respectively
‡ Transliterate
```
[Answer]
# JavaScript (ES6), 34 bytes
```
s=>'TI-'+s[4]+s[5]+[{P:'+'}[s[6]]]
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@7/Y1k49xFNXXbs42iQWSJjGakdXB1ipa6vXRhdHm8XGxv5Pzs8rzs9J1cvJT9dI01DS0grxtDTVUtLUVFBQ0NdXAOq2NOXCosjCOABZkYWxNjZV5qiqzLGrskC10AKXhe7uIGVwC/8DAA "JavaScript (Node.js) – Try It Online")
### Commented
```
s => // s = input string: **TIddp[…]
// 0123456
'TI-' + // append the prefix
s[4] + // append the first digit (5th character)
s[5] + // append the second digit (6th character)
[ // wrapper to make sure that undefined is turned into an empty string
{P: '+'} // define an object with a single key 'P' mapped to the value '+'
[s[6]] // and attempt to retrieve this '+', using the 7th character
// (which is either 'P' or '*')
] // end of wrapper
```
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 28 bytes
```
,,..34{<{__5|..,;,;#@$_#_.@;
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/19HR0/P2KTapjo@3rRGT0/HWsda2UElXjlez8H6/38trRBPC@MAAA "Hexagony – Try It Online")
Accepts input on `stdin` and prints to `stdout`.
# Explanation
[](https://i.stack.imgur.com/bejlu.png)
I'll use the test case `**TI83P` for illustration.
Execution starts at the top left corner and follows instruction pointer 0 (IP0) along the red path.
* `,,` reads and discards the first two asterisks from `stdin`.
* `,;` reads the `T` from `stdin` and prints it to `stdout`.
* `,;` does the same but for the letter `I`.
At this point, the current memory edge holds the integer 73 (the ASCII character `I`).
* `#` takes the current memory edge modulo 6 (1 in this case) and transfers control to the corresponding instruction pointer.
This pauses IP0 at the `@` command and picks up execution in the top right corner, following IP1 along the blue path.
* `{` moves the memory pointer to its left neighbor.
Memory edges are 0 by default, so this is easier than trying to zero the previous edge.
* `45;` prints `-` to `stdout`.
* `,;,;` reads the two digits of the model number and prints them.
The zigzag pattern allows reuse of the same instructions that printed the letters `TI`.
* `{` moves the memory pointer again.
This instruction is superfluous, however, because
* `,` overwrites the current memory edge with the next character read from `stdin`.
This character is either `*` (ASCII 42) or `P` (ASCII 80).
* If it is `*`,
+ `#` transfers control back to IP0 (because 42 mod 6 = 0).
IP0 picks up at the `@` instruction, which finally terminates the program.
* If it is `P`,
+ `#` transfers control to IP2 (because 80 mod 6 = 2), which starts in the right corner and follows the grey path.
+ `$` skips the `;` instruction to avoid printing `P` to `stdout` instead of `+`.
+ `{43;` prints `+` to `stdout`.
+ `@` terminates the program.
---
I had a lot of fun (ab)using the `#` instruction with this solution.
*Image courtesy of Timwi's [HexagonyColorer](https://github.com/Timwi/HexagonyColorer).*
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), 21 bytes
```
I
^\*.|\*.*
P.*
I-
+
```
[Try it online!](https://tio.run/##KyxNTCn6/9@TKy5GS68GiLW4AoDYU5eLS/v/fy2tEE9LU62knMQMBRDBBRKwMA4A0@bGAVrpiUVJiempEHFTLQA "QuadR – Try It Online")
[Answer]
# [J](http://jsoftware.com/), 24 bytes
```
'TI-',4 5&{,'+'#~'P'=6&{
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/1UM8ddV1TBRM1ap11LXVlevUA9RtzdSq/2v@T1NQ19IK8bQ01VLngrItjAPgbHMktgWqGnd3BM9MK7E4JU3LEmyUUQCQow4A "J – Try It Online")
### How it works
```
'TI-',4 5&{,'+'#~'P'=6&{
'P'=6&{ 6th position = 'P'?
'+'#~ either take 0 or 1 '+' and
4 5&{, append it to the 4th and 5th char
'TI-', prepend 'TI-'
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 19 bytes
```
1M!`TI..P?
P
+
I
I-
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w39BXMSHEU08vwJ4rgEuby5PLU/f/fy2tEE9LUy0uEG1hHACmzaG0BULc3R3MsjQKCHCGMC3MtBKLU9K0LKHiQA4A "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
1M!`TI..P?
```
Extract the `TI`, 2 digits, and a possible trailing `P`.
```
P
+
```
If there was a `P` then change it to a `+`.
```
I
I-
```
Add a `-` after the `I`.
Retina 1 saves a byte because it uses `0L` instead of `1M!`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 16 bytes
```
TI-§θ⁴§θ⁵×+⁼P§θ⁶
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvREMpxFNXSdOaC8JzLPHMS0mt0CjUUTDRxCZqihANycxNLdZQ0lbSUXAtLE3MAbIDgGwkxWaaQGD9/7@WVoinpVFAgLP7f92yHAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
TI-
```
Print the initial `TI-`.
```
§θ⁴§θ⁵
```
Print the 4th and 5th characters of the input (0-indexed).
```
×+⁼P§θ⁶
```
Print as many `+`s as there are `P`s equal to the 6th character of the input.
[Answer]
# [Vyxal](https://github.com/Vyxal), 20 bytes
Port of [@Daniel H.](https://codegolf.stackexchange.com/questions/206158/what-calculator-is-this-datafile-for/206171#206171)'s answer.
```
`TI-`?46fiJ?6i×≠\+*J
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiYFRJLWA/NDZmaUo/NmnDl+KJoFxcKypKIiwiIiwiKipUSTgzUEdHXG4qKlRJODMqYWZkYVRJMzNQIl0=)
### Explained
```
`TI-`?46fiJ?6i×≠\+*J
`TI-` # Stack "TI-"
?46fi # Stack input[4:6]
J # Join
?6i×≠\+*J # Stack "+" and join if input[6] is equal to "*"
```
Basically my first vyxal answer, thanks so much to all who helped me, including @lyxal.
## 13 bytes @lyxal
```
7Ẏ‛P+*×P\-2Ṁ
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiN+G6jsOXb1xcSTrigLlW4oCbUCsqIiwiIiwiKipUSTgzUEdHXG4qKlRJODMqYWZkYVRJMzNQIl0=)
[Answer]
# [str](https://github.com/ConorOBrien-Foxx/str), 21 bytes
```
2G2G'-:2G:g'P='+x:O;q
```
Explanation:
```
2G Read the `**` at the beginning (this stays on the stack for the entire program, but does nothing)
2G Read the string `TI`
'-: Concatenate a - to it, to get `TI-`
2G: Read the next two characters (the version number) and concatenate them to the assembled string
g Read the next character (either `P` to signify I need to add a plus sign, or garbage)
'P= Check if it's equal to `P`, producing a zero or one
'+x: Repeat the string `+` a number of times equal to the number on top of the stack (zero or one in this case), and concatenate it to the assembled string
O;q Output the result, then tell the interpreter to ignore the rest of the input
```
[Try it online!](https://tio.run/##Ky4p@v/fyN3IXV3XysjdKl09wFZdu8LK37rw/38trRBPC@MAd3cA "str – Try It Online")
[Answer]
# [Befunge-93](https://github.com/catseye/Befunge-93), 27 bytes
```
~~~,~,"-",~,~,~"P"-#@_"+",@
```
[Try it online!](https://tio.run/##S0pNK81LT/3/v66uTqdOR0lXSQdE1ykFKOkqO8QraSvpOPz/r6UV4mlpGuDuDgA "Befunge-93 – Try It Online")
Read two characters (and ignore them). Read a char (`T`) and print it. Read another char (`I`) and print it. Print a `-`. Read a char (a digit) and print it. Read another char (a digit) and print it†. Read a char, end the program if it's not a `P`, else print a `+` and end the program.
†We cannot just read a number and print a number, as that will be printed with an additional trailing space.
[Answer]
# [Haskell](https://www.haskell.org/), 35 bytes
```
f s="TI-"++s!!4:s!!5:['+'|s!!6>'*']
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02h2FYpxFNXSVu7WFHRxApImFpFq2ur1wBZZnbqWuqx/3MTM/MUbBUy80pSixKTSxTS/mtphXhaGGu5uwMA "Haskell – Try It Online")
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 16 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
7<2/╞├'-⌐~'P='+*
```
[Try it online.](https://tio.run/##y00syUjPz0n7/9/cxkj/0dR5j6bMUdd91DOhTj3AVl1b6/9/JS2tEE9LUy0lLjDLwjgAyjKHsyyQZd3dYWwzrcTilDQtS7ABRgFAjhIA)
**Explanation:**
```
7< # Leave the first 7 characters of the (implicit) input-string
2/ # Split it into parts of size 2
╞ # Discard the first part (the "**")
├ # Remove and push the first part to the stack (the "TI")
'- '# Push "-"
⌐ # Rotate the stack once towards the left (so the remaining pair is at
# the top again)
~ # Pop and dump its contents onto the stack (the number and "*"/"P")
'P= '# Check if the top of the stack equal "P" (1 if truthy; 0 if falsey)
'+* '# Repeat "+" that many times ("+" if it was "P"; "" if not)
# (output the entire stack joined together implicitly as result)
```
[Answer]
# Rust macro, 135 bytes
```
macro_rules!f{(* * T I$($n:literal)*P$($x:tt)*)=>{[84,73,45,$($n+48,)*43]};(* * T I$($n:literal)**$($x:tt)*)=>{[84,73,45,$($n+48),*]};}
```
Defines a macro `f` that takes a list of tokens and returns an array of integers (ASCII chars).
[try it online](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&code=macro_rules!f%7B%0A%20%20%20%20(*%20*%20T%20I%20%24(%24n%3Aliteral)*%20P%20%24(%24x%3Att)*)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20%5B84%2C%2073%2C%2045%2C%20%24(%24n%2B48%2C)*%2043%5D%0A%20%20%20%20%7D%3B%0A%20%20%20%20(*%20*%20T%20I%20%24(%24n%3Aliteral)*%20*%20%24(%24x%3Att)*)%20%3D%3E%20%7B%0A%20%20%20%20%20%20%20%20%5B84%2C%2073%2C%2045%2C%20%24(%24n%2B48)%2C*%5D%0A%20%20%20%20%7D%3B%0A%7D%0Afn%20main()%20%7B%0A%20%20%20%20assert_eq!(%26f!(*%20*%20T%20I%209%205%20*)%2C%20%22TI-95%22.as_bytes())%3B%0A%20%20%20%20assert_eq!(%26f!(*%20*%20T%20I%208%203%20P)%2C%20%22TI-83%2B%22.as_bytes())%3B%0A%20%20%20%20assert_eq!(%26f!(*%20*%20T%20I%207%203%20P)%2C%20%22TI-73%2B%22.as_bytes())%3B%0A%20%20%20%20assert_eq!(%26f!(*%20*%20T%20I%208%205%20*)%2C%20%22TI-85%22.as_bytes())%3B%0A%20%20%20%20assert_eq!(%26f!(*%20*%20T%20I%208%203%20P%20G%20G)%2C%20%22TI-83%2B%22.as_bytes())%3B%0A%20%20%20%20assert_eq!(%26f!(*%20*%20T%20I%208%206%20*%20a%20s%20d%20f%20*%209%20*%20*%20T%20I%209%202%20P%20a%20s%20d)%2C%20%22TI-86%22.as_bytes())%3B%0A%7D)
## Explanation
```
macro_rules! f {
( // if the input has the following tokens:
* * T I // * * T I
$($n:literal)* // zero or more literals (called n)
P // P
$($x:tt)* // anything
) => { // expand to this:
[ // an array
84, 73, 45, // with the ASCII codes for TI-
$($n+48,)* // add 48 to each n and append a comma
43 // the ASCII code for +
]
};
( // if the input has the following tokens:
* * T I // * * T I
$($n:literal)* // zero or more literals (called n)
* // *
$($x:tt)* // anything
) => { // expand to this:
[ // an array
84, 73, 45, // with the ASCII codes for TI-
$($n+48),* // add 48 to each n and join with commas
]
};
}
```
[Answer]
# [PHP](https://php.net/), ~~39~~ ~~38~~ 36 bytes
```
fn($s)=>"TI-$s[4]$s[5]".'+'[$s[6]<P]
```
[Try it online!](https://tio.run/##K8go@G9jX5BRwKWSZvs/LU9DpVjT1k4pxFNXpTjaJBZImMYq6alrq0cDmWaxNgGx/625uFKTM/I1VNI0lLS0QjwtTbWUNBX0FJRi8pQ0rRUUFPT1FYD6LU1RlVkYB2BTZmGsjarOHLs6c3R1FtittcC01t0dWSHc2v8A "PHP – Try It Online")
Basically a port of Arnauld's answer with a bit of inspiration from Sqepia's one for the "+".. Let's say that's what I would have done anyway ;)
EDIT: saved 1 byte using `<` instead of `!=`
EDIT2: Thanks to Ismael Miguel for saving another 2 bytes using vars in double quotes!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 50 48 47 bytes
Thanks to Arnauld for the initial suggestion.
Not much to say here except that I conditionally print a plus sign at the end of the string if a `P` is in the seventh position.
```
f(char*s){printf("TI-%.2s%s",s+4,"+"+s[6]%80);}
```
[Try it online!](https://tio.run/##VY4/b8IwEMV3f4qTK1e2kyAKFIJMsyK2DGyoQ@rEYCk4KBfogPjqTZ3iDJ1@d@@9@6OTo9Z9b7g@Fa1Ecb@01nWG0/0uYZMZMqQxRouYRjTCw/KTpVOhHv2Ldbq@lhVssCttMzll5J9U269BI34XnAvr@K2xpYA7ARgOgURFfG2aliswqAtn@LDJxUDZ2d@EVxTZVMHl2iGnVMSmrSqOQsD4IEP4yMAn0ZveUeTRS7nfrd8l@eMsD3z26TpwGRhy6SIPDP18ZNDH@bcnVyG3Gv15vt3@aFMXR@yT718 "C (gcc) – Try It Online")
[Answer]
# Java 8, 35 bytes
```
a->"TI-"+a[4]+a[5]+(a[6]>79?"+":"")
```
[Try it online.](https://tio.run/##VZA/b8IwEMV3PsXJk@00GdryJyCoKgbEUIRUtijD1XGKaXCQbagQymdPTUhAXU7vnu7557sdnjDcZT@1KNBa@EClLz0ApZ00OQoJq2sL8OmM0t8gqNiiSVJANvF@1fPFOnRKwAo0TGsMZ2SzDEmAyWvqSz8NKCaDdDaM30hAxoSwenJNHY5fhU@14VOpMth7OL2BGsKNnJemNcFJ6@ZoJYxBy1/oRi@E880y7nPyBI0cvaw7OXzI0b@BxeLeDDjaLOdx88rz2jekYg3b7322Tu6j8uiig6e5QtPuF34bIIGOxN2JXDn353k3Bs@UsfZEVf0H)
**Explanation:**
```
a-> // Method with character-array parameter and String return-type
"TI-" // Return "TI-"
+a[4]+a[5] // Appended with the (0-based) 4th and 5th characters of the input
+(a[6]>79? // And if the (0-based) 6th character is larger than 'O' (thus 'P'):
"+" // Append a "+"
: // Else:
"") // Append nothing more
```
---
# C# .NET, 35 bytes
```
s=>"TI-"+s[4]+s[5]+(s[6]>79?"+":"")
```
Only difference is the `=>` instead of `->`, and the input parameter is a string instead of character-array. Apart from that it's the same as the Java lambda above.
[Try it online.](https://tio.run/##VY7NCoJAEIDvPsUwJ3fVS@Vfph2CROggJHQQD2Jr7WUDx@gQPfsmikaXme8b5q8hpyGpj0/V7KjvpLrZMOUEWog1xQkWmYMWlZtqCG5lmVR6VeKHe7Rwi8h0ZLSPTtTN3ZwmoRfUH2oSIBUo8YLzWC6rN3JeZKHL0YYRg3U@o//D4K8hTRfxeE3XlofjllU@CH6YAXDpZC9OUglzvjx8Bmi1izMW6S8)
[Answer]
# [Whitespace](https://web.archive.org/web/20150618184706/http://compsoc.dur.ac.uk/whitespace/tutorial.php), 150 bytes
```
[S S S N
_Push_0][S N
S _Dupe_0][S N
S _Dupe_0][S N
S _Dupe_0][T N
T S _Read_as_character_(*1)][T N
T S _Read_as_character_(*2)][T N
T S _Read_as_character_(T)][T T T _Retrieve][S N
S _Dupe][S N
S _Dupe][T N
S S _Print_as_character][T N
T S _Read_as_character_(I)][T T T _Retrieve][S N
S _Dupe][S N
S _Dupe][T N
S S _Print_as_chartacer][S S S T S T T S T N
_Push_45_-][T N
S S _Print_as_character][T N
T S _Read_as_character_(digit1)][T T T _Retrieve][S N
S _Dupe][S N
S _Dupe][T N
S S _Print_as_character][T N
T S _Read_as_character_(digit2)][T T T _Retrieve][S N
S _Dupe][S N
S _Dupe][T N
S S _Print_as_character][T N
T S _Read_as_character_(*/P)][T T T _Retrieve][S S S T S T S S S S N
_Push_80][T S S T _Subtract][N
T S N
_If_0_Jump_to_Label_P][N
N
N
_Exit][N
S S N
_Create_Label_P][S S S T S T S T T N
_Push_43_+][T N
S S _Print_as_character]
```
Letters `S` (space), `T` (tab), and `N` (new-line) added as highlighting only.
`[..._some_action]` added as explanation only.
[Try it online](https://tio.run/##K8/ILEktLkhMTv3/X0FBgQsIIYiTixOBOTlhggqYAkAAEgFJYJPGKQDWBtIN5IMFuUAAbD1YhhNi4P//WlohnhZmAVqJxSlpWpYgnqVRAJADAA) (with raw spaces, tabs and new-lines only).
**Explanation in pseudo-code:**
```
Character c = STDIN as character (the first leading "*")
c = STDIN as character (the second leading "*")
c = STDIN as character (the "T")
Print c as character to STDOUT
c = STDIN as character (the "I")
Print c as character to STDOUT
Print '-' as character to STDOUT
c = STDINT as character (the first digit)
Print c as character to STDOUT
c = STDIN as character (the second digit)
Print c as character to STDOUT
c = STDIN as character (the '*'/'P')
If(c == 'P'):
Print '+' as character to STDOUT
```
[Answer]
# SimpleTemplate, 52 bytes
So far, it is the 2nd longest answer, but works...
```
{@setA argv.0}TI-{@echoA.4,A.5}{@ifA.6 is equal"P"}+
```
Just naively grabs the characterss from the string, at a predefined position. Nothing fancy...
---
**Ungolfed:**
Both codes behave exactly the same:
```
{@set argument argv.0}
{@echo "TI-", argument.4, argument.5}
{@if argument.6 is equal to "P"}
{@echo "+"}
{@/}
```
Everything outside the code is just printed out.
Basically, `TI-` and `{@echo "TI-"}` do the same exact thing.
---
You can try this on <http://sandbox.onlinephpfunctions.com/code/1a2faee21e43109e148b057df65d2f119780ca45>
I've implemented this version, and an aditional version as a function, to compare outputs.
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 51 bytes
```
read a
b=${a:6:1}
b=${b%\*}
echo TI-${a:4:2}${b:++}
```
[Try it online!](https://tio.run/##S0oszvj/vyg1MUUhkSvJVqU60crMyrAWzExSjdGq5UpNzshXCPHUBUmZWBnVAsWttLVr///X0grxtDDTSixOSdOyBHGMjQKAHAA "Bash Try It Online")
Uses standard input and output.
a holds the first line, any other input is ignored.
b holds the \* or P after the number, and then the \* is removed.
data is assumed to be correct.
The echo outputs the three pieces, adding the + only if b is non-blank.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 33 bytes
Port of [Daniel H.‘s Python answer](https://codegolf.stackexchange.com/a/206171/11261).
```
->s{"TI-"+s[4,2]+(s[6]>?*??+:"")}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpcsEiN9ulpSVpuhY3FXXtiquVQjx1lbSLo010jGK1NYqjzWLt7LXs7bWtlJQ0a6EKFYJDXDz99FITkzPiczLzUhWqa3JqFApKS4oV3KJzYhWg6hbcdNTSCvG0NNXiAtEWxgFg2hxKWyDE3d0hLDOtxOKUNC1LsDajACAHYhIA)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 21 bytes
```
++"TI-":z4 6*\+q@z6\P
```
[Test suite](https://pythtemp.herokuapp.com/?code=%2B%2B%22TI-%22%3Az4+6%2a%5C%2Bq%40z6%5CP&test_suite=1&test_suite_input=%2a%2aTI95%2a%0A%2a%2aTI83P%0A%2a%2aTI73P%0A%2a%2aTI85%2a%0A%2a%2aTI83PGG%0A%2a%2aTI86%2aasdf%2a9%2a%2aTI92Pasd&debug=0)
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), 29 bytes
```
O+"TI-"+G=sP4 2*"+">Gs 6 1'*'
```
[Try it online!](https://knight-lang.netlify.app/#WyJPK1wiVEktXCIrRz1zUDQgMipcIitcIj5HcyA2IDEnKiciLCIqKlRJNzNQIiwiMi4wIl0=)
[Answer]
# [Go](https://go.dev), 95 bytes
```
import."strings"
func f(s string)string{R:=Replace
return"TI-"+R(R(s[4:7],"P","+",1),"*","",1)}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70oPX_BzoLE5OzE9FSF3MTMPK7M3IL8ohI9pbTcEqWlpSVpuhY342FixSVFmXnpxUpcaaV5yQppGsUKEBFNCFUdZGUblFqQk5icylWUWlJalKcU4qmrpB2kEaRRHG1iZR6roxSgpKOkraRjqKmjpAVkgli1EGtuMRqCjQW5QkOzmisAaGRJTp6GkpZWiKelKVC1Asg4S1MgIw0hqqmJqtLCOACq0sJYG6EUJIyu1Byu1BxZqTkWpRZw-y2Q7LfAbr-7Ow4XACUwlJtpJRanpGlZgv1jFADkwDSbIenFogpoEjTkFiyA0AA)
] |
[Question]
[
Here's a very simple little problem that I don't believe has been asked before.
# Challenge
Write a program or a function that takes in four positive integers that represents the lengths of movable but unbreakable and unbendable straight fences. Output the area of the largest rectangular yard that can be fully encompassed with these fences.
The fences can be moved and rotated in increments of 90°, but can't overlap or be cut.
Fences that just touch at a yard corner still count as encompassing the yard at that corner.
For example, given fence lengths 2, 8, 5, and 9, the best you can do is to make the 2 and 5 sides parallel, and the 8 and 9 sides parallel for a yard that is 2 by 8:
```
888888885
2yyyyyyyy5
2yyyyyyyy5
9999999995
5
```
Make any one side longer and the fences won't fully surround the yard. Thus the output here, the area of the yard, would be 16.
As another example, given 1, 1, 2, 2, the largest area yard that can be made is 2:
```
22
1yy1
22
```
A yard with area 1 like
```
22
1y1
22
```
is a valid yard since it's perimeter is fully fenced, but 1 is an invalid output since it's not maximal.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest program wins!
You may *not* assume the 4 integer inputs to your program are in any particular order.
Here are some more test cases:
```
Inputs -> Output
1,1,1,1 -> 1
1,2,3,4 -> 3
4,3,2,1 -> 3
90,1,2,1 -> 2
1,90,1,1 -> 1
44,51,50,36 -> 1800
3,3,3,3 -> 9
3,3,3,4 -> 9
3,4,3,4 -> 12
4,4,3,4 -> 12
4,4,4,4 -> 16
```
[Answer]
# Python, 28 bytes
```
lambda*a:min(a)*sorted(a)[2]
```
It's an anonymous function that when called returns the answer, like `func(2,8,9,5) -> 16` or `func(1,1,2,2) -> 2`.
Unless I'm totally misunderstanding my own problem, I believe it can be solved by sorting the 4 input numbers and taking the smallest times the second biggest, since those sides will be matched parallel with the second smallest and the biggest respectively.
Like if the sorted inputs are `a <= b <= c <= d` then the biggest rect you can make will have area `a * c`, where side `a` is parallel to `b` and `c` parallel to `d`, and some of the `b` and `d` fences may have to be wasted.
(I'm a new user here so I'd love to know if this Python can be shortened at all. Thanks!)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `g`, 27 bits[v1](https://github.com/Vyxal/Vyncode/blob/main/README.md), 3.375 bytes
```
sI÷*
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJBZz0iLCIiLCJzScO3KiIsIiIsIlsyLCAyLCAxLCAxXVxuWzgsIDUsIDIsIDldXG5bMiwgOSwgOCwgNV1cblszLCAzLCAzLCAzXVxuWzEsIDIsIDEsIDJdIl0=)
What I was thinking is that the side lengths can be split into two groups: those likely to be the long side of the rectangle and those likely to be the short side.
The long side of the rectangle will be the second most longest side, as it's guaranteed to be smaller or equal to than the other longer side.
The short side of the rectangle will be the shortest side, as it's guaranteed to be smaller than or equal to the other short side.
For example:
```
[2, 5, 8, 9]
```
The side length of 9 can't be the long side because there's no matching 9. But the side length of 8 can be because it's got that length in the 9. Hence, the second smallest length is the long side.
The side length of 5 can't be the short side, because there's no matching 5. But the side length of 2 can be because it's got that length in 5. Hence the smallest length is the short side.
## Explained
```
sI÷*
s # sort the list ascending. The idea here is that the sides that are more likely to be the longer sides go to the end of the list and the ones likely to be the shorter sides go to the front.
I # split the list into two halves - [shorts, longs]
÷* # dump each item onto the stack and multiply each item in shorts by each item in long.
# the g flag gets the smallest item of that list, which is also the first item.
```
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 7 bytes
```
&napfp*
```
[Try it online!](https://tio.run/##y6n8/18tL7EgrUDr/38TEy5TQy5TAy5jMwA "Ly – Try It Online")
Similar to other solutions, this sorts the numbers the messes with the stack to get the smallest and second largest. Then it multiples them to get the answer.
```
&n - read in all the numbers
a - sort
p - discard top (largest)
f - flip two entries (pushes 2nd largest down)
p - discard top (3rd largest)
* - multiple what's left (smallest and 2nd largest)
- exits and prints what's on the stack as a number
```
[Answer]
# Excel, 22 bytes
```
=MIN(A:A)*SMALL(A:A,3)
```
The `SMALL()` function finds the nth smallest number in a range.
[](https://i.stack.imgur.com/w2BI2.png)
[](https://i.stack.imgur.com/ak8u6.png)
[Answer]
# [Nekomata](https://github.com/AlephAlpha/Nekomata), 4 bytes
```
o;*ṁ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70iLzU7PzexJHFZtJJurlLsgqWlJWm6FsvyrbUe7mxcUpyUXAwVWnCzONpQBwxjuYAsIx1jHRMgywRIG4HFLA10DKFMQx0wB8Q0MdExNdQxNdAxNgPyjHXAEM4yAbNM4GYhs4AwFmI3AA)
```
o;*ṁ
o Sort
; Nondeterministically split the list into two parts
* Multiply; fails if the two parts have different lengths
ṁ Take the minimum
```
[Answer]
# [Julia](https://julialang.org), 24 21 **bytes**
-3 bytes: by @MarcMush
```
!a=(b=sort(a))[1]b[3]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=fY9BCsIwEEXX5hQjbloZoWmiqBDxAp6gdJHWFCsSJWn1MG668QgewUN4G9Oo1YXILMJ7n_xhzpdtvStlc78VSudKJCSh6CcFsQCKLcfIkHtmjrmj-JW3PIuQdiL2H7z6NHCOY4rjCNnk6aZR5DRDP17NOuZfzDumsd_8Q_C3mCBJL3VVjKbXvhRBJuzeVIEMw4SmWcJe2f1U7A0EpT6g1DaEUoO_nPSW0lplKui7TAgXEqXXhAzgSOdQBBI_jSJzncO21MV5bYzS1XIlTb6q7WYOf9Y3zfN9AA)
[Answer]
# [Arturo](https://arturo-lang.io), 20 bytes
```
$->a[sort'a a\0*a\2]
```
[Try it](http://arturo-lang.io/playground?Vyx02s)
Sort the lengths then multiply the first by the third. Same algorithm as blaketyro arrived at independently.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Linux utilities, 19
```
sort -n|dc -e??k?*p
```
Reads input from lines of STDIN.
### Explanation
```
sort -n # sort numerically
| # pipe to ...
dc -e # ... dc expression
?? # push [1] and [2]
k # pop [2] to precision register (unused)
? # push [3]
* # pop and multiply [1] and [3]
p # print
```
[Try it online!](https://tio.run/##S0oszvj/vzi/qERBN68mJVlBN9XePtteq@D/fxMTLlNDLlMDLmMzAA "Bash – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṣm2P
```
A monadic Link that accepts a list of the four fence lengths and yields the maximal yard area.
**[Try it online!](https://tio.run/##y0rNyan8///hzkW5RgH///@PNtKx0DHVsYwFAA "Jelly – Try It Online")**
### How?
```
Ṣm2P - Link: list of integers, F
Ṣ - sort -> [a, b, c, d]
m2 - modulo-2 slice -> [a, c]
P - product -> a × c
```
[Answer]
# [R](https://www.r-project.org/), 28 bytes
```
function(l)min(l)*sort(l)[3]
```
[Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9PI0czNxNEahXnF5UA6Wjj2P9pGskaJjomOsY6JpqaXGkaJlaGmv8B "R – Try It Online")
-2 bytes thanks to pajonk.
# [R](https://www.r-project.org/), 30 bytes
```
function(l)prod(sort(l)[!0:1])
```
[Try it online!](https://tio.run/##K/qfZqP7P600L7kkMz9PI0ezoCg/RaM4v6gEyI5WNLAyjNX8n6aRrGGiY6JjrGOiqcmVpmFiZaj5HwA "R – Try It Online")
[Answer]
# [J](https://www.jsoftware.com), 8 bytes
```
]`*/@\:~
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT31NAVbKwV1BR0FAwUrINbVU3AO8nFbWlqSpmuxIjZBS98hxqoOwr25RpMrNTkjXyFNwRACEVwjBWMFExjXBMgxQshaGoAVIKkGi8D5JiYKpoYKpgYKxmYwIWMIROWaILgmqNZhcIEQ4uYFCyA0AA)
Sort down, then reduce from the right by alternatingly taking the right value and multiplying:
```
\:~2 8 5 9
9 8 5 2
]`*/9 8 5 2
9]8*5]2 -> 9]8*2 -> 9]16 -> 16
```
[Answer]
# [Factor](https://factorcode.org) + `math.unicode`, 19 bytes
```
[ sort <evens> Π ]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=bdBNDsFAFAfw2PYUfwdo048hvmIrNjZiJRZNPTR0WjNTIeIkNt1wAfdwAKdR0yoSeYv38nsfmcz5uvADFYvsUTMn4-Fo0IGMhQr5EpK2KfGApEV7JXyJyFcrK-VhEM8JaxKcNkgEKXVIRMjVZwFdwzgaRzhlnFCH2YejyYUH9iYvJ5aD-5l6UdvWg5W5elPrzzXG0HDQsOE1K27Zdt7xyii1XRH7JfZNjquf89_YlzWN0yVVC7N1m-rvQo92xGUf9wyzonOJ_ARWUWdZkZ8)
Sort the input, get the elements at even indices, then take the product.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 26 bytes
```
N`
.+¶.+¶(.+)¶.+
$.($&*$1*
```
[Try it online!](https://tio.run/##K0otycxLNPyvqhGcoPPfL4FLT/vQNhDW0NPWBLG4VPQ0VNS0VAy1/v831AFDLkMdIx1jHRMuEyBpBORbGugYghmGOmCmIZeJiY6poY6pgY6xGZexDhhCaRMgbQLVjaCBEAA "Retina – Try It Online") Takes input on separate lines but link is to test suite that splits on commas for convenience. Explanation: Port of @blaketyro's Python answer.
```
N`
```
Sort numerically.
```
.+¶.+¶(.+)¶.+
$.($&*$1*
```
Multiply the first number by the third.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 13 bytes
```
I×⌊θ⌈Φθ⁻κ⌕θ⌈θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEIyQzN7VYwzczLzO3NFejUFNHwTexAsx2y8wpSS3SKASKZOaVFmtk6yi4ZealgAWgSgo1ocD6///oaBMTHVNDHVMDHWOz2Nj/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a list of four elements. Explanation:
```
θ Input list
⌊ Take the minimum
× Multiplied by
θ Input list
Φ Filtered where
κ Current index
⁻ Subtract i.e. is not equal to
θ Input list
⌈ Take the maximum
⌕ First index in
θ Input list
⌈ Take the maximum
I Cast to string
Implicitly print
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 5 bytes
```
*F%2S
```
[Try it online!](https://tio.run/##K6gsyfj/X8tN1Sj4//9oExMdU0MdUwMdY7NYAA "Pyth – Try It Online")
### Explanation
```
*F%2SQ # implicitly add Q
# implicitly assign Q = eval(input())
SQ # sort Q
%2 # take every other element (so first and third)
*F # reduce on multiplication
```
[Answer]
# [Scala](https://www.scala-lang.org/), 25 bytes
Saved bytes thanks to the comments of @corvus\_192 and @user
---
Golfed version (25 bytes). [Try it online!](https://tio.run/##fZJLa8MwDMfv@RRaycEOacmrZS1LoIwddhg7rPfhJu7IyBIvVsZg9LNnsps@V2aMXz/pLyFZ56ISfbN@lznCSmq8F1pqkN8o60LDUin4cb5EBZsFe6zR42lGW9qLNBOTj7L2xEQ3LcpigqKsWMh7AGOOB6kUnoRiDtB4kZ8s9GGYHMYZHU5J5EPsQ2JJfCSJfY72PidkHlitA4rO5Ab6J1JCglMCU@LxbEdvg@BoENuAZlo4v0KSKyQ5IWF0lv//KDmgGRHu0LJpWmCsrFWHPrVDUX9k8dwh3TncjY8F5tQgo2aq3krdVUgl3@w8F/DqcUuF1rJFtjdILyR90KOH4QXcS7buEN4aBHdwN7lZfXDtNjIxtiZr1ZY1VjUbLavdH4DcfgJl4hc3ZLh1@l8)
```
a=>a.min*a.sorted.tail(1)
```
Alternative:
```
//scala 3
import scala.util.chaining._
def f(a:Int*):Int = a.sorted.pipe(a=>a(0)*a(2))
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `M`, 4 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Ṡz€p
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faGm0kq9S7IKlpSVpuhYrHu5cUPWoaU3BkuKk5GKo4IK10SYmOqaGOqYGOsZmsRBBAA)
#### Explanation
```
Ṡz€p # Implicit input
Ṡ # Sort in ascending order
z # Uninterleave ([a, b, c, d] -> [[a, c], [b, d]])
€p # Product of each inner pair
# Implicit output of minimum (M flag)
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{ιPß
```
[Try it online](https://tio.run/##yy9OTMpM/f@/@tzOgMPz//@PNtIx1bHQsYwFAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/6nM7Aw7P/6/zPzraSMdUx0LHMlYn2lAHDMEsIx1jHRMgywRIG4HFLA10DKFMQx0wB8Q0MdExNdQxNdAxNgPyjHXAEM4yAbNM4GYhs4AwNhYA).
**Explanation:**
```
{ # Sort the (implicit) input-quartet from lowest to highest
ι # Uninterleave it into two parts: [a,b,c,d]→[[a,c],[b,d]]
P # Get the product of both inner lists
ß # Get the minimum of this pair
# (which is output implicitly as result)
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt) [`-g`](https://codegolf.meta.stackexchange.com/a/14339/), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
Íó Ë×
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWc&code=zfMgy9c&input=WzQ0LDUxLDUwLDM2XQ) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=zfMgy9c&footer=Zw&input=WwpbMSwxLDEsMV0KWzEsMiwzLDRdCls0LDMsMiwxXQpbOTAsMSwyLDFdClsxLDkwLDEsMV0KWzQ0LDUxLDUwLDM2XQpbMywzLDMsM10KWzMsMywzLDRdClszLDQsMyw0XQpbNCw0LDMsNF0KWzQsNCw0LDRdCl0tbVI)
```
Íó Ë× :Implicit input of array
Í :Sort
ó :Uninterleave
Ë :Map
× : Reduce by multiplication
:Implicit output of first element
```
[Answer]
# [Desmos](https://desmos.com/calculator), 19 bytes
```
f(l)=l.minl.sort[3]
```
[Try It On Desmos!](https://www.desmos.com/calculator/66pwlknqki)
Port of literally all the other answers here.
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 30 bytes
```
$_=(@F=sort{$a-$b}@F)[0]*$F[2]
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3lbDwc22OL@opFolUVclqdbBTTPaIFZLxS3aKPb/fxMTBVNDBVMDBWOzf/kFJZn5ecX/dX19MotLrKxCSzJzbAuK8lNKk0uAgqZ6BoYG/3ULEnMA "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 21 bytes
```
->*l{l.sort![2]*l[0]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf104rpzpHrzi/qEQx2ihWKyfaILb2f4FCWrShjqGOkY5RLBeIY6ljoWMK5PwHAA "Ruby – Try It Online")
Nothing particularly original here.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 7 bytes
```
×´0‿2⊏∧
```
[Try it](https://mlochbaum.github.io/BQN/try.html#code=RuKGkMOXwrQw4oC/MuKKj+KIpwoKRsKo4p+oMeKAvzHigL8x4oC/MSDii4QgMeKAvzLigL8z4oC/NCDii4QgNOKAvzPigL8y4oC/MSDii4QgOTDigL8x4oC/MuKAvzEg4ouEIDHigL85MOKAvzHigL8xIOKLhAogICA0NOKAvzUx4oC/NTDigL8zNiDii4QgM+KAvzPigL8z4oC/MyDii4QgM+KAvzPigL8z4oC/NCDii4QgM+KAvzTigL8z4oC/NCDii4QgNOKAvzTigL8z4oC/NCDii4QgNOKAvzTigL804oC/NCDin6k=)
```
∧ # ascending sort
0‿2⊏ # select first and third elements
×´ # product
```
[Answer]
# C (gcc), 59 bytes
```
g(a,b)int*a,*b;{b=*a-*b;}f(int*l){qsort(l,4,4,g);*l*=l[2];}
```
[Try it online!](https://tio.run/##RYtBDsIgEEX3nILUmACZmqqtG6wXqV1QsJUEqbbohnB2pNHo/M3k//dkPkgZ40AEdFRbxwSwjvuuZiJPT@jJUhrqH/M4OWKgTBkoZ4bVptm1PMSVttI81QUfZ6f0uLmeEEoSvgltyWvUiiKP8PeWwejZNS2usS9LqLZQFbA/BP5jerIQ9F/cp6T1JFurs83g4xdtAkJ8Aw)
Takes a 4-element integer array as input and stores the result in the first element of that array. It can probably be shortened, but it's still one of my better submissions :)
Explanation:
```
// This will be used as a comparison function for qsort(), so that
// integers can be sorted in ascending order.
g(a,b)int*a,*b;
{
b=*a-*b;
}
f(int*l)
{
// Sort l, assuming it has 4 elements with element size 4 (which is usually
// the size of integers in bytes), and using g() as a comparator.
qsort(l,4,4,g);
// Stores the first (minimum) element of l times the second-largest element
// in the first element of l.
*l*=l[2];
}
```
46-byte version using some complicated flag (`-zexecstack`), suggested by @ceilingcat:
```
f(int*l){qsort(l,4,4,"\x8b\7+\6ð");*l*=l[2];}
```
[Try it online!](https://tio.run/##RYxRDoIwAEP/OcWCMdlwGFRAE8SLMD5wY7g4h7JpiIQ7eQfv5YRotP1rX0v9ilJrORTKeBJ1F103BkocDnZJu9mT9YzEz4eLEk96qcyWedLbiVBUXlkJttowUc8PO8cZDsCpEAreasGQ0zngq7GQQpssBynowhBHCxwFeBX3yY/hcCTQPzg3w4xDd8qIcvFnH@QD0NsX5bKotPXvZVtSbQp6fAM)
[Answer]
# [Lua](https://www.lua.org/), 35 bytes
```
table.sort(arg)print(arg[1]*arg[3])
```
[Try it online!](https://tio.run/##yylN/P@/JDEpJ1WvOL@oRCOxKF2zoCgzD8yKNozVAlHGsZr///83Mflvavjf1OC/sRkA "Lua – Try It Online")
] |
[Question]
[
This is the robber's thread. The [cop's thread is here](https://codegolf.stackexchange.com/questions/112299/cops-crack-the-regex-make-a-snake).
---
A snake matrix is a square matrix that follows this pattern:
3-by-3:
```
1 2 3
6 5 4
7 8 9
```
and 4-by-4:
```
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
```
Your task is to write a code that takes an input `n` and creates such a matrix, in the same language as a cop post, and with a code that matches the cop's regex. The output format of your code must match the output format of the cop's code.
Please leave a comment under the Cop's post to indicate that you have cracked it.
**Winning criterion:**
The winner will be the user that has cracked the most submissions. In case of a tie, then there will be multiple winners.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes, cracks [@Dennis' answer](https://codegolf.stackexchange.com/a/112304/62131)
```
²sµUFḤ$¦G
```
[Try it online!](https://tio.run/nexus/jelly#@39oU/GhraFuD3csUTm0zP3///@mAA "Jelly – TIO Nexus")
Should be correct now; I had to rather rethink what I was doing.
## Explanation
The hardest part of this problem is getting a list of the even indices inside the `¦` (which applies an operation at specific indices). Unlike most operations, which use the input to the whole program as a default for the second operand, `¦` uses the most recently seen value as a default (because it conceptually has two left operands, rather than a left and a right operand like most things that take in two values).
However, we can observe that we have a list of numbers, including all integers from 1 to half the input, already in the current value at the time. As such, flattening and doubling it gives us a list of even numbers, including all the even indices (also some other even numbers but we don't care about those). It's even possible to spend one `µ` solely to avoid a parsing ambiguity and still come in within 9 characters.
```
²sµUFḤ$¦G
s Split
² {the list of numbers from 1 to} the square of {the input}
µ into a number of pieces equal to {the input};
U then reverse
¦ the elements at indexes
F obtained by flattening the split list
$ and
·∏§ doubling each element in the flattened list;
G finally, format it into a grid.
```
[Answer]
# [05AB1E, Emigna](https://codegolf.stackexchange.com/a/112302/34718)
This was my first time using 05AB1E. Got it with a little bit of help. That was fun. :)
```
UXFXLNX*+N2BSR1k_iR}ÀÜ
```
[**Try it online**](https://tio.run/nexus/05ab1e#@x8a4Rbh4xehpe1n5BQcZJgdnxlUe7rt/38TAA)
**Explanation:**
```
U Assign input to X
XF For N in range(0,X):
XL Push list [1 .. X]
NX*+ Add N*X to each element of the list
N2BSR1k_ Super clever way to get N%2:
not bool(reversed(str(bin(N))).index('1')) (N%2 is odd)
iR} if N%2 is odd, then reverse the list
ÀÜ Add row to global array
Implicit print
```
I actually found this similar program on my own, but the output format is different:
```
UXFXLNX*+N2BSR1k_iR}=
```
[**Try it online**](https://tio.run/nexus/05ab1e#@x8a4Rbh4xehpe1n5BQcZJgdnxlUa/v/vwkA)
```
[1, 2, 3, 4]
[8, 7, 6, 5]
[9, 10, 11, 12]
[16, 15, 14, 13]
```
See the edit history for my previous two attempts.
[Answer]
# Python 2, [Dennis](https://codegolf.stackexchange.com/a/112371/45268)
This is a fun token golfing problem.
```
while ord>eval:1;int,eval=int<1and(int,eval+1)or(-input(),1);i=int;ord=i*i;print'%*s'%(-i,(eval+~i+~-eval%-i*~1,eval)[eval/i&1])+'\nt'[:-1<eval%int],
```
[Regex verification](https://regex101.com/r/bqyfyL/1)
[Answer]
# [Ohm, Nick Clifford](https://codegolf.stackexchange.com/a/112316/47066)
My first time attempting Ohm.
Really nice language that I look forward to use again :)
```
²@┼σ▓_^è?R
```
**Explanation**
```
² # square input
@ # range [1 ... input^2]
┼σ # split in input sized chunks
‚ñì # perform the following block on each element of the array
_ # current element
^è? # if index is odd
R # reverse
```
My first attempt that didn't work as adding an array and an int is not possible:
```
@┼MDR┼+;W
```
My second attempt that didn't match the regex:
```
²@┼σ▓_^MR
```
[Answer]
# [05AB1E, Emigna (2nd submission)](https://codegolf.stackexchange.com/a/112346/52194)
First time working with 05AB1E.
```
VYLUYFYXDÀÜ+RU
```
[Try it online!](https://tio.run/nexus/05ab1e#@x8W6RMa6RYZ4XK6TTso9P9/EwA "05AB1E – TIO Nexus") | [Regex verification](https://regex101.com/r/YRaqdG/2)
**Explanation**
```
VYLUYFYXDÀÜ+RU # Implicit input
V # Save input to Y
YL # Push [1 .. Y]
U # Save list to X
YF # Repeat Y times:
YX # Push Y, then X
DÀÜ # Add X into the global array (could've used X here instead)
+ # Push X + Y
R # Reverse top of stack
U # Save updated list to X
# Implicit loop end
# Implicit global array print if stack is empty
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), [Lynn](https://codegolf.stackexchange.com/a/112747/8478)
```
esmpmpmeimtmemqmememqicelic
esmpmpmeimememqmlmtmemoc
esmpmpmeimememqmtmtmtmtmeic
esmpmpmeimememqmtmtmtmtmeic
esmpmpmeimeiscic
esmpmpmeimemeimfsic
esmpmpmeisciscimqmtmemeic
esmpmpmeiscimlmqmqmemeic
esmpmpmeimemomqmqmemeic
esmpmpmeisciscimfsimqic
esmpmpmeimeiscic
esmpmpmeisciscimfsimqic
esmpmpmeimemomqmemqmemtmemoc
esmpmpmeiscic
esmpmpmeimemomeimqmeic
esmpmpmeimemeimqmlmtmeic
esmpmpmeimtmtmqmemtmtmeic
esmpmpmeimemomqmqmtmeic
esmpmpmeimemqmqmemeic
esmpmpmeiscimlmqmqmemeic
esmpmpmeiscimqmtmtmtmqmemeic
esmpmpmeimeimemtmqmemeic
esmpmpmeimeiscimlmlmtmlmtic
esmpmpmeimemeimqmlmtmeic
~~
```
All linefeeds are for cosmetic purposes and can be removed without affecting the program.
[Try it online!](https://tio.run/nexus/cjam#jVFbCsAgDPvfeXYj6aBgcaLfu7prq7L5GsMXJDU2MUGgkwcgRQLyvHhHAxbN9nCKktUaNxKxDMDfHAbTFyMd4Y1xBU@VgPa6wJYJ3xPS3gwvUqwv5j76WBeqcE6oT2Gw4uTwYxxYQ2wISSfLxoWbEZ97nIdSQ6zv9D@hT8@IrCgN8/rycl0p7Tc "CJam – TIO Nexus")
### Explanation
After Lynn removed `{|}` from the list of allowed characters, I had to try something new. It turns out we can still construct arbitrary strings and evaluate them as code.
First, we need to get some value onto the stack. The only available built-ins that push something without popping something else first (and without reading the input) are `es`, `ea` and `et`. I'm sure you could start from all of these one way or another, but I went with `es` which pushes the current timestamp. Since I didn't want to make any assumptions about its actual value, I test its primality with `mp` (which gives `0` and `1`) and test that value's primality again to ensure I've got a `0` on the stack. A `1` will be more useful, so we compute `exp(0)` with `me` and turn it into an integer with `i`. So all the numbers start with:
```
esmpmpmei
```
Now we've got a whole bunch of unary maths operators to work with:
```
i int(x) (floor for positive numbers, ceiling for negative)
me exp(x)
ml ln(x)
mq sqrt(x)
mo round(x)
mt tan(x)
```
We can also combine a few built-ins for more elaborate functions of `x`:
```
sci Extract first digit of x and add 48 (convert to string, convert
to character, convert to integer).
ceui Convert to character, convert to upper case, convert to integer.
celi Convert to character, convert to lower case, convert to integer.
mfsi Get a sorted list of prime factors of x and concatenate them into
a new number.
mfseei Get a sorted list of prime factors, interleave it with 1,2,3,..., and
concatenate the result into a new number.
```
Using these, we can obtain any number in `0 <= x < 128` (and many others) in less than 10 steps from `1`. I'm sure a much smaller subset of these commands would also suffice. I've written a small Mathematica program, to determine all of these snippets (it's not very readable, sorry):
```
codes = SortBy[
Select[Nest[Select[DeleteDuplicatesBy[SortBy[Join @@ (Through[{
List,
If[1 <= # < 50, {Exp@#, #2 <> "me"}, Nothing] &,
If[# >= 1, {Log@#, #2 <> "ml"}, Nothing] &,
If[# > 1, {Sqrt@#, #2 <> "mq"}, Nothing] &,
{If[# > 0, Floor@#, Ceiling@#], #2 <> "i"} &,
{Floor[# + 1/2], #2 <> "mo"} &,
{Tan@#, #2 <> "mt"} &,
If[NumberQ@# && # >= 0, {First@
ToCharacterCode@ToString@#, #2 <> "sci"},
Nothing] &,
If[IntegerQ@# &&
32 < # < 65536, {First@
ToCharacterCode@
ToUpperCase@FromCharacterCode@#, #2 <> "ceui"},
Nothing] &,
If[IntegerQ@# &&
32 < # < 65536, {First@
ToCharacterCode@
ToLowerCase@FromCharacterCode@#, #2 <> "celi"},
Nothing] &,
If[IntegerQ@# && # > 0, ## & @@ {
{FromDigits[
"" <> (ToString /@ (f =
Join @@ Table @@@ FactorInteger@#))], #2 <>
"mfsi"},
{FromDigits[
"" <> (ToString /@
MapIndexed[## & @@ {#2[[1]] - 1, #} &, f])], #2 <>
"mfeesi"}
}, Nothing] &
}@##] &) @@@ #, StringLength@*Last],
First], #[[1]] < 1000000 &] &, {{1, "esmpmpmei"}}, 9],
IntegerQ@# && 0 <= # < 128 &@*First], First]
```
With that, we can simply push an arbitrary list of character codes, converting each of them to a character with `c` afterwards. Once we've pushed the entire code we want to execute, we push `95` (`]`). We eval that one with `~` to wrap all the others in a string, and then we eval that string with `~`.
The actual code run at the end of the program is again:
```
ri__2#,:)/2/[1W]f.%:~<p
```
See [my previous solution](https://codegolf.stackexchange.com/a/112743/8478) for an explanation.
[Answer]
# [Python 3, TuukkaX](https://codegolf.stackexchange.com/a/112347/52194)
Sorry, the regex you used was too easy to trivialize. No `0`, `#` or ? No problem!
I might've misinterpreted the example output but it's still pretty easy to tweak since I have 45 spare characters left over
```
n=int(input())
print(str(n)+":")
x=1-1
exec("print([*range(1+x*n,1+n*-~x)][::(1,-1)[x%2]]);x+=1;"*n)
"no-op:a_string_that_doesnt_actually_matter"
```
[Answer]
# R, [MickyT](https://codegolf.stackexchange.com/questions/112299/cops-make-a-regex-make-a-snake/112328#112328)
```
lets_make_a_snake<-function(n)`for`(i,1:n,cat(i*n+1-`if`(i%%2,n:1,1:n),"\n"))
```
Tests cases:
```
> lets_make_a_snake(4)
1 2 3 4
8 7 6 5
9 10 11 12
16 15 14 13
> lets_make_a_snake(7)
1 2 3 4 5 6 7
14 13 12 11 10 9 8
15 16 17 18 19 20 21
28 27 26 25 24 23 22
29 30 31 32 33 34 35
42 41 40 39 38 37 36
43 44 45 46 47 48 49
```
And regex confirmation: <https://regex101.com/r/OB8ZIM/1>
I also had:
```
invisible(sapply(1:(n=scan()),function(i)cat(i*n+1-`if`(i%%2,n:1,1:n),"\n")))
```
which gives the same output and [match the same regex](https://regex101.com/r/sAzKwY/1).
[Answer]
# [Röda](https://github.com/fergusq/roda/tree/roda-0.12), [fergusq](https://codegolf.stackexchange.com/a/112387/41805)
```
{|i|;a=1;while[a<=i]do;b=a*i-i+1;c=[];while[b<=a*i]do;c+=b;b++;done;{d=[];x=0;while[x<i]do;d+=c[i-x-1];x++;done[d]}if[a%2<1]else{[c]};a++;done;r="||||||"}
```
This is an anonymous function that matches this PCRE regex: `^{(\|[^\/#\s]*){8}$`.
[Try it online!](https://tio.run/nexus/roda#NY7LCsMgFET3@QoJdFMRYunuer9EXPgquZAm0C4qqN9ua7CznHMYpj0t7SxPjK3IcqECFiV8VtqitgrJhAMc2isJ4hI8ajOgU73t2HN04DiHcOwRcuhOwmV4SZ1S4Og1iSTkDw5XB1Ppoe3lpqSJ2ztm7U0F@5964VzOzLX/Y/eptvYF "Röda – TIO Nexus")
[Answer]
# Bash, [@Marcos M](https://codegolf.stackexchange.com/a/112561/32353)
```
sort -n <(seq 1 $((n * n)) | xargs -n$n | sed -n 'p;n'; seq $((n * n)) 1 | xargs -n$n | sort -n | sed -n 'n;p')
```
Prettified:
```
sort -n <( # feed the stdout of this subshell into stdin for `sort -n`
seq 1 $((n * n)) | # generate 1 2 3 ... n²
xargs -n$n | # add line break every n numbers
sed -n 'p;n'; # print only odd lines
seq $((n * n)) 1 | # generate n² ... 3 2 1
xargs -n$n | # add line break every n numbers
sort -n | # reverse all lines (keeping each row decreasing)
sed -n 'n;p' # print only even lines
)
```
The first part of the subcommand will generate `1 2 3 4`, `9 10 11 12`, and the second part will generate `8 7 6 5`, `16 15 14 13`. The outer `sort -n` will properly mix them together to form the snake pattern.
I used the trick in <https://superuser.com/a/101760> to print the odd and even lines. Thank you Marcos, really a fun one.
[Answer]
# [Javascript, Tom](https://codegolf.stackexchange.com/a/112310/64121)
```
f=(a,i=1,j=0)=>Array(a).fill(0).map(b=>Array(a).fill(0).map(a=>i++)).map(a=>j++%2?a.reverse():a).map(a=>a)
console.log(f(4))
```
[Answer]
# Python 3, [@TuukkaX](https://codegolf.stackexchange.com/a/112390/32353)
```
n=int(input());j=0;exec("print([(j-+i%n-n++2*n-0,j+i%n+1)[1&int(i/n)//1^(0x1)//1]*(2*(i%n)*0+2222222//2222222)for i in range(j,j+n)]);j+=n;"*n)
```
* Verify: <https://regex101.com/r/GI1Zvh/1>
---
Slightly analyzing the cop's regex shows a fixed template:
```
________________________"___________i%n____2*n-____i%n__________i/n)//1_____)//1___2*(i%n)____^^^^^^^^^^^^^^^^for i in range(j,____])______"*n)
```
where `_` is any character except `[ '"#]` and `^` is any of `[int()2/]`.
The `"*n)` at the end clearly shows an `eval("..."*n)` or `exec("..."*n)` is going on, so we just need to make sure the `"..."` prints the j-th row.
The `for i in range(j,` is too close to the end of the string, hinting list comprehension without any `if`. So we need to construct the i-th column using those `i%n`, `2*n` stuff.
```
n = int(input())
j=0
exec("""print([
(
j - +i%n - n ++ 2*n - 0, # equivalent to (n + j - i%n) for the decreasing rows
j + i%n + 1 # equivalent to (j + i%n + 1 == i + 1) for the increasing rows
)[1 & int(i/n)//1 ^ (0x1)//1] # int(i/n) -> get row number 0, 1, 2, 3, ...;
# 1 & int(i/n)//1 -> 0 for increasing rows, 1 for decreasing rows,
# 1 & int(i/n)//1 ^ (0x1)//1 -> flip 0 and 1
* (2*(i%n)*0+2222222//2222222) # multiply by the constant 1.
for i in range(j,j+n)
]); j+=n; "*n)
```
[Answer]
## [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), [Mitchell Spector](https://codegolf.stackexchange.com/a/112350/59010)
This was my first entry to a cops and robbers challenge, and I had a lot of fun. The regex needed to be matched was simple, `^[^# !]{59}$`, which basically turned my job into a golfing one, without using those 3 characters. Initially I had difficulties getting below 60 bytes, but I cracked it in the end.
```
?sN0[AP]sP[ddlN~_2*lN+1-r2%*+1+n32P1+dlN%0=PdlNd*>L]dsLxqqq
```
**[Try it online!](https://tio.run/nexus/dc#@29f7GcQ7RgQWxwQnZKS41cXb6SV46dtqFtkpKqlbaidZ2wUYKgNlFA1sA0AUiladj6xKcU@FYWFhf//mwAA)**
**Explanation:**
My code uses one loop with N 2 iterations, keeping a zero based counter (1D), and calculates what number needs to be printed based on the corresponding matrix row and column (r, c) coordinates.
Example of what I mean, if N = 4:
```
0 1 2 3 (0,0) (0,1) (0,2) (0,3) 1 2 3 4
4 5 6 7 -> (1,0) (1,1) (1,2) (1,3) -> 8 7 6 5
8 9 10 11 (2,0) (2,1) (2,2) (2,3) 9 10 11 12
12 13 14 15 (3,0) (3,1) (3,2) (3,3) 16 15 14 13
```
It looks complicated, but the intermediary step is helpful. Plus, I've tried using 2 loops from the start, but I ended up above the regex character limit. Number generation at each iteration (zero based):
* if `r % 2 = 0` (normal row), `n = (r * N) + c = counter`
* if `r % 2 = 1` (reversed row), `n = ((r + 1) * N) - c - 1 = counter + N - (2 * c) - 1`
Or all at once, as one based numbering: `n = counter + ((N - (2 * c) - 1) * (r % 2)); n++`
```
?sN0 # read input, save as N, initialize iteration counter
[AP]sP # macro 'P' that prints a newline (ASCII code 10 = A)
[ # start loop
ddlN~ # push N, calculate row and column coordinates:
#r = int(counter / N), c = counter % N, '~' calculates both
_2*lN+1- # c is on top, so this does: N - (2 * c) - 1
r2%*+ # now r is on top, do: (r % 2) * (previous result) + counter
1+n32P # do: n++, print space (ASCII code 32)
1+ # increment counter
dlN%0=P # call macro 'P' every Nth printed number
dlNd*>L # if: N * N > counter, repeat loop
]dsLx # this saves the loop to macro 'L', then executes it
qqq # my script was shorter, so I added a bunch of quit commands to
#fit the regex limit. Use of comments ('#') was prohibited.
```
[Answer]
## PowerShell, [ConnorLSW](https://codegolf.stackexchange.com/a/112541/52023)
Crack
```
$mySnakeIndex=1;$seq=1..$args[0];$seq|%{$rowNum=$seq|%{($mySnakeIndex++)};if(!($_%2)){[array]::Reverse($rowNum)};$rowNum-join" "}
```
I started with a smaller solution to the issue and padded my variable names to get the regex to match. Trying to find a use for the colon I suppose was the hardest part to wrap my head around.
```
$a=1..$args[0];$i=1;$a|%{$r=$a|%{($i++)};if(!($_%2)){[array]::Reverse($r)};$r-join" "}
```
# Explanation
```
# Initialize a counter that starts at one.
$mySnakeIndex=1
# Save the integer array from 1 to the input value.
$seq=1..$args[0]
# For each row of the output...
$seq|%{
# Build the integer array for this row sequentially
$rowNum=$seq|%{
# Increase the integer index while sending it down the pipeline
($mySnakeIndex++)}
# Check if this is and odd row. If so reverse the integer array.
if(!($_%2)){[array]::Reverse($rowNum)}
# Take this row and join all the numbers with spaces.
$rowNum-join" "
```
[Answer]
## CJam, [Lynn](https://codegolf.stackexchange.com/a/112715/8478)
Something like this:
```
ri
{s}seu~~ci{zs}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c{z}seu~~{w}seu~~sc~c{w}seu~~z{w}seu~~sc~c~
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c
{s}seu~~c{a}seu~~|
{s}seu~~c{c}seu~~|
{t}seu~~sc{a}seu~~|
{s}seu~~c{a}seu~~|{w}seu~~z{w}seu~~sc~c
{s}seu~~sc{fb}seu~~||
{s}seu~~sc{i}seu~~|
{s}seu~~sc{fb}seu~~||
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c{z}seu~~{w}seu~~sc~c{w}seu~~z{w}seu~~sc~c
{a}seu~~scs
{w}seu~~
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{z}seu~~{w}seu~~sc~c
{fb}s{b}s{w}seu~~sc~
{s}seu~~sc{ee}seu~~||
{s}seu~~sc{z}seu~~|{w}seu~~{w}seu~~sc~{w}seu~~{w}seu~~sc~
{t}seu~~sc{a}seu~~|
{~}s{}s{w}seu~~sc~
{t}seu~~sc{c}seu~~|
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{z}seu~~{w}seu~~sc~c~
s~
p
```
All whitespace is for... "readability"... and can be omitted to comply with Lynn's regex.
[Try it online!](https://tio.run/nexus/cjam#xVFBCoQwDLznPX5IS4XeZOMiNG6@3q3W1FqCdL3soTBMZjJNEl4OCD9o38zGkRdIfQIr05KQF4Amln3CF04TMlzaH67GlH9bs7CgTKZmsWgyoe4TonccDuVasq7uqCt/H675cCCN0CBIoTFYyYD9@7S9ky2ns1bbg6/WWJgVSr8Jx8wq9pTlcz4fjQEZphC6Lw "CJam – TIO Nexus")
### Explanation
The regex requires that we solve problem using only:
* Lower-case letters.
* `{}`, which can be used to create blocks.
* `|`, mostly used for bitwise OR.
* `~`, "eval" and bitwise NOT (also "dump array", but I'm not going to use it).
Since we have, `~`, if we can construct arbitrary strings, we can run arbitrary code. However, at first it's not obvious how to do that.
The first piece of the puzzle is that blocks are unevaluated bits of code, which can turn into strings with `s`. So `{abc}s` gives us `"{abc}"`. Next, we can use `eu` to convert these strings to upper case.
```
{abc}seu e# gives "{ABC}"
```
The benefit of this is that upper-case letters are pre-initialised variables, so we can get a lot of constant values by creating such a string, and eval'ing it twice (once to turn the string back into a block and once to execute that block). We can't get all the letters, because some, like `x` aren't valid commands (so CJam will refuse to parse a block containing them). We can't use `f` as is, because it needs to be followed by another command, but we can use `fb` and then OR the two values together. Likewise, we can use `ee` instead of `e`. With that, we can get the numbers `0`, `-1`, `3`, and `10` to `19`. The `-1` is convenient, because if we turn it into a string (`"-1"`) then into a character (`'-`) and then eval it, we can get either subtraction or set difference. Like I said, we can't get `X` (for `1`), but we can take the absolute value of `-1` with `z`.
We can also use `s` to get a string containing a space, and use `c` to turn that into a space *character*:
```
{s}seu~~c
```
This is convenient, because from there we can get lots of useful commands in the lower ASCII range by ORing the space with various numbers. To get some of the characters above code point `48`, we use the character `'0` as the basis instead:
```
{t}seu~~si
```
This is already enough to construct arbitrary strings, because we can get `'+` (addition and string concatenation) from the following snippet:
```
{s}seu~~c{b}seu~~|
```
And we have a literal `1` so we can just push space characters, increment them to the value we need and then concatenate them all together, but that's a bit boring and the code would become massive.
Instead, I've generated `[` and `]` and evalled them, so that all the characters I push in between are wrapped in a string automatically. That's these two lines:
```
{s}seu~~ci{zs}seu~~c{a}seu~~|~{w}seu~~z{w}seu~~sc~c{z}seu~~{w}seu~~sc~c{w}seu~~z{w}seu~~sc~c~
...
{s}seu~~ci{z}seu~~{s}seu~~c{a}seu~~|~{z}seu~~{w}seu~~sc~c~
```
And finally, we'll need `f` and `~` in the string we're generating. While those are valid characters already, we don't have string literals or character literals, so we'd have to generate these as well and building up larger code points from the space is a bit annoying. Instead, I've made use of the set subtraction here, but subtracting two blocks (to get rid of the `{}`):
```
{fb}s{b}s{w}seu~~sc~
...
{~}s{}s{w}seu~~sc~
```
That's pretty much all there is to it. We eval `[`. We push all the characters, obtained by various computations from the few built-in constants we have, `|`, `-` (via eval) and `+` (via eval). We eval `]`. We flatten the entire thing into a string, because at some point I added some strings or numbers into the list. We eval our arbitrary string with `~`.
The `ri...p` are part of the actual final program, but I've extracted them because they don't need encoding.
Finally, this is the program we're actually running:
```
ri___*,:)/2/[1-1]f.%:~<p
ri e# Read input and convert to integer.
__ e# Make two copies.
_* e# Square the last copy.
, e# Turn into range [0 1 ... n^2-1].
:) e# Increment each to get [1 2 ... n^2].
/ e# Split into chunks of length n, creating a square.
2/ e# Split into pairs of lines.
[1-1] e# Push [1 -1].
f.% e# Use this to reverse the second line in each pair. If n was odd,
e# this will pair a -1 with the last line.
:~ e# Flatten the pairs back into the square.
< e# Truncate to n lines to get rid of that extraneous -1 for odd inputs.
p e# Pretty-print.
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), [@DLosc](https://codegolf.stackexchange.com/a/112721/56183)
```
(v(c(h(q(d)))(c(h(q(f)))(q((c(q(n))(q((g(v(h(q(n))))(s(v(h(q(n))))(v(h(q(1)))))())))))))))(v(c(h(q(d)))(c(h(q(mod)))(q((c(c(h(q(x)))(q(y)))(q((i(l(v(h(q(x))))(v(h(q(y)))))x(mod(s(v(h(q(x))))(v(h(q(y)))))y))))))))))(v(c(h(q(d)))(c(h(q(range)))(q((c(c(h(q(x)))(c(h(q(y)))(c(h(q(z)))(q(w)))))(q((i(l(times(v(h(q(z))))(v(h(q(x))))(v(h(q(0)))))(times(v(h(q(z))))(v(h(q(y))))(v(h(q(0))))))(range(v(h(q(x))))(s(v(h(q(y))))(v(h(q(z)))))z(c(s(v(h(q(y))))(v(h(q(z)))))w))w)))))))))(v(c(h(q(d)))(c(h(q(times)))(q((c(c(h(q(x)))(c(h(q(y)))(q(acc))))(q((i(l(v(h(q(x))))(v(h(q(0)))))(times(s(v(h(q(0))))(v(h(q(x)))))(s(v(h(q(0))))(v(h(q(y)))))acc)(i(e(v(h(q(x))))(v(h(q(0)))))acc(times(s(v(h(q(x))))(v(h(q(1)))))y(a(v(h(q(y))))(v(h(q(acc))))))))))))))))(v(c(h(q(d)))(c(h(q(g)))(q((c(c(h(q(n)))(c(h(q(w)))(q(r))))(q((i(l(v(h(q(w))))(v(h(q(0)))))r(g(v(h(q(n))))(s(v(h(q(w))))(v(h(q(1)))))(c(i(e(v(h(q(0))))(mod(v(h(q(w))))(v(h(q(2))))))(range(a(v(h(q(1))))(times(v(h(q(w))))(v(h(q(n))))(v(h(q(0))))))(a(a(v(h(q(1))))(times(v(h(q(w))))(v(h(q(n))))(v(h(q(0))))))n)1())(range(a(times(v(h(q(w))))(v(h(q(n))))(v(h(q(0)))))n)(times(v(h(q(w))))(v(h(q(n))))(v(h(q(0)))))(s(v(h(q(0))))(v(h(q(1)))))()))r)))))))))))
```
[Try it online!](https://tio.run/nexus/tinylisp#nVTbDoMgDP2VPbZvc9kPEXS6ZLKoyxB/3iFlWgTdhfjQ0tPTQymO8AQJFTSQI6I3L5PZgPUaUGSWFleRaze6wCM7Q@fgvFLM9T2fuWmnJ9/47SvcPF/PuI0j7Kf0uXYcN/u1W6HKIlVdzhzeHAilicqrelzr4l17YLW5jiNlbEFNBEVSFVB1CbRjwcHq245q9@00wMn60IAGhJS4exnBITu@ycGYDNEVTSUsebFJbgEr/j6aNAMi0Qqvnq9UK8pVG9QS0hRq4yboSGe78S50/C4kOzB1ZBrmGH4K5kJwkmCueI5KzJX4P1dhBkzB95nqlzLJ@Vh@Ii27wREuhzOOLw "tinylisp – TIO Nexus")
This defines a function `f` that returns the answer. It also prints the names of the functions I defined to stdout, but I assume that doesn't matter, since [we're allowed to choose our output stream] for code golf, at least. If it's a big deal, I think I can tweak it to not print those. How did I do it? I started with something fairly standard:
```
(d f (q ((n)
(g n (s n 1) ()))))
(d mod (q((x y)
(i (l x y) x
(mod (s x y) y)))))
(d range (q((x y z w)
(i (l (times z x 0) (times z y 0))
(range x (s y z) z (c (s y z) w))
w))))
(d times (q ((x y acc)
(i (l x 0) (times (s 0 x) (s 0 y) acc)
(i (e x 0) acc
(times (s x 1) y (a y acc)))))))
(d g (q ((n w r)
(i (l w 0) r
(g n (s w 1)
(c (i (e 0 (mod w 2))
(range (a 1 (times w n 0)) (a (a 1 (times w n 0)) n) 1 ())
(range (a (times w n 0) n) (times w n 0) (s 0 1) ()))
r))))))
```
Then, I observed that one can transform functions definitions like this:
```
(d mod (q ((x y) (body))))
```
becomes
```
(v(c(h(q(d)))(c(h(q(mod)))(q((c(c(h(q(x)))(q(y)))(q((body)))))))))
```
And function calls like this:
```
(a x y)
```
becomes
```
(a(v(h(q(x))))y)
```
I used this recursive Vim macro, stored in register `q`, to do the second one (I have `jk` mapped to `<Esc>`): `f s(v(h(q(jkea))))jk@q`.
These two transformations were sufficient to eliminate all spaces.
[Answer]
# Swift, [@James Webster](https://codegolf.stackexchange.com/a/112388/32353)
```
{n in for j in 0..<n{print((1...n).map{j%2==0 ?$0+j*n:j*n+n+1-$0})}} as(CShort)->()
```
Verification: <https://regex101.com/r/7ukrM0/1>
[Answer]
# PHP, [@JörgHülsermann](https://codegolf.stackexchange.com/a/112325/32353)
```
<?=(function($n,$snake){foreach(array_chunk(range(1,$n*$n),$n)as$i=>$a){if($i%2)$a=array_reverse($a);echo"\n",join('',array_map(function($e){return(sprintf("%3d",$e));},$a));}})($argv[1],'-=-=-=-=-=-=-=-=-=-=-=-=-=-o~')?>
```
* Verify: <https://regex101.com/r/81pUrB/1>
* TIO: <https://tio.run/#aNvF0>
---
221 bytes is too long (thus the snake), and the lack of whitespace can be easily worked-around.
Prettified:
```
<?=
(
function($n, $snake) {
foreach (array_chunk(range(1, $n*$n), $n) as $i => $a) {
if($i % 2)
$a = array_reverse($a);
echo "\n", join('', array_map(function($e) {
return (sprintf("%3d", $e));
}, $a));
}
}
)($argv[1], '-=-=-=-=-=-=-=-=-=-=-=-=-=-o~')
?>
```
[Answer]
# [Jelly, length 12, @JonathanAllan](https://codegolf.stackexchange.com/a/112438/12012)
```
Ḷ-*m@"s@²$G
```
[Try it online!](https://tio.run/nexus/jelly#@/9wxzZdrVwHpWKHQ5tU3P///28CAA "Jelly – TIO Nexus")
### How it works
```
Ḷ-*m@"s@²$G Main link. Argument: n
·∏∂ Unlength; yield [0, ..., n-1].
-* Yield [(-1)**0, ..., (-1)**(n-1)].
$ Combine the two links to the left into a chain.
² Yield n².
s@ Split [1, ..., n²] into chunks of length n.
m@" Take the lists to the right modulo the units to the left, 1 being
normal order and -1 being reversed.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes, cracks [@JonathanAllan's second answer](https://codegolf.stackexchange.com/a/112472/62131)
```
²sµ;@/€FḤ$¦G
```
[Try it online!](https://tio.run/nexus/jelly#ARgA5///wrJzwrU7QC/igqxG4bikJMKmR////zQ "Jelly – TIO Nexus")
## Explanation
This is almost the same as [my other answer](https://codegolf.stackexchange.com/a/112349/62131). I just made two changes:
First, I changed `U` ("reverse each element") to `Ṛ€` ("reverse" "each element"). That doesn't help by itself, because `Ṛ` is also banned.
Then, I changed the `·πö` ("reverse") to `;@/` (`/` "fold by" `;` "concatenating" `@` "in the opposite order to the original list"). That avoids all the banned characters, giving a valid solution.
I assume the next step would be to start banning array-manipulation *quicks*, in addition to the atoms.
[Answer]
# [Jelly, length 13, @JonathanAllan](https://codegolf.stackexchange.com/a/112492/12012)
```
1r-*Nm@"s@²$G
```
[Try it online!](https://tio.run/nexus/jelly#@29YpKvll@ugVOxwaJOK@////00A "Jelly – TIO Nexus")
### How it works
```
1r-*Nm@"s@²$G Main link. Argument: n
1r Range 1; yield [1, ..., n].
-* Yield [(-1)**1, ..., (-1)**n].
N Negate each unit.
$ Combine the two links to the left into a chain.
² Yield n².
s@ Split [1, ..., n²] into chunks of length n.
m@" Take the lists to the right modulo the units to the left, 1 being
normal order and -1 being reversed.
```
[Answer]
# [Jelly, length 14, @JonathanAllan](https://codegolf.stackexchange.com/a/112496/12012)
```
²sµðạ"J×2$$¦GµL.xị"ḅ1µ$
```
[Try it online!](https://tio.run/nexus/jelly#ASkA1v//wrJzwrXDsOG6oSJKw5cyJCTCpkfCtUwueOG7iyLhuIUxwrUk////NA "Jelly – TIO Nexus")
[Answer]
# [Scala, @Soapy](https://codegolf.stackexchange.com/questions/112299/cops-make-a-regex-make-a-snake/112429#112429)
```
def g(n:Int) = {
var vec = Vector.fill(0)(Vector.fill(0)(1))
for (p <- 1 to n) {
var vec2 = Vector.fill(0)(1)
for (q <- (p-1)*n+1 to p*n) {
vec2 = vec2 ++ Vector(q)
}
if (p%2==1) vec = vec ++ Vector(vec2)
else vec = vec ++ Vector(vec2.reverse)
}
println(vec)
}
```
Haven't touched Scala in awhile, it was fun to revisit. Unfortunately, this solution misses out on a lot of Scala's cool features.
[Try it out here](https://scalafiddle.io/sf/03K0lrG/1)
[Regex Confirmation](https://regex101.com/r/qCDbWS/1)
[Answer]
# QBasic (QB64), [@DLosc](https://codegolf.stackexchange.com/a/112376/32353)
Note that since the `.` does not match `\n` (U+000A, LF), the newline here is a `\r` (U+000D, CR).
```
INPUT N:ZERO=N-N:ONE=N/N:FOR I=ZERO TO N-ONE:FOR J=ONE TO N:IF ZERO=I MOD(ONE+ONE)THEN PRINT I*N+J;ELSE PRINT I*N+N-J+ONE;REM
NEXT:PRINT:NEXT
```
Verify:
```
>>> re.match('^([A-Z]+.)+$', 'INPUT N:ZERO=N-N:ONE=N/N:FOR I=ZERO TO N-ONE:FOR J=ONE TO N:IF ZERO=I MOD(ONE+ONE)THEN PRINT I*N+J;ELSE PRINT I*N+N-J+ONE;REM\rNEXT:PRINT:NEXT')
<_sre.SRE_Match object; span=(0, 141), match='INPUT N:ZERO=N-N:ONE=N/N:FOR I=ZERO TO N-ONE:FOR >
```
---
The main difficulty is how to insert a word after the `;`. Thankfully, QB64 treats CR as a newline while Python's regex doesn't, so we could slip a `REM\r` here. Out of the five allowed regex flavors,
* Perl accepts `"\r" =~ /./`
* JavaScript **rejects** `!/./.test('\r')` ([`\n`, `\r`, `\u2028`, `\u2029` are all line separators](https://tc39.github.io/ecma262/#prod-LineTerminatorSequence))
* Python accepts `re.match('.', '\r')` ([only `\n` is considered a line break](https://github.com/python/cpython/blob/b5c51d3dd95bbfde533655fb86ac0f96f771ba7b/Modules/_sre.c#L101-L102))
* Golang accepts `regexp.Match(".", "\r")`
* Ruby accepts `/./ =~ "\r"`
So this crack is fine as long as we don't mention JavaScript... ü§ê
[Answer]
# Python 3, [kennytm](https://codegolf.stackexchange.com/a/112596/45268)
```
def S(N,A=1,K=1,E=list,r=range):print(E(r(A,A+N)[::K]))or(A>N*N-N)or(((S(N,A+N,-K))))
```
[Regex verification](https://regex101.com/r/c4o1gd/1)
[Answer]
# ><>, [torcado](https://codegolf.stackexchange.com/a/112479/41881)
```
!v &0_!
_<>~ao1+>_v_
?______;__>:&:&=?;::2%:}+&:&*{3+0$.
?!v1+:n' 'o:&:&%_
?!v:n' 'o1-:&:&%_
```
[Answer]
# C, [@Yimin Rong](https://codegolf.stackexchange.com/a/112418/32353)
```
main(int c,char**p){int n=atoi(*++p),i=n-n,t,o=c;for(--o;i<n;++i)for(t=o;t<=n;++t)printf("%-*d%c",n-o,i%c?i*n+n+o-t:i*n+t,t%n?' ':'\n');}
```
The program cannot contain numbers, but we can get numbers via:
1. `c`, commonly known as "argc", which is always 2.
2. `+` and `-` are available, so we can create 0 with `n-n`, and create 1 with `o=c;--o`.
[Answer]
# Ruby, [@Value Ink](https://codegolf.stackexchange.com/a/112321/32353)
```
->n{(1..n).map{|r|x=(r*n-n+1..r*n).to_a;if(r.modulo(2)==1)then(x)else(x.reverse)end}}#1-2-3-4-5-6--
```
`[(-=Z-~]*` means "I can write anything I like :)"
[Answer]
# tinylisp, [@DLosc](https://codegolf.stackexchange.com/a/112605/32353)
A very straightforward solution, and totally unoptimized :)
```
(d p(q((m n)(s m(s(s 1 1)n)))))(d j(q((f g)(i(l f g)(c f(j(p f 1) g))()))))(d r(q((f g)(i(l f g)(c(s g 1)(r f(s g 1)))()))))(d k(q((m o f g n)(i(l n g)()(c(m f(p f n))(k o m(p f n)(p g 1) n))))))(d f(q((n)(k j r 1 1 n))))
```
Call as `(disp (f 4))`.
* `(p m n)` computes m + n using subtraction `s` (m + n == m - ((1 - 1) - n))
* `(j f g)` generates `(f f+1 f+2 ... g-1)`
* `(r f g)` generates `(g-1 g-2 g-3 ... f)`
* `(k m o f g n)` generate one row of the snake matrix, and then recurve itself for the next row, until n rows are created. The arguments `m`, `o` are substituted by `j`/`r` to generate increasing or decreasing rows. The arguments `f`, `g` are running indices to know which row we are on.
* `(f n)` calls `(k j r 1 1 n)` to start the generation.
[Answer]
# PHP, [@Ionut Botizan](https://codegolf.stackexchange.com/questions/112299/cops-make-a-regex-make-a-snake/112606#112606)
In the moment I have no better idea to crack the original solution.
Supports n<=15
It is the first time that I use getopt. Maybe not the best idea to use options as input.
start from the command line like this
```
php hack.php -a=4
```
## Original Regex
Level 1:
```
^<[^'"\d{vV;<$]+$
```
Very nice combination of letters. Feel free to vote up the cops thread.
It blocks me functions like
- strrev
- array\_reverse
- get\_defined\_vars
<https://regex101.com/r/5rGTnw/2>
Level 2:
```
^<[^'"\d{v;<$_~|&A-Z]+$
```
<https://regex101.com/r/XtVl9G/1>
## Solution
```
<?php
error_reporting(~E_NOTICE)&
define(A,a.chr(E_COMPILE_ERROR-E_NOTICE+E_WARNING))
&define(B,getopt(A,[])[a])&print_r(array_chunk(
array_slice(
array_merge(
range(E_ERROR,B)
,range(E_WARNING*B,E_ERROR+B)
,range(E_WARNING*B+E_ERROR,(E_WARNING+E_ERROR)*B)
,range(E_PARSE*B,+E_ERROR+(E_WARNING+E_ERROR)*B)
,range(E_PARSE*B+E_ERROR,(E_PARSE+E_ERROR)*B)
,range((E_PARSE+E_WARNING)*B,+E_ERROR+(E_PARSE+E_ERROR)*B)
,range((E_PARSE+E_WARNING)*B+E_ERROR,(E_NOTICE-E_ERROR)*B)
,range(E_NOTICE*B,+E_ERROR+(E_NOTICE-E_ERROR)*B)
,range(E_NOTICE*B+E_ERROR,(E_NOTICE+E_ERROR)*B)
,range((E_NOTICE+E_WARNING)*B,E_ERROR+(E_NOTICE+E_ERROR)*B)
,range((E_NOTICE+E_WARNING)*B+E_ERROR,(E_NOTICE+E_WARNING+E_ERROR)*B)
,range((E_NOTICE+E_PARSE)*B,E_ERROR+(E_NOTICE+E_WARNING+E_ERROR)*B)
,range((E_NOTICE+E_PARSE)*B+E_ERROR,(E_NOTICE+E_PARSE+E_ERROR)*B)
,range((E_CORE_ERROR-E_WARNING)*B,E_ERROR+(E_NOTICE+E_PARSE+E_ERROR)*B)
,range((E_CORE_ERROR-E_WARNING)*B+E_ERROR,(E_CORE_ERROR-E_ERROR)*B)
)
,B-B,B*B
),B)
)
?>
```
Level 2:
```
<?php
define(aa,a.chr(ord(strtoupper(a))-ord(h)+ord(a)))and
define(bb,getopt(aa,[])[a])and
define(us,chr(ord(a)-true-true))and
(prin.t.(us).r)(
(arra.y.(us).chunk)(
(arra.y.(us).slice)(
(arra.y.(us).merge)(
range((ord(b)-ord(a)),bb)
,range((ord(c)-ord(a))*bb,(ord(b)-ord(a))+bb)
,range((ord(c)-ord(a))*bb+(ord(b)-ord(a)),((ord(c)-ord(a))+(ord(b)-ord(a)))*bb)
,range((ord(e)-ord(a))*bb,+(ord(b)-ord(a))+((ord(c)-ord(a))+(ord(b)-ord(a)))*bb)
,range((ord(e)-ord(a))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(c)-ord(a)))*bb,+(ord(b)-ord(a))+((ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(c)-ord(a)))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))-(ord(b)-ord(a)))*bb)
,range((ord(e)-ord(a))*bb,+(ord(b)-ord(a))+((ord(e)-ord(a))-(ord(b)-ord(a)))*bb)
,range((ord(e)-ord(a))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(c)-ord(a)))*bb,(ord(b)-ord(a))+((ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(c)-ord(a)))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))+(ord(c)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(e)-ord(a)))*bb,(ord(b)-ord(a))+((ord(e)-ord(a))+(ord(c)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(e)-ord(a))+(ord(e)-ord(a)))*bb+(ord(b)-ord(a)),((ord(e)-ord(a))+(ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(q)-ord(a))-(ord(c)-ord(a)))*bb,(ord(b)-ord(a))+((ord(e)-ord(a))+(ord(e)-ord(a))+(ord(b)-ord(a)))*bb)
,range(((ord(q)-ord(a))-(ord(c)-ord(a)))*bb+(ord(b)-ord(a)),((ord(q)-ord(a))-(ord(b)-ord(a)))*bb)
)
,bb-bb,bb*bb
),bb)
)
?>
```
] |
[Question]
[
The **Sixers sequence** is a name that can be given to sequence [A087409](http://oeis.org/A087409). I learned about this sequence in a [Numberphile video](https://youtu.be/OeGSQggDkxI?t=114), and it can be constructed as follows:
First, take the multiples of 6, written in base 10:
`6, 12, 18, 24, 30, 36, ...`
Next, concatenate the numbers into a stream of digits:
`61218243036...`
Finally, regroup the stream into pairs and interpret each as an integer:
`61, 21, 82, 43, 3, ...`
As we're grouping the numbers into pairs, the maximum number in the sequence will be 99, and it turns out that all non-negative integers less than 100 are represented in the sequence. This challenge is to find the index of the first instance of a number in the Sixers sequence.
## Input
An integer in the range `[0-99]`. You do not need to account for numbers outside this range, and your solution can have any behaviour if such an input is given.
## Output
The index of the first occurrence of the input number in the Sixers sequence. This may be 0- or 1-indexed; please say which you are using in your answer.
## Rules
* The procedure to generate the sequence noted in the introduction is for illustrative purposes only, you can use any method you like as long as the results are the same.
* You can submit full programs or functions.
* Any sensible methods of input and output are allowed.
* Standard loopholes are disallowed.
* Links to test your code online are recommended!
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in each language wins!
## Test cases
Here is a list of all input and outputs, in the format `input, 0-indexed output, 1-indexed output`.
```
0 241 242
1 21 22
2 16 17
3 4 5
4 96 97
5 126 127
6 9 10
7 171 172
8 201 202
9 14 15
10 17 18
11 277 278
12 20 21
13 23 24
14 19 20
15 29 30
16 32 33
17 297 298
18 35 36
19 38 39
20 41 42
21 1 2
22 46 47
23 69 70
24 6 7
25 53 54
26 22 23
27 11 12
28 62 63
29 219 220
30 65 66
31 68 69
32 71 72
33 74 75
34 49 50
35 357 358
36 80 81
37 83 84
38 25 26
39 89 90
40 92 93
41 27 28
42 42 43
43 3 4
44 101 102
45 104 105
46 8 9
47 177 178
48 110 111
49 13 14
50 28 29
51 119 120
52 122 123
53 417 418
54 79 80
55 128 129
56 131 132
57 134 135
58 55 56
59 437 438
60 140 141
61 0 1
62 31 32
63 75 76
64 5 6
65 120 121
66 82 83
67 10 11
68 161 162
69 164 165
70 58 59
71 477 478
72 170 171
73 173 174
74 34 35
75 179 180
76 182 183
77 497 498
78 85 86
79 188 189
80 191 192
81 18 19
82 2 3
83 78 79
84 93 94
85 7 8
86 37 38
87 168 169
88 12 13
89 228 229
90 88 89
91 218 219
92 221 222
93 224 225
94 64 65
95 557 558
96 230 231
97 233 234
98 40 41
99 239 240
```
[Answer]
# JavaScript (ES6), ~~71 65~~ 55 bytes
Output is 0-indexed.
```
n=>(g=([a,b,...c])=>b?a+b-n&&1+g(c):g([a]+6*++i))(i='')
```
[Try it online!](https://tio.run/##FcpBCoMwEEDRvaeYhehMR4NuuqiNPUgRjKmGiEyKlm7Es6d29@H92XzNZlf//pQSXmOcdBTdotP4NMVQKKVsR7odHoaHUrKsZoeWbu7kjq8XZk@EXuc5xSmsKKChakDgDnX1D2aCPQGwQbawjGoJDnuD6S4HnW@6Tyh09NQkR/wB "JavaScript (Node.js) – Try It Online")
### How?
Using a recursive function, we either 'consume' the first 2 characters of the string of concatenated multiples of \$6\$, or append new characters if we have less than 2 of them.
Example for \$n=3\$:
```
string | operation | result
--------+------------------------------------+--------
'' | not enough characters: append '6' | 0
'6' | not enough characters: append '12' | 0
'612' | consume '61', increment the result | 1
'2' | not enough characters: append '18' | 1
'218' | consume '21', increment the result | 2
'8' | not enough characters: append '24' | 2
'824' | consume '82', increment the result | 3
'4' | not enough characters: append '30' | 3
'430' | consume '43', increment the result | 4
'0' | not enough characters: append '36' | 4
'036' | consume '03': success | 4
```
### Commented
```
n => ( // n = input
g = ( // g is a recursive function taking either a string or an array of
// characters split into:
[a, b, // a = 1st character, b = 2nd character,
...c] // c[] = array of all remaining characters
) => //
b ? // if b is defined:
a + b - n && // if n subtracted from the concatenation of a and b is not zero:
1 + g(c) // add 1 to the final result and do a recursive call with c[]
// (otherwise: yield 0 and stop recursion)
: // else:
g( // do a recursive call with:
[a] + // the concatenation of a (forced to an empty string if undefined)
6 * ++i // and 6 * i, with i pre-incremented
) // end of recursive call
)(i = '') // initial call to g with an empty string,
// and i set to empty string as well (zero'ish)
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~93~~ ~~92~~ ~~85~~ ~~83~~ ~~81~~ ~~68~~ ~~65~~ 59 bytes
```
f=lambda n,s='612',i=18:n-int(s[:2])and-~f(n,s[2:]+`i`,i+6)
```
[Try it online!](https://tio.run/##DcpBCoAgEADAr3jTJYP0ECH4EgnaMEuoTdRLl75uzXnSU4@bdGvBnnitHhnJYvmoNJfRqslQH6mK4oyeAcn3bxD/cNrM3RIXGbsRWsr/YRcmESTLSPsm1DAAtA8 "Python 2 – Try It Online")
---
* -2 bytes, thanks to Grimy
* -3 bytes, thanks to ArBo
* -6 bytes, thanks to xnor
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 31 bytes
```
{+(comb(2,[~] 1..ⅮX*6)...$_)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1pbIzk/N0nDSCe6LlbBUE/vUeu6CC0zTT09PZV4zdr/aflFCnGGBgYK1VwKCsWJlQp6amlctf8B "Perl 6 – Try It Online")
Uses the 1-indexed sequence.
### Explanation:
```
{ } # Anonymous code block
1..Ⅾ # The range 1 to 500
X*6 # All multiplied by 6
[~] # Join as one giant string
comb(2, ) # Split into pairs of characters
...$_ # Take up to the input
+( ) # And return the length of the list
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~82 ... 65 58~~ 54 bytes
```
k$show=<<[6,12..]
k(a:b:c)t|read[a,b]==t=0|let=1+k c t
```
[Try it online!](https://tio.run/##DchLDsIgEADQvaeYRRd@KmldmLRhvIEnQBZTREuAlhQSE9OzO3b53kjZ2xA44oN9lcf5g1Kqa91ehNA7v6d@6M2hrIulp6J60IgFmzXYgu3Jg4HCkdyEkdId0uKmAhV8XQJ5vMGWEDerRoiu0/wzr0DvzGeT0h8)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
₄L6*J2ôIk
```
0-indexed. Accepts either a single integer, or a list of integers as input.
[Try it online](https://tio.run/##yy9OTMpM/f//UVOLj5mWl9HhLZ7Z//8bAAA) or [verify all test cases](https://tio.run/##DZC7TUVREAP7QROc/e@WAKKDJwKQCBABAR0gSqIDOqGRy6aWbI/98fn88vZ6XX9f349596C/P/fv13U7CIrhBEnRDLKiIIoY4kggiRTSyKAHXY@ihjoaaKKFNjrYwQTbSMMcCyyxwhob/OCCK76NjgeeeOGND3EIIZQwYoGCSKKIJoY8pJBKGunk8iZZZJNDHUoopYxyKqidU1RTQx9aaKWNdjropHdt08McRhhljHEmmGSK2TPm6R8).
**Explanation:**
```
₄L # Create a list in the range [1,1000]
6* # Multiply each value by 6
J # Join the entire list of integers together to a string
2ô # Split into parts of size 2
Ik # Get the index of the input integer(s)
# (and output the result implicitly)
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 26 bytes
```
{⍵⍳⍨⍎¨((≠\=⍨)⊂⊢)∊⍕¨6×⍳325}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHvZsf9a541Nt3aIWGxqPOBTG2QK7mo66mR12LNB91dD3qnXpohdnh6UB1xkamtf/THrVNAKp@1DfV0/9RV/Oh9caP2iYCecFBzkAyxMMz@P@j3lVph1YY6AC1WFoCAA "APL (Dyalog Unicode) – Try It Online") - Tests for all valid inputs.
### How:
```
{⍵⍳⍨⍎¨((≠\=⍨)⊂⊢)∊⍕¨6×⍳325} ⍝ Dfn, input is ⍵.
6×⍳325 ⍝ Generates the first 325 multiples of 6.
⍕¨ ⍝ Format each number into a string
∊ ⍝ Enlist, flattens the vector
( ⊂⊢) ⍝ Dyadic enclose, takes a boolean mask as left argument
(≠\=⍨) ⍝ Generates the mask 1 0 1 0...
⍝ Enclose then returns the Sixers sequence as a string
⍎¨ ⍝ Execute each element in the string, turning it into a numeric vector
⍵⍳⍨ ⍝ Find the first occurrence of ⍵ in the vector
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
I⌕I⪪⭆φ×⁶⊕ι²N
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwy0zLwXCCi7IyQSSJUC5dN/EAo00HYWQzNzUYg0zHQXPvOSi1NzUvJLUFI1MTU1NHQUjEOGZV1Ba4leam5RapAEU1bT@/9/gv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code. 0-indexed. Explanation:
```
φ Predefined constant 1000
⭆ Map over implicit range and join
ι Current index
⊕ Incremented
×⁶ Multiplied by 6
⪪ ² Split into pairs of digits
I Cast to integer
N Input as a number
⌕ Find its index
I Cast to string
Implicitly print
```
[Answer]
# [J](http://jsoftware.com/), ~~29~~ 26 bytes
-3 bytes thanks to FrownyFrog!
```
i.~_2(".\;)6<@":@*1+i.@325
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/M/Xq4o00lPRirDXNbByUrBy0DLUz9RyMjUz/a3IpcKUmZ@QraFgrGSikaWbqGRn8BwA "J – Try It Online")
0-based
[Answer]
# [Python 3](https://docs.python.org/3/), ~~87~~ 81 Bytes:
```
lambda n:[*zip(*[iter(''.join(map(str,range(6,1951,6))))]*2)].index((*'%02d'%n,))
```
integer input, 0-indexed output.
[Try it online!](https://tio.run/##LctBCoMwEADAr/Qi2SxBEqVChb5EPUQS7Za6hjQH9fOpBec@YU@vles8Pfv8scvo7I3bDg8KgB0lH0GI8r0Sw2IDfFNU0fLsoVHmcTeqkacBKzmUxM5vACgKXTlRsJIyh0icAP91uqLR@iz5Bw)
---
-6 bytes, thanks to @TFeld.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 74 bytes
```
#&@@Position[FromDigits/@Flatten@IntegerDigits[6Range@365]~Partition~2,#]&
```
[Try it online!](https://tio.run/##JcuxCsIwEAbghwl0UgqKhQ7KDVJwi64hwyHXeGAukP6uffUodv3gy4yXZIY@uc3n5joiXxaFFgtTLfmqSbH0NL0ZEKObQZLUjcPwYEtCx@EUV88V/7cedi527f5RQfBVDcHtLzP9sKctjGNsXw "Wolfram Language (Mathematica) – Try It Online")
2 bytes saved from @Expired Data
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 14 bytes
```
;İS∧⟦×₆ᵐcġ₂iSt
```
[Try it online!](https://tio.run/##AS0A0v9icmFjaHlsb2cy//87xLBT4oin4p@mw5figobhtZBjxKHigoJpU3T//zEw/1o "Brachylog – Try It Online")
Too slow for test cases with larger outputs.
[Answer]
# [R](https://www.r-project.org/), ~~75~~ 62 bytes
-13 bytes thanks to Giuseppe.
```
match(scan(,''),substring(Reduce(paste0,3*(a=2*1:999)),a-1,a))
```
[Try it online!](https://tio.run/##K/r/PzexJDlDozg5MU9DR11dU6e4NKm4pCgzL10jKDWlNDlVoyCxuCTVQMdYSyPR1kjL0MrS0lJTUydR11AnUVPzv7n5fwA "R – Try It Online")
[Answer]
# x86-16 machine code, ~~54~~ 53 bytes
```
00000000: bde5 032b e58b fc57 9633 c0b9 2701 0506 ...+...W.3..'...
00000010: 0050 e80d 0058 e2f6 965f 49f2 aff7 d103 .P...X..._I.....
00000020: e5c3 bb0a 0052 33d2 f7f3 85c0 7403 e8f4 .....R3.....t...
00000030: ff92 aa5a c3 ...Z.
```
**Listing:**
```
BD 03E5 MOV BP, 997 ; digits list buffer size
2B E5 SUB SP, BP ; allocate from stack
8B FC MOV DI, SP ; DI = start of digits buffer
50 PUSH AX ; save input value
57 PUSH DI ; save buffer offset
33 C0 XOR AX, AX ; counter in AX = 0
B9 0127 MOV CX, 295 ; generate 295*6 multiples
SIX_LOOP:
05 0006 ADD AX, 6 ; increment counter by 6
50 PUSH AX ; save AX (clobbered by OUT_DECU)
E8 000D CALL OUT_DECU ; write AX to BCD at ES:DI
58 POP AX
E2 F6 LOOP SIX_LOOP ; loop 295 times
5F POP DI ; restore start of output buffer
58 POP AX ; restore input number
49 DEC CX ; loop count FFFFh (solution guaranteed)
F2 AF REPNZ SCASW ; search for input value
F7 D1 NOT CX ; ones complement sign without increment
03 E5 ADD SP, BP ; restore stack pointer
C3 RET
OUT_DECU: ; divide unsigned word AX into base 10
; decimal digits to buffer at ES:DI
BB 000A MOV BX, 10 ; decimal divisor = 10
OUT_DECU_R:
52 PUSH DX ; save remainder digit / caller DX
33 D2 XOR DX, DX ; clear high word of dividend
F7 F3 DIV BX ; AX = DX:AX / 10, DX = DX:AX % 10
85 C0 TEST AX, AX ; is zero?
74 03 JZ OUT_DECU_DONE ; loop while AX > 0
E8 FFF4 CALL OUT_DECU_R ; recursive call to next division
OUT_DECU_DONE:
92 XCHG AX, DX ; AL = digit
AA STOSB ; write to digits list
5A POP DX ; restore digit
C3 RET
```
Callable function, input value as little endian BCD in `AX`. Output 1-based index in `CX`.
The easy approach... generate the entire list and search it.
Note: I found experimentally that `295*6` is sufficient to generate needed values: `295*6 = 1770` of which the `77` is the value for the highest index (497 or 498). This would produce a string 997 digits long.
**Tests:**
[](https://i.stack.imgur.com/FjNUA.png)
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), 10 bytes
```
•╒6*y░2/i=
```
[Try it online!](https://tio.run/##FZJNapZBEIT3dYoiSzfOdPf8LQLeRCRoFNRACIhIwCso6AG8iOBRcpH4fJuefmequ6ur3k9vHt7f3n189/z89P3P06@f88XXp98/4uWH6@fXr67//f125Zu7@/u3Nw9Xj@Rf7u8@3149PjdHdXVHV7hPpUvlMzXcY2r6aLmvru1oXce91Bs36hQtjuBBPR2pXu5HfTiI0xnqixzQdg7149yKZiZGNyFcU5GeR1EmHR6pmI5QMBfI9iQ/EDzK5jmU3XMrw7DK9CpluXgdDFnK6d2UyzuVsKbgeB9V8wnVhbWKweTpVMGZxYp9G6tTrLpsDGhDoKnYOTUQamvAGh4DqWA4EAshRnlxdxEMxATdNWiRpbE9hsZx5dJEtmqa3YQwqAn7oVkmXMq5Z35oUk3O/AmI@bO0msfW6i6oLQisppUcqVVm1qIDPBYEaLEWkgDc3kOLFntrQ@DgJEvwgW/aECDF8NQeXtq4RmQ@Em8IgEF7FjvNtDiXP4WDYv6Yg@tROlhHxDvkP5iXTQfjM3W2WfnQIs9/ "MathGolf – Try It Online")
Basically the same as the 05AB1E answer, but I lose a byte by having to convert the concatenated number to string explicitly.
## Explanation
```
•╒ push [1, 2, ..., 512]
6* multiply by 6
y join array without separator to string or number
░ convert to string (implicit map)
2/ split into groups of 2 characters
i convert to integer (implicit map)
= find index of implicit input in the array
```
[Answer]
# APL+WIN, 37 bytes
Prompts for input of integer. 1 indexed.
```
↑(⎕=⍎,((n,2)⍴(⍕6×⍳n)~' '),' ')/⍳n←600
```
[Try it online! Coutesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4/apuoARSyfdTbp6OhkadjpPmod4vGo96pZoenP@rdnKdZp66grqkDIvRBfKBOMwOD/0C9/9O4zAy50rgMgNjSFERYAgA "APL (Dyalog Classic) – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), ~~123 bytes~~ 115 bytes
```
a=>m.First(y=>int.Parse(string.Join("",m.Select((x,i)=>++i*6)).Substring(y*2,2))==a);var m=Enumerable.Range(0,640);
```
[Try it online!](https://tio.run/##VcqxDoIwEIDh3acgTndQGySGBdtNBuNgZHAu5CCX0Jq0xcjTVxInh3/58g/hMARO7eKGM7sotnQ2qmSUtrJlHyKsSm8q78YHghA9u0leX@xgvxdWdjTTEAE@glHpouC8RpTd0v9OWPNKVIhKGWzexmdWXdxiyZt@JvkwbiIoRX0qsUm7p@dIN3YEI9RHxOZPqnKT9AU "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), 22 bytes
**Solution:**
```
(.:'0N 2#,/$6*1+!999)?
```
[Try it online!](https://tio.run/##y9bNz/7/X0PPSt3AT8FIWUdfxUzLUFvR0tJS097S8v9/AA "K (oK) – Try It Online")
**Explanation:**
0-indexed.
```
(.:'0N 2#,/$6*1+!999)? / the solution
? / lookup right in left
( ) / do this together
!999 / range 0..999
1+ / add 1, range 1...1000
6* / multiply by 6, 6...6000
$ / convert to strings
,/ / flatten
0N 2# / reshape into 2xN
.:' / value each, convert to numbers
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
ȷ×€6DFs2Ḍi
```
[Try it online!](https://tio.run/##y0rNyan8///E9sPTHzWtMXNxKzZ6uKMn87@hgcHDHduO7jncDhRWcf8PAA "Jelly – Try It Online")
TIO link gives all values for 0 to 99.
### Explanation
```
ȷ | 1000
×€6 | each times 6 (using implicit range from 1..1000)
D | Convert to decimal digits
F | Flatten
s2 | Split into pairs
Ḍ | Convert back from decimal digits to integer
i | Find index of left argument to link
```
[Answer]
# Java 10, ~~119~~ ~~104~~ 102 bytes
```
n->{int i=2;for(var s="612";!s.substring(0,2).equals(""+n/10+n%10);)s=s.substring(2)+6*++i;return~-i;}
```
Port of [*@TFeld*'s Python 2 answer](https://codegolf.stackexchange.com/a/186890/52210).
-2 bytes thanks to *@Imus*.
1-indexed.
[Try it online.](https://tio.run/##TY9NbsIwEIX3nGJqqZJdN6mTBYua9AZlw7LtwgSDBoJDPXakCqVXT@3Aops3mp@n983RDKY47k5T2xkieDforgsAdMH6vWktrHM7D6DlWZ3QaTIuklAwAVtYg4NmcsXbNe@xqfW@93wwHqhhy6pm@oFKilsKHt2Bq@dalPY7mo44Y9K9VEq6x0oJLaj5f1gLuXySErW3IXr3W6AeJ52DL3HbpeB7/tDjDs6JnG9m48cXGHHDziA3KKUBV5XKRUoxLwE2PxTsuexjKC/JGTrHUbLXz5CwyvSuuP86Tn8)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
int i=2; // Index-integer, starting at 2
for(var s="612"; // String, starting at "612"
!s.substring(0,2) // Loop as long as the first two characters of the String
.equals( // Are not equal to:
""+n/10 // The input integer-divided by 10 as String
+n%10);) // Concatenated with the input modulo-10
// (which will add leading 0s for inputs < 10)
s=s.substring(2) // Remove the first two characters of the String
+6*++i; // And append 6 times `i`,
// after we've first increased `i` by 1 with `++i`
return~-i;} // Return `i-1` as result
```
---
**Original ~~119~~ 117 bytes version:**
```
n->{var s="";for(int i=0;i<2e3;)s+=i+=6;return java.util.Arrays.asList(s.split("(?<=\\G..)")).indexOf(""+n/10+n%10);}
```
0-indexed.
[Try it online.](https://tio.run/##TY8xT8QwDIX3@xVWJKRE0YUWJAbSgJhY4Bhu5BhCmyKXXlolbsXp1N9e0nIDiy0/23rfa@xot031PZetjRFeLfrzBgA9uVDb0sFuGVcBSr5UL3RSpk0qkSxhCTvwYGa/fTiPNkA0jOm6C@sxmkxjceNutYjSoDR3OjgagocmGauBsFVPIdhTVDa@YCQeVexbJM74Y2EOh2elBBNCoa/cz1vNGZP@Os@kv8ozoadZLxz98NkmjgvO2GEFxxSE7ymg/3r/ACv@UvzHAizybGlSinUJsD9FckfVDaT69Emt5yjZ/YGSqUrpxSX6NP8C)
**Explanation:**
```
n->{ // Method with integer as both parameter and return-type
var s=""; // String we're building, starting empty
for(int i=0;i<2e3;) // Loop `i` in the range [0, 2000):
s+=i+=6; // Increase `i` by 6 first every iteration
// And then append the updated `i` to String `s`
return java.util.Arrays.asList(
s.split("(?<=\\G..)") // Split the String in parts of size 2 (as array)
) // Convert the array to a List
.indexOf( // And get the index of the following in this list:
""+n/10 // The input integer-divided by 10 as String
+n%10);} // Concatenated with the input modulo-10
```
[Answer]
# [PHP](https://php.net/), 58 bytes
```
<?=array_search($argn,str_split(join(range(6,1950,6)),2));
```
[Try it online!](https://tio.run/##K8go@P/fxt42sagosTK@ODWxKDlDQyWxKD1Pp7ikKL64ICezRCMrPzNPoygxLz1Vw0zH0NLUQMdMU1PHSFPT@v9/U4N/@QUlmfl5xf913QA "PHP – Try It Online")
Input is 0-based via `STDIN`.
```
$ echo 0|php -F sixers.php
241
$ echo 50|php -F sixers.php
131
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 17 bytes
```
325,:)6f*s2/:~ri#
```
[Try it online!](https://tio.run/##S85KzP3/39jIVMdK0yxNq9hI36quKFP5/39LSwA "CJam – Try It Online")
0-based.
### Explanation
```
325, e# Range [0 1 2 ... 324]
:) e# Add 1 to each: gives [1 2 3 ... 325]
6f* e# Multiply each by 6: gives [6 12 18 ... 1950]
s e# Convert to string: gives "61218...1950"
2/ e# Split into chunks of size 2: gives ["61" "21" ... "95" "0"]
e# Note how the last chunk has size 1; but it is not used
:~ e# Evaluate each string in that array: gives [61 21 ... 95 0]
ri e# Read input as an integer
# e# Index of fist occurrence, 0-based
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 12 bytes
0-indexed.
```
L²õ*6 ¬ò b¥U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TLL1KjYgrPIgYqVV&input=NjE) or [test all inputs](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TLL1KjYgrPIgYqVV&input=MTAwCi1t)
```
L²õ*6 ¬ò b¥U :Implicit input of integer U
L :100
² :Squared
õ :Range [1,L²]
*6 :Multiply each by 6
¬ :Join to a string
ò :Split to array of strings each of length 2
b :First 0-based index of
¥U :Test for equality with U (bU wouldn't work here as each string would first need to be cast to an integer, costing more bytes)
```
[Answer]
# [Red](http://www.red-lang.org), ~~97~~ 94 bytes
```
func[n][(index? find/skip rejoin collect[repeat i 325[keep i * 6]]pad/left/with n 2 #"0"2)/ 2]
```
[Try it online!](https://tio.run/##PcuxCsIwFEbh3af4iYsKkjaiQxffwfVyh5Lc4LUlDTGibx@Lg9P5llMktJsE4k0cWnwlT4lppynI54q41j4nzSjyWDTBL/MsvlKRLGOF4uTONInklQdcmPMY7Cyx2rfWOxIctqYzbm/huP2vvutAuWiqIMURPcxgEPEzc/sC "Red – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 11 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Æ▒§±~>ûπ╞öt
```
[Run and debug it](https://staxlang.xyz/#p=92b115f17e3e96e3c69474&i=0%0A99&a=1&m=2)
Input is an integer. Output is 0-indexed.
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=any -ap`, 50 bytes
```
$\=0,$b.=6*++$,while!any{++$\;"@F"==$_}$b=~/../g}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxtZARyVJz9ZMS1tbRac8IzMnVTExr7IayIuxVnJwU7K1VYmvVUmyrdPX09NPr63@/9/oX35BSWZ@XvF/XV9TPQNDAyDtk1lcYmUVWpKZYwvU/V83sQAA "Perl 5 – Try It Online")
1-based output
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), ~~83~~ 77 bytes
I am really out of practice at complicated programming in Retina, but I'm satisfied with the length I managed to do it in.
Outputs the 0-indexed result.
```
.+
6*1
325+-1%`1+
$0¶6*1$0
1+
$.0
¶
L`..
m`^0
$
¶$+
s`\b(\d+)\b.*\b\1$
C`¶
```
[**Try it Online**](https://tio.run/##JcixDYNADAXQ/s9hJMDCOoOAAWgzghU5JygooCCZ7Qa4xQ6kvPJd228/P1qKMKZWMfQj151WrgwKOT1HAU3X/0cCcgJeLoLD3wGgJ4jxdYu1rdxYlNaiKQGL51TKrDc "Retina – Try It Online")
---
### Explanation
```
.+ Replace the input with 6 in unary
6*1
325+-1%`1+ Do 325 times: append line with previous + 6
$0¶6*1$0
1+ Convert all lines to decimal
$.0
¶ Remove line breaks
L`.. List pairs of digits
m`^0 Remove leading zeros
$ Append the original input N on a new line
¶$+
s`\b(\d+)\b.*\b\1$ Remove occurrences of N and anything in between
C`¶ Count the number of line breaks
```
[Answer]
# [Swift 5/Xcode 10.2.1](https://developer.apple.com/swift/), ~~140~~ ~~134~~ 133 bytes
```
let s=sequence(first:6){$0+6}.lazy.map{String($0)}.joined();return(0...).first{$0%2==0&&Int(String(s.dropFirst($0).prefix(2)))==n}!/2
```
[Try it online!](https://tio.run/##lZjNbtNAFIX3fQojlcoWwtjzP0VmidQVizxBlTqVUXGD7YhClGcPSe7Nvt@qqpKTa5/55sy9M/8ZNos7bnbjutgM07z8WK9309SP6/5hXA1v/TSv@t@78//leF88jEtVfP52/lvsjy/9UszdfP38or8P1f62@RQO9cvjv7/1r8ftfrVMw/hc3jbVof75Ooz9U1l9nfplN41lU9d1VV@UJ9lH03XN3d3p10sVzfXT9Lr9fv78/AP1duo3w1tpqqrquvHw4Ys5Hm5utqfvLuU7nr@piq4rjGur92ta0RCJuUjaACT2InFA4S6KTIp4eS5DNEHKAEWUKpE4lsTkhmiy1CGetY0@G9EoABGJjL4Q0QgDxhKNUNCS9WkFA4M0goE1RBO1DjJOSLCeaIQEm8gWFRJQEhghAUmEA0d2nBEOAlkfIxygMoKBJ7gZwcAQDIzmAbJNKAioTtagJr5ZwSAQ3KxgEAhuVjhAmWiFg0gCzgoHDnngdcuRfWqFhEQCzgoJiRBn9WRACyQkJGKCExAyIc5dTwai0UBAdQQEYpvTcwEdqE77gwa1IQoCkVw7BGRc0hghxDntEYh1XptE8kZeTwaUPV7bRJSmXhtF1MJ4oSGip7s2i8iHoH4T7LziYAl2XnDwJBe80OAs8S5oy@gId0F4QBKhATkX9IQgJgRhAUmuKKD30VwgcAclAdXRXAjIOM2FQJCLQoInGyIKCA5FXdRgiMSHaFVEsi4KDGjnRaUBpUnUYEA4xKjNDDJPeEgE8Kg4JLK0SYMhozlXDwpUSGdJItFgQGX0QoHwk4QFsj5JJ0mk0VxALXfSYEC@6QyBDr0sICB48vVWCYkUBHQXlfVWwZA9nnWcRBqdJ9EYkXWgtCTqsl4sWIJqFhzQMZ4Vh9NAcfwP "Swift – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 36 bytes
```
^
2406$*_
_{6}
$.`
^0(..)+?.*\1$
$#1
```
[Try it online!](https://tio.run/##K0otycxL/M9laamixWXIdWiboYpeApeqhnvC/zguIxMDMxWteK74arNaLpB4nIGGnp6mtr2eVoyhCpeKsuH//wA "Retina 0.8.2 – Try It Online") Link includes test suite. 1-indexed. Explanation:
```
^
2406$*_
```
Prefix 2406 `_`s to the input.
```
_{6}
$.`
```
Replace every 6 `_`s with the number of preceding `_`s. This generates the sequence `0`, `6`, `12` ... `2400`, but automatically concatenates the numbers.
```
^0(..)+?.*\1$
```
Skip the leading 0 and find the first pair of digits that match the last two digits i.e. the zero-padded input (because the string ends in `0`; in fact the test suite uses the fact that it ends in `00`).
```
$#1
```
Output the number of pairs of digits up to and including the match.
Retina 1 saves a couple of bytes because its string repetition operator is a byte shorter and already defaults to `_` as its right-hand operand, so that the second line of code becomes just `2406*`. Another feature of Retina 1 is the `>` modifier which generates the substitution in the context of the separator after the match, which in the case of `$.>`` causes it to include the length of the match in the result. Although this costs a byte we save it immediately as we don't need to match the `0` any more. (The repetitions also have to be reduced by 6.) Retina 1 can also do basic arithmetic in a substitution. This means that we don't have to resort to tricks to take multiples of 6, instead we just generate the numbers `1..400` and multiply by 6 in the substitution. Remarkably, this also doesn't affect the overall byte count, as the final result looks like this:
```
^
400*
_
$.(6*$>`
^(..)+?.*\1$
$#1
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 80 bytes
1-indexed.
```
dc<<<6[p6+lax]salax|sed 's/./\n&/g;s/\n//'|sed 'N;s/\n//'|sed -n "/^0*$1$/{=;q}"
```
[Try it online!](https://tio.run/##S0oszvj/PyXZxsbGLLrATDsnsSK2OBFI1hSnpiioF@vr6cfkqemnWxcDaX19dYiwHwpXN09BST/OQEvFUEW/2ta6sFbp////lhYA "Bash – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 88 bytes
```
n=>{int i=2;for(var s="612";!s.StartsWith($"{n:d2}");s=s.Substring(2)+6*++i);return~-i;}
```
[Try it online!](https://tio.run/##JYyxDoIwFEV3vqI2Dq0VAx0YeJTRyc2BGRH0Lc@kr3Uh@Ou1xuHcnOQmZ@JyYkznSFOHFI6ZfnGJXL9mFegsLC@v3qMX7GRTWwk7Pl3D6AMPGJ5qL1dq73aTGtjlJ944eKSHsto0B2NQg59D9PQpEbYExS/3T1eAXV3lNUYXQgwew3xBmhUa2Qpp1KJQaw3pCw "C# (Visual C# Interactive Compiler) – Try It Online")
Another port of the [Java](https://codegolf.stackexchange.com/a/186887/8340) and [Python](https://codegolf.stackexchange.com/a/186890/8340) answers.
My original answer below:
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 102 bytes
```
n=>{dynamic s="",t=$"{n:d2}",i=0;for(;i++<400;s+=i*6);for(i=0;s[i++]!=t[0]|s[i++]!=t[1];);return i/2;}
```
[Try it online!](https://tio.run/##RYwxD4IwFIR3fkVtHFqLsRDiwKOMTu4OhMEUSN7gM2nLYJDfXguLww13391Zf7Ye420m2yCFPKmdTCTTLsOHni@0zBvO82COfKF6KFeeo9EwvZ0AVKqptAavDJ6ucg836LtE@oMJne6/f1P0IMGNYXbE8FLCGiHbJxTYNsOmSGepLTPGHg7DeEcaBSpeM67EJFBKCfEH "C# (Visual C# Interactive Compiler) – Try It Online")
Both solutions use 1-based indexing.
] |
[Question]
[
Here the first 100 numbers of an easy sequence:
```
0,1,0,2,1,4,3,7,6,11,10,16,15,22,21,29,28,37,36,46,45,56,55,67,66,79,78,92,91,106,105,121,120,137,136,154,153,172,171,191,190,211,210,232,231,254,253,277,276,301,300,326,325,352,351,379,378,407,406,436,435,466,465,497,496,529,528,562,561,596,595,631,630,667,666,704,703,742,741,781,780,821,820,862,861,904,903,947,946,991,990,1036,1035,1082,1081,1129,1128,1177,1176,1226
```
**How does this sequence work?**
```
n: 0 1 2 3 4 5 6 7 8 9 10 11 12
0, 1-1=0, 2-1=1, 4-1=3, 7-1=6, 11-1=10, 16-1=15,
0+1=1, 0+2=2, 1+3=4, 3+4=7, 6+5=11, 10+6=16, 15+7=22
```
* `a(0) = 0`
* For every odd `n` (0-indexed), it's `a(n-1) + X` (where `X=1` and increases by 1 every time it's accessed)
* For every even `n` (0-indexed), it's `a(n-1) - 1`
## Challenge:
One of:
* Given an input integer `n`, output the `n`'th number in the sequence.
* Given an input integer `n`, output the first `n` numbers of the sequence.
* Output the sequence indefinitely without taking an input ([or taking an empty unused input](https://codegolf.meta.stackexchange.com/questions/12681/are-we-allowed-to-use-empty-input-we-wont-use-when-no-input-is-asked-regarding)).
## Challenge rules:
* Input `n` can be both 0- or 1-indexed.
* If you output (part of) the sequence, you can use a list/array, print to STDOUT with any delimiter (space, comma, newline, etc.). Your call.
* Please state which of the three options you've used in your answer.
* You'll have to support at least the first 10,000 numbers (10,000th number is `12,497,501`).
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if possible.
## Test cases:
[Pastebin with the first 10,001 numbers in the sequence.](https://pastebin.com/JX6g4Nky) Feel free to pick any you'd like.
Some higher numbers:
```
n (0-indexed) Output:
68,690 589,772,340
100,000 1,249,975,000
162,207 3,288,888,857
453,271 25,681,824,931
888,888 98,765,012,346
1,000,000 124,999,750,000
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~32~~ ~~28~~ 25 bytes
```
lambda n:(~-n|1)**2/8+n%2
```
[Try it online!](https://tio.run/##Xc5BCsIwEIXhvacIiNBUxJlJk5kI3sRNRYqCxiLdCOLVY2wxDb5VCF/C3z@H8z1Q7PaHeG1vx1Orwq56b8ILdV3TVtZhRbF/XMKgusqAXvzOTpwHvVTzrHhmMg1kg/BdiZAa79mm2xk5IuASGZJxljNqrCHGEpF1gpK@M5jV9KxUXthZwFTl/qrKrLFqyoL4AQ "Python 2 – Try It Online")
Returns the `n`-th number (`0`-indexed)
[Answer]
# Excel, 31 bytes
Answer is `0` indexed. Outputs the `n`the number.
```
=(A1^2+IF(ISODD(A1),7,-2*A1))/8
```
The sequence described is ultimately just two sequences interlaced:
```
ODD: (x^2+x+2)/2
EVEN: (x^2-x)/2
```
Interlacing these into one `0` indexed sequence gives:
```
a = (x^2 - 2x)/8 if even
a = (x^2 + 7 )/8 if odd
```
Which gives:
```
=IF(ISODD(A1),(A1^2+7)/8,(A1^2-2*A1)/8)
```
which we golf down to the `31` bytes.
---
Using the same approach, `1` indexed gives `37` bytes:
```
=(A1^2-IF(ISODD(A1),4*A1-3,2*A1-8))/8
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Rj-ḣ⁸S
```
[Try it online!](https://tio.run/##y0rNyan8/z8oS/fhjsWPGncE////39AADAA "Jelly – Try It Online")
0-indexed. Returns `n`th number.
Explanation:
```
Rj-ḣ⁸S Arguments: z
R [1..x]: z (implicit)
j- Join x with y: ^, -1
ḣ⁸ Take first y of x: ^, z
S Sum: ^
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 23 bytes
```
x=>(7+(x-2|1)**2)/8-x%2
```
1-indexed. [Try it online!](https://tio.run/##bcxBDoIwEEDRvafoxqTFVGamQFsT3HkQUorREEqEmC68e43sALc/L//ZvJvJvR7jLIfQ@tTVKdZXrk88SvqgyDISuZHxSMmFYQq9P/fhzjuuUIjDOllNJARjLM/ZLY7ezb69MESDRAo3GAEAf3qNqbC6BNjgylR2j0tjtSZVwJ/18t6tlzekLw "JavaScript (Node.js) – Try It Online")
```
f(x) = f(x+1) + 1 if x is even
= SUM{1..(x-3)/2} if x is odd
SUM{1..(x-3)/2}
= (1+(x-3)/2)*((x-3)/2)/2
= (x-1)*(x-3)/8
= ((x-2)^2-1)/8
```
[Answer]
# [Haskell](https://www.haskell.org/), ~~40 38~~ 37 bytes
```
scanl(flip($))0$[1..]>>=(:[pred]).(+)
```
Returns an infinite list, [try it online!](https://tio.run/##DcpBCoAgEADAr3josBJJXYP6QS8wicW0pE0W7f1tzXlOrFcgElSTWqV6zASREkOjdd/YwRg3zxOMlkvYnTbQarkx5b/fyMumuKT8KJTXR8KjSueZPw "Haskell – Try It Online")
### Explanation
`scanl` takes three arguments `f`, `init` and `xs` (**[** *x0*, *x1* ... **]**) and builds a new list:
**[** *a0 = init*, *a1 = f(a0,x0)*, *a2 = f(a1, x1)* ... **]**
We set `init = 0` and use the flipped `($)` application operator (thus it applies *ai* to the function *xi*), now we only need a list of functions - the list `[1..]>>=(:[pred]).(+)` is an infinite list with the right functions:
```
[(+1),(-1),(+2),(-1),(+3),(-1),(+4),...
```
### Interesting alternative, 37 bytes
`flip` having the type `(a -> b -> c) -> b -> a -> c` we could also use `id :: d -> d` instead of `($)` because of Haskell's type inference the type `d` would be unified with `a -> b`, giving us the same.
[Try it online!](https://tio.run/##y0gszk7NyfmfqGCrEPO/ODkxL0cjLSezQCEzRdNAJdpQTy/Wzs5Wwyq6oCg1JVZTT0Nb839uYmYeUHluYoFvvEJBUWZeiULi/3/JaTmJ6cX/dZMLCgA "Haskell – Try It Online")
**Edit**
-2 bytes by using `(>>=)` instead of `do`-notation.
-1 byte by using `scanl` instead of `zipWith`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
HḶS‘_Ḃ
```
A monadic link accepting (1-indexed) `n` which returns `a(n)`.
**[Try it online!](https://tio.run/##y0rNyan8/9/j4Y5twY8aZsQ/3NH0//9/QyMA "Jelly – Try It Online")** Or see the [test-suite](https://tio.run/##y0rNyan8/9/j4Y5twY8aZsQ/3NH0/@iew@2Pmta4//8fbWZhZmmoY2gABEDKzMjIwELHxNTYyNxIxwIELCFyBoax2jmZxSUaRYl56akaIB2GmpoA "Jelly – Try It Online")
### How?
```
HḶS‘_Ḃ - link: n
H - halve -> n/2.0
Ḷ - lowered range -> [0,1,2,...,floor(n/2.0)-1]
S - sum -> TriangleNumber(floor(n/2.0)-1)
‘ - increment -> TriangleNumber(floor(n/2.0)-1)+1
Ḃ - bit = 1 if n is odd, 0 if it's even
_ - subtract -> TriangleNumber(floor(n/2.0)-1)+isEven(n)
```
[Answer]
# [Haskell](https://www.haskell.org/), 25 bytes
```
scanl(+)0$(:[-1])=<<[1..]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfYxvzvzg5MS9HQ1vTQEXDKlrXMFbT1sYm2lBPL/Z/bmJmnoKtQkFRZl6JQs7/f8lpOYnpxf91kwsKAA "Haskell – Try It Online")
Constructs an infinite list.
---
**[Haskell](https://www.haskell.org/), 27 bytes**
```
0:0%1
a%d=a+1:a:(a+d)%(d+1)
```
[Try it online!](https://tio.run/##y0gszk7NyfmfYxvz38DKQNWQK1E1xTZR29Aq0UojUTtFU1UjRdtQ839uYmaegq1CQVFmXolCzv9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
**[Haskell](https://www.haskell.org/), 30 bytes**
```
0:do a<-scanl(+)0[1..];[a+1,a]
```
[Try it online!](https://tio.run/##y0gszk7NyfmfYxvz38AqJV8h0Ua3ODkxL0dDW9Mg2lBPL9Y6OlHbUCcx9n9uYmaegq1CQVFmXolCzv9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ÎF<NÈi¼¾>+
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cJ@bjd/hjsxDew7ts9P@/9/MwszSAAA "05AB1E – Try It Online")
**Explanation**
```
Î # initialize stack with: 0, input
F # for N in [0 ... input-1] do:
< # decrement the current number
NÈi # if N is even
¼ # increment a counter
¾> # push counter+1
+ # add to current number
```
Another 10-byter: `ÎFNÈN;Ì*<O`
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 32 bytes
```
@(x)fix((x-~(m=mod(x,2)))^2/8)+m
```
[Try it online!](https://tio.run/##Zc1LCsIwFIXheVeRiZCLWnNv2zyEghO3IZS2kYIxIkUycusxbXFgPeOf7/h2bF59tHWe5/HEA9ghcB72b@5q5zsedgQAFzpo2Lpo/dM1I7v5@zWzXGppBLBpG3YOj74d@@7IKm2UoqIUKTGKaCl@EkSNRAWmAkXaP4JUGlWJydDzYF0YrWQlMB3JL7NAa2Z2RBY/ "Octave – Try It Online")
Outputs the n-th number, 0-indexed. Uses the same formula as several other answers.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~16~~ 12 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319 "When can APL characters be counted as 1 byte each?")[SBCS](https://github.com/abrudz/SBCS ".dyalog files using a single byte character set")
Anonymous tacit prefix function. 0-indexed.
```
+/⊢↑∘∊¯1,¨⍨⍳
```
[Try it online!](https://tio.run/##Vc6xasMwEAbgvU/hvReqO1nSac6STAlxXsBQ3MXQrp0LIRhskiGQJUumbBn8Bn6UexH3FEipf05a9In7y6969v5d1p8fo3Sn9Vp2Bwzj65s0V9kdZX@WfTPcEYabtDr9WKmQtlO8XEnzM9xtct2p2Mz13i6WxVgl3CO9VJlnH032jLSXLHMcIQQCmxsFaFImAIHyCDE40JdEPJEJE2KBmIHTcUFJ7iwFnBBy4BmBKYdoUQ0/MjGRIXhdg6mN/2tj/hlM/6M2dibV@QU "APL (Dyalog Unicode) – Try It Online")
`+/` the sum of
`⊢↑` the first `n` elements
`∘∊` of the **ϵ**nlisted (flattened)
`¯1,¨⍨` negative-one-appended-to-each
`⍳` first `n` **ɩ**ndices (0 through `n`–1
[Answer]
# [PHP](http://php.net/), ~~73~~ ~~64~~ ~~55~~ ~~51~~ 47 bytes
# First method
First code golf answer!
I'm sure there's PHP tricks to make it shorter and the maths can probably be improved.
Takes n as the first argument and outputs the nth number in the sequence.
```
$y=$argv[1]/2;for(;$i<$y+1;)$x+=$i++;echo$x-($y|0);
```
Minus 9 bytes by removing "$x=0;" and "$i=0".
Minus 9 bytes thanks to @Kevin Cruijssen improving the for loop and loss of the end tag.
Minus 1 byte using bitwise or "|" rather than "(int)"
Minus 3 bytes thanks to @Dennis as you can remove the tags by running it from the command line with "php -r 'code here'"
[Try it online!](https://tio.run/##DcRJCoAwDADAz@SgFHG5SSw@wQeIiLi1lybUIi34dqNzGDYsXc//kDQs/rzHeiobPMhnCLaDpGrMISoNVincV0MQiwzSU@UoIu3vJQ6W3CXFdhnyYSbe3RyWUw/uAw "PHP – Try It Online")
# Second method
Matched my previous answer with a whole new method!
```
for(;$i<$argv[1];$i++)$x+=($y^=1)?$i/2+1:-1;echo$x;
```
Using XOR and the tenary operator to switch between sums in the loop.
Edit: This doesn't work for n=0 and I have no idea why. $i isn't assigned so therefore it should be 0, therefore the loop `($i<$argv[1])` should fail as `(0<0==false)`, therefore a non assigned $x should output as 0 and not 1.
[Try it online!](https://tio.run/##DcZBCoAgEEDRy8zCkAjblUlH6ABREWXpxhlMoi7f5F88PjnirqfsgVFo8B2s8bxHNeWXsoBHGgHvbFTRg69qqdpSabs5hEczc5P7kJLHcHG5Xw5jWpBsWNJ6miH8 "PHP – Try It Online")
# Third method
Converting the excel formula @Wernisch created to PHP gives a 47 byte solution
```
$z=$argv[1];echo(pow($z,2)+(($z&1)?7:-2*$z))/8;
```
[Try it online!](https://tio.run/##K8go@G9jXwAkVapsVRKL0suiDWOtU5Mz8jUK8ss1VKp0jDS1NYC0mqGmvbmVrpGWSpWmpr6F9f///y2B4F9@QUlmfl7xf92U4oz8opL4/ILUvPiSxHRb/zwA "PHP – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 35 bytes
```
diffinv(rbind(n<-1:scan(),-1)[n-1])
```
[Try it online!](https://tio.run/##K/r/PyUzLS0zr0yjKCkzL0Ujz0bX0Ko4OTFPQ1NH11AzOk/XMFbzv6HBfwA "R – Try It Online")
I thought this was an interesting alternative to [@JayCe's answer](https://codegolf.stackexchange.com/a/165853/67312) since it doesn't port very well to languages without built-in support for matrices, and happens to be just as golfy.
1-indexed, returns the first `n` elements of the sequence.
### How it works:
`rbind(n<-1:scan(),-1)` constructs the following matrix:
```
[,1] [,2] [,3] [,4]
[1,] 1 2 3 4
[2,] -1 -1 -1 -1
```
Because R holds matrices in column-major order, if we were to convert this to a `vector`, we would obtain a vector
```
1 -1 2 -1 3 -1 4 -1
```
which if we take a cumulative sum of, we would get
```
1 0 2 1 4 3 7 6
```
which is the sequence, just without the leading `0`. `diffinv` fortunately adds the leading zero, so we take the first `n-1` values from the matrix and `diffinv` them, obtaining the first `n` values of the sequence.
[Answer]
# [R](https://www.r-project.org/), ~~35~~ 34 bytes
```
(u=(n=scan())-n%%2-1)-n+(15+u^2)/8
```
[Try it online!](https://tio.run/##K/r/X6PUViPPtjg5MU9DU1M3T1XVSNcQSGtrGJpql8YZaepb/Dc0@Q8A "R – Try It Online")
First output option.Same formula as many other answers (I'd like to point to the first answer providing the formula, I can't figure which it is).
Second and third output options below:
### [R](https://www.r-project.org/), 43 bytes
```
function(m,n=1:m,u=n%%2+1)((n-u)^2-1)/8+2-u
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jVyfP1tAqV6fUNk9V1UjbUFNDI0@3VDPOSNdQU99C20i39H@ahpGh5n8A "R – Try It Online")
### [R](https://www.r-project.org/), 51 bytes
```
while(T){cat(((T-(u=T%%2+1))^2-1)/8+2-u," ");T=T+1}
```
[Try it online!](https://tio.run/##K/r/vzwjMydVI0SzOjmxRENDI0RXo9Q2RFXVSNtQUzPOSNdQU99C20i3VEdJQUnTOsQ2RNuw9r@R4X8A "R – Try It Online")
[Answer]
# Matlab/Octave, ~~31~~ 26 bytes
5 bytes saved thx to Luis Mendo!
```
@(n)sum(1:n/2+.5)-fix(n/2)
```
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 20 bytes
```
x->x%2+(x=~-x|1)*x/8
```
[Try it online!](https://tio.run/##ZY29jsIwEIT7PMU2JzlEMT/VSSFIlBSIAlGdKPYCQRsc27I3yBEHrx4cTlddsfq0M6OZBm@YN6frQK01jqGJv@yYlJwUyT@t7nTFZPRoVgq9hy2ShnsCYLtvRRV4Ro64GTpBGz2xZ0f68nUEdBefvqMAG80Hja7f2bNDNg7qcgj5KnwsMhHKZx5@5ukkTD@H4h2vjROkGQhKmBURS1iMzLK/QoB97/ncStOxtHGRlRa1RGtVv/ZxTlCa/pY9kvEewws "Java (JDK 10) – Try It Online")
Port of [TFeld's Python 2 anwser](https://codegolf.stackexchange.com/a/165792/16236), so go give them an upvote! ;)
[Answer]
# [Dodos](https://github.com/DennisMitchell/dodos), 69 bytes
```
. w
w
. h
+ r . ' dab h '
h
h ' '
. dab
r
r dip
.
dot
'
dip
```
[Try it online!](https://tio.run/##NY69DsIwDITn@CluKAoI9YeO0Ik3aeNUyRKXNKhC4t2LpYrFd/5Osm8a17AvOaYywz4/xTt5p3KHJTcWDAOsl9nii@BHRu3qm/riPZywV7s5hbtpsNFGKoHMFRkNLHicEPSQIhU1GiujTIZMBseFGjIshTTSbddPRLNkRMSE6rz6Fzr03eUBFgL@NU89QxuiigpbWUrLwrIe8yimEUvy@w8 "Dodos (with Bash wrapper) – Try It Online")
---
Somehow this is the longest answer.
Explanation.
```
┌────┬─────────────────────────────────────────────────┐
│Name│Function │
├────┼─────────────────────────────────────────────────┤
│. │Alias for "dot", computes the sum. │
├────┼─────────────────────────────────────────────────┤
│' │Alias for "dip". │
├────┼─────────────────────────────────────────────────┤
│r │Range from 0 to n, reversed. │
├────┼─────────────────────────────────────────────────┤
│h │Halve - return (n mod 2) followed by (n/2) zeros.│
└────┴─────────────────────────────────────────────────┘
```
[Answer]
# [QBasic 1.1](http://www.qbasic.net/), 49 bytes
```
INPUT N
R=1
FOR I=1TO N\2-1
R=R+I
NEXT
?R-N MOD 2
```
1-indexed.
[Answer]
# [QBasic 1.1](http://www.qbasic.net/), 30 bytes
```
INPUT N
?(N-1OR 1)^2\8+N MOD 2
```
Uses TFeld's algorithm. 0-indexed.
[Answer]
# QBasic, 31 bytes
The just-implement-the-spec solution comes in slightly longer than [Erik's solution](https://codegolf.stackexchange.com/a/166168/16766).
```
DO
?n
i=i+1
n=n+i
?n
n=n-1
LOOP
```
This outputs indefinitely. For purposes of running it, I recommend changing the last line to something like `LOOP WHILE INPUT$(1) <> "q"`, which will wait for a keypress after every second sequence entry and exit if the key pressed is `q`.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 56 bytes
```
n=>{int a=0,i=0;for(;++i<n;)a+=i%2<1?-1:i/2+1;return a;}
```
*-2 bytes thanks to Kevin Crujssen*
[Try it online!](https://tio.run/##bVNNa9tAED1bv2IwLUhonO6uviMrpRRySqG0hx5CDoq8ThaUVZDkNkXot7tvbceEUPDsx@zMvPc042ZYNV2v901bDwN977uHvn6iyRvGejQN/fw7jPrp4npnm7WxI8OuaEsV7W11NeFGdSXYVKLcdr1fhqFZ2zKow8p8VGv5eSUvzScVyrLX4663VJfzvvS85919i@InjN@d2dC32lg/mLwFat7eETj1uhl/6GHXjgPwrP5DhydvMQmWLFhhjTnijFOWkiW8OCSsFCvJqmCVc5RxlHKMX8JJyknCKcJTzgrOci4UFy4RaSJhiSypUAVJMnKlYljEMgNShjcXWwAXYApoKgJQhDPiFOJUlsFSjoSECY4UzirhKFEw@AAaATUWGQyUHLMoATvHEHsBfwGSoJ6Ae5IqmOTE@QowB1YaCdB3EqBBxDDojxVMQpAzwTl05NCRIz9HfoG4AnFFnMFSLqCjgA4pnEgBBlLkyi3QJwGOJccCOVgQotRhSWZ0buHa7Npu0BNRYlu/69XFjbYP4yOewjDAIC0WX4ZB96NvQsnvYm/NXVB6i9mb/zsTr4mAs@y6T/rlGdl6A/CVDDw3Llvyz941iQDzAcw3gQIIbqroBRfpLtBAZxHyKMIeCePVpR/KYoSpQv5RxZuaq1MdEHfudtBufxcUVvQShuew2ck8TDfVzbirW0BvfRu4b3rfdS31h08C7@tzdVbrYk5/xK@dHbpWX/zqzahvjNX@h@U15Bj7vBtpsvMlTa9pM9V2Q9Ox3kxLCsk/oXym5VM9No9LuqTlpiPbjXR0BGCEfuwfddt2/wA "C# (.NET Core) – Try It Online")
1 indexed. Returns `a(n)`
Ungolf'd:
```
int f(int n)
{
// a needs to be outside the for loop's scope,
// and it's golfier to also define i here
int a = 0, i = 1;
// basic for loop, no initializer because we already defined i
for (; ++i < n;)
{
if (i%2 < 1) {
// if i is even, subtract 1
a -= 1;
}
else
{
// if i is odd, add (i / 2) + 1
// this lets us handle X without defining another int
a += i / 2 + 1;
}
}
// a is the number at index n
return a;
}
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~11~~ ~~9~~ 8 bytes
```
ΘṁṠe→Θ∫N
```
Saved a byte thanks to H.PWiz.
Outputs as an infinite list.
[Try it online!](https://tio.run/##ARoA5f9odXNr///OmOG5geG5oGXihpLOmOKIq07//w "Husk – Try It Online")
### Explanation
```
ΘṁṠe→Θ∫N
∫N Cumulative sum of natural numbers (triangular numbers).
Θ Prepend 0.
ṁṠe→ Concatenate [n + 1, n] for each.
Θ Prepend 0.
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
Return the first `n` numbers.
```
Rj-ÄŻḣ
```
[Try it online!](https://tio.run/##y0rNyan8/z8oS/dwy9HdD3cs/v//v6EBAA "Jelly – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 15 bytes
```
I∨ΣEN⎇﹪ι²±¹⊕⊘ι⁰
```
[Try it online!](https://tio.run/##DYhBCgIxDEWv0mUGKqg7cenGWcwo6AViJ2ihTYeYDnj6mLf47/PSByU1LGZ3yaxwwa/CTeDRK0y4wshr17nXFwkMMTxJGOUHU1t6aZBjOHqd6Y1KcPA7chKqxEoLXLFsrjw4Mex9z2Ynx3Zb@QM "Charcoal – Try It Online") 0-indexed. Link is to verbose version of code. The formula would probably be shorter, but what's the fun in that? Explanation:
```
N Input as a number
E Map over implicit range
⎇ Ternary
﹪ι² Current value modulo 2
±¹ If true (odd) then -1
⊕⊘ι Otherwise calculate X as i/2+1
Σ Take the sum
∨ ⁰ If the sum is empty then use zero
I Cast to string and implicitly print
```
[Answer]
# JavaScript, ~~49~~ ~~48~~ 45 bytes
```
x=>eval('for(i=0,r=1;++i<x+2;)r+=i%2?-1:i/2')
```
[Try it online!](https://tio.run/##dcxLDsIgFEDRufswhWAtPJXWVnQtpIJ5iqUB09TV42dmiHd4BveqJx37gOOjjCOeTbj74Waeyao0q6OZtCOF9YGg4qugRMcYHmYGHQ1M4RJOpWixgoKm3g/RO7N2/kIskY3cc0oXvyr4p5wlAK8z3u42UIuMm29/3u95egE)
Not as pretty as @tsh answer, but mine works for bigger numbers.
And now thanks @tsh, for the `eval` solution !
[Answer]
# Befunge 93, 26 bytes
```
<v0p030
>:.130g+:30p+:.1-
```
Runs indefinitely
[Try it online](https://tio.run/##S0pNK81LT/3/36bMoMDA2IBLwc5Kz9DYIF3bytigQBvI1v3/HwA "Befunge-93 – Try It Online"), though output gets a little wonky and goes back down after x=256, presumably TIO can't handle characters above U+256. Works fine at <https://www.bedroomlan.org/tools/befunge-playground> (Chrome only, unfortunately. With Firefox, endlines get removed at runtime, for some reason...)
[Answer]
# [J](http://jsoftware.com/), 17 bytes
```
1#.[{._1,@,.~1+i.
```
A port of Adám's APL solution.
[Try it online!](https://tio.run/##Vc9NCgIxDAXg/Zwi6GIQQ2jSv3RAEA/gBVy4EAd142KWolevrTJiH3SVj@bllsdpQ2BgAJN5SYcHHRm3SC9eXymvugVBP26oB4TnAOPUdefT5Q4jBA3JQMl@R/CN14QxClpnZsWmplGM4hKm6LFMfi6ImNg4i6KKWp@Ps3PeSuTGicegjCoOk@UZ6icNTIoxlK1cG4a2ofmDXH9K5RRvasX8Bg "J – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 8 bytes
```
s<s,R_1S
```
Returns `n`th number in the sequence, 0-indexed. [Try it online](https://pyth.herokuapp.com/?code=s%3Cs%2CR_1S&test_suite=1&test_suite_input=0%0A1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A9999&debug=0)
Explanation, with example for `n=5`:
```
s<s,R_1SQQ Final 2 Q's are implicit, Q=eval(input())
SQ 1-indexed range [1,2,3,4,5]
,R_1 Map each to [n,-1] [[1,-1],[2,-1],[3,-1],[4,-1],[5,-1]]
s Sum (Flatten) [1,-1,2,-1,3,-1,4,-1,5,-1]
< Q Take 1st Q [1,-1,2,-1,3]
s Sum, implicit output 4
```
[Answer]
# [Perl 6](https://perl6.org), ~~38~~ 26 bytes
```
{(0,{$_+(($+^=1)??++$ !!-1)}...*)[$_]}
```
[Try it](https://tio.run/##VZBBT9wwEIXv@RUPEYjDBitZIKRabemhlXriygFBZJIBTB072E7parW/fbEDqsTBmif7m@c3M5JV9X5yhL8171ZJMmxw3JmesN5vWVls03bBWLq4X1f51dVikeLg4LTKd5zzk/w2be92eyc2iB2s5Lwqy5y/GKlZVmR5sBsnz2J10wOE2@jutJduVKGFpW2ObQIcQnp0QsOLPwQBZfQTvBwI3uCJNFnhg34mOHqdSHc0NzmDN4KddPDFIPQm1tE4Jx8UQWqMwgqlSCUBHyf3DOej0Y/RmkE6ckW8sB4xP38cPMuOmj7LC2RYf0dWgM@L@Hyqzvt5oPj1EIO6yX6kCn4dOYfekNOZB/0L80zaSxWfQ6zAhSCBk9pTHxx@Xf@EeBMB@x9mleyShB9/XdGjsWCBB@qmrb@VRdRhxW1Zfup62S7Ly1mfX5y1y8tq1k3TtOEEXUX2g89X@9@klMGNsap/Bw "Perl 6 – Try It Online")
```
{(+^-$_+|1)**2 div 8+$_%2}
```
Based on reverse engineering TFeld's [Python answer](https://codegolf.stackexchange.com/questions/165791/x-steps-forward-1-step-back/165792#165792).
[Try it](https://tio.run/##NY5BbsIwEEX3PsVfBGyT1LJdMK4QXfcG3dUCHCQqB0cJQUKUs6d2ShejedL8/zRt3QUzDn2NqxGHDSHNDfND9DW2452VXy@FK38UXyw0/OkKWxZuph9jv7uBSSGUlFw0u5ZNHS6@4@nMaEV5MrXDheXdD/vU7duQO4XjuBMgC8SxuTA6s57yChTbd9AKYjI9T2rps@pBiJj/K46xA0sGwFhn3mSVOf3hpHyy0U7L9cTL1avTazWxtdalSaxy9i/PN@NHHULEZ@yC/wU "Perl 6 – Try It Online")
## Expanded
### 38 byte (sequence generator):
```
{ # bare block lambda with implicit parameter $_
(
# generate a new sequence everytime this function is called
0, # seed the sequence
{ # bare block that is used to generate the rest of the values
$_ # parameter to this inner block (previous value)
+
(
# a statement that switches between (0,1) each time it is run
( $ +^= 1 )
?? # when it is 1 (truish)
# a statement that increments each time it is run
++$ # &prefix:« ++ »( state $foo )
!! # or else subtract 1
-1
)
}
... # keep generating until:
* # never stop
)[ $_ ] # index into the sequence
}
```
Note that this has the benefit that you can pass in `*` to get the entire sequence, or pass in a Range to more efficiently generate multiple values.
### 26 byte (direct calculation):
```
{ # bare block lambda with implicit parameter $_
(
+^ # numeric binary negate
-$_ # negative of the input
+| # numeric binary or
1
) ** 2 # to the power of 2
div 8 # integer divide it by 8
+ $_ % 2 # add one if it is odd
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 8 bytes
```
;L¨O>¹É-
```
[Try it online!](https://tio.run/##MzBNTDJM/f/f2ufQCn@7QzsPd@r@/29oAAKGAA "05AB1E – Try It Online")
Based on Jonathan Allan's Jelly approach (which was probably based on OP editing the question with another definition of the sequence), so 1-indexed.
[Answer]
# [Convex](https://github.com/GamrCorps/Convex), ~~10~~ 9 bytes
```
_½,ª)\2%-
```
[Try it online!](https://tio.run/##S87PK0ut@P8//tBenUOrNGOMVHX///9vaAAChgA "Convex – Try It Online")
Based on Jonathan Allan's Jelly approach (which was probably based on OP editing the question with another definition of the sequence). 1-indexed.
Explanation:
```
_½,ª)\2%- Stack: [A]
_ Duplicate. Stack: [A A]
½ Halve. Stack: [A [A]½]
, Range, [0..⌊N⌋). Stack: [A [[A]½],]
ª Sum. Stack: [A [[A]½],]ª]
) Increment. Stack: [A [[[A]½],]ª])]
\ Swap. Stack: [[[[A]½],]ª]) A]
2 2. Stack: [[[[A]½],]ª]) A 2]
% Modulo. Stack: [[[[A]½],]ª]) [A 2]%]
- Minus. Stack: [[[[[A]½],]ª]) [A 2]%]-]
```
] |
[Question]
[
# The magic music box (MMB)
*This explains the motivation for the challenge, feel free to ignore.*
The magic music box is a word game played by a group of people, where one is the owner of the magic music box and the other people are trying to put words inside the magic music box.
Rules for the game with humans: the game goes in turns, one person at a time. In your turn, you have to say a word you want to put in the MMB and the MMB owner says if your word can get in or not, depending on the game criterion. If you are the MMB owner, you have to say a word that can go in the MMB.
# The task
You have to code a function/program that receives a word as input (in any sensible format) and outputs Truthy or Falsy. Truthy if the word can go in the MMB and Falsy otherwise.
For a word to be able to go in the MMB, it has to contain at least one of the following seven strings:
* `do`
* `re`
* `mi`
* `fa`
* `sol`
* `la`
* `si`
# Input
A lowercase "word" in any sensible format, for example:
* a string
* a list of characters
* a list of ASCII values of the characters
# Test cases
(Edited test cases to include `obsolete`, `also`, some answers may not have it yet)
```
far -> Truthy
solace -> Truthy
boat -> Falsy
shrimp -> Falsy
fire -> Truthy
summit -> Truthy
biscuit -> Falsy
bullet -> Falsy
doctor -> Truthy
blast -> Truthy
college -> Falsy
subsidiary -> Truthy
obsolete -> Truthy
also -> Falsy
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~15~~ 14 bytes
```
’ïêo‡Åefa’7äåà
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcPMw@sPr8p/1LDwcGtqWiKQb354yeGlhxf8/19cmlScmZKZWFQJAA "05AB1E – Try It Online")
```
’ïêo‡Åefa’ # dictionary string "soldosimilarefa" (using the words sold and similar)
7√§ # split in 7 parts of almost-equal length (excess length goes to the first parts)
å # for each part, check if it’s in the input
à # maximum
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~ 18 ~~ 14 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
-4 thanks to Nick Kennedy & [Grimmy's 05AB1E answer](https://codegolf.stackexchange.com/a/199161/53748)
```
7“Ẉ|nŻUḋ}»œsfẆ
```
A monadic Link accepting a list of characters which yields a, possibly empty, list of lists.
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5yHuzpq8o7uDn24o7v20O6jk4vNVdIe7mr7f3TPo4a5IUDsdrjd/lHTGvf//6PV0xKL1HUU1IvzcxKTU0GspPzEErBIRlFmbgGIlZZZBJYpLs3NzQTLJWUWJ5dCmaU5OalgVkp@ckk@2LCknMRisFByPlAyHao5qTgzJTOxqBLEy08CWphakqoeCwA "Jelly – Try It Online")**
### How?
Note that in Jelly an empty list is falsey, while a non-empty list is truthy (as employed by the if-else, `”T”FÇ?`, in the footer of the Try it online link, above).
```
7“Ẉ|nŻUḋ}»œsfẆ - Link: list of characters, w
7 - seven
“Ẉ|nŻUḋ}» - "solfa"+"similar"+"edo"
œs - split into (seven) equal chunks
-> ["sol","fa","si","mi","la","re","do"]
Ẇ - all sublists (w)
f - filter keep
```
Aside: [solfa](https://en.wikipedia.org/wiki/Tonic_sol-fa) is a name of a [solfège](https://en.wikipedia.org/wiki/Solf%C3%A8ge) method, where tones are given single syllable names, and was when `si` first became `ti`.
[Answer]
# [Python](https://docs.python.org/2/), 52 bytes
```
import re
re.compile('do|re|mi|fa|sol|la|si').search
```
[Try it online!](https://tio.run/##FY1BCsQgDEX3OUV3bTeFmeXAnGWIVseANhIjpeDdrV09@LzPy5cGPt69U8osOokD/xW3WU6ZolvmnZu4lqh5bIVjiwM0r1txKDb0Mwxren2y0KGTXwTPHx256rKu3aPA@KB1YBgVSpCRAU@jUmpKpGCo2PqwxugUdrbKAiZiUbA8tv@jmkI7oVw3 "Python 2 – Try It Online")
Yup, a regex. A match produces a Truthy match object, and a non-match produces a Falsey None. Using `re.compile` to make an compiled pattern as a function is a bit shorter than a direct `lambda`:
**55 bytes**
```
lambda w:re.search('do|re|mi|fa|sol|la|si',w)
import re
```
[Try it online!](https://tio.run/##FYvLCsMgEADv@xXemkAptMdA/6RQ1ldd0CjrigT8d5ucBoaZckjI@2v692dGTNqi6hu7R3XIJiw3mwe7kWh4HDXHEU/Q7d5XoFQyi2I3e6Do1HMrTLsovzD2L@2lybKu0yPDOaJxoDMK1MDnCZ7YQW0pkYCmatrFFqMTsNlIZtARq4DJp/tdqa5kCfn4Aw "Python 2 – Try It Online")
For comparison, without regex:
**58 bytes**
```
lambda w:any(map(w.count,'do re mi fa sol la si'.split()))
```
[Try it online!](https://tio.run/##FYtLCsMwDAX3OoV3caAE2mWgNykU@dcI/EOWMTm9m6wG3ryppxwlv2Z4f2bEZByqsWM@dcKqx2ZLz/JYXFHsVSIVULUSVbxAy9ZqJNHrus5xUPTquVemLCpoxvGlXPttZ0CGq0LrwRQUaAdTqhCIPbSeEgkYarbf7DF6AVesFAYTsQnYcm2/@2oaOUI@/w "Python 2 – Try It Online")
We can almost save a byte by writing `1in map(...)`, but this doesn't catch the string appearing two or more times.
[Answer]
# [CP-1610](https://en.wikipedia.org/wiki/General_Instrument_CP1600) assembly ([Intellivision](https://en.wikipedia.org/wiki/Intellivision)), 41 DECLEs1 ≈ 52 bytes
A routine taking a pointer to a NUL-terminated string into **R4** and setting the carry if the test is successful, or clearing it otherwise.
```
**275** | PSHR R5
**2A0** | @@read MVI@ R4, R0
**338 061** | SUBI #'a', R0
**20B 01B** | BMI @@rtn
**04C** | SLL R0, 2
**04C** | SLL R0, 2
**048** | SLL R0
**3E0** | XOR@ R4, R0
**2A1** | MVI@ R4, R1
**33C 002** | SUBI #2, R4
**001** | SDBD
**2BD 0C6 048** | MVII #@@tbl, R5
**368** | @@loop CMP@ R5, R0
**204 00D** | BEQ @@rtn
**001** | @@next SDBD
**37D 0CC 048** | CMPI #@@so, R5
**22C 008** | BNEQ @@loop
**368** | CMP@ R5, R0
**22C 01B** | BNEQ @@read
**379 06C** | CMPI #'l', R1
**22C 01F** | BNEQ @@read
**2B7** | @@rtn PULR R7
**00F** | @@tbl DECLE $00F
**245** | DECLE $245
**1E9** | DECLE $1E9
**0C1** | DECLE $0C1
**101** | DECLE $101
**229** | DECLE $229
**22F** | @@so DECLE $22F
```
### How?
Each note made of the ASCII codes \$(c\_0,c\_1)\$ is encoded as a single DECLE with the following formula:
$$((c\_0-97)\times 32) \operatorname{xor} c\_1$$
The edge case *"sol"* is encoded as *"so"* and put at the end of the lookup table. There's an additional test for the *"l"*.
### Full commented test code
```
ROMW 10 ; use 10-bit ROM width
ORG $4800 ; map this program at $4800
;; ------------------------------------------------------------- ;;
;; main code ;;
;; ------------------------------------------------------------- ;;
main PROC
SDBD ; set up an interrupt service routine
MVII #isr, R0 ; to do some minimal STIC initialization
MVO R0, $100
SWAP R0
MVO R0, $101
EIS ; enable interrupts
SDBD ; R5 = pointer into the test case index
MVII #tc.tbl,R5
MVII #$200, R3 ; R3 = backtab pointer
MVII #14, R1 ; R1 = number of test cases
@@loop MVI@ R5, R4 ; R4 = pointer to next string
SDBD
ADDI #tc.00, R4
PSHR R5 ; save the test variables
PSHR R3
PSHR R1
CALL mmb ; invoke our routine
PULR R1 ; restore the test variables
PULR R3
PULR R5
MVII #$88, R0 ; R0 = '1'
BC @@draw
MVII #$80, R0 ; or '0' if the carry is not set
@@draw MVO@ R0, R3 ; draw this character
INCR R3 ; increment the backtab pointer
DECR R1 ; next test case
BNEQ @@loop
DECR R7 ; done: loop forever
ENDP
;; ------------------------------------------------------------- ;;
;; test cases ;;
;; ------------------------------------------------------------- ;;
tc PROC
@@tbl DECLE @@00 - @@00, @@01 - @@00, @@02 - @@00, @@03 - @@00
DECLE @@04 - @@00, @@05 - @@00, @@06 - @@00, @@07 - @@00
DECLE @@08 - @@00, @@09 - @@00, @@10 - @@00, @@11 - @@00
DECLE @@12 - @@00, @@13 - @@00
;; truthy
@@00 STRING "far", 0
@@01 STRING "solace", 0
@@02 STRING "fire", 0
@@03 STRING "summit", 0
@@04 STRING "doctor", 0
@@05 STRING "blast", 0
@@06 STRING "subsidiary", 0
@@07 STRING "obsolete", 0
;; falsy
@@08 STRING "boat", 0
@@09 STRING "shrimp", 0
@@10 STRING "biscuit", 0
@@11 STRING "bullet", 0
@@12 STRING "college", 0
@@13 STRING "also", 0
ENDP
;; ------------------------------------------------------------- ;;
;; ISR ;;
;; ------------------------------------------------------------- ;;
isr PROC
MVO R0, $0020 ; enable display
CLRR R0
MVO R0, $0030 ; no horizontal delay
MVO R0, $0031 ; no vertical delay
MVO R0, $0032 ; no border extension
MVII #$D, R0
MVO R0, $0028 ; light-blue background
MVO R0, $002C ; light-blue border
JR R5 ; return from ISR
ENDP
;; ------------------------------------------------------------- ;;
;; our routine ;;
;; ------------------------------------------------------------- ;;
mmb PROC
PSHR R5 ; save the return address on the stack
@@read MVI@ R4, R0 ; R0 = current character
SUBI #'a', R0 ; turn it into an index in [0..25]
BMI @@rtn ; if the result is negative, it means
; we've reached the end of the string:
; we return with the carry cleared by SUBI
SLL R0, 2 ; multiply R0 by 32
SLL R0, 2
SLL R0
XOR@ R4, R0 ; XOR it with the next character
MVI@ R4, R1 ; and load a 3rd character in R1
SUBI #2, R4 ; rewind the pointer by 2 characters
SDBD ; R5 = pointer into the lookup table
MVII #@@tbl, R5
@@loop CMP@ R5, R0 ; compare the lookup table entry with R0
BEQ @@rtn ; match? (if yes, the carry is set)
@@next SDBD ; if we haven't reached the end of the table,
CMPI #@@so, R5
BNEQ @@loop ; try again with the next entry
CMP@ R5, R0 ; last test with 'so'
BNEQ @@read ; abort if it doesn't match
CMPI #'l', R1 ; otherwise, make sure it's followed by a 'l'
BNEQ @@read ; abort if it doesn't match
; otherwise, the carry is set
@@rtn PULR R7 ; return
;; lookup table: 'do', 're', 'mi', 'fa', 'la', 'si', 'so'
@@tbl DECLE ('d' - 'a') * 32 XOR 'o'
DECLE ('r' - 'a') * 32 XOR 'e'
DECLE ('m' - 'a') * 32 XOR 'i'
DECLE ('f' - 'a') * 32 XOR 'a'
DECLE ('l' - 'a') * 32 XOR 'a'
DECLE ('s' - 'a') * 32 XOR 'i'
@@so DECLE ('s' - 'a') * 32 XOR 'o'
ENDP
```
### Output
[](https://i.stack.imgur.com/8s3At.gif)
*screenshot from [jzIntv](http://spatula-city.org/~im14u2c/intv/)*
---
*1. A CP-1610 opcode is encoded with a 10-bit value (0x000 to 0x3FF), known as a 'DECLE'.*
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 26 bytes
```
{?/do|re|mi|fa|sol|la|si/}
```
[Try it online!](https://tio.run/##TY49EsIgEIX7nGIro0USKztj5wnsHAsgYHZmkQwLBRM8e8QqVDvfvp95i/Z02WyCg4Hrtt6GyWWvs8VsRGZHmcrB4bsZ54Hwo3kce14Iw7HtxvYEawPAIkH/PL/6g2mKU3joRnj4GObUlA6hdPWQToQ/3gVxkWePdtnZoK/NHK3FUKeRVcSqQEYiXfHkVHD1AEmC6wblSuCtqwlRMk4ofNpdPw "Perl 6 – Try It Online")
Boring regex solution that checks for any of the strings.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 58 characters, 70 bytes
```
c;f(int*s){for(c=7;c&&!strstr(s,L"潤敲業慦慬楳\x6c6f73"+--c););}
```
Creative method required to save bytes/characters.
*-17 thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)!*
*-8 bytes thanks to [gastropner](https://codegolf.stackexchange.com/users/75886/gastropner)!*
*-2 bytes and -12 characters thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!*
[Try it online!](https://tio.run/##XVExTsMwFN1zio9RUdwmUAmplUhbNiZGtraD4ySNpSSu/B1EqTr2CNyAMsECM9fJNYKTFEhqWbbf03vfz9/cXXFeltyLbJHpPtJtJJXNp2OPX1ycoVZm2ujck@L7tXj5LA4fxf6t2L8Xh6/F04iPovE1Gbgupx71duW5yHiSByFMUAdCXsYzyzJlIWUisx@lCKi1tcCMitQhaq9GPGYK@hXG@RKmNdfoqkEipojzD1EmjIdtxpdMdxSxEum6zURCdRyYp6noeHyBPD@h8iQJO0wguZadMH7CsCPh0phWJ5f5KALB1KbNSt88JNQdJUtQHvHOs@q9@o66VTCFodecJoDiOZSRXbeMXrXRfLikjWwwAPpXeq1MyyOb9BDcGfRwkREHGkO1Lh349deQwi2QB5XreEPgBsidSbYh9JhJhTpXmYlj7cof "C (gcc) – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), ~~47~~ \$\cdots\$ ~~31~~ 30 bytes
```
{print/do|re|mi|fa|sol|la|si/}
```
[Try it online!](https://tio.run/##FYxBCgMxCADvfmbfpInZSpO6qKGU2ren2dPAMAy@n2t9L5NXHFXTOIdkw3Tt2Tfk@K3V0GALLAykGOAPk3FBE2PwOYYEkHiZN2fvHFC1hBpQRw8out15p@RSBe0DSvvHwX8 "AWK – Try It Online")
`awk` automatically compares any regex with `$0` (current line).
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 21 bytes
```
do|re|mi|fa|sol|la|si
```
[Try it online!](https://tio.run/##K0otycxLNPz/PyW/pii1JjezJi2xpjg/pyYHSGX@/5@fBOSklqQCAA "Retina – Try It Online")
Very obvious and boring solution. `0` for false, nonzero for true.
[Answer]
# Java 8, 43 bytes
```
s->s.matches(".*(do|re|mi|fa|sol|la|si).*")
```
[Try it online.](https://tio.run/##bZExb8MgEIX3/IoTk0kUog5dErVjt2ZJt6rDGeOYFIMF50hRnd/uEuJWMu0C4juO9x53wjOuT9XnKA2GAK@o7dcCQFtSvkapYH87ApTOGYUWZHEgr@0RAt/FwnURl0BIWsIeLDzBGNbPQbRIslGhYGJZVG7wamj1UOMQnBlM3DQXS8bH3a2960sT26dXzk5X0EYbk9D7ByC/e9hs4M331Fy26UgqUMFq9CxZ@QFRIvqes1r7jIS@bTXNWeUkuey1Mn4L5a1l0JVGf5lzV0ZpRb9Ch0sg1QrXk@hiEjK24ClwSvKCJqhZktJhrtR43XaZIR1knzsvexOV50y6yI5Z7Cjq5oT9mWOaQCpOo9a262mawT@hUnnFtmzFgAmvOoVUPDyuExdG2SM1BecrK@T9Lp8kr@M3)
**Explanation:**
```
s-> // Method with String parameter and boolean return-type
s.matches( // Check if the String matches this regex fully:
".* // Any amount of optional leading characters
(do|re|mi|fa|sol|la|si)
// Followed by one of our music sounds
.*") "// Followed by any amount of optional trailing characters
```
[Answer]
# [Python 3](https://docs.python.org/3/), 60 bytes
```
lambda w:any(i in w for i in'do re mi fa sol la si'.split())
```
[Try it online!](https://tio.run/##JY2xDsMwCER3voKtzpKlW6X@SRcc2y2SbSIgqvL1qa2yHDq4d/vpH@n3q@ATX1elFhPh90H9DIzc8YtFFOd6S4KasTEWQpOKdQjfVtsre1iWi9su6minAcxQ5Z4nYhireeK@aqYUln9iXi0sD8Axu3L3UMI0B6mQwmigLUMUcrCPDjgU1gx2tMYOkW07ph61Zockm4tCrGQOmwzvPV@jcWLS8wc "Python 3 – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 63 bytes
```
func[s][parse s[to["do"|"re"|"mi"|"fa"|"sol"|"la"|"si"]to end]]
```
[Try it online!](https://tio.run/##VU85DgMhDOx5BaLPB1LkEWkRBYfJWoL1yoYiUv6@gShSiIuRPZ6RPQzpvEOyTuXrmfserTh7eBbQYhtZk8i8DMOAigOyHyBUBpZPi8Y10rAn585MDD5uWhprq/S3hofNbxpmH2EhAvm27jfGeixERl7l0mvF1RBQYv9neimwEolio/WJULysgkjD8fg/EwQTen4arZzVc3Mw7k3bGc9cbibPoE65qT/f "Red – Try It Online")
[Answer]
# Scratch 3.0, 13 blocks/135 + 21 = 156 bytes
*+21 for having a predefined list `n`. Y'all do that by creating a new list within Scratch and entering each item manually. It took 21 keystrokes to manually create the list.*
[](https://i.stack.imgur.com/RKga4.png)
*As SB Syntax*:
```
when gf clicked
ask()and wait
set[o v]to(0
set[i v]to(1
repeat(7
change[o v]by<(answer)contains(item(i)of[n v
change[i v]by(1
end
say(o
```
This was a rather simple approach, as thankfully, there were appropriate built-ins. Zero is falsey and anything else is truthy.
I still don't have access to my old account, but y'all can still [Try it on~~line~~ Scratch!](https://scratch.mit.edu/projects/366486822)
[Answer]
# [R](https://www.r-project.org/), ~~44~~ 40 bytes
Another simple regex implementation. Fixed stupid mistake, thanks @Giuseppe.
```
grepl("do|re|mi|fa|sol|la|si",scan(,''))
```
[Try it online!](https://tio.run/##FYwxCsQwDAR7PSNNEsinZFvOCeRTkOTiwH/3OdXAzjI25230yLEVHUaj8ag4XGXIAm@XZ/we176f56xosAxmgqQY4B/j9kBlI/DeGgck9txfdhEKKJpDDZKgB2Rd2/1ek3NhtB9oWj0KAhTX@Qc "R – Try It Online")
One could also save a character by using grep instead of grepl, where integer(0) is falsey and everything else truthy... but that's not a big change and can't process a whole list at once.
[Answer]
# [Zsh](https://www.zsh.org/), ~~36~~ 35 bytes
```
[[ $1 =~ 'do|re|mi|fa|sol|la|si' ]]
```
~~[Try it online!](https://tio.run/##bYyxjsIwEET7@YoVCiKhgvp0zfVwzXVAYSfry0pOjLyOIu7MtwenRxpppHlP86f94uqmXi4Xqo70Sfu6CzlyHiQ7kzX47EtJs6fbbWkAFyLNVMOZiEJNy7DBJGgfZbjDSWToNAySYEXbae3Je07oQptChPVGE9pQtt9VtSqdmPhAsOWPE6Ohf0AcOarmD0o9jyC6RxmTo932eFCSknEldDp9Xccdbap5A/bKb8zz98872wnwXF4 "Zsh – Try It Online")~~
[Try it online!](https://tio.run/##bYwxa8MwFIT3@xWP4GJ7a@aSpXvapVuaQbL14geyFfRkTBKlf92V98DBwX0fd9dh5aZt1tOJqj0d/qjuQ44uj5LZZA0@@1JS0/m8tgCHSAs1YBNRoOkcbDAJOkQZr2CJDjqPoyRY0W7eevbeJfShSyHCeqMJXSjbZVOtSi8m3hBs@XPJoaUHIExM1fJBaXATiK5RpsRUv@3flaRk2ggdj5@/U027atnBeXUvzK/vn1c2C/Bc/wE "Zsh – Try It Online")
The `=~` operator enables regex matching with the `zsh/regex` module, which is one byte shorter than glob matching using `=` (see ~~previous answer~~).
---
If truthy-falsy convetions can be swapped, then **35 bytes**:
```
[ ${1:#*(do|re|mi|fa|sol|la|si)*} ]
```
[Try it online!](https://tio.run/##bYyxTsNAEAX79xWrYBQ7FWmhow80dIHizt7FK5190e1ZVsjl243dpxrpzej9Wb9I3dTLmarb8fXpUHexJC6DFnHFYihhhTaHO/0sDSAx0Uw1xCWs1rUMH12G9UmHC0QTw6Zh0Ayv1k4bpxA4o4ttjgk@OMto47r9bqk37dSlK6Jf/zgzGroBKiRUzW@Uex5BdEk6ZqH98/HFSI0@Pr9Ix83S6fT@Pe5pV807cDB@UD8oRYH78g8 "Zsh – Try It Online")
In any case, writing all syllables out is just as short as any combination, such as `(do|re|[ms]i|[fl]a|sol)`.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), `-rR` 53 bytes
```
@h2|/÷!1≠:[⑹]øƒ0&᠀®s`do,re,mi,fa,sol,la,si`\,/÷(©s@hƒ
```
[Try it online!](https://tio.run/##y05N///fIcOoRv/wdkXDR50LrKIfTdwZe3jHsUkGag8XNBxaV5yQkq9TlKqTm6mTlqhTnJ@jkwOkMhNidIBaNA6tLHbIODbp///EnOL8/7pFQQA "Keg – Try It Online")
A rather regex-less approach for a rather regex-less language. :P
Zero is falsey, any other value is truthy.
## Explained
This program has two parts: the helper function (`h`) and the main part. Here is the extracted function:
```
@h2|/÷!1≠:[⑹]øƒ
```
This function `h` takes 2 parameters from the stack, both of which are going to be strings.
```
@h2| # Function definition
/√∑ # Split the first string (input) on the second string (note) and push individual items
!1≠ # Push the length of the item splitted stack and see if it doesn't equal 1
[‚ëπ] # If the above comparison results in true, increment the register
øƒ # Clear the stack of all remaining items and end the function
```
Now that the function is out of the way, we can get on to the real fun stuff: the body of the program.
```
0&᠀®s`do,re,mi,fa,sol,la,si`\,/÷(©s@hƒ
0& # Store 0 in the register
᠀®s # Take the input as a string and store it in var "s"
`do,re,mi,fa,sol,la,si`\,/√∑ # Push the string "do,re,mi,fa,sol,la,si", split on ","s and item split
(©s@hƒ # Apply function "h" to each and every item in that list.
# -rR automatically prints the value stored in the register at End Of Execution
```
[Answer]
# [Python 3](https://docs.python.org/3/), 59 bytes
```
lambda w:any('sdrmflsooeiaail'[i::7]in w for i in range(7))
```
[Try it online!](https://tio.run/##JYqxTsUwDAB3f4W3l8wMT6rE@FhZ2IDBSZNXiySuHEelX19aMd3pdOtui7SXI@Mrfh2FapgJt4na7m591ppLF0lMxOX2ydN0/@aGG2ZRZDxVqT2Tu3t/bAuXhB860gSIpvsFxFW5mcuO2zrMee/Pmn5jWg0f728PVdH/MWiinyOTQpdCMUEQMuiLcl0hsyboo1Y2CNzjuDhKSQazRBOFUKgbRDnb81pD55lJ9z8 "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~20~~ 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
`ÎolÌ·nè^`qÍøUã
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YM4Ob2zMEbdu6JheG2BxzfhV4w&input=WyJmYXIiLCJzb2xhY2UiLCJib2F0Iiwic2hyaW1wIiwiZmlyZSIsInN1bW1pdCIsImJpc2N1aXQiLCJidWxsZXQiLCJkb2N0b3IiLCJibGFzdCIsImNvbGxlZ2UiLCJzdWJzaWRpYXJ5Iiwib2Jzb2xldGUiXQotbVI)
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 34 bytes
```
:a;7,{a"sdrmflsooeiaail"@>7%/,2=},
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/3yrR2lynOlGpOKUoNy2nOD8/NTMxMTNHycHOXFVfx8i2Vud/wv/i0qTizJTMxKJKAA "GolfScript – Try It Online")
## Explanation
```
:a; # Assign the input to the "accumulator"
7, # Yields [0 1 2 3 4 5 6]
{ }, # Keep all that full fill this condition
# Item = current item
# ac = accumulator
a"sdrmflsooeiaail" # Stack: <item> <ac> "sdrmflsooeiaail"
@ # Stack: <ac> "sdrmflsooeiaail" <item>
> # The slice begins at the current item
7% # With a step of 7
/ # Try to split the input by the sliced item
,2= # Is the slice was successful?
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 20 bytes
At least it's as long as the regex...
See TIO for the two unprintables in the packed string.
```
:z."a|√™)H¬∑>√îMùv¬¥#¬∞"
```
[Try it online!](https://tio.run/##pVK9TsMwEB7Y/BTXstiSxQMwICFVFUjt0vQFrs2FhDpxlbhEQTwGKy/AxIDEnj5YOTswNQkDUhTH@X58d5/3jUtPp@vnqym@XBzf1V37dXN8XbZvT@3nZfsxPZ1mFmRsFZQEsiQFeQYyz5SYI8gEFVSMV4wb3hveO8ZdpiDudGJmNWs16zQkqJmvmauZp5kzEbFlECEmKv2aUI6GwlbIFU34YGwCobR7sAk8WBNTAdWhEHKZMZ4HfYE5wT1s0RjIm4pMIuQcGU4w@BpbPOjwhhobcBZK7xBZplRUBwuimI/eH4zJmObSkjAWcuFdfMXMsI68NLHG2JpbEXLtS3CEXYlZsYM6cyk8Yg5YxLAJHusUHf/n0jaltz5UsMHtzlvxmGzaPTyqCcjeUSjBowjY2RSU4Cl46HwCPqQA9TavRNSd19u3EotOe9azEtyzHO5WjbcrbnuzXg2mvBzKdz6WbDSW6WIgzfV/cvzzpnvcf5sfzHM812t@8TF9ZMP6DQ "Pyth – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 17 bytes
```
}#zc7."as√ê@¬ª„¬∏√è
```
[Try it online!](https://tio.run/##K6gsyfj/v1a5KtlcTymx@PAEaQfhQ7sPtRzacbj////i/JzE5FQA "Pyth – Try It Online")
Makes use of Pyth's string compression feature, `."`, to compress the string `soldosimilarefa`, then chops that string into 7 pieces, extra length in the first one, then filters which of those strings are contained in the input. If there is at least one, the result is truthy.
[Answer]
# [J](http://jsoftware.com/), 42 bytes
```
[:>./^:_(;:'do re mi fa sol la si')&=@<\\.
```
There's probably a way to golf the string, but I had a hard enough time coming up with this as is. Fun challenge!
Explanation:
```
[: NB. Capped fork
>./^:_ NB. Get the largest value in the resulting array, i.e. 1 or 0
(;:'do re mi fa sol la si') NB. Array of boxed words
& NB. Bind words to
=@< NB. Box and compare
\ NB. With the prefixes
\. NB. Of the suffixes
```
[Try it online!](https://tio.run/##FYyxCsIwFEV3v@KiYKxoqWu0UhCcnFwtSpImNpLwJEkHvz6mw@XA5XA@eVkzg5aDYYcGvGxf43K/XfODbw@r@slfmyNnAyFoeAsjEMnBFVhWrdvu1Pd1rhZajQTTnZcNim5EmDWhNCSJhDgG678wtkTi5L1NkDaqaebknE4YSCUKkE7EBEXle8@qjHawIvxAsvR00hAuEst/ "J – Try It Online")
[Answer]
# [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc) with `/u:System.Text.RegularExpressions.Regex`-flag, 37 bytes
```
s=>IsMatch(s,"do|re|mi|fa|sol|la|si")
```
[Try it online.](https://tio.run/##TZDBasMwEETv/gqhk00ahx56SZrcGiikUNpAz7K8thdky2hXJaHur9eVnVLrtHrD7OwgTWtNOB59px@JHXb1nSisNQdRif1I@8MzvSjWTUp3srSDg6HFoVIDWTOYMFBm4y7ZbMTZeW6u2@QMxKmslJPZ7g@CV2lYuEIXEfm2RV64tJpttF0YRRzbC8ISlbsumi3CCeA59MMhwwk7SANMxY7KEPwXK6yKwxqHbR/dQtI@LlN4E4IX1jZwHbUP4Xah6ZV8WizFzLcPFdj1nrOvRIil3Kyt5FaupMxfVXmCitP7h/Ws5yfoam6yVXXzZSH2e/yxPaPtaNz47fuVGNr8DBfO36D2RrmnS@@AaHJMElx@AQ)
**Explanation:**
```
s=> // Method with string parameter and bool return-type
IsMatch(s, // Check if the string contains the following regex-match:
"do|re|mi|fa|sol|la|si") // One of the music sounds
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 33 bytes
```
s=>s.match`do|re|mi|fa|sol|la|si`
```
[Try it online!](https://tio.run/##bY8xDsMwCEX3HiNTMjQ3SM8SjO2ECofIOJUq@e6Ou1ZM8P@DL3jDBxQzneV5iA8tLk2Xl84JCu6rl5pDTVQjVBWu3AutDeXoKsws2xjHIUIepunx5/YeMBjACRRrfs@UTgNEylaMXimRFeRI8bLJxRws4AWLWE84BrUWUHrSZp/llDxB/hpQ3E8Vaw9YpdvtBg "JavaScript (Node.js) – Try It Online")
[Answer]
## [W](https://github.com/A-ee/w) `d`, ~~24~~ 22 bytes
I finally managed to compress the string!
Take your input in the form `"['your string']"`. Languages without grouping are having a terrible time here.
```
☺¶4∙)╘┐►↔₧uVÿñ☼╠◙╤Γ()¿
```
Uncompressed:
```
1y56WX0y`2,"Wb,R`3,+,ak2=W
```
## Explanation
```
1y56WX0y`2, # Split "farmiesila" into chunks of 2
"Wb,R`3,+ # Add "sol" and "do" wrapped into a list into the list
, # Try to split the input by all these strings
ak2=W # Choose all lengths that are equal to 2 (i.e. split successful)
```
[Answer]
# [J](http://jsoftware.com/), 33 bytes
```
[:OR@,do`re`mi`fa`sol`la`si E.&><
```
[Try it online!](https://tio.run/##fYw9C8IwGIT3/orDwSBq7Rw/EEQnQejaJR9NNJLwSpIO/vqaDjo6HMfd@7z3HGc1s9hzMKzQgBeta5za62Xs@K09rnoS0YjghJUikRe@mMO5nh9246Lq@LLe/IUqox8EC2ZlZL@gSOZvOh5mDbZ8AlCepTaYzkiP6MIL1kWDNITgMpRLeph88N5k9KQzRSgvU4am0t0nVCXXOxnfIFX2TDaQPhEbPw "J – Try It Online")
### How it works
```
[:OR@,do`re`mi`fa`sol`la`si E.&><
do`re`mi`fa`sol`la`si NB. 7 enclosed strings to search for
< NB. Enclose the input
E.&> NB. Find matches for each of the 7 strings
[:OR@, NB. Flatten and take OR
```
[Answer]
# Excel, 155 bytes
```
=ISNUMBER(FIND(0,SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(A1,"si",0),"la",0),"sol",0),"fa",0),"mi",0),"re",0),"do",0)))
```
A sequence of `SUBSTITUTE`, and then a check to see if any of them found a match.
`FIND` returns error `#VALUE!` if no match is found, so would have to wrap each usage in error handling.
[](https://i.stack.imgur.com/IAMXZ.png)
] |
[Question]
[
Given a string containing a sequence of ascending consecutive positive integers, but with no separators (such as `7891011`), output a list of the separated integers. For that example, the output should be `[7, 8, 9, 10, 11]`.
To disambiguate the possible outputs, we add the restriction that the output must always have at least two elements. This means that the output for `7891011` is definitely `[7, 8, 9, 10, 11]`, and not the singleton list `[7891011]`.
## Test cases
```
1234 -> [1, 2, 3, 4]
7891011 -> [7, 8, 9, 10, 11]
6667 -> [66, 67]
293031323334 -> [29, 30, 31, 32, 33, 34]
9991000 -> [999, 1000]
910911 -> [910, 911]
```
## Rules
Input must be taken as a single unseparated string, integer, or list of digits, in decimal only.
Output must be a proper list/array type, or a string with non-digit separators.
You may assume the input is always valid. This means you **do not have to handle** inputs like:
* the empty string
* `5` (the output would need to have length \$ < 2 \$)
* `43` (cannot make an ascending sequence)
* `79` (cannot make a consecutive sequence)
* `66` (ditto)
* `01` (zero is not a positive integer)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~8~~ 6 bytes
```
Ṁ∧⟦₂?c
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HOhkcdyx/NX/aoqck@@f//qP@WhgaGhgA "Brachylog – Try It Online")
*Thanks to @UnrelatedString for -2 bytes*.
Takes an integer as the output variable, and unifies the answer with the input variable (so the opposite of what is usually done).
Atrociously slow, as concatenation on integers computes constraints on the digits with powers of 10, instead of being "string" concatenation.
### Explanation
```
Ṁ The answer has 2 or more elements
∧ And
⟦₂? The answer is a range between 2 integers
?c The given input is the concatenation of this range
```
[Answer]
# Regex (.NET) + `x` flag, ~~418~~ ~~209~~ ~~204~~ ~~199~~ ~~132~~ ~~115~~ 99 bytes
*-209 bytes (418 → 209) thanks to Neil*
`(\5$|(.*(?=(0.*1|1.*2|2.*3|3.*4|4.*5|5.*6|6.*7|7.*8|8.*9)(?<=(.)))|(?=9+(?<4>1))).9*(?=(\2\4 0*)))*`
Returns its result as the list of captures on the Balancing Group 1 stack.
[Try it online!](https://tio.run/##RY@xasMwFEV3f4Uxgkhq8rAsx46Suil06lDo1iHJYFwlNjiykRVSEmXtB/QT@yPuox26PLj3cA@8vjtrO9S6bUdii43VB/2xWy6NPtPHyUi3c@IpcLouaAxceAE88Qlw6SXw1KfA534OPPMZ8NznwBd@AVwxur4vKDDGPE7VHcb0QWAE9evaJts0jDkWfJw8TqOn7tg3rX6fPh9MZ/Vr6Zy25q1unB76stIRW5FLEa/2CMuqpqQNGxOSxvQnx67NnpJjQSy8lK6q9YCY/bUXdj1blMzqbnA3VIjVfw5npsM/28boMELj9@dXSNAEB9ud@mEjdlCVvTtZPbDodhtFItMgXygRCxFkWZYHiZKxFDKREolSSOI4wKuE@AE "PowerShell – Try It Online")
```
# Main loop - Iterates once for each matched number in the squashed sequence.
# There is no need to anchor, because the input is guaranteed to be valid.
( # \1 = push matched number onto the Group 1 stack
\5$ # Stop immediately if the previous iteration identified
# this as being next, and there is nothing following it.
|
# Using greedy quantifiers, the following, up to and including "9*",
# matches the number with as many digits as possible that is followed by
# the next consecutive number.
( # \2 = the prefix portion of the number that won't
# change when incremented
.*
(?=
# Depending on this next digit, capture its incremented form in \4.
# Only digits that do not carry when incremented are handled here.
(
0.*1 |
1.*2 |
2.*3 |
3.*4 |
4.*5 |
5.*6 |
6.*7 |
7.*8 |
8.*9
)
(?<=(.)) # \4
)
|
# Treat a prefix of all 9s as a special case, because when incremented
# it will be one digit longer, e.g. 999 -> 1000. In this case, \2 will
# be empty.
(?=
9+
(?<4>1) # \4 - Technically this should capture "10", but since
# our input is guaranteed to be valid, we can
# assume that the "0*" below will match the
# correct number of zeroes.
)
)
. # Skip over the first digit that will be different when
# incremented.
9* # Skip over the portion that will become all 0s when
# incremented.
# Match the next consecutive number. This constraint is what tells the
# above how many digits to match.
(?=
( # \5 = Capture the next number. This allows the last
# number in the sequence to be matched as a whole
# unambiguously, in case its digits form their own
# "nested" squashed sequence.
\2
\4 # Note that since this is followed by a "0", to get
# this to parse correctly we could either concatenate
# them as "\4[0]*", or enable the /x flag (ignore
# whitespace) and use "\4 0*".
0* # Technically this should match the same number of 0s
# however many 9s were matched by "9*" above, but since
# our input is guaranteed to be valid, we can assume it
# will do this without being forced, since none of the
# numbers in the sequence will have leading zeroes.
)
)
)* # Iterate as many times as possible, with minimum zero.
```
Solving this problem is a bit verbose in pure regex, since it has no concept of alphanumeric/ASCII order or sorting. So each digit needs to be handled as a separate case.
Rejecting invalid input takes **138 bytes**: `^(\6$|(?!0)(.*(?=(0.*1|1.*2|2.*3|3.*4|4.*5|5.*6|6.*7|7.*8|8.*9)(?<=(.)))|(?=9+(?<4>10))).(9)*(?=(?(7)\7))(?=(\2\4(?<-5>0)*(?(5)^))(.*)))*$`
# Regex (PCRE) + `x` flag, 107 bytes
`(\4$|(?|(.*)(?=(?:0.*1|1.*2|2.*3|3.*4|4.*5|5.*6|6.*7|7.*8|8.*9)(?<=(.)))|()(?=9+(1))).9*(?=(\2\3 0*))(?C))*`
Returns its result using a `(?C)` callout to report each split point (the number of split points will be one less than the number of consecutive integers).
[Try it online!](https://tio.run/##fVT/btpIEP7fTzHhLtddYywbpyTEmOguRWqlXlqhVOopIMuYBTZxbGttl0tq/r0HuEe8Bymd9Q/iADoLod2Z2fm@@WZ2/TjuLH1/@wsP/SCbMxjEvmD6aqj4K0@AG99NwYFx64/1@mFmZX89PX29XfXWK7Ilk7Nfc3KVE12l5MohV5eGrpq5qavdvKurVm7p6ll@pqtv87e62st7unqen@vqRX6hq308MnCITinNiTzebxMTN3pflbkm3YkFhkrRc02puqX78C0N1Nhx47ZpKy/Uk3TOI8m9aRI8XL628QitzHs8jGtavjE/jcRQ4WEKMTpTlwkRCeJHYZJCoY76yJLEWzL6HZEvL30MgMEAKqtcFnYWzgMbBEszEYJpb5TCWuYfYOIheGGyZsIusB6fXN8LgihLiWxFvXFnQeQ/gOpT@K4AfuUZPc6SlTvz/Afid4Z@JgRDpnGU8JRHIbWL0ArasJVNCeHxkNR54jusPWAhiWnHnDqGDRnGWF03hUju5IElLorggnmpFTriLLVBkgRVMBuayqAUcSrK04IlWZCWa6nhYpGwVAMsCmGX6ar0RKUgd9a0Jo2DVyoQPcY8YCTW4PP1eOSOvt6Obt6N3mnwWwlTLuq8RlU1XwA5EYzW5S@KLi4I1oDRGrRksoKQAA/xi@NwOr@E02QS4oQ1cpY4VeJmW5DjS8NK9wLzEVnRs5SvUGzJ0oCHjJRjwkOtFI/adRMaDfUD5glSQZVCSPlqMdjfzCeCaXDz5ePHKo/uu9gTQuttwp@Z3BnFrxJWA6uRVIpTJh46BuR5hXLilAqPx5/G7s2nP3@/vX7f5FgffaaAQLLV5M0kfENtLNa0X4Ut1oKnjPwvQVOT@kRSCWxPliakBf/98y@0Xuy7nJsj3GGA3T5Cr/KeOHCsnGoOWiPZ@lYTAliQsL18uzrvZJmyr7y@DbtSZce9LI3g3qm7OGNLeclsG9rt@32ONU9O67K1ozU3Y@@dXW58UAg9lrPgW1V3mkxbe/MBbeBHsstvhg/iw6Frc0gFBcBri@Oo3kMH@HGyGDFwZGuq8j6E37yAz2Hupd60UWmFewhzbHokfU2CvxqcQ/yC22v7Zm@Myv@FYAxnhe4e5@qlUjZbs2udKecXfdMwTaXX650r3b5lWKbVtSz09PvoMQwF//um@cNfBN4y2XYCeUV/Ag "C++ (gcc) – Try It Online") - PCRE1
[Try it online!](https://tio.run/##fVbvUuJIEP/OU7TZu92ZGHIJKIIhWq5SpVW7usVi3d6qlQphgGhIUknQ0w1f7wHuEe9BzuuZTCAItykLMt093b9f/0MvjusTz3t9N2JjP2Tw5bTfazinV2c95/ryYuD8fnE2OId27Z0fesF8xKAbewlr6NOjmjd1E3Dimzuwoa98fHp6GDbnfzw/fxtMW09T8kpu937JyXFOdJWSY5scHxq6auamrjbyhq4286au7uV7urqf7@tqK2/p6kF@oKvtvK2rHbzStYlOKc0Jv97ZJSYe9I7Kfd02bptgqBQ1p5Sqr/RteEUDNbadeNe0KtjTbORHHHtVlPjhZF3mRyhl7mzTrip5ZF4WJUc1P8wgRmXmsCSJEuJFYZqByI46Y2nqThj9gZEPDz00gG4XpJS/CjkLR4EFCcvmSQimtdhwyc9eNGIaDKMogMgeu0HKKPyoAT4ilPR509hv3VlC7I@BiGI5EyYdOdKKFM5IUe3r0/OTflulUqlB6r@waExK8PBbKanYYy1EFP6QCI4LJl40z@AQlmwp56iIayAQHILyJgPisqLgLeU2VGiBfZmL2qImnBXJ7mIijsAN0yeWWCJLs2fHc4MAw0qu8uQMg8h7ANXT4DHyR6CO3MwtE8Yzw8@wYwPhapW@XzmiZXSjwFKE0@N5OnWGrvdAvPqRN08ShuWJo9TP/Chch21w2AKd64ekjBrfYA8FLCQxrZt3tmHBHG2aDSfDguKJX5jYMqggXfQcKuJ5ZoHkh5UDNWHleeZm3tQRbNTVe@EtYek8yLQi85ac7a8X33tCMh6nDJXIGEFNsumagRoVGS954YyX8WexHzAie@Hrl0Gfxpq8@r3Xv3IGvf7ni8uTQe@sFPe@DXqXZ/z8XkCR3xKAQVf9upOwZfqrAyA@pV2Fsb2RBAfPbsaccRLNnNjNMpaEJMGevrz@9Ek6qN7BYc3Ynxnmrnyzt@mlW7LhBRksG7B0oVW6UtvWYIWDcZSAmOwXXn1RcBzUALcwKebHD7Wi9tQqe6jSj17A3IRIX0WReLXX8Qvq1VIJf7rnYGsRKt3rfLr5yRB/q2Tiu6RUCcPLVIQ6sg3Icxl3x5a17vev@s7l1eeTwel5FXZ594UCxuQ7i3y4DT9QC/mb1prZ@CnxMdk/xWpqPGUimzBGRUoU@Oevv0FZyZc@F1vAd41t4H7KpdqQ5WhlyZxVIwHDxfzG8ZLuDWfLK@6XY75kzHvBnWcR3NtlfYdswreHZcHu7v1bsCVgn5bsta3Uq7b39tI3/uIQus2nwMt5jonya3qnlGmXVYBd8Ld4588QJ@RhU7XYhIIJwI2DjareQx387WDRomvzGkl6F@GjG@Ai5315V2Eq426G2dZEHL7Gg6/1z2Z8gW1dvnjTTYv/WyW4ehgjq8HZXFGFwfJMq6u9UOIWXP4/UHQa/qK8mo3mXu2g3TEN06y1Wq2DWqPTNJpms9FsoqbTQY1h1PCzY5r/euPAnaSv9UA4r7f/Aw "C++ (gcc) – Try It Online") - PCRE2 v10.33
[Attempt This Online!](https://ato.pxeger.com/run?1=fVbdUttGFL7t-CkOSpvsCluVbDA2smAoeAZmEsg4zjQNMBohr22BLGn0A4XIt32A3vamN73MA9HLTh-kZ1crW8ZuPGBrz-_3nZ-1__jqRn6W8H974rpfL5WGH7kxazY6yvXz4NWIjb2AwfvjQb9pH1-c9O2P52dD--ezk-EpdGqvvMD1sxGDnnDSpgc1d-rEYEeX12DBQPnp4eHuppX98vj4aThtP0zJX1k6bnSe78jVzvc5OcyJplJyaJHDfV1TjdzQ1Gbe1NRW3tLUnXxHU3fzXU1t521N3cv3NLWTdzS1iy49i2iU0pxw9-42MfCgdVUe66p51QJdpag5plQtUv793b_0JRqlDmpk2dG2YVaoJOnICzmVqij2gsmqzAtRypzZul1Vcs_cNIwPal6QQoTK1GZxHMbEDYMkBVEsdcaSxJkw-gUz7--7aAC9HkgpfxRyFox8E2KWZnEAhjlfC8nPbjhidbgJQx9Ca-z4CaPwpQb4EqlkzMvmbvvaFGJvDET0zp4wGciWVqQIRormfzw-PRp0VCqVdUi8JxaOSQkefiwlFXvsicjCXySEw4KJG2Yp7MOCLeUcFeEGAsE-KC8qIJwVBb2Uq0ChBfZFLWrzmghWFLuHhTgAJ0geWGyKKs0ebdfxfUwrucqTfeOH7h2obh3uQ28E6shJnbJgvDL8DFsWEK5W6etlIFpm1wssRTotypKpfeO4d8RtHLhZHDNsTxQmXuqFwSpsncMW6BwvIGXW6BJnyGcBiWjDuLZ0EzK0aTXtFBuKJ-4wsWRSQbqYOVREWWqC5IedAzVm5XnmpO7UFmzU5XMRLWZJ5qf1ovKmXPUPZ5_7QjIeJwyVyBhBTdLpioEaFhUveeHKl_lnkeczImfhw_vhgEZ16fq5P7iwh_3Bu7Pzo2H_pBT3Pw375yf8_FpAkZ8SgE6X87oVs0X5qwsg3qVdhbG1VgQbz07K7HEczuzISVMWByTGmT7_-PatDFD1wWVN2a8p1q58sjbpZViyFgUZLAawDFGvTGV904AVAcZhDGKzn3j3RcNxUX28lEmxP15QL3pPzXKGKvPo-syJiYxVNIl3exW_oF5tlYinuTaOFqEyvMa3m5908bcsJj5LSpU0vE1FqgNLhzyXebcs2evB4GJgn1-8Oxoen1Zhl75PFDAnv7PIm6vgDTWRv2GumI0fYg-L_U2sRp2XTFQTxqhIiAL__PY7KEv5IuZ8A_ievgncN7lUB7JcrTTOWDUTMLyYXwRe0L3kbHnHvXLNF4z5LDhZGsKtVfb3hk347WGasL19-xJsCdijJfv6RupV21trERu_cQjdFFPg5TzHRPkhuVbKsssuwDZ4G6Lz1w1uyN26ar4OBQuANw4OqnoLDfA2g0WLnsV7JOmdBfeOjxc5n8vrClOZdz3NpiHi8Os8-cr8rOcX2Fbl8xfTNP-_qwSvHsbIcnHWr6jCYHGm1au9UOItuPg9UEwafqMUP3b-fG4YzdZOba_TNXTDqLXb7b1as9vSW0ar2WqhpttFja7X8L1rGIXXfw) - PCRE2 v10.40+
This is a straightforward port of the .NET version.
```
# Main loop - Iterates once for each matched number in the squashed sequence.
# There is no need to anchor, because the input is guaranteed to be valid.
(
\4$ # Stop immediately if the previous iteration identified
# this as being next, and there is nothing following it.
|
# Using greedy quantifiers, the following, up to and including "9*",
# matches the number with as many digits as possible that is followed by
# the next consecutive number.
(?|
(.*) # \2 = the prefix portion of the number that won't
# change when incremented
(?=
# Depending on this next digit, capture its incremented form in \3.
# Only digits that do not carry when incremented are handled here.
(?:
0.*1 |
1.*2 |
2.*3 |
3.*4 |
4.*5 |
5.*6 |
6.*7 |
7.*8 |
8.*9
)
(?<=(.)) # \3
)
|
# Treat a prefix of all 9s as a special case, because when incremented
# it will be one digit longer, e.g. 999 -> 1000. In this case, \2 will
# be empty.
() # \2 = empty prefix
(?=
9+
(1) # \3 - Technically this should capture "10", but since
# our input is guaranteed to be valid, we can
# assume that the "0*" below will match the
# correct number of zeroes.
)
)
. # Skip over the first digit that will be different when
# incremented.
9* # Skip over the portion that will become all 0s when
# incremented.
(?=
( # \4 = Capture the next number. This allows the last
# number in the sequence to be matched as a whole
# unambiguously, in case its digits form their own
# "nested" squashed sequence.
\2
\3 # Note that since this is followed by a "0", to get
# this to parse correctly we could either concatenate
# them as "\3[0]*", or enable the /x flag (ignore
# whitespace) and use "\3 0*".
0* # Technically this should match the same number of 0s
# however many 9s were matched by "9*" above, but since
# our input is guaranteed to be valid, we can assume it
# will do this without being forced, since none of the
# numbers in the sequence will have leading zeroes.
)
)
(?C) # PCRE callout - report each split point to the caller
)*
```
Rejecting invalid input is not so straightforward to port from the .NET version, and takes **175 bytes**: `^(?>\7$((9(?=9*\4\5(\3?+0)))*(?=(?(6)\6))\4\5\3?+)?|(?|(?!0)(.*)(?=(?:0.*1|1.*2|2.*3|3.*4|4.*5|5.*6|6.*7|7.*8|8.*9)(?<=(.)))|()(?=9+(10))).(?=(?1)(.*))9*(?=(\4\5 0*)\6)(?C))*$`
# Regex (PCRE2) + `x` flag, 166 bytes
`(?=(.*))(?:^(?3)|((?<=(?=^((?|(.*)(?=(?:0.*1|1.*2|2.*3|3.*4|4.*5|5.*6|6.*7|7.*8|8.*9)(?<=(.)))|()(?=9+(1))).9*(?=(\4\5 0*)))*(?=\1$)(?>\6$|)(?(?=$)^)|(?2)).))(?3)|.+)`
Returns its result as the list of individual matches.
[Attempt This Online!](https://ato.pxeger.com/run?1=XVDLbtswEESv-gpGICIuY9OiZMuWFVWXukGAIinc3qKYUA36gciyISlAgTDXfkCuvQQo2mu_Jz32S7q00xxykLi7M7Mz5Pcfu9Xu8c-b36cZFoTWJCVuzyWC7Gq9VLXelcVcM68neKbUqihbNd9udutS1znLIcmnvcbrEA-_BQ7VUltC1eqqbZhS788_TJSCDpGAK93eVzdxFtua0XXqJ7RMF8hv2KfP784vIIE7sl4wWl41bV3qCivoyus0dfPKBSQ3t18QwXHH73QlJA5BPmFHjN6k-7Sbop2vVFGWjNYdpNENABCqD2hZNK3SdY32cJSmH6eTM3VxqSbT6eX0_y56Q4xBBZA7G2UNer7aWv-EYGSZENsTWgqP_P324CX3LzogeC9dzFeMbq78a1I0hFZw4HvEE7R6yYsmx8d7k2d0YkONkfQqp9o0S4b3vH_18jj7edsuuqOnXyxLmeAALBvPWBaCYSw7TXE6w8JYyDKysS-4NFLwwASChyYUvG_6gg_MQPDIRIIPzVDwkRkJHsN-hcC3M8zK4xMmsRExt7vyfj4gPlqCbXNJkfI2j6jBEwcUZijLAuTbVJhInMAh7ePz8dSVQdh3hqNY-lI6URQNnSAO_VCGQRgiEseI-L6D_1jKg-of)
A lot of overhead is added to achieve this output method. Captures are not preserved from one individual match to the next, thus to avoid incorrectly splitting the last number, the regex must look all the way back to the start, then parse forward from there, for each individual match. There's no variable-length lookbehind in PCRE2, so it is emulated using recursion.
[Answer]
# [Haskell](https://www.haskell.org/), 62 bytes
```
f s=[[a..b]|a<-[1..],b<-[a..a+length s],([a..b]>>=show)==s]!!0
```
[Try it online!](https://tio.run/##JYrRCoMgGEZf5S92UayJvw6bMHuDPYHIMFYzZhYZdLN3d8JuPg7nfM7Gz@B9SiNEpbUlpDdfe79oJMQ0fYas7NkP4b07iKap/p@uU9EtR61UNEVB02ynAApmuz6eUK3bFHYy1nCCY9leEUpk/ArtTSJFBCFEC0xyypEzznORMhdKIa9ELNMP "Haskell – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~10~~ 8 bytes
```
øṖ⌊'ḣtṡ⁼
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLDuOG5luKMiifhuKN04bmh4oG8IiwiIiwiXCI3ODkxMDExXCIiXQ==)
Incredibly slow for some inputs, reasonable for others.
## Explained
```
øṖ⌊'ḣtṡ⁼
øṖ⌊ # All sublists of the input, as numbers
' # Keep only those where:
ḣtṡ # The range between the first and last item
⁼ # Exactly equals the original item
```
[Answer]
# [Julia](https://julialang.org), 71 bytes
```
! =length
*(s,a=1,b=a,j=join(a:b))=!j<!s ? s*a*-~b : j!=s ? s*-~a : a:b
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VY-xasMwEIZ3PcXZQ5CNXCQr2HGo0qENnQodOhSCB4UorYxRgux0zIt0aJY8Rh8kb9NTHEIqEJz-__77Tt_HZtdafTgcd_06m5yeI1CtcR_9J0lpx7QSbKk0a1SzsY7q6TJJVNTcRx08QJfqNNsvYQpNpAYh22t8Yttl3M9646G1zoB14I1ehbqjCQE8lhlQ0G1b29OgM_DxAuo0m8UJOXcE33zplr6YXt9tte8MNcmQ9iqldii33rq-ddSCmoG_2BBhFkajqxvP31_nj2_zpynEDExCjFsNax5OvyKXY7iebAYLwSBnIBmMa1JOKsGFuHFLBhMGFQPB8YqaFEVR_h9QFAyKsiZ5JbkUMpcyIIKTY05iTiJDBghSJGKqCjGc38xAJSA4R1Pw6rrCYAY2avXwiz8)
Takes a string as input and returns a range (`2:5 == [2,3,4,5]`).
A brute-force approach that's actually not that bad. `a` is the starting number and `b` the last number. We increment `b` until the list is too long and start over for `a=a+1`
[Answer]
# [R](https://www.r-project.org), 66 bytes
```
\(n)repeat for(i in 1:(T=T+1))if(n==Reduce(paste0,i:T))return(i:T)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72waMHK0rziwtLE4gzbpaUlaboWN51iNPI0i1ILUhNLFNLyizQyFTLzFAytNEJsQ7QNNTUz0zTybG2DUlNKk1M1ChKLS1INdDKtQjSBWkpKi_I0QGyISZthJmtYGhoYGhoaGRpDZRYsgNAA)
[Answer]
# [J](http://jsoftware.com/), 37 bytes
```
0{<((=<@;\"1)#&,<\"1@])".\<@":@+/i.@#
```
[Try it online!](https://tio.run/##TYzBCsIwEETv/YolhSbBNO4mkpqYSlDwJB4815NY1Isf4MfHCGJ7GIaZnbfPzDQfoQ/AQQFCKGo17M/HQ8Z3FKKPaTMwknWjYvF0kUwPMbGQFsuHTnWW1WmnIYIQbWi2StaqbOB7gt8MClHdrvcXjMDJ2BX/p27tCYmmwjnXTcl4i5assXYOeV8gxFlB6MuT/AE "J – Try It Online")
Not much in the way of golfiness (and it could surely be golfed more), but it executes decently fast, solving the test cases effectively instantly.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 10 bytes
```
ḟo=⁰ṁsṁṫḣN
```
[Try it online!](https://tio.run/##yygtzv7//@GO@fm2jxo3PNzZWAzED3eufrhjsd////@VDA0MDQ2NlAA "Husk – Try It Online")
```
ṁ N # map across all integers N & concatenate:
ḣ # range 1..N
ṫ # suffix series: 1..N, 2..N, 3..N, ...
ḟo # now return the first series
=⁰ # for which the input equals
ṁs # mapped & concatenated string representations
```
[Answer]
# JavaScript (ES6), 82 bytes
```
f=(S,i=s='')=>(k=s+=S[i++],g=q=>q==S?o:S.match(q)?g(q+k,o.push(k++)):f(S,i))(o=[])
```
[Try it online!](https://tio.run/##bZBBbsIwEEX3PcWIDbY8NXaGOhjJcIgsoyyilIQ0FJOG9vqpXRUk6lryxnrz/f681V/11Hz0l@vz2b8e5rl1rMDeTW655G7HBjcJV5S9EBV2bnS70bli77eFfK@vzZGNfN@xUQzo5eVzOrJBCM63bczgnHlXVnxu/Hnyp4M8@Y61bKEzWi/gdjiH1QpKjZAhEMK6evrD5xurldaLBz5H2CBYBK3C1cmQMSZPPjEGweQJm1lSpCkjimK/bBayKWRTMKOoFtwolbM2yCn1KBceo5hSKa6VvVe547GD/adE3NSLufVPNoUgpfxpP38D "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
S, // S = input string
i = // i = pointer in S
s = '' // s = current prefix extracted from S
) => ( //
k = s += S[i++], // append the next character from S to s,
// copy the prefix in k and increment i
g = q => // g is a recursive function taking a string q
q == S ? // if q is equal to S:
o // success: return o[]
: // else:
S.match(q) ? // if q is found in S (*):
g( // do a recursive call:
q + k, // append k to q (q is coerced to a
// string if it's not already)
o.push(k++) // append k to o[] (and increment k)
) // end of recursive call
: // else:
f(S, i) // try again with an additional character
)(o = []) // initial call to g with s = o = []
```
(\*) This doesn't mean that **q** is correct so far because it can be found in the middle of the string. The purpose of this test is rather to know when to give up.
[Answer]
# [Curry (KiCS2)](https://www-ps.informatik.uni-kiel.de/kics2/index.html) + `:set +first`, 37 bytes
```
f(x#y)=[x..y]
x#y|y-x>0=[x..y]>>=show
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m706ubSoqDI-OzO52GjBgqWlJWm6FjdV0zQqlCs1baMr9PQqY7mA7JpK3Qo7A6iAnZ1tcUZ-OUTxptzEzDwFW4U0BSVzC0tDA0NDJahEtJJVcWqJko6CknZaZlFxiVIs1HwA)
A port of [Fatalize's Brachylog answer](https://codegolf.stackexchange.com/a/249210/9288).
This does not work on PAKCS.
[Answer]
# Python3, 142 bytes:
```
f=lambda x,l=[]:l if''==x else max(w,key=len)if(w:=[f(x[k+1:],l+[int(x[:k+1])])for k,_ in enumerate(x)if l==[]or int(x[:k+1])==l[-1]+1])else w
```
[Try it online!](https://tio.run/##XY1BDoMgFET3PQU7IdoEpLFi8k9CSENTSI2IxtqIp6fooqnd/XnzZ2Zc5@fgeT1OMVpwur8/NAqFA6kah1qbZQABGfcyqNcBL0VnVnDGk9bipQFpcZBdzhpVuFy2fk6ySVoRRewwoa64odYj49@9mfRscEhB5CDVJ/f3H8DJM1Pbua8tcZw23@KMlfySEXL6gmstGGXswKqquh5AKTjljJec/6WFSGlKj4xRsRfGDw)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 13 bytes
```
ef!-.+T1sMM./
```
[Try it online!](https://tio.run/##K6gsyfj/PzVNUVdPO8Sw2NdXT///fyVzC0tDA0NDJQA "Pyth – Try It Online")
Accepts a string as input.
```
ef!-.+T1sMM./
./ String partitions of the input
sMM Convert elements to integers
f T Filter for paritions T such that:
.+ The list of deltas between elements of T...
!- 1 ...becomes empty when 1s are removed
e Keep the last remaining partition
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
ŒṖḌIİƑ$ƇḢ
```
[Try it online!](https://tio.run/##y0rNyan8///opIc7pz3c0eN5ZMOxiSrH2h/uWPT/cLu3ZuT//4ZGxiY6CuYWloYGhoY6CmZmZuY6CkaWxgbGhsZGxsYgSUtLoKSBAZBhaGAJUgRWCwA "Jelly – Try It Online")
```
ŒṖ Find every partition of the input's digits,
Ḍ and convert each slice in each partition back to an integer.
Ƈ Filter to only those which
I have forward differences
İƑ$ which are all their own inverses (i.e. 1).
Ḣ Yield the first remaining partition (nontrivial).
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 94 bytes
```
f=lambda a,d=2,c=1:(r:=(*range(x:=int(a[:c]),x+d),))*(d*"%d"%r==a)or f(a,d:=d%len(a)+1,c+1//d)
```
[Try it online!](https://tio.run/##XczRCoIwFIDh@55CAvEcHbjjQt3gPEl0sZxWYFOGF/b0y7oI7PaH759fy33yqp1DjAOP9nl1NrHCcSU6JgPBMOTB@lsPq@GHX8CeTXdBsRYOBWIOLj@m7pgGZotTSAbYtGGXjr0HiwWJrqCydBjn8OEDZFSpU4Z4@IWm1SSJdq2u62YXKq2kIlUp9ae13rSU@0ZSf4fxDQ "Python 3.8 (pre-release) – Try It Online")
Nothing too fancy here.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 28 bytes
```
FIEθ…θ⊕κFLθ⊞υI…ι⁺⊕ι⊕κΦυ⁼θ⪫ιω
```
[Try it online!](https://tio.run/##bY27CgIxFER7vyLlXVjBVCqWQUFRCP5BiNdNMHtjXopfHzdbWTjdwJwz2qiovXK13n1kIFTKcFFPCD0TH@1QGD@XI@mII1LGGzy6FjYDZ6QhGwhTlyUZKBPXHFdFA4LtmXQlwS9tu3@23UJGSxkO1mWMTbMPRbnUvk/eUlO952Gt682Wrzivy5f7Ag "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
FIEθ…θ⊕κ
```
Loop over all of the nontrivial prefixes of the input.
```
FLθ⊞υI…ι⁺⊕ι⊕κ
```
Create ranges of length 2 up to the length of the input starting at each prefix.
```
Φυ⁼θ⪫ιω
```
Find any ranges whose concatenation equals the original input.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 51 bytes
```
n=>(g=s=>s.match(n.join`,?`)||g(s+[,++i]))(i='')[0]
```
[Try it online!](https://tio.run/##dZBBbsIwEEX3PcUoGxxlamwPOHhhOEgUiSiFEAR2VaOuuHuwK6VVi2tpNtY8zfv/3H12of8Y32@vzr8dpqOdnN2ywQa7Dfza3foTc/zsR7fH3b683wcWqgaramzLko12sSgb0U69d8FfDvziB3ZkDee8kIpWBcwvbsNyCY1EUAiEsGpfMlC9MVJIWfyGaoQNgkGQIo7Mklrr@vmc1gi6zgLKkCBJiih5zoCKVyheoShKyTSqUt7VmOgqxB/X@Js8hcgzUpjveD9MymX@CZZ6XOu5mOceEeLWVy3TAw "JavaScript (Node.js) – Try It Online")
Input an array of characters. Output comma separated numbers as a single string.
It passes all testcases listed here. But I still have no idea if this answer is correct or not. Failed testcases are welcomed and I will try to fix it some how.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
.œ.Δ¥P
```
[Try it online](https://tio.run/##yy9OTMpM/f9f7@hkvXNTDi0N@P/f3MLS0MDQEAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeV/vaOT9c5NObQ04H@tzv9oQyNjEx1zC0tDA0NDHTMzM3MdI0tjA2NDYyNjY6CMpSVQxsBAB0haGhrGAgA).
**Explanation:**
```
.œ # Get all partitions of the (implicit) input (the partition-list is ordered from
# longest (all single digits) to shortest (single original integer))
.Δ # Find the first which is truthy for:
¥ # Pop and push the deltas / forward differences
P # Take the product of that
# (only 1 is truthy in 05AB1E)
# (after which the result is output implicitly)
```
[Answer]
# [Prolog (SWI)](http://www.swi-prolog.org), ~~68~~ 64 bytes
*-4 bytes thanks to Steffan pointing out a golf I somehow missed*
```
A+B:-nth1(X,_,_),between(1,X,Y),numlist(Y,X,B),concat_atom(B,A).
```
[Try it online!](https://tio.run/##bY5BasMwEEX3PsVsjGwyDhpNkKMuCvEZunAowaRBNIbYKrVCju@OQkkaUsEsJL357399h1P4rKZLP8@bRfNSjfFIRYsddiV@@HjxfiwIW9yWOJ6HUz/FYivXpsRDGA/72O1jGIoGN@VynhUZXqlFu4T7yatXeCcEg8AIq12WqXrtSBP9Ba9UjbBGcAikZSih1tr6v0BrEWydCONYM7FhvqmvhJEclhwWNye52Dnpc3g7@slD7AcP4RyzXDknhbR@KiTvqYzWaU0J4x5b/1KprvzsfgA "Prolog (SWI) – Try It Online")
Pretty straightforward.
### Explanation:
```
A+B:- % A predicate with an atom A and a list of numbers B
nth1(X,_,_), % Find a positive number X
between(1,X,Y), % And a number Y between 1 and X
numlist(Y,X,B), % Generate the range [Y,X] into B
concat_atom(B,A). % The concatenated list should be the same atom as A
```
[Answer]
# Rust, ~~242~~ 235 bytes
```
|t:Vec<u64>|(0..).map(|v|{let mut y=vec![];y.extend(t.iter().scan((v,0),|(a,b),c|Some(if *b*10+c==*a+1{*a=c+*b*10;*b=0;Some(*a)}else{*b=*b*10+c;None})));y.last().unwrap().and(Some(y.into_iter().flatten()))}).flatten().next().unwrap();
```
Tries every initial number till it finds one that completes the sequence. [Playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=952da1e61d2cccfaa8139156e8d2b8f5)
Saved 7 bytes by using `let mut y=vec![];y.extend(X)` unstead of `let y:Vec<Option<u64>>=X.collect()`
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 120 bytes
```
lambda s:g(s)[1]
g=lambda s:s and[j+[k]for i in range(-len(s),0)for j in g(s[:i])if{*j[-1:]}<={~-(k:=int(s[i:]))}]or[[]]
```
[Try it online!](https://tio.run/##PY7LDoIwEEX3fsXspCqmQw3QRr6kdoHhYQFL07IxBH8d242bWdxzz83Yz/KaDSut27vqsU/1@9nU4EWfeCJRHfrqH3moTSOHsxxVNzvQoA242vRtkk6tCf0LJREMEQRfCq2I7tbTIFMUartX6zdNRlFpswSqhSJkU7OTUqk9ij6KR8zYDYqSI0WEPM8LyDijDFnGWCCcB0IphMsRj1dvJ70kRIB1cbcLf5D9Bw "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Raku](https://raku.org/), 44 bytes
```
{+«m/^(\d+?)+<?{1==all $0[1..*]Z-$0}>$/[0]}
```
[Try it online!](https://tio.run/##DcnRCoIwFAbgV/mREZWk52wxG7j5HpmJULtSCruSsSfqLXqxtZvv5ns/11mnZcPOw6ZQ/r5Lfd/fHmV3KNsusLXTPENQz1V1HK4nQdGJuqchps@0oRAjrEPwEGMs4F8rWpbqjOZimJihtW4gjSLFSiqVx5g8RMgaZpf@ "Perl 6 – Try It Online")
The regex match `m/.../` does the heavy lifting here.
* `^` matches the start of the input string or number, as usual.
* `(\d+?)+` matches a sequence of groups of digits, each of minimal length such that the overall match succeeds.
* `<?{ ... }>` is an assertion; the Raku code inside the braces must evaluate to a true value for the match to succeed. Inside the braces, `$0` is a list of the matched digit groups. `$0[1..*] Z- $0` is the tail of the list zipped using subtraction with the list; this is the list of differences between each adjacent pair of digit groups. `1 == all ...` tests that all of them are equal to 1. If the assertion fails, the match backtracks to try a different group of digits.
* `$` matches the end of the input, as usual.
Finally, `[0]` extracts the first matching group--which is a list, since the group was followed by a quantifier--and `+«` converts those match objects to numbers.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 71 bytes
```
f=(s,i,p='',...a)=>p==s?a:s.match(p)&&f(s,-~i,p+i,...a,i)||!p&&f(s,-~i)
```
[Try it online!](https://tio.run/##bZDBTgMhEIbvPsW4h3aJUwpMyxYT9EGMB7Lt6ja1S6Tx1Pjq69DYTSqScIGP4fv/ffgKqf3s42lxHLa7cex8nbDH6OdzlFIG4Z@i9@k5PCb5EU7tex3FbNYxtPhm7KG/UNiL8/k@ThdibIdjGg47eRje6q6utKFVBdclBCyX8KIRDAIhrF7v/vDNxmmldXXDNwgbBIegFW9dPLLWNsUn1iLYpmCNI0WaDFEW@2UNzyaeTWxGWY3dqJRzjuWUupXjwyymVIlr5aYoE54zuH9C5KbW9pq/aAqB@76kH38A "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Write a function that takes in a string and for each character, returns the distance to the nearest vowel in the string. If the character is a vowel itself, return 0.
Vowels are : `aeiouAEIOU`
For the purposes of this challenge, `y` is not a vowel.
The input will be a string consisting of uppercase and lowercase letters.
## Edge cases :
* You will be tested for empty strings as well, so `''` is a valid input, which should return `[]`
* The input string will contain at least one vowel (unless it is the empty string)
* Obviously in case someone missed it uppercase and lowercase letters both exist
* It is also possible you end up getting nothing but vowels in a string, the answer in that case obviously would be 0 across the board
## Examples :
```
distanceToNearestVowel("aaaaa") ➞ [0, 0, 0, 0, 0]
distanceToNearestVowel("abcdabcd") ➞ [0, 1, 2, 1, 0, 1, 2, 3]
distanceToNearestVowel("shopper") ➞ [2, 1, 0, 1, 1, 0, 1]
distanceToNearestVowel("") ➞ []
distanceToNearestVowel("AaAaEeIeOeAU") ➞ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
distanceToNearestVowel("bcdfghjklmno") ➞ [11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0] ----> added thnx to @Shaggy
```
Input : String
Output : Array or string (or equivalent in your language of choice)
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins.
I will probably not mark any answer as accepted (since different languages different standards)
If you can and have some time kindly do explain your answers (this is mostly for me so I can understand how they work; I like learning. Obviously not compulsory.)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
e€ØcTạⱮJṂ€
```
A monadic Link that accepts a list of characters and yields a list of non-negative integers.
**[Try it online!](https://tio.run/##y0rNyan8/z/1UdOawzOSQx7uWvho4zqvhzubgAL///9XKs7ILyhILVICAA "Jelly – Try It Online")**
### How?
```
e€ØcTạⱮJṂ€ - Link: list of characters, S e.g. "shopper"
Øc - vowels "aeiouAEIOU"
€ - for each (c in S):
e - (c) exists in (vowels)? [0,0,1,0,0,1,0]
T - truthy indices [3,6]
J - range of length (S) [1,2,3,4,5,6,7]
Ɱ - map with:
ạ - absolute differences [[2,5],[1,4],[0,3],[1,2],[2,1],[3,0],[4,1]]
Ṃ€ - minimum of each [2,1,0,1,1,0,1]
```
[Answer]
# [APL(Dyalog Unicode)](https://dyalog.com), 23 bytes [SBCS](https://github.com/abrudz/SBCS)
```
⌊/∘|⍳∘⍴∘.-∘⍸'aeiou'∊⍨⎕C
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9TTpf@oY0bNo97NQOpR7xYgqacLZu5QT0zNzC9Vf9TR9ah3xaO@qc4A&f=Szu0QkE9EQTUgXRScgoIA5nFGfkFBalFQBYQOSY6Jrqmeqb6pzqGArlAFWnpGVnZObl5@eoA&i=AwA&r=tryapl&l=apl-dyalog&m=train&n=f)
Needs version 18 for the new Case Convert system function.
`⎕C` convert the argument to lower. According to the documentation this *folds* the case for case-less comparisons but it is actually implemented as converting to lower case, at least for the latin alphabet.
`'aeiou'∊` for each character, is it a vowel?
`⍸` get all indices of 1's (vowels)
`⍳∘⍴` all indices from 1 to the length of the string
`∘.-` table of differences between each index and each index of a vowel
`|` the absolute value of each difference
`⌊/` for each index in the string, get the minimum value
[Answer]
# [Haskell](https://www.haskell.org/), 70 bytes
```
(\z->[minimum[abs$i-j|(j,c)<-z,elem c"aeiouAEIOU"]|(i,_)<-z]).zip[0..]
```
[Try it online!](https://tio.run/##FckxDsIgFADQq/yQDjQB4gGsiYODk5MTJQYJ2F@B/hS7kJ5djG99ky1vH2MLw9j4WOVJJ8yYtqTts3Qo553PwvVHWYWPPoFj1uOynS/X252ZnaN4/NP0qiLpg1KmJYsZBqAV8wc6CMDKtBD5lbWvC9G@SpOO6Ac "Haskell – Try It Online")
[Answer]
# JavaScript (ES6), ~~83~~ 69 bytes
Expects an array of ASCII codes.
```
a=>a.map((_,x)=>a.map(m=c=>m=(v=x--<0?~x:-~x)>m|~2130466>>c&1?m:v)|m)
```
[Try it online!](https://tio.run/##bZFRT4MwEMff@RQXHkxJSgfbRJ22CzF78MknnwgxtSvDSSmBhfCw8NWRVsZM9HJtrr1f7/5tj7zljag/q5Nf6r0cMjpwyjhRvELoHXfeZaGooExR1NLO95@Cbd9t/L7zmDr3y3AVrKOIMXETbtWm9c7KGx4TB8DlxlwMky0WkAQYrp5a6EPszZi4CQoxLO08xytLN7muKllfihr6NzcFFr02nlG7H/OY7@SLfJXx28j8UfWv25OjyuyQH78KVWr3p2Jomo7AA4Z7DHcYIgy3GNaj3vkGqZM6JNP1joscNUAZCF02upCk0AeUoYQQ0qT2nYXNEpHz@nn8kPiEPGPDNw "JavaScript (Node.js) – Try It Online")
### Commented
```
a => // a[] = input array
a.map((_, x) => // for each entry at position x in a[]:
a.map(m = // initialize m to a non-numeric value
c => // for each ASCII code c in a[]:
m = // update m:
( v = // set v to abs(x)
x-- < 0 ? ~x // and decrement x afterwards
: -~x //
) > m | // if v is greater than m
~2130466 >> c & 1 ? // or c is the code of a consonant:
m // leave m unchanged
: // else:
v // update it to v
) | m // end of inner map(); yield m
) // end of outer map()
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~88~~ 85 bytes
-3 bytes thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper)
```
lambda s,E=enumerate:[min(abs(j-i)for j,y in E(s)if y in'aeiouAEIOU')for i,_ in E(s)]
```
[Try it online!](https://tio.run/##NYo9C4MwFEX3/oq3JYId2lFwyODg1MmpLeVZX5pnzQcaKf76NBZ6uRfOhRO2aLw7J13f0oS2HxCWsqnJrZZmjFRdLTuJ/SLHIxfazzCWG7CDRi4Fa9hZILFfVdNeOvFTuHz8lXv6GJ4IThWEmV0ELdmFNcqiSAL3iIPA/jnsy7gYHwLNmXIVKmyopQupLt9s6JcZ35N1XnwB "Python 2 – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 72 bytes, \$O(n^2)\$
```
f x|q<-zip[0..]x=[minimum[abs$i-j|(j,v)<-q,elem v"aeiouAEIOU"]|(i,_)<-q]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hoqbQRrcqsyDaQE8vtsI2OjczLzO3NDc6MalYJVM3q0YjS6dM00a3UCc1JzVXoUwpMTUzv9TR1dM/VCm2RiNTJx4kGfs/NzEzz7agKDOvRCVNyQkIHIE4EcRwUvoPAA "Haskell – Try It Online")
I realized I I was still holding onto an efficiency mindset when I was golfing this earlier, which isn't needed for codegolf. This goes through every letter in the input and checks the distance to every vowel taking the minimum.
# [Haskell](https://www.haskell.org/), ~~95~~, 92 bytes, \$O(n)\$
```
a%b=sum[b+1|all(/=a)"aeiouAEIOU"]
g u=u(%)=<<length
zipWith min.g scanr<*>tail.g(scanl.flip)
```
[Try it online!](https://tio.run/##FYexCsIwFAD3fkUIFlKFiHsitODg5CQO4vAqSfroSwxNsoj/HtuDg7sJ0myIaoV21Kn453g4/YBIHDV0HAx@Sn@53u781ThWdBFtp5UiE1yeGqu/GB@YJ@YxSMfSG8Ki9ucMSNKJbUlawthVDxh0XDDkneXDSr8KWwy8/gE "Haskell – Try It Online")
We create a scanning function `(%)`. This takes a number and a character. If the character is a vowel it gives `0` otherwise it gives one more than the provided number.
We scan the input from right to left starting with the total length of the list
```
bbabbabb
789012012
```
We chop off the extra number at the start. Then we do the same scan in the other direction
```
bbabbabb
210210987
```
We don't bother chopping the extra here, because next we zip the two together taking the minimum entry in each list
```
bbabbabb
21011012
```
And that is our result.
This answer happens to implement the original spec of the challenge giving the length of the list when there are no vowels, whereas the first has an error on this case.
[Answer]
# [R](https://www.r-project.org/), 82 bytes
*-1 byte thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen).*
```
function(x)Map(function(i)min(abs(i-el(gregexpr("[aeiou]",x,T)))),seq(l=nchar(x)))
```
[Try it online!](https://tio.run/##hZC/TsMwEMb3PoUVlrN0lSj/O3TIwMAALIWlynBNr4nBtYOdiDxNH44XCQ5USZGK/OnOuhu@38mf6zbK12RyXtonJse@frWfrBfdtjF5rayBVj5SBcOq5E4ZoLUHNWUNheOC28pBsiJWtskSbHEpg9DzB@iFyUtyASJl1xgdjsHpi5BQr0RKcfa134vVOYqxsskk5l7nm77/AGYoLn7eYb6Mk3xpq4rdCDpGHIY4pbcf9EuJW1JK6Z4f@JnTl39yOFlxcshlW5Rv73pn7Eie9f8JgDmKOxS3KG5QXKO4CikNuWXdNw "R – Try It Online")
(or **[R](https://www.r-project.org/)>=4.1, 68 bytes** replacing both `function` appearances with `\`)
---
Previous solution (with explanation):
### [R](https://www.r-project.org/), 83 bytes
```
function(x)apply(abs(outer(seq(l=nchar(x)),el(gregexpr("[aeiou]",x,T)),`-`)),1,min)
```
[Try it online!](https://tio.run/##fY@xDoJADIZ3noLgcpeciejMwODgogu6EBIKVCHBu/MOIr4MD@eLIChBBuBP2zT5@7WpapJMF8Bj9MQRQaEuLuKJudNcSx4XmeCkoiBl/iIQaSLKAhXR@CC5w@MUVOtShjm5KbxhJRWxfMBMlIHFKua1XrgO22qze8bpzC1iQSeLmqt3XZv@hpn/CAxjloripMsxaDNz@61Dv1vYoFMhJaphwRjtmwW6xXr96IVRF1zY4wFP6J6n/5yMwGg@ "R – Try It Online")
```
function(x){ # a function taking string x
a=seq(l=nchar(x)) # make a sequence 1..length(x) (empty if x empty)
b=el( # take first (and only) element of list with
gregexpr( # positions
"[aeiou]", # of vowels
x, # in x
T)) # with ignored case
c=outer(a,b,`-`) # matrix of position differences
# with length(x) rows and (# vowels in x) columns
d=abs(c) # absolute value
apply(d,1,min) # row-wise minimum
}
```
[Answer]
# [jq](https://stedolan.github.io/jq/), ~~73~~ ~~69~~ 62 bytes
-7 bytes thanks to [Michael Chatiskatzi](https://codegolf.stackexchange.com/users/90812/michael-chatiskatzi)!
```
[explode[]%32]|keys[]as$y|[indices(1,5,9,15,21)[]-$y|fabs]|min
```
[Try it jqplay!](https://jqplay.org/s/t4DNHUMWLd) `fabs`, like many of the math builtins, doesn't seem to work on TIO.
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, 12 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
¬£ð\v maY rm
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&flags=LVE&code=rKPwXHYgbWFZIHJt&input=ImJjZGZnaGprbG1ubyI) or [run all test cases](https://petershaggynoble.github.io/Japt-Interpreter/?v=2.0a0&code=rKPwXHYgbWFZIHJt&input=WwoiYWFhYWEiCiJhYmNkYWJjZCIKInNob3BwZXIiCiIiCiJBYUFhRWVJZU9lQVUiCiJiY2RmZ2hqa2xtbm8iCl0tbVI)
```
¬£ð\v maY rmUl :Implicit input of string U
¬ :Split
£ :Map 0-based indices Y
ð : 0-based indices in U of
\v : RegEx /aeiou/i
m : Map
aY : Absolute different with Y
r : Reduce by
m : Minimum
```
[Answer]
# [J](http://jsoftware.com/), 36 34 bytes
```
i.@#<./@(|@-/~I.)'aeiou'e.~tolower
```
[Try it online!](https://tio.run/##XY5tC4JADMff9ylGvTiF88yekwIlCoQgCPoAl52pWSdW9Cb86tddimdtbIztt@2fii5BESxdQIChD64Mi8Bqv92IhHi9BbE94@1ZdhkQE1GW8CdipHzwjL9YIcwOC2MORgSIKkMmWOpE7a3pMTypqAEMDobBNzf1UNP3mOc5Kyq4jdWFJisEId3xqU/XLGA75h/@5Py6XpG6onOcXrLrjVcrjvolP80xzDBMMUwwjDGMpMpGt/gA "J – Try It Online")
*-2 thanks to FrownyFrog*
Solved independently, but appears to be almost identical to ovs's APL approach.
[Answer]
# JavaScript, 75 bytes
```
a=>(g=a=>a.map(n=>p=/[aoeui]$/i.test(n)?0:++p>n?n:p,p=1/0).reverse())(g(a))
```
[Try it online!](https://tio.run/##bZBNb4MwDIbv@xVWtUOiZgnse5VCxWGHnXbaCXHwqKF0NIkI699nUKG00mLZlg9@bL8@4Al91bduuDN2R2OtR9QZa/SUUR7RMaMzp1WBln7b8la1ciA/MMO3yWa9dpnZmo0TTqcq4bKnE/WeGOesYcj5WFnjbUeysw2rWSGlXOFsq5JzWEwpKBIBFy9vYth3tZsjkAuWCrg/51A/RHm/t85Rf1k889fkUkTh63MDHO3MMcd3@qBPyr/O1D91UY/OmtTWzf7w0x2NDbPS@dQJeRPwKuBFwLOAJwGPk@7wiXL8Aw "JavaScript (Node.js) – Try It Online")
Input an array of characters, output an array of numbers. For input which is both non-empty and contains no vowels, it returns `Infinity`.
It would be 74 bytes if we allow return `false` in place of 0:
```
a=>(g=a=>a.map(n=>p=++p>n?n:/[^aoeui]/i.test(n)&&p,p=1/0).reverse())(g(a))
```
A typical solution runs in \$O\left(n\right)\$. Looks like most other answers are \$O\left(n^2\right)\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 72 bytes
```
lMin@Abs@Pick[j-#,Capitalize@l,"A"|"E"|"I"|"O"|"U"]&/@(i=0;j=i++&/@l)
```
[Try it online!](https://tio.run/##FcpLCsIwFIXhuctIoSi26FwqCaLQgbRQHZUOrjFt0@ZR0jjxtQh34ApdQk0ufPAfuBJsyyRYTmGqk0n8Pt8jV5hcRpxz2pddHEQ7GLgFwe8MiwgR9ER7J3Uy54yqcIXnPFlvuoQvl26IxZQbrmx50oV10ZRBlKrhZg/ayCre1njXggFqmRlxUIXvgoJ6P2YI/KHIxYVePd9jq4eBGZ8eAQJ7lrKMkbPf7qtu2q4XUmk0e01/ "Wolfram Language (Mathematica) – Try It Online")
Input a character list.
[Answer]
# JavaScript, 73 bytes
Takes input as an array of characters.
```
a=>a.map((b,x)=>a.map(c=>b=!/[aeiou]/i.test(c,y=x--<0?~x:-~x)|y>b?b:y)|b)
```
[Try it online!](https://tio.run/##NY6xCoMwGIT3vkWdEjCxs20iDh06deokDn9itFo1wdgSQXz11BR6cPB9cMN18AErp9bMZNSV8jXzwDjQAQxCInb4L5JxwY5JAarV7zJp6azsjGS8MEfI5ZRtLiWbw@vCRSbSBa8C@3NxiCAkincQsgoNbJ/aGDUFDM0hh6u6qbvKH8H3Vd08u1c/jHr38nfAMS71aHWvaK8bVKOCUupKjLH/Ag)
This started off at around 100 bytes but I tapped away at it through most of an insomniac night, determined to beat Arnauld's 83 only to come back this morning to discover that not only had he blown me out of the water by knocking 14 bytes off his score but tsh had also sniped me by a byte. Borrowing Arnauld's absolute value trick, though, allowed me to save 3 bytes putting me in second place (for now) so I'll take it. Still think there's a byte or 2 more to be shaved off this but that'll need to wait until caffeine kicks in.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 63 bytes
```
iL$`(?=(.*?)[aeiou])?.(?<=[aeiou](.*?))?
$.1;$.2
%(N`\d+
0L`\d+
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8D/TRyVBw95WQ0/LXjM6MTUzvzRW015Pw97GFsoDy2jac6noGVqr6BlxqWr4JcSkaHMZ@ICo//8TQYCLKzEpOQWEubiKM/ILClKLuIDAMdEx0TXVM9U/1TGUiwsom5aekZWdk5uXDwA "Retina – Try It Online") Link includes test cases. Explanation:
```
iL$`(?=(.*?)[aeiou])?.(?<=[aeiou](.*?))?
$.1;$.2
```
Looping over each letter, look for nearby vowels.
```
%(
```
Loop over each result separately.
```
N`\d+
0L`\d+
```
Take the minimum. (I feel there should be a shorter way to do this, but I can't think what is might be.)
[Answer]
# [PHP](https://php.net/) < 7.1.0 -F , 125 bytes
```
for(;$c=($a=$argn)[$i++];$r[]=$p)for($j=0,$p=-1;$p<0;$j=$j<0?-$j:-$j-1)!stripos(_aeiou,$a[$i+$j-1])?:$p=abs($j);var_dump($r);
```
[Try it online! (wrong PHP version, works with some test cases)](https://tio.run/##1UxLCoMwFLxKC7NI0EDcGoO7XkJEntpPhJpHoj1@0@QYHZiBYT784tT1nPXhgzBYrABZUHjucoCrqtEgDKMFy1LAZnUNtqox4E6b7LF1ulfY2kzVyGs8gmMfxUR3588aVG5KNMq@zVOaY76R5kNhWs83CwRp0uV/kGhe1sKv58P5PSZ1@wE "PHP – Try It Online")
[test the last case (or others) with the right version of PHP](http://sandbox.onlinephpfunctions.com/code/95fb8ff55bd8c4cb1a6bfee9bdcf3a3cee631372)
This is the first shot I gave it to it, without looking at other answers, pretty sure it can be golfed more using subte tricks.
Straightforward code, only for PHP < 7.1.0 because for newer versions, negative index is supported and accesses chars from the end of the string
displays NULL or empty string for an empty input, depending on the site. It would cost 5 bytes for initialization of `$r` to an empty array to be sure to have an array as output.
[Answer]
# JavaScript, ~~95~~ 85 bytes
```
a=>[...a].map((_,B,V)=>Math.min(...V.map((c,C)=>/[aeiou]/i.test(c)?C>B?C-B:B-C:1/0)))
```
## Edits :
@Neil Thanks for the 10 bytes
* since I've already spread the array, I can just call it using map's third param instead of spreading again
* Instead of `Math.abx()` do `C>B?C-B:B-C`
* change length a.length to 1/0
Any suggestion on how to improve would be appreciated
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 7 bytes
```
ẏƛ?ATεg
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJBIiwiIiwi4bqPxps/QVTOtWciLCIiLCJhYWFhYWFcbmFiY2RhYmNkXG5zaG9wcGVyXG5cIlwiXG5BYUFhRWVJZU9lQVVcbmJjZGZnaGprbG1ubyJd)
-4 bytes thanks to Lyxal.
```
ƛ # For each
ẏ # number from 0 to len(input)
T # Indices of
A # vowels
? # In the input
ε # Difference between each index and the given number
g # Find the minimum
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 20 bytes
```
IEθ⌊↔⁻κΦLθ№aeiou↧§θλ
```
[Try it online!](https://tio.run/##PYxBCoMwEAC/EjytkL6gJxGEgkK/sKZLE4zZmGza/n5rL53jwIzzWBxjVL2XkARGrAILZjisWUIKe9thWCvHJgSnaBU2a6YQhQrMlJ7i4eitGbmddYcUuHXWzPym4rASDHJLD/r8frH/c1WtnnOmopdX/AI "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
θ Input string
E Map over characters
θ Input string
L Length
Φ Filter over implicit range
§θλ Inner character
↧ Lowercase
№ Is contained in
aeiou Lowercase vowels
⁻ Vectorised subtract
κ Current index
↔ Vectorised absolute value
⌊ Minimum
I Cast to string
Implicitly print
```
[Answer]
# [Python 2](https://docs.python.org/2/), 112 bytes
```
s=input();n=0;exec"print min(abs(y-n)for x in'aeiouAEIOU'if x in s for y,z in enumerate(s)if z==x);n+=1;"*len(s)
```
[Try it online!](https://tio.run/##HYy9DsIgFIVfhbAU1CbqShgcOjg5@QC03sab2AvhJ4G@PAWHM5zvOzmuxK@le61BI7kUhVSkrwoyLNx5pMg2JGHmIMpIcrWeZYY0GECbHtPz9R5w/SMWWLflsvcClDbwJoIIsg12rXM7Puub4qcfUKO1cjMvnx5@AA "Python 2 – Try It Online")
# [Python 2](https://docs.python.org/2/), 115 bytes
```
def f(s,n=0):print min(abs(y-n)for x in"aeiouAEIOU"if x in s for y,z in enumerate(s)if z==x);n+1<len(s)and f(s,n+1)
```
[Try it online!](https://tio.run/##JY2xDsIgFEV/5YWJl9bEOqoMDh2cOvUDqDwiiX00QJPSn8eiwx3uOTe5S05vz5dSDFmwMrasznhdguMEs2OppyjzidH6ABs4FpqcXx/9cxiFsz8EEarN7V4L8TpT0IlkxGOwK7XhjZvu/iE@kGbzv2k6LFYKPb1MjcDyBQ "Python 2 – Try It Online")
# Ungolfed
```
# Relavant function
# Recursively check each indices in string
# s is the input string
# idx is the current index
def f(s, idx=0):
# The algorithm is
# We first list the vowels
# Take their all indices in string
# Take the absolute difference of the current position with the vowel indices
# Take the minimum
# Print
print min(
abs(index - idx)
for vowel in "aeiouAEIOU"
if vowel in s for index, char in enumerate(s)
if char == vowel
)
# Then check if current index+1 is less than the string length (basically check if we are out of the string)
# If then we make a recursive call to go to next index
# If not we short circuit to break the boolean chain and break out of the function
idx + 1 < len(s) and f(s, idx + 1)
```
[Try it online!](https://tio.run/##bVNNT8MwDL33V1jj0oohAUfEDhw4cAIhEOc0dVZraTIl6T5@/bDTlm4TlfoR@71n5zndHlPr3ePpdAOfaNVOuQSmdzqRd4XEdB8i7dAeQbeoN4BKt0CuIY2R3xBTILdmKK8ipBY5uO3THKfmMGVYKyAXYDoeoCgaNGDKuBTM6r56Kgrg6wa@GKvs2gdKbcfkMfyDYCjEBJb4IYI7v0c7pb/UBiVKgcn2nx4vYaDq6G2fEBoyBrkxjeDNRaNbH0mcgD13MlectK8VO3LU9d0Y/uCiadjSVj4lXeblfHEP5eDGnZhQwVXe@PBXEhYKyfcvr2/v34trIJkZFzMtyy55akq@AV3fYVAJy1j9Q86w1WoQyenqbBpuHL4Az2d4@yCjtRhlvsplEwazOejW7FlZq0ia53GcJfbsfWCv@ZSMfg@caiz4loNOcJ1YqyBMxxBECpKHtZenw8PYyUx1Pgkztj4k0BR0T0mwdUC1ydVq7y0q2ZNiY5RrxtxZQ3@/QNaVI3wLD/AsuxL/hDMdXMlUJ1MuVK0buRdVcbE6/QI "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/), 89 bytes
```
sub{$n=1e9;$n=$_?$n:0,$_=$_<$n?$_:$n++for reverse@r=map$n=/[aeiou]/i?0:$n+1,pop=~/./g;@r}
```
[Try it online!](https://tio.run/##1ZZNT8JAEIbv/IpJs1gKi21FVKi15eDBmMhFT0CaolsoH7vrtvgRgn@97pZKSNR7O9lOp@kenpl3ZrOciFU3Q5GbJZvpFlHXJj1HvlDgIdq3MApkeI2oh4I@oq1WxAQI8kZEQnzhrkMu95qjkMRsMzFjz1KbbMwZd7/MU3Pm@GKXOVBlq8mUGxXGV26khco0cG/AwkdrgiuCP31@Uc9PBjaGs9wf4k4pUynwkznjnIic/pi7CEqrQoGfc5e@Vf7FH4SD8JbckSEZPP0egT9XKZIt8GXbR7P5YrlaU5bj26pzJGUPwxWGSwwXGLoYzuUQHMZiUgJ8Y1vpc1@59WcDJanAPvnghuujwKkYPvgzlronKMrzMJzKVV8WHiOZg6EuG7BgMW3oWMdSCgOPlSzSy99OCfG5iGkagVZv290E4D2kqVtvdywZg1JlH9eTMdVwGcuvLO9@yFUAJcM@BvKaf4EHOlvq0Ae92Ww@DB9heK@XQIrartJXzuwb "Perl 5 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 69 bytes
```
->s{w=s.size;s.chars.map{|c|w=[w+=1,s=~/[aeiou]/i||w].min;s[0]='';w}}
```
[Try it online!](https://tio.run/##bY8/D4IwEMV3P0WDA4NYQEdSEwYHJyenpkPBIlWBhoY0SvGrV/5UdPDy7nK593tJWzfJw2TIrHeyVUhCyZ8skjDNaS1hQUWrU60QVisUehK9fEwZrxric60VgQUvI4kDglw3Ul1nBMiwQxOapL3OQ2fjuDhkMXlDOQQsAQ488NXHtqmZCD2wGee8by0q80oIVk/kL2MXi/W@rR6zt5jGdM8O7Mji05@3/JWNjp/Jr7d7UVZD1LwB "Ruby – Try It Online")
### Break it down bro
```
->s{w=s.size;
```
Initialize with the worst case (will never happen)
```
s.chars.map{|c|
```
For every character of the input string
```
w=[w+=1,s=~/[aeiou]/i||w].min;
```
The value is the minimum between the position of the next vowel in the string (if any) and the previous value incremented by one.
```
s[0]='';w}}
```
Cut the first character of the string, output the current value.
[Answer]
# [Python3](https://www.python.org/), 198 bytes
Golfed:
```
def f(s):
v='aeiouAEIOU';l=[];r=[];L=R=len(s:=s.lower())-2
for i in range(R+2):l.append(L:=0if s[i]in v else L+1);r.append(R:=0if s[~i]in v else R+1)
return[min(l[x],r[~x])for x in range(len(s))]
```
removed 42 bytes by removing whitespace (thank you Aaron Miller)
removed 77 bytes shortened variable names(thank you Browncat Programs)
removed 43 bytes by implementing Aaron Miller's solution(thank you Aaron Miller)
Non-golfed:
```
def dTNV(s):
s=s.lower()
left_min=[]
right_min=[]
distl=distr=len(s)-2
for i in range(len(s)):
distl=0 if s[i] in 'aeiouAEIOU' else distl+1
distr=0 if s[-(i+1)] in 'aeiouAEIOU' else distr+1
left_min.append(distl)
right_min.append(distr)
return [min(left_min[i],right_min[-(i+1)]) for i in range(len(s))]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 174 bytes
```
def f(s):
o=[]
for c,l in enumerate(s):
i,j=c,0
while 1:
if i in range(len(s))and s[i]in'aeiouAEIOU':
o+=[abs(c-i)]
break
j+=1
i+=j*(j%2*2-1)
return o
```
[Try it online!](https://tio.run/##NY2xisMwEERr6SvUHJFiB865LqDCRYpUqVIZF7K9ildxVkKWOe7rfZaPG1gYZh6z4SeNnr7WdQArrJzVhTOvm5Yz66Poy0kgCaDlDdEk@OsZlk735efmvkecQFQ5ZGgFZjoaeoKcgDZaGRrE3GCLdDCAfqmvt/vjsPPMF7ox3Sz7E6p2T7oI5pWdK3S1bxbaHaX7OB/Pp0pxFiEtkYRf/x@HiJSklUhhSVIptZosbrp@yMfn0YcAkfPa1OYKN7hD/eBbY5@je01v8r8 "Python 3 – Try It Online")
---
# [Python 3](https://docs.python.org/3/), 82 bytes
```
lambda s:[min(abs(s.index(v)-s.index(l))for v in s if v in'aeiouAEIOU')for l in s]
```
[Try it online!](https://tio.run/##NcmxDoIwFIXhvU/RjXbQxLiROHRgYGJiUoeL3Nqr5bahgPr0VUg8yUn@5IufyQU@Znu6ZA9D14NM5XkgVtAllfbEPb7Vonf/9FrbMMpFEsskyW5VAFKYTVU3bbGx3/iaX448ykMZR@JJWUUc50lprTOsE9Dd@vUiuRAjjkIYMFBhjQ2aVvzE3t3j6QcOXw "Python 3 – Try It Online")
As [xnor](https://codegolf.stackexchange.com/users/20260/xnor) pointed out, this doesn't work when a vowel appears multiple times in the string. The version above is longer but works when a vowel appears multiple times in the string.
[Answer]
## C++20, ~~145~~ 141 bytes (+17 bytes with a necessary #include +3 bytes for the general case with `int` instead of `char`)
One can use the function (in strict C++ language, it is a function template that can be turned into a function by substituting `auto s` by `std::string s` adding another 7 bytes)
```
auto f(auto s){int c=63,p=0;auto r=s;for(int i:s){for(int x:"AOEUI")c=i-x&~32?c:0;r[p++]=c++;}for(;--p>=0;)r[p]=r[p]<=c++?c=r[p]:c;return r;}
```
together with `std::vector<int>` or `std::string`, which requires the corresponding header to be included (`#include<string>` or `#include<vector>` = 16 bytes code + 1 byte line break).
```
auto f(auto s){
auto r=s; // r: output (same type and length as s)
int c=63,p=0; //c: distance counter, p: position in r
//iterate forwards counting distance from previous vowel (or c+distance from beginning if vowel not yet found) and store it in r
for(int i:s) {
for(int x:"AOEUI") {
if(!((i-x)&(~32))) c=0; //set c to zero if c is a vowel (assuming ASCII)
//i-x == [ 0:upper case, 32:lower case]
//(i-x)&(~32) == [ false:i==x ignoring case, true:else ]
}
r[p++]=c++;
}
//iterate backwards counting distance and store lower value from both iterations in r
for(--p;p>=0;--p) {
if(r[p]<=c) {
c=r[p];
} else {
r[p]=c;
}
++c;
}
return r;
}
```
### `char` and `int` case
In the `char` case we assume that the input is not longer than 63 bytes. Then the initial value `c=63` will not cut off the distance even in cases where the vowel is at the end. It is also small enough not to lead to integer wrap-around, when the type of the elements of the data is signed char (-128..127).
If we want to have the general case for `int`egers, we need to initialize `c` with a larger value. In that case we substitute
```
int c=63,p=0;
```
by
```
int c=-1/4u,p=0;
```
adding **3 more bytes**. The signed number -1 corresponds to the largest unsigned integer. Dividing it by unsigned four (4u) converts the -1 to unsigned integer and reduces the value to the middle of the positive signed-integer range.
To cover both cases (`char` up to 63 bytes and longer `int` sequences) one can use
```
int c=size(s),p=0;
```
which would **add 5 bytes** compared to the `char` case.
### Usage example:
```
#include<iostream>
#include<string>
#include<vector>
auto f(auto s){int c=63,p=0;auto r=s;for(int i:s){for(int x:"AOEUI")c=i-x&~32?c:0;r[p++]=c++;}for(;--p>=0;)r[p]=r[p]<=c++?c=r[p]:c;return r;}
int main() {
std::string result_str=f(std::string("abcdAbcd"));
std::vector<int> result_vec=f(std::vector<int>({'a','b','c','d','A','b','c','d'}));
std::cout << "std::string: ";
for(int i:result_str) std::cout << i << " ";
std::cout << std::endl;
std::cout << "std::vector<int>: ";
for(int i:result_vec) std::cout << i << " ";
std::cout << std::endl;
return 0;
}
```
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~32~~ 31 bytes
Not a very optimal solution because I couldn't get the short function defintion using the L command. Feel free to help me out here
## Code
```
DtZJrZ0R.ehSmadksmxdcJ1"aeiou"J
```
## Big-Pyth Version
```
def
tail
zero-var
implicit-assign
auto-var
lower
zero-var
0
return
enumerate-map
head
sorted
map
absolute-difference
map-var
enumerate-map-ind
flatten-once
map
ind-all-occurrences
map-var
chop-into-size-n
auto-var
1
str-start aeiou str-end
auto-var
```
[Try it online!](https://tio.run/##K6gsyfj/36UkyqsoyiBILzUjODcxJbs4tyIl2ctQKTE1M79Uyet/VlJuSYpe1f9EEOBKTEpOAWGu4oz8goLUIi4ux0THRNdUz1T/VMdQLqBMWnpGVnZObl4@AA)
[Translation Link](https://github.com/Hydrazer/pyth-programs/blob/main/zz_makeProgram/z_big-pyth.py)
[Answer]
# [Husk](https://github.com/barbuz/Husk), 27 bytes
feel free to golf down my terrible husk
had to shift the line numbers by 1 to be able to run all the test cases correctly
```
₃W₂m_¹ŀ
#"aeiou
mλ▼mλa-²⁰)²
```
first line: `₃W₂m_¹ŀ`
```
-- implicit parameter ⁰ (last argument)
ŀ -- get the indices of the list (1 to len(list))
m_¹ -- map lowercase on a copy of last argument
W₂m_¹ -- filter by line function 2 and return indicies of truthy results
₃W₂m_¹ŀ -- call line function 3 with two arguments (W₂m_¹ & ŀ)
```
second line: `#"aeiou`
```
-- implicit parameter ⁰ (last argument)
"aeiou -- string "aeiou"
#"aeiou -- get amount of occurences in list
```
third line: `mλ▼mλa-²⁰)²`
```
-- implicit parameters ⁰ & ² (last and second last argument)
mλ -- map over implicit last parameter (ŀ)
mλ )² -- map over the second last parameter
mλ -²⁰)² -- get the difference between the last parameter (defined in this scope) and second last parameter (defined from the first lambda)
mλa-²⁰)² -- get the absolute value
▼mλa-²⁰)² -- get the minimum of that list
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f@jpubwR01NufGHdh5t4FJWSkzNzC/lyj23@9G0PUAyUffQpkeNGzQPbfr//3@0UiIIKOkoJSYlp4AwkFmckV9QkFoEZAGRY6JjomuqZ6p/qmMokAtUkZaekZWdk5uXrxQLAA)
[Answer]
# Excel, 198 bytes
```
=LET(x,LEN(A1),a,SEQUENCE(x),b,IFERROR(FIND(MID(A1,a,1),"aeiouAEIOU")^0*a,99999),d,SEQUENCE(x^2,,x),e,MOD(d,x)+1,f,INT(d/x),g,INDEX(ABS(b-TRANSPOSE(a)),e,f),IF(A1="","",FILTER(SORTBY(g,f,,g,),e=1)))
```
[Link to Spreadsheet](https://1drv.ms/x/s!AkqhtBc2XEHJnHIFCo0kl7Qdhyc6?e=CEKe1f)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā©žMIlSåƶ0K®.xα
```
Input as a list of characters.
[Try it online](https://tio.run/##yy9OTMpM/f//SOOhlUf3@XrmHF56bJuB96F1ehXnNv7/H61UrKSjlAHE@UBcAMWpQFykFAsA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaVLcOj/I42HVh7d5xuRc3jpsW0G3ofW6VWc2/j/9Byd/9FKiSCgpKOUmJScAsJAZnFGfkFBahGQBUSOiY6Jrqmeqf6pjqFALlBFWnpGVnZObl6@UiwA).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
© # Store it in variable `®` (without popping)
žM # Push builtin "aeiou"
I # Push the input-list of characters
l # Convert each character to lowercase
å # Check for each if it's in the vowel-string
ƶ # Multiply each by its 1-based index
0K # Remove all 0s
® # Push the [1, length] list from variable `®`
.x # Get for each index the closest vowel-index
α # Get the absolute difference of these with the indices
# (after which the result is output implicitly)
```
[Answer]
# [Arturo](https://arturo-lang.io), 69 bytes
```
$->s[i:0map s=>[min map match.bounds s{(?i)[aeiou]}'x->abs-x\0i'i+1]]
```
[Try it](http://arturo-lang.io/playground?cHckZW)
```
$->s[ ; a function taking an argument s
i:0 ; assign 0 to i
map s=>[ ; map over s
min ; minimum value in a list
map ; map over...
match.bounds s{(?i)[aeiou]} ; the indices of the vowels in s
'x-> ; ...and assign current element t x
abs ; absolute value
- ; subtract
x\0 ; first elt of x (because match.bounds returns range)
i ; and i
'i+1 ; increment i
] ; end map
] ; end function
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2), 8 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Żı$ṃV-AM
```
#### Explanation
```
Żı$ṃV-AM # Implicit input
Żı # Map over the length range:
$ṃV # Indices of vowels in the input
-AM # Minimum of absolute differences
# Implicit output
```
#### Screenshot
[](https://i.stack.imgur.com/shzn9.png)
] |
[Question]
[
Write a quine which attempts to invert the case of as many ascii characters in the source code as possible. For example in javascript:
```
(x=function(y){return ('(x='+y+')(x)').toUpperCase();})(x)
```
* Standard quine rules apply.
* The score is given by *number of bytes in the source code* - *number of case inversions*. For example, the quine above has a score of 29.
* The program with the lowest score wins. If two programs have the same score then the shorter one wins.
[Answer]
# [><>](http://esolangs.org/wiki/Fish), score 479 - 479 = 0
```
lllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllllbfppllfepeeppppgglcepppbeppppppppppplfdppedpddpgglcdppbdpfcpecpggldcppllccpbcpplfbpebppldbppcbpggcbglefgpgbeglefgpgcbglefgpgggggedglefgpgccglefgpgfdglefgpgebglefgpgecglefgpggdcglefgpgceglefgpgeeglefgpgbcglefgpgfbglefgpgcdgfefgpbdgeefgpfegdefgpccgcefgpfdgbefgpdbgaefgpppddglefgpgbcglefgpgfcglefgpgdbglefgpgdcglefgpgecglefgpgddglefgpgdbglefgplffpbfgffgefgpcbgefgefgp
```
[Try it online!](https://tio.run/##vY@7jkMxCES/dYdhSCQXSPl/ecG6uEkfCs/hjfX@vPZevzcocy15umdZxLIGHO@xJWY6kzz5csCUpVv7tJ5glmgQ0lHKegyVN8RyRQb8gRtpc07UHtBEfOp8UsEhm2E@gNs/bcZQA1hVpfJga22y47NuKiXirzXrg1/DBjhT7wn3qts1NUtKKKQ469DStPc/)
### How it works
Very few useful instructions in ><> are letters.
However, we still have the `l`, pushing the length of the stack to the stack. As such, it's possible to (very verbosely) push arbitrary values to the stack. Thus, strings can be encoded in a similar fashion to brainfuck, using `a` to increase the length of the stack, and `g` or `p` to reduce it.
As per usual quine rules, `g` is not used to read the source code itself, instead maintaining registers at locations such as`bb` and `bc` and so on.
The string encoded is the prefix:
`"r&:20&3-:&?.p48*-od0l2)?.;lllll"]"`
Which after over 7,000 instructions outputs the original string in upper case.
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), ~~77~~ 75 - 75 = 0
```
urassssissezplzelssmzmzpssazmkqjmkrmbrrrrrtsuotlballsssssassmzpsssssbssmzpu
```
[Try it online!](https://tio.run/##HYtBEsAgCMTeCjO2VWG0rlz4PC3mlENyD7kqnghbhJ8KFJ/iRQB19QmQa3@b9qW8kg0bW5hEcgBlOI/yUYv4AA "Gol><> – Try It Online")
Based on [Bubbler's answer](https://codegolf.stackexchange.com/a/209774/76162), this goes even further by also putting the `"` at the start of the code to get a score of `0`!
### Explanation
```
ur Move over one on the stack tape and reverse the stack
assssissez Push 10+16*4=74,-1+16*2=31,!(15)=0
p And put the 74 (J) at position 0,31
lz Push 0 if there is anything on the stack
e Push 14 for later
lssmzmz Push 2+16*2=34, !(-1)=0, !(-1)=0
p Put the 34 (") at position 0,0
sss Add 3*16 to the -1 from earlier
az Push !(10)=0
mkq Some no-ops
J And jump to 0,47 if the stack was initially empty
lballsssssassmzp Put T at position 0,43
sssssbssmzpu Put S at position 0,44
u Move one over on the stack again (effectively resetting the stack)
" Wrap, pushing everything to the stack
r Reverse
......... Put everything again
J But this time don't jump, since the stack is not empty
mk Copy the bottom of the stack (u)
rm Push a -1 to the bottom of the stack
brrrrr No-ops
T t Finally, loop over the stack,
Suo Capitalising then outputting everything until we get to the -1
```
[Answer]
## 80186+ machine code (MS-DOS .COM format), 115-115=0
It was a bit tricky to do this, as I only had access to `INC`, `DEC`, `PUSH`, certain `POP` variations, `POPA`, `IMUL`, and certain conditional jumps. Fortunately, `IMUL` could do the heavy lifting for this challenge!
I encoded the actual code that does the printing in a series of values that get multiplied together. I compute those values (which get truncated to 16-bit values), store them on the stack which I moved to be just above the code, and then jump to the generated code to print the program's code in the opposite case.
Machine code:
```
hrXhCNhGUhnPhPwhYkhvLhKwaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaPQRjZTUVjfaiQVGARiQSCARiQPQARiQMJARiQJZARiQGuARiQDkARiQAWARpI
```
Assembler source:
```
IDEAL
P186
MODEL TINY
CODESEG
ORG 100H
MAIN:
; Encoded code:
; MOV SI,100H
; MOV CX,73H
; PRINT:
; LODSB
; XOR AL,20H
; INT 29H
; NOP
; LOOP PRINT
; INT 20H
; Offset Bytes Multiplier
PUSH 5872H ; +41 BE 00 4157H
PUSH 4E43H ; +44 01 B9 416BH
PUSH 5547H ; +47 73 00 4175H
PUSH 506EH ; +4A AC 34 415AH
PUSH 7750H ; +4D 20 CD 414AH
PUSH 6B59H ; +50 29 90 4151H
PUSH 4C76H ; +53 E2 F8 4143H
PUSH 774BH ; +56 CD 20 4147H
REPT 30
POPA ; Adjust stack to point to end of generated code
ENDM
PUSH AX
PUSH CX
PUSH DX
PUSH 5AH
PUSH SP
PUSH BP
PUSH SI
PUSH 66H
POPA ; Use POPA as POP DX and POP DI are not in [A-Za-z]
IMUL DX,[BX+DI+56H],4147H
PUSH DX
IMUL DX,[BX+DI+53H],4143H
PUSH DX
IMUL DX,[BX+DI+50H],4151H
PUSH DX
IMUL DX,[BX+DI+4DH],414AH
PUSH DX
IMUL DX,[BX+DI+4AH],415AH
PUSH DX
IMUL DX,[BX+DI+47H],4175H
PUSH DX
IMUL DX,[BX+DI+44H],416BH
PUSH DX
IMUL DX,[BX+DI+41H],4157H
PUSH DX
JO $+4BH ; Jump to start of generated code
END MAIN
ENDS
```
[Answer]
# [Gol><>](https://github.com/Sp3000/Golfish), score 34 - 33 = 1
```
"mrllssslssscsmzpdsmzprrrrrrtsuota
```
[Try it online!](https://tio.run/##S8/PScsszvj/Xym3KCenuLgYhJOLc6sKUkBEERiUFJfmlyT@/w8A "Gol><> – Try It Online")
Outputs the following and exits by error, which is every char uppercased except the leading `"`.
```
"MRLLSSSLSSSCSMZPDSMZPRRRRRRTSUOTA
```
### How it works
The lines marked with `*` are the differences from the previous version.
```
"..." Push every char except `"`
mrl Push -1, reverse stack, push stack length (34 = `"`)
* lsss Push stack length (35) and add 16 three times (83 = S)
* lsss Push stack length (36) and add 16 three times (84 = T)
* csmzp Push 13, add 16 (29), push -1, boolean negate (0), and
replace the command at (29,0) by T
* dsmzp Push 14, add 16 (30), push -1, boolean negate (0), and
replace the command at (30,0) by S
* rrrrrr Reverse the stack 6 times;
no-op to move the positions to overwrite
TSuot Infinite uppercase-print loop; halt by error at -1
a Not executed
```
---
# [Gol><>](https://github.com/Sp3000/Golfish), score 34 - 31 = 3
```
"mrlTSuotaaaaaaaaaaaaaaaaaaaaaaaaa
```
[Try it online!](https://tio.run/##S8/PScsszvj/Xym3KCckuDS/JBEX@P8fAA "Gol><> – Try It Online")
Outputs the following and exits by error.
```
"MRLTSUOTAAAAAAAAAAAAAAAAAAAAAAAAA
```
Every lowercase letters are uppercased, so the only chars that are not modified are `"TS`.
### How it works
```
"..." Start string literal, push every char in the source code (except `"`),
wrap around and end string literal
mr Push -1 and reverse the stack
(setup the chars for printing from top, and bury the trap at the bottom)
l Push length of stack, which gives 34 == `"`
T...t Infinite loop until it errors in the middle:
Su Uppercase the char at the top (errors when trying to uppercase -1)
o Pop and print as char
a... Not reached
```
~~I suspect 2 or lower might be possible.~~
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), score 3
```
2i2I
```
[Try it online!](https://tio.run/##K/v/3yjTyPP/fwA "V (vim) – Try It Online")
4 bytes with 1 case inversion. Twice inserts (`2i`) the string `2I`.
[Answer]
# 05AB1E, 16 - 6 = 10
```
0"D34çýu"D34çýu
```
(trailing newline)
# Explanation
```
0"D34çýu"D34çýu # full code
0"D34çý "D34çý # standard 05AB1E quine
u u # uppercase string in stack
# implicit print
```
Not the *best* golf, but it is my *first* golf so have mercy please.
[Try It Online!](https://tio.run/##yy9OTMpM/f/fQMnF2OTw8sN7S@EMrv//AQ)
---
# 05AB1E (legacy), 16 - 8 = 8
```
0"D34çýš"D34çýš
```
(trailing newline)
# Explanation
```
0"D34çýu"D34çýu # full code
0"D34çý "D34çý # standard 05AB1E quine
š š # switch case builtin
# implicit print
```
Thanks to Kevin Cruijssen for -2 score.
Doesnt work with current 05AB1E becuase the switch case function is `.š` which makes the byte count larger
[Try It Online!](https://tio.run/##MzBNTDJM/f/fQMnF2OTw8sN7jy5EsLj@/wcA)
[Answer]
# [Ruby](https://www.ruby-lang.org/), score ~~24~~ ~~20~~ ~~16~~ ~~12~~ 11
*Saved a byte thanks to a comment by @Sisyphus on another answer.*
```
eval S="print'EVAL s=%p'%S.swapcase"
```
[Try it online!](https://tio.run/##KypNqvz/P7UsMUch2FapoCgzr0TdNczRR6HYVrVAXTVYr7g8sSA5sThV6f9/AA "Ruby – Try It Online")
36 bytes with 25 case inversions. The case of every letter is changed in the output.
[Answer]
# [Husk](https://github.com/barbuz/Husk), Score = ~~3~~ 2
```
foccmawSeohs"foccmawseohs
```
[Try it online!](https://tio.run/##yygtzv7/Py0/OTk3sTw4NT@jWAnKKQZx/v8HAA "Husk – Try It Online")
So many letters!
Thanks Dominic van Essen for -1 to the score.
### Explanation
The standard quine in Husk is `S+s"S+s"`: it takes the string `S+s`, and concatenates it with its version surrounded by quotes. The swapcase command `\` would be easy to add here, but being an escape character as well it needs to be doubled inside the quoted string, resulting in too many unswappable character for my tastes.
What we do instead is convert each character to uppercase (with the conveniently lowercase builtin `a`), and then we just need to make sure to use only lowercase letters as much as possible. We can get rid of a final `"` by using `h` (init) on the quoted string, then the rest of the code is devoted to getting rid of that `+` symbol to concatenate strings.
```
foccmawSeohs"foccmawseohs
"foccmawseohs A string
Se put it in a 2-elements list
ohs with the quoted version of itself, minus the last quote
w Join the two strings with a space
ma Convert each character to uppercase
f And keep only those characters that are truthy when...
occ converted to charcode and back
```
The last part is just an identity function (but `I` would be uppercase), and spaces are falsy in Husk, so we are just keeping all non-space characters in the string.
I'd love to get rid of the `S` but I don't see how, and I don't think it is possible to have a quine without quotes, barring convoluted conversions from numbers that would score terribly in this challenge... (Prove me wrong and you get a bounty!)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 70 - 38 = 32
```
f=x=>`f=${f}`.replace(/(.)/g,y=>y<'`'?y.toLowerCase():y.toUpperCase())
```
[Try it online!](https://tio.run/##XY7LCsIwFET3fkUFwYTG1HXxVtCtO3GlxcT0plVKUpr6iKXfXisoiMsZhjnnIm/SqfpcNTNjM@x7DQ9IhIZJqzvBa6xKqZBEhNMoZx4Sv5iK6dLzxm7sHeu1dEho/M67qvpm2itrnC2RlzYnDjShTByMoKPfXqx8gy4OgmDSnsDxEk3eFN3/al1Ik2MWByLcc84HNxHqdFDLroMZOTLPnhQSFYIfg9s/U6ZgTv9OtsrW@EHN1MDoXw "JavaScript (Node.js) – Try It Online")
BTW: This is my first contribution and I'm a bit confused. I made sure to swap every possible character. The example only uppercases. If you don't *need* to actually swap cases, then one can get 11-0=11 with a simplified variant of an answer given above:
```
f=x=>"f="+f
```
[Answer]
# [Python 2](https://docs.python.org/2/), Score 52 - 33 = 19
```
s='S=%r;PRINT S%%S.SWAPCASE()';print s%s.swapcase()
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v9hWPdhWtcg6IMjTL0QhWFU1WC843DHA2THYVUNT3bqgKDOvRKFYtVivuDyxIDmxOFVDk@v/fwA "Python 2 – Try It Online")
Case inverts every letter in the quine.
[Answer]
# [Perl 5](https://www.perl.org/), 37 bytes, 20 swapped case, Score 17
Thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen) for -1!
```
eval($a=q{print uc"eval(\$a=q{$a})"})
```
[Try it online!](https://tio.run/##K0gtyjH9/z@1LDFHQyXRtrC6oCgzr0ShNFkJLBQDFlNJrNVUqtX8/x8A "Perl 5 – Try It Online")
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), score 4
```
`④`④
```
[Try it online!](https://tio.run/##y05N//8/4dHExSD8/z8A "Keg – Try It Online")
4 bytes with 0 case conversions.
The standard quine without case conversion easily beats any Keg approaches that would have case conversion: by the time you've thrown case conversion techniques into the mix, you might as well have just written a standard quine with no fancy details.
[Answer]
# Javascript, 27 - 13 = 14
```
f=x=>`f=${f}`.toUpperCase()
```
[Try It Online!](https://tio.run/##Xc2xDoIwFIXh3aeoCUMbSuNMchnkEYwTElvLLWpIS2g1AuHZK4ODYT35c76neiuvh0cfMusajNHABwppIJnNIkVw577HoVQeKYvaWe86FJ1rqQdDGZcXK9nuf5fHMaDPCSHJfAMvOrRtuC/bqrwr22KTE5lWQogVlKmpxYDNSyOlVz7yiUGhUxj34Kup5hoObHNy0m7AH5Xp1Yhf)
[Answer]
# [R](https://www.r-project.org/), score = 78 - 53 = 25
```
a='a=%s;cat(toupper(sprintf(a,squote(a))))';cat(toupper(sprintf(a,sQuote(a))))
```
[Try it online!](https://tio.run/##K/qfmVeWWZyZlJOqEVxZrFecWpKTn5wI5CUnlqSm5xdVKtgqKPk4xzv6@CjpKEDkQELOSpqa/xNt1RNtVYutgWo1SvJLCwpSizSKC4oy80rSNBJ1igtL80tSNRI1gUAdl5pAhJr//wE "R – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 10 bytes − 8 inversions = score 2
```
`NDqp`NDqp
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%60NDqp%60NDqp&inputs=&header=&footer=)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), Score = ~~very big number - very big number~~ 4508 - 4508 = 0
```
XaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXODTnBsbRvTTTTngmngmnngmngDUTnBsTTnnngmgTnBsTTTngmnnnngmgDVTnBsTTTnnngmngmngTnBsYTnBsTXmRykTnBXaKsYTnBsJ
```
[Try it online!](https://tio.run/##vVfBCoMwDP230dN2KIgb2VFhyBi6gzDY13dat5OOtu8liliNaUzavJf4HJv2fgtBGu@8@Dj49cP6uqW7OfzXS3wt12iWsbRJyY2ryO3CD@bZBtcg7VmmNh90cTip2ULsPGAHwUNZCGVzFRIacyzXCxOeQHCpAFLBU1Lw1MW2GPebZASIfHGU26QyTDd7@UHUFaEzkqVPanmIpVNoD0xJAkabVXHli4FyxTZxFbFGpDNNbzg8DaorFDXdUJvzJgcirT8FnVJt@CsiWnkOgE9UcVvWs2nTMVLGFBpxGm1i1TnKzh1hYdSuHg5jW73q6Ri6fj7j4M7zi0k2P3bLfVRYBO7yEw3fWVHnGqXSV@/HdCfNaZEcQ/gA "05AB1E – Try It Online")
EDIT: Can now finish in the lifetime of the universe!
Explaination:
```
XaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOOXaODOOXaODOOXaODOOXaODOXOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOOXaODOXOXaODOOXaODOXOXaODOXOXaODOOXaODOXO
pushes 395523372811533155555555231622231622232316222316395655233728555523232316221655233728555555231622232323231622163957552337285555552323231622231622231655233728605523372855592253342055233759104628605523372845
D duplicate it
TnB and convert one of the duplicated to base 10^2 = 100, which is this code case inverted
s swap, moving to front the number
b convert it to binary
R and reverse the binary
v for each digit
TTTT push 10,10,10,10^1
n square, 10,10,10,10^2
g length, 10, 10, 10, 3
m exponent, 10,10,10^3
n square, 10,10,10^6
gm 10^length, 10,10^7
n square, 10, 10^14
n square, 10, 10^28
gm 10^length, 10^29
n square, 10^58
g 59
DU duplicate and save in variable X
TnB convert to base 100, "x"
s and swap, so the stack is "x", "<string>"
TTnnngmg push 10, in the same way as 59
TnBs convert from base 100 and swap, so the stack is "x", "A", "<string>"
TTTngmnnnngmg push 50, in the same way as 59 and 10
DV save in variable Y
TnBs convert from base 100 and swap, so the stack is "x", "A", "o", "<string>"
TTTnnngmngmng push 39
TnBs convert from base 100 and swap, so the stack is "x", "A", "o", "d", "<string>"
Y push variable Y, 50
TnBs convert from base 100 and swap, "x", "A", "o", "d", "o", "<string>"
TXmRyk X if the current bit is 0, else 0
TnBXaK convert from base 100 and remove zeros, "X" if the value is 0 else ""
sYTnBs add "o" again
J join everything
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 44 - 25 = 19 bytes
SwapCase all the char of the quine leaving only the non-alpha chars unchanged
```
exec(a:="input('EXEC(A:=%r)'%a.swapcase())")
```
[Try it online!](https://tio.run/##K6gsycjPM7YoKPr/P7UiNVkj0cpWKTOvoLREQ901wtVZw9HKVrVIU101Ua@4PLEgObE4VUNTU0nz/38A "Python 3.8 (pre-release) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), score 16 - 6 = 10
Sadly, a [standard quine with no toggling](https://codegolf.stackexchange.com/a/71932/16484) scores the same (10 bytes), but this is way more fun. Every letter is toggled.
```
"i34d¹²u"i34d¹²u
"i34d¹²u" // Take this string, shortly just the program string after the quote
i // Prepend
34d // a quote char,
¹ // and then (closing parens)
²u // repeat the result twice and uppercase it.
```
[Try it here.](https://ethproductions.github.io/japt/?v=1.4.6&code=ImkzNGS5snUiaTM0ZLmydQ==&input=)
[Answer]
# [Haskell](https://www.haskell.org/), score 29
```
import Data.Char;main=putStr x>>print x;x=map toUpper"import data.char;main=putstr x>>print x;x=map toupper"
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzzkjscg6NzEzz7agtCS4pEihws6uoCgzr0ShwrrCNjexQKEkP7SgILVICaorBaQrGVlXMXZdpWBdXP//AwA "Haskell – Try It Online")
The non-flipped bytes are:
```
D.C;=S >> ;= U" .;= >> ;= "
```
[Answer]
# [Python 2](https://docs.python.org/2/), 43 - 27 = 16 bytes
```
a="print'A=%r;EXEC A'%a.swapcase()";exec a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P9FWqaAoM69E3dFWtcjaNcLVWcFRXTVRr7g8sSA5sThVQ1PJOrUiNVkhkev/fwA "Python 2 – Try It Online")
Same answer than my Python 3 solution ... but ths time I can remove the parenthesis of the `exec` function and the `print` function (costing one char for the trailing newline)
] |
[Question]
[
### Input:
An integer
### Output:
Sum of the input itself + the length of the input + each individual digit of the input.
```
nr + nr-length + {sum of digits} = output
```
### Examples:
Input: `99`
Output: `99` (nr) `+ 2` (nr-length) `+ (9 + 9)` (digits) → `119`
Input: `123`
Output: `123 + 3 + (1 + 2 + 3)` → `132`
### Challenge rules:
* The input can also contain negative input, which are resolved special. The `-`/minus-sign is also `+1` for the length, and is part of the first `digit`.
For example:
Input: `-123`
Output: `-123 + 4 + (-1 + 2 + 3)` → `-115`
* You can assume that the input nor output will ever be outside the range of an (32-bit) integer.
### General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
### Test cases:
```
87901 → 87931
123 → 132
99 → 119
5 → 11
1 → 3
0 → 1
-3 → -4
-123 → -115
-900 → -905
-87901 → -87886
```
Semi-related: [Count Sum of all Digits](https://codegolf.stackexchange.com/questions/18556/count-sum-of-all-digits)
[Answer]
# Python 2, 39 bytes
```
lambda x:x+len(`x`)+eval("+".join(`x`))
```
[Test suite](https://repl.it/C78p)
Using the same eval-trick as in my [Pyth-answer](https://codegolf.stackexchange.com/a/84081/49110).
[Answer]
## 05AB1E, ~~28~~ ~~20~~ ~~18~~ 8 bytes
```
ÐgsS'+ýO
```
**Explanation**
```
Ð # triplicate input
g # get length of input
sS'+ý # split input and merge with '+' as separator
O # sum and implicitly display
```
[Try it online](http://05ab1e.tryitonline.net/#code=w5Bnc1MnK8O9Tw&input=LTEyMw)
Saved 10 bytes thanks to @Adnan
[Answer]
# Pyth, ~~11~~ 10 bytes
Thanks to @LeakyNun for a byte!
```
++vj\+`Ql`
```
[Test suite](http://pyth.herokuapp.com/?code=%2B%2Bvj%5C%2B%60Ql%60&input=-123&test_suite=1&test_suite_input=87901%0A123%0A99%0A5%0A1%0A0%0A-3%0A-123%0A-900%0A-87901&debug=0)
## Explanation
```
++vj\+`Ql`QQ # Q = input, last two implicitly added
vj\+`Q # Join the input on '+' and eval it
l`Q # Length of the input
Q # The input itself
++ # Add those three values to obtain the result
```
[Answer]
# CJam, 18
```
q_,\~__Ab(@g*\~]:+
```
[Try it online](http://cjam.aditsu.net/#code=q_%2C%5C~__Ab(%40g*%5C~%5D%3A%2B&input=-123)
**Explanation:**
```
q_ read the input and make a copy
,\ get the string length and swap with the other copy
~__ evaluate the number and make 2 copies
Ab convert to base A=10 (array of digits), it uses the absolute value
( take out the first digit
@g* get a copy of the number, get its sign and multiply with the digit
\~ dump the other digits on the stack
]:+ add everything together
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), ~~35~~ 32 bytes
```
~~lL,?:ef+:?:L+I,(0>?h:2\*:Ir-:1+.;I.)~~
lL,(0>?h:1--I;I0),?b:ef+:?:L:I+.
```
### Explanation
```
lL, L is the length of the Input
(
0>? Input < 0
h:1--I I is (First digit - 1) * -1
; Or
I0 I is 0
),
?b:ef+ Sum all digits of the Input
:?:L:I+. Output = sum of digits + (Input minus first digit) + L + I
```
[Answer]
# XSLT 1.0 (without EXSLT), 673 bytes
```
<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0"><output method="text"/><param name="i"/><template match="/"><variable name="d"><variable name="s">0<if test="0>$i">1</if></variable><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,$s+2)"/></call-template></variable><value-of select="substring($i,1,$s+1)+$d"/></variable><value-of select="$i+string-length($i)+$d"/></template><template name="d"><param name="i"/>0<if test="$i!=''"><variable name="d"><call-template name="d"><with-param name="i" select="substring($i,2)"/></call-template></variable><value-of select="substring($i,1,1)+$d"/></if></template></transform>
```
Lightly inflated:
```
<transform xmlns="http://www.w3.org/1999/XSL/Transform" version="1.0">
<output method="text"/>
<param name="i"/>
<template match="/">
<variable name="d">
<variable name="s">0<if test="0>$i">1</if></variable>
<variable name="d">
<call-template name="d">
<with-param name="i" select="substring($i,$s+2)"/>
</call-template>
</variable>
<value-of select="substring($i,1,$s+1)+$d"/>
</variable>
<value-of select="$i+string-length($i)+$d"/>
</template>
<template name="d">
<param name="i"/>0<if test="$i!=''">
<variable name="d">
<call-template name="d">
<with-param name="i" select="substring($i,2)"/>
</call-template>
</variable>
<value-of select="substring($i,1,1)+$d"/>
</if>
</template>
</transform>
```
Run using xsltproc:
```
xsltproc --param i -87901 ild.xsl ild.xsl
```
Yes, `ild.xsl` is passed twice: Once as the XSLT document and then as the XML document to be transformed. An input document must be present because an XSLT processor generally requires one to begin running. (XSLT is designed to define a transformation from an input document to an output document; running a transform solely with command-line parameters as I've done here is atypical.) For this program, any well-formed XML document will suffice as input, and, XSLT being an application of XML, any well-formed XSLT transform is by definition a well-formed XML document.
[Answer]
# MATL, 20 bytes
```
tVtnw48-PZ}t0<?x_]vs
```
[**Try it Online**](http://matl.tryitonline.net/#code=dFZ0bnc0OC1QWn10MDw_eF9ddnM&input=OTk)
[All test cases](http://matl.tryitonline.net/#code=YGkKdFZ0bnc0OC1QWn10MDw_eF9ddnMKRFRd&input=ODc5MDEKMTIzCjk5CjUKMQowCi0zCi0xMjMKLTkwMAotODc5MDE)
**Explanation**
```
% Implicitly grab the input
tV % Duplicate the input and convert to a string
tn % Duplicate and find the length of this string
w % Flip the top two stack elements to get us the string again
48- % Subtract 48 (ASCII 'O'). Yields a negative number for a negative sign
% and digits otherwise
P % Flip the resulting array
Z} % Break the array up so each element is pushed to the stack
t0<? % If the first character was a negative sign
x_ % Pop the negative sign off the stack and negate the first digit
] % End of if
vs % Vertically concatenate and sum all stack contents
% Implicitly display the result
```
[Answer]
# Clojure, 102 bytes
```
(fn[n](load-string(str"(+ "n" "(count(str n))" "(apply str(map #(if(= % \-)%(str %" "))(str n)))")")))
```
Anonymous function which constructs a string that looks like `(+ -123 4 -1 2 3 )` and evals it. Everything pretty verbose as it is, construct string from number, its length, and then map each symbol of string representation of the number except minus to itself plus space and minus remains the same
You can see it running here: <https://ideone.com/FG4lsB>
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), ~~19~~ ~~17~~ 16 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
```
≢+#⍎'\d'⎕R'&+',⊢
```
Takes string and returns
`≢` length
`+` plus
`#` in root namespace
`⍎` evaluation of
`'\d'⎕R'&+'` regex append digits with a plus
`,` followed by
`⊢` the unmodified string
–3 thanks to ngn
[Answer]
## Matlab, ~~76~~ 67 bytes
```
n=input('');t=num2str(n)-48;if(n<0)t(1)=0;t(2)=-t(2);end
n+sum(t+1)
```
9 bytes saved thanks to [@Luis Mendo](https://codegolf.stackexchange.com/users/36398/luis-mendo)
**Explanation:**
```
n=input(''); -- takes input
t=num2str(n)-48; -- makes it a string and then array of digits with "-" becoming -3 (48 is code for 0)
if(n<0)
t(1)=0; -- set first element (-3) to 0
t(2)=-t(2); -- the second element is the most significant digit, so we have to negate it
end
n+sum(t+1) -- take sum of n, sum of all digits and length of t
(guaranteed by +1 of every element)
```
[Answer]
# dc, 57 bytes
```
dc -e"0 1?rdsc*d[1r]s+d0>+dZr[+la10~lc*rdsaZ1<A]sAdsaZ1<Ala+++f"
```
Explained:
```
0 1 # Push 0, then 1 on the stack
? # Wait for input from stdin
# If input is negative, the leading minus will subtract 1 from 0
r # Swap (rotate) top two items on stack.
# Stack status if input (`$') was...
# positive negative
# TOP 1 <- coefficient -> -1
# $ $
# 0
dsc # Store a copy of coefficient in `c'
* # Multiply input by coefficient:
# If input was positive, it stays positive.
# If input was negative, it's actually interpreted as positive.
# In this case, multiply by -1 to make it negative.
d # Duplicate signed input
[1r]s+ # Define a function `+': Push 1 and rotate
d 0>+ # If input is negative, push 1 underneath the top of the stack
# This 1 represents the length of the `-` in the input
# Note that the stack now has 3 items on it, regardless of input sign
dZ # Push the length of the input (not including leading minus)
r # Rotate, moving a copy of the input to the top
[ # Begin function definition
+ # Add top two items of stack
la # Load value from `a' (which holds nothing at time of function definition)
10~ # Slice the last digit off `a' (spoiler: `a' is going to hold the input while
# we gather its digits)
lc* # Multiply digit by coefficient
# Since the input is signed, the input modulo 10 will have the same sign.
# We want all digits to be positive, except the leftmost digit, which should
# have the sign of the input.
# This ensures that each digit is positive.
r # Rotate: move remaining digits to top of stack
dsa # Store a copy of the remaining digits in `a'
Z 1<A # Count the number of digits left; if more than 1, execute A
]sA # Store the function as `A'
d sa # Store a copy of the input in `a'
# Props to you if you're still reading this
Z 1<A # Count the number of digits left; if more than 1, execute A
la # Load leftmost digit of input (still signed appropriately)
+++ # Add the top four items on the stack
f # Dump stack
```
This was far more complicated than I had expected! Good challenge :)
[Answer]
## Bash + coreutils, 36 bytes
```
bc<<<$1+${#1}+$(sed s:\\B:+:g<<<0$1)
```
**Explanation:**
```
$1+ # the input number (+)
${#1}+ # the length of the number, the '-' sign included (+)
$(sed s:\\B:+:g<<<0$1) # insert '+' between two consecutive word characters
#A word character is any letter, digit or underscore.
bc<<< # calculate the sum
```
In sed, `\B` also matches between two consecutive non-word characters, so for a negative number it matches between '^' and '-'. Note the `0$1` trick needed for `\B` to give `0-1+2+3`, for example.
**Run example:** 'input.txt' contains all the test cases in the question's statement
```
while read N;do echo "$N -> "$(./ILD_sum.sh "$N");done < input.txt
```
**Output:**
```
87901 -> 87931
123 -> 132
99 -> 119
5 -> 11
1 -> 3
0 -> 1
-3 -> -4
-99 -> -96
-123 -> -115
-900 -> -905
-87901 -> -87886
```
[Answer]
## PowerShell v4, 48 bytes
```
param($n)$n,"$n".length+[char[]]"$n"-join'+'|iex
```
This *should* work in v2+, but I only tested in v4.
Takes input `$n`. Creates a new array with the `,` operator consisting of `$n` and the `.length` when `$n` is converted to a string. Concatenates with that the string `$n` cast as a char-array. Then, that whole array is `-join`ed together with `+` before being piped to `iex` (similar to `eval`). The result is left on the pipeline and output is implicit.
For example, for input `-123`, the array would look like `(-123, 4, -, 1, 2, 3)`, and the string after the `-join` would look like `-123+4+-+1+2+3`. Then the `Invoke-Expression` happens, and the result is `-115` as expected.
[Answer]
# Factor with `load-all`, 175 bytes
Well, this is not very short. The special handling of unary minus is really annoying; I guess I could do it better and I will, maybe.
```
[ dup [ 10 >base length ] [ [ 10 >base >array [ 48 - ] V{ } map-as ] [ 0 < ] bi [ reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip ] [ ] if 0 [ + ] reduce ] bi + + ]
```
Using this substitution regex:
```
s/(-?[\d]+)\s*->\s*(-?[\d]+)/{ $2 } [ $1 calculate-ild ] unit-test/g
```
We can turn the OP's test cases into a Factor test suite.
```
USING: arrays kernel math math.parser sequences ;
IN: sum-ild
: sum-digits ( n -- x )
[ number>string >array [ 48 - ] V{ } map-as ]
[ 0 < ]
bi
[
reverse dup pop* dup pop swap [ neg ] dip dup [ push ] dip
]
[ ] if
0 [ + ] reduce ;
: calculate-ild ( n -- x )
dup
[ number>string length ]
[ sum-digits ]
bi + + ;
USING: tools.test sum-ild ;
IN: sum-ild.tests
{ 87931 } [ 87901 calculate-ild ] unit-test
{ 132 } [ 123 calculate-ild ] unit-test
{ 119 } [ 99 calculate-ild ] unit-test
{ 11 } [ 5 calculate-ild ] unit-test
{ 3 } [ 1 calculate-ild ] unit-test
{ 1 } [ 0 calculate-ild ] unit-test
{ -4 } [ -3 calculate-ild ] unit-test
{ -115 } [ -123 calculate-ild ] unit-test
{ -905 } [ -900 calculate-ild ] unit-test
{ -87886 } [ -87901 calculate-ild ] unit-test
```
[Answer]
## C#, 118 bytes
```
int k(int a){var s=a.ToString();for(int i=0;i<s.Length;a+=s[i]<46?-(s[++i]-48)+ ++i-i:(s[i++]-48));return a+s.Length;}
```
[Answer]
# SpecBAS - 147 bytes
```
1 INPUT a$: l=LEN a$: b$="text "+a$+"+"+STR$ l+"+": FOR i=1 TO l: b$=b$+a$(i)+("+" AND i<l): NEXT i: EXECUTE b$
```
Builds up a string which then gets run. Unfortunately `EXECUTE` doesn't work with the `?` shorthand for `PRINT`, but `TEXT` saved 1 character.
[](https://i.stack.imgur.com/1oYXd.png)
[Answer]
# C#, 106 bytes
I beat java my a byte, my life is complete
```
int r(int n){var s=n+"";return n+s.Length+s.Select((k,j)=>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();}
```
Ungolfed (kinda)
```
public static int r(int n)
{
var s = n + "";
return n + s.Length + s.Select((k, j) =>int.Parse(s[k==45?1:j]+"")*(k==45?-2:1)).Sum();
}
```
[Answer]
# [Perl 5](https://www.perl.org/), 22 + 1 (-p) = 23 bytes
```
$_+=eval s//+/gr.y///c
```
[Try it online!](https://tio.run/##K0gtyjH9/18lXts2tSwxR6FYX19bP71Ir1JfXz/5/39DI@N/@QUlmfl5xf91CwA "Perl 5 – Try It Online")
[Answer]
# Java 8, ~~174~~ ~~136~~ ~~122~~ ~~107~~ ~~105~~ ~~93~~ 78 bytes
```
i->{int f=0;for(int j:(i+"").getBytes())i+=j<48?f++:f-->0?50-j:j-47;return i;}
```
-14 bytes thanks to *@LeakyNun*.
-15 bytes thanks to *@cliffroot*.
**Explanation:**
[Try it online.](https://tio.run/##hZCxbsMgFEV3f8VTJpCFRdJEiU2dSNmbJWPVgRKIoA62AEeKIn@7i90OXSqWJ/Hukc59GH7npO2kNZevUTTce3jj2j4zAG2DdIoLCafpOS9AoGlqzOJmyOLwgQct4AQWahg12T8nQNWUqdbNsKmQzhcLXFxlOD6C9Ahjndfmdb07qDyvFCF7ethQYipD1lvmZOidBc2GkU2Grv9souFXdG/1BW6xIjoHp@31/QM4/ul3fvggb0Xbh6KLUWgssoVAu21Jl3hu/C@zXL0kiLJMAJuUIpHTRE5SDUn6CFLSpObPdw3ZMH4D)
```
i->{ // Method with integer as both parameter and return-type
int f=0; // Integer-flag, starting at 0
for(int j:(i+"").getBytes())
// Loop over the digits as bytes
i+= // Increase the input with:
j<48? // If the current byte is '-':
f++ // Increase the input with the flag-integer `f` (which is 0),
// and increase the flag-integer `f` by 1 afterwards
: // Else:
f-->0? // If the flag-integer `f` is 1,
// and decrease the flag-integer `f` back to 0 afterwards
50-j // Increase it with 50 minus the current byte
: // Else
j-47; // Increase it with the byte as digit
// + 1 to cover for the length part in ILD
return i;} // Return the modified input as result
```
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `s`, 7 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
Ðls'+jE
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMyU5MGxzJyUyQmpFJmZvb3Rlcj0maW5wdXQ9ODc5MDEmZmxhZ3M9cw==)
or
[verify all test cases](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMyU5MGxzJyUyQmpFJmZvb3Rlcj0maW5wdXQ9ODc5MDElMjAtJTNFJTIwODc5MzElMEExMjMlMjAtJTNFJTIwMTMyJTBBOTklMjAtJTNFJTIwMTE5JTBBNSUyMC0lM0UlMjAxMSUwQTElMjAtJTNFJTIwMyUwQTAlMjAtJTNFJTIwMSUwQS0zJTIwLSUzRSUyMC00JTBBLTEyMyUyMC0lM0UlMjAtMTE1JTBBLTkwMCUyMC0lM0UlMjAtOTA1JTBBLTg3OTAxJTIwLSUzRSUyMC04Nzg4NiZmbGFncz1Dcw==)
#### Explanation
```
Ðls'+jE '# Implicit input
Ð # Triplicate input
l # Push its length
s # Swap to get input
'+j '# Join on "+"
E # Evaluate as Python
# Sum the stack
# Implicit output
```
[Answer]
# Perl 6 - 30 bytes
As literal as it gets
```
{$^a+$^a.chars+[+]($^a.comb)}
```
Use it as an anonymous function
```
> {$^a+$^a.chars+[+]($^a.comb)}(99)
119
```
[Answer]
## JavaScript (ES6), 38 bytes
```
n=>eval([n+=``,n.length,...n].join`+`)
```
Uses the old join-and-eval trick. Save 4 bytes if I can insist on string input:
```
f=
n=>eval([n,n.length,...n].join`+`)
;
```
```
<input type=number oninput=o.value=f(this.value)><input id=o readonly>
```
[Answer]
**C++, 255 Bytes**
```
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
int main(){
string input;
cin >> input;
int sum = atoi(input.c_str()) + input.length();
for(unsigned i = 0; i < input.length(); ++i)
sum += input.at(i) - 48;
return 0;
}
```
[Answer]
## Perl 5 - 37 Bytes
```
warn eval(join'+',/./g)+($_+=()=/./g)
```
Input is in $\_
[Answer]
## Javascript (using external library) (45 bytes)
Using a library I wrote to bring LINQ to Javascript, I was able to write the following:
```
(i)=>i+(i+"").length+_.From(i+"").Sum(x=>x|0)
```
[](https://i.stack.imgur.com/Hat03.png)
[Answer]
# C, ~~132~~ ~~116~~ ~~113~~ 80
```
t,c;f(char*v){for(c=atoi(v+=t=*v==45);*v;t=0,++v)c+=t?50-*v-2*c:*v-47;return c;}
```
Function `f()` takes the input as a string and returns the result as an integer. Full program version (113 bytes):
```
t;main(int c,char**v){char*p=v[1];c=atoi(p+=t=*p==45);for(c=t?-c:c;*p;++p,t=0)c+=t?50-*p:*p-47;printf("%d\n",c);}
```
Requires one argument.
[Answer]
## Perl, 27 bytes
**22 bytes code + 5 for `-paF`.**
```
$"="+";$_+=@F+eval"@F"
```
### Explanation
Uses the `-a` autosplit option with an empty delimiter (`-F`) creating an array of the digits passed in. Uses the magic variable `$"` which controls which char is used to join an array when it's interpolated into a string (we use `"+"` here) and the fact that a list used in scalar context will return the length of the list (the number of digits).
### Usage
```
echo -n 99 | perl -paF -e'$"="+";$_+=@F+eval"@F"'
119
```
---
## Perl, 27 bytes
**22 bytes code + 5 for `-paF`.**
Alternative solution, that's a lot more readable for no more bytes. I prefer the other as it looks more cryptic!
```
$_+=@F+eval join"+",@F
```
[Answer]
## dc, 56 bytes
```
?dZrdd1sa[1+r0r-_1sa]sb0>b[A~rd0<x]dsxxrla*[+z1<y]dsyxp
```
No shorter than Joe's above, but a somewhat different implementation (and one that takes negative numbers as input vs. a subtraction command). Can probably be golfed more, but lunch only lasts so long.
```
? #input
dZrdd #find no. of digits, rotate to bottom of stack, dup input twice
1sa #coefficient for first digit stored in register 'a'
[1+r0r-_1sa]sb #macro 'b' executes on negative numbers. add one (for the neg. sign)
#rotate this value out of the way, leave a positive copy on top
0>b #run the above macro if negative
[A~rd0<x]dsxx #create and run macro 'x'; mod 10 to grab least significant digit
#keep doing it if quotient is greater than zero
rla* #a zero remains in the way of our most significant digit, rotate it down
#and multiply said digit by our coefficient 'a' from earlier
[+z1<y]dsyx #add two top stack values (we left that zero there to ensure this always
#works), check stack depth and keep doing it while there's stack
p #print!
```
[Answer]
## R, 108 bytes
A bit late to the party again but here it goes:
```
s=strsplit(paste(n<-scan()),"")[[1]];n+nchar(n)+sum(as.integer(if(n<0)c(paste0(s[1],s[2]),s[1:2*-1])else s))
```
In order to generally split the digits of any number (e.g. to sum them), R requires us to first convert to a string and subsequently split the string into a string vector. To sum up the elements, the string vector has to be converted to numeric or integer. This together with the exception with the sum of a the digits of a negative number eats up a lot of bytes.
The exception can be golfed a bit (to 96 bytes) if warning messages are allowed.
```
s=as.integer(strsplit(paste(n<-scan()),"")[[1]]);if(n<0){s[2]=s[2]*-1;s=s[-1]};n+nchar(n)+sum(s)
```
In this case the string vector is converted to integer directly using `as.integer`. However, for negative numbers the first element in the vector will be a minus sign: `"-"`. This causes some trouble, e.g.: `as.numeric(c("-",1,2,3))` will return `NA 1 2 3` and a warning message. To circumvent this, remove the NA and then multiply the first element with `-1` before taking the sum.
[Answer]
# RProgN, 30 Bytes
```
] '' . ] '-?.' | sum _ \ L + +
```
## Explination
```
] # Clone the input
#
'' . ] # Convert it to a string, then clone it again.
'-?.' | sum # Split it into chunks via the pattern '-?.' (A - if there is one, followed by a single character). Sum the resulting array.
_ # Floor the value, purely because I hate floats.
\ L + + # Swap the top value with the value underneith it, to work with the string again. Get it's length, add the top, middle, and bottom, which is now the length, the sum and the input respectively.
```
[Try it Online!](https://tehflamintaco.github.io/Reverse-Programmer-Notation/RProgN.html?rpn=%5D%20%27%27%20.%20%5D%20%27-%3F.%27%20%7C%20sum%20_%20%5C%20L%20%2B%20%2B&input=-123)
] |
[Question]
[
# Challenge :
Count the number of ones `1` in the binary representation of all number between a range.
---
# Input :
Two non-decimal positive integers
---
# Output :
The sum of all the `1`s in the range between the two numbers.
---
# Example :
```
4 , 7 ---> 8
4 = 100 (adds one) = 1
5 = 101 (adds two) = 3
6 = 110 (adds two) = 5
7 = 111 (adds three) = 8
10 , 20 ---> 27
100 , 200 ---> 419
1 , 3 ---> 4
1 , 2 ---> 2
1000, 2000 ---> 5938
```
I have only explained the first example otherwise it would have taken up a huge amount of space if I tried to explain for all of them.
---
# Note :
* Numbers can be apart by over a 1000
* All input will be valid.
* The minimum output will be one.
* You can accept number as an array of two elements.
* You can choose how the numbers are ordered.
---
# Winning criteria :
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so shortest code in bytes for each language wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
f=lambda x,y:y/x and bin(x).count('1')+f(x+1,y)
```
[Try it online!](https://tio.run/##LYzNCsIwEAbP@hTfpSRLV21aQSjou6SWYEA3paSQPH38iZeZOc2S4yNIX4q7Pu1rmi0S5zGfEqzMmLzoRMd72CRqZRS1TqfWcKbiwgqdGJngBfrMuBBDm47Rd7V@WZsx/N3TuN8tq5cI1Qwb4wMcbl8pNHXJcHVN5Q0 "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 38 bytes
Takes input in currying syntax `(a)(b)`.
```
a=>b=>(g=c=>a>b?0:1+g(c^c&-c||++a))(a)
```
[Try it online!](https://tio.run/##bcxBCsIwEIXhvaeYlWQItUksVAuJNxGmYxuU0kgrrnr3GDGr4OZtPt7/oDetvNyfr2oOtyGONpJ1vXXCW7aOXH9RnZZe8JX3FW@blIQoCCOHeQ3TcJiCF6MAaDBNiwh1DaddoVolNeqnpi1Yq8RGZW70ubyD/saP2f@ryfH4AQ "JavaScript (Node.js) – Try It Online")
### Commented
```
a => b => ( // given the input values a and b
g = c => // g = recursive function taking c = current value
a > b ? // if a is greater than b:
0 // stop recursion and return 0
: // else:
1 + // add 1 to the final result
g( // and do a recursive call to g() with:
c ^ c & -c // the current value with the least significant bit thrown away
|| ++a // or the next value in the range if the above result is 0
) // end of recursive call
)(a) // initial call to g() with c = a
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
rBFS
```
[Try it online!](https://tio.run/##y0rNyan8/7/IyS34////Jv/NAQ "Jelly – Try It Online")
### Explanation
```
rBFS – Full program. Takes the two inputs from the commands line arguments.
r – Range.
B – For each, convert to binary.
FS – Flatten and sum.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
ŸbSO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//6I6kYP///024zAE "05AB1E – Try It Online")
[Answer]
# [Java (JDK 10)](http://jdk.java.net/), 55 bytes
```
a->b->{int c=0;for(;a<=b;)c+=a.bitCount(b--);return c;}
```
[Try it online!](https://tio.run/##LY5BS8QwEIXv/RVzTNQED4KHbAsiCB7Ew@JJPEyyaUlNk5BMFsrS317j6umbx5uZ92Y8o5hP37tbUswEc9OykvNyrMGQi0HeqM54LAXe0AW4dACpau8MFEJqOEd3gqV57EjZhenzCzBPhV9XAV7@/xxeA9nJ5rvGj4B5fU82I8U8wNjvKAYthosLBKa/V2PMTOGh14qb2x6ldvQcayCmheAqW6o5gFHbrq4Zx7WQXWSsJFOrQD6wUWJKfmUP/G94Ki2XPXL@e7F12/4D "Java (JDK 10) – Try It Online")
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~8~~ 7 bytes
1 byte thanks to Mr. Xcoder.
```
ssjR2}F
```
[Try it online!](http://pyth.herokuapp.com/?code=ssjR2%7DF&input=4%2C7&debug=0)
[Answer]
# [Python 2](https://docs.python.org/2/), 45 bytes
```
lambda x,y:`map(bin,range(x,y+1))`.count('1')
```
[Try it online!](https://tio.run/##LYxBCsIwFETXeorZlOTjV5pUEAp6EhdN1WihTUJJwZw@VuNm3mMGJqT48k5nizOueTRTfzd4c2q7yQTZD45n454PuVY7RdQdbn5xUQolKFs/Yx2QCIODPDJOxJCqZui62E@LM5o/NbXbTZgHFyGqZmGsgf3lC4GqXDJsuab8AQ "Python 2 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~5~~ 4 bytes
```
&:Bz
```
[Try it online!](https://tio.run/##y00syfn/X83Kqer/fxMucwA "MATL – Try It Online")
*Thanks to Luis Mendo for saving a byte!*
```
(implicit input a and b, a<b)
&: % two-element input range, construct [a..b]
B % convert to Binary as a logical vector (matrix)
z % number of nonzero entries
(implicit output of the result)
```
[Answer]
# [R](https://www.r-project.org/), ~~41~~ 34 bytes
```
function(a,b)sum(intToBits(a:b)>0)
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJs7g0VyMzryQk3ymzpFgj0SpJ085A83@ahomOuSZXmoahgY6RAYQBYkGYOsYQykjzPwA "R – Try It Online")
Heavily inspired by [the other R solution by ngm](https://codegolf.stackexchange.com/a/166216/80010). This uses a different approach after the conversion to bits. Huge thanks to Giuseppe for hinting at a possible 34 bytes solution.
[Answer]
# [Ruby](https://www.ruby-lang.org/), 38 bytes
```
->a,b{("%b"*(b-a+1)%[*a..b]).count ?1}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5RJ6laQ0k1SUlLI0k3UdtQUzVaK1FPLylWUy85vzSvRMHesPZ/QWlJsUJatImOeex/AA "Ruby – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 16 [bytes](https://github.com/abrudz/SBCS)
```
{≢⍸(⍵⍴2)⊤⍺↓0,⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR56JHvTs0HvVufdS7xUjzUdeSR727HrVNNtB51LsZKFr7//@j3rkK4Zk5OQq5idmpCpklCkmpJSWpRQo5iUBSj4vL0MBAoVr7Uc9@HTzGKBgZGAAA "APL (Dyalog Unicode) – Try It Online")
-1 thanks to [H.PWiz](https://codegolf.stackexchange.com/users/71256/h-pwiz).
Left argument = min
Right argument = max
[Answer]
# [Octave](https://www.gnu.org/software/octave/) with Communication toolbox, 21 bytes
```
@(a,b)nnz(de2bi(a:b))
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999BI1EnSTMvr0ojJdUoKVMj0SpJU/N/moaJjrkmV5qGoYGOkQGEAWJBmDrGEMpI8z8A "Octave – Try It Online")
The code should be fairly obvious. Number of nonzero elements in the binary representation of each of the numbers in the range.
This would be `@(a,b)nnz(dec2bin(a:b)-48)` without the communication toolbox.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~56~~ ~~54~~ 52 bytes
~~This can be golfed more imo.~~
-2 Bytes thanks to Mr.Xcoder
-2 More bytes thanks to M. I. Wright
```
lambda a,b:''.join(map(bin,range(a,b+1))).count('1')
```
[Try it online!](https://tio.run/##K6gsycjPM/6fbhvzPycxNyklUSFRJ8lKXV0vKz8zTyM3sUAjKTNPpygxLz1VAyijbaipqamXnF@aV6Khbqiu@b@gKBPITNcw0THX1ORC8Cw0Nf8DAA "Python 3 – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `d`, 2 bytes
```
ṡb
```
[Try it online](https://vyxal.pythonanywhere.com/#WyJkIiwiIiwi4bmhYiIsIiIsIjRcbjciXQ==) or see a [four byte flagless version](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuaFiZuKIkSIsIiIsIjRcbjciXQ==).
Gets the range between the two inputs, converts each to a list of 1s and 0s, then deep flattens and sums with the `d` flag.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
çy╠Ƽ☻
```
[Run and debug it](https://staxlang.xyz/#p=8779cc92ac02&i=4+7&a=1)
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 72 bytes
```
param($x,$y)$x..$y|%{$o+=([convert]::ToString($_,2)-replace0).length};$o
```
[Try it online!](https://tio.run/##BcFRCoMwDADQy2TQMi3RT8VTuD@RUSSoUJuSlU3RnT2@l/hH8lkoBNXkxW8G9gIOC7tzcFyPE/jZmWHi@CXJY9O8uM@yxtnAu6htKZSCnwitCxTnvPxbYFWtELVGvAE "PowerShell – Try It Online")
Long because of the conversion to binary `[convert]::ToString($_,2)` and getting rid of the zeros `-replace0`. Otherwise we just take the input numbers, make a range `$x..$y` and for each number in the range convert it to binary, remove the zeros, take the `.length` thereof (i.e., the number of ones remaining), and add it to our `$o`utput.
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + common utilities, 50
```
jot -w%o - $@|tr 247356 1132|fold -1|paste -sd+|bc
```
[Try it online!](https://tio.run/##S0oszvj/Pyu/REG3XDVfQVdBxaGmpEjByMTc2NRMwdDQ2KgmLT8nRUHXsKYgsbgkVUG3OEW7Jin5////hgb/jQwA "Bash – Try It Online")
Converting integers to binary strings is always a bit of pain in bash. The approach here is slightly different - convert the integers to octal, then replace each octal digit with the number of binary 1s it contains. Then we can just sum all converted digits
[Answer]
# APL+WIN, ~~33~~ 26 bytes
Prompts for vector of integers:
```
+/,((↑v)⍴2)⊤(1↓v)+0,⍳-/v←⎕
```
[Try it online! Courtesy of Dalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/5r6@toaDxqm1im@ah3i5Hmo64lGoaP2iaXaWob6Dzq3ayrXwZUC9TzH6j6fxqXuYIJVxqXkYGCoQGYBjFALGMFQxBfwRAA "APL (Dyalog Classic) – Try It Online")
Explanation:
```
v←⎕ prompt for input of a vector of two integers max first
(v←1↓v)+0,⍳-/ create a vector of integers from min to max
(↑v)⍴2 set max power of 2 to max
⊤ convert integers to a matrix of binaries
+/, convert matrix to a vector and sum
```
[Answer]
# [R](https://www.r-project.org/), ~~44 40~~ 37 bytes
```
function(a,b)sum(c(0,intToBits(a:b)))
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP08jUSdJs7g0VyNZw0AnM68kJN8ps6RYI9EqSVNT83@ahomOueZ/AA "R – Try It Online")
Previously:
```
function(a,b)sum(strtoi(intToBits(a:b)))
function(a,b)sum(as.integer(intToBits(a:b)))
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 8 bytes
```
⟦₂ḃᵐcọht
```
[Try it online!](https://tio.run/##ASkA1v9icmFjaHlsb2cy///in6bigoLhuIPhtZBj4buNaHT//1sxMCwyMF3/Wg "Brachylog – Try It Online")
### Explanation
```
⟦₂ Ascending range between the two elements in the input
ḃᵐ Map to base 2
c Concatenate
ọ Occurrences of each element
h Head: take the list [1, <number of occurrences of 1>]
t Tail: the number of occurrences of 1
```
[Answer]
# [Forth (gforth)](http://www.complang.tuwien.ac.at/forth/gforth/Docs-html/), 69 bytes
```
: f 1+ 0 -rot swap do i begin 2 /mod -rot + swap ?dup 0= until loop ;
```
[Try it online!](https://tio.run/##LY3NDsIgEITvPsWk14ZK8S9poz6LilSS2t0gjY@PC3iZ@TazmXEU4ktNLltKAxz6FhoqUMTne2NYgsf9OfkFBts32Zq1Nb3alaHPWJfoZ8xEjFFaGCYH5eWALlTpGkCpSyMjx3w/wrjppZVFd6J7nDJrGF08w58KCqcf "Forth (gforth) – Try It Online")
### Explanation
The basic algorithm is to loop over every number in range, and sum the binary digits (divide by two, add remainder to sum, repeat until number is 0)
### Code Explanation
```
1+ \ add one to the higher number to make it inclusive
0 -rot swap \ create a sum value of 0 and put loop parameters in high low order
do \ start a loop over the range provided
i \ place the index on the stack
begin \ start an indefinite loop
2 /mod \ get the quotient and remainder of dividing by 2
-rot \ move the quotient to the back
+ swap \ add the remainder to the sum and move it down the stack
?dup \ duplicate the quotient unless it equals 0
0= \ check if it equals 0
until \ if it does equal 0, end the inner loop
loop \ end the outer loop
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes
```
Σṁḋ…
```
[Try it online!](https://tio.run/##yygtzv7//9zihzsbH@7oftSw7P///yb/zQE "Husk – Try It Online")
### Explanation
```
Σṁḋ…
… Get the (inclusive) range.
ṁḋ Convert each to binary and concatenate.
Σ Get the sum.
```
[Answer]
## PHP, 97 Bytes
(sure this can be shortened, but wanted to use the functions)
[**Try it online**](https://tio.run/##K8go@G9jX5BRwKWSWJReFm0Qa2tiDWUbxtqaW3PZ2wEV2BaXJhWXFMUn55fmlWhk5hbk5KekaiQWFSVWxucmFmikleYll2Tm52molGlWF6WWlBblKaSkJidlgkWsa3WKEvPSUzVgdujALNDU1NQx1LT@/x8A)
**Code**
```
<?=substr_count(implode(array_map(function($v){return decbin($v);},
range($argv[0],$argv[1]))),1);
```
**Explanation**
```
<?=
substr_count( //Implode the array and count every "1"
implode(
array_map(function($v){return decbin($v);}, //Transform every decimal to bin
range($argv[0],$argv[1]) //generate a range between the arguments
)
),1); //count "1"'s
```
[Answer]
# [Haskell](https://www.haskell.org/), 42 bytes
```
import Data.Bits
a%b=sum$popCount<$>[a..b]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzO3IL@oRMElsSRRzymzpJgrUTXJtrg0V6Ugv8A5vzSvxEbFLjpRTy8p9n9uYmaegq1CQVFmXomCioKhgYGqhpGBgZWVZ16JpsJ/AA "Haskell – Try It Online")
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 10 bytes
```
$+JTB:a\,b
```
[Try it online!](https://tio.run/##K8gs@P9fRdsrxMkqMUYn6f///4YGBv@NDAwA "Pip – Try It Online")
### Explanation
```
a and b are command-line args (implicit)
a\,b Inclusive range from a to b
TB: Convert to binary (: forces TB's precedence down)
J Join into a single string of 1's and 0's
$+ Sum (fold on +)
```
[Answer]
# [Proton](https://github.com/alexander-liao/proton), ~~[40](https://codegolf.stackexchange.com/revisions/166208/1)~~ 37 bytes
```
x=>y=>str(map(bin,x..y+1)).count("1")
```
[Try it online!](https://tio.run/##KyjKL8nP@59m@7/C1q7S1q64pEgjN7FAIykzT6dCT69S21BTUy85vzSvREPJUEnzf0FRJpCZpmGiqWGuqfkfAA "Proton – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 10 bytes
```
IΣ⭆…·NN⍘ι²
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEI7g0VyO4BMhP900s0MjMS84pLc4sSw1KzEtP1fDMKygt8SvNTUot0tDUUUDhAvlOicWpEL0amToKRpogYP3/vwmXxX/dshwA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NN Input numbers
…· Inclusive range
⭆ Map over range and join
ι Current value
² Literal 2
⍘ Convert to base as string
Σ Sum of digits
I Cast to string
Implicitly print
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils, ~~38~~ 32 bytes
```
seq -f2o%.fn $*|dc|tr -d 0|wc -c
```
*Thanks to @Cowsquack for golfing off 6 bytes!*
[Try it online!](https://tio.run/##S0oszvj/vzi1UEE3zShfVS8tT0FFqyYluaakSEE3RcGgpjxZQTf5////hgb/jQwA "Bash – Try It Online")
[Answer]
# [K (ngn/k)](https://gitlab.com/n9n/k), ~~19~~ 13 bytes
```
{+//2\x_!1+y}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqlpbX98opiJe0VC7svZ/WrSJtXnsfwA "K (ngn/k) – Try It Online")
`{` `}` is a function with arguments `x` and `y`
`!1+y` is the list 0 1 ... y
`x_` drops the first x elements
`2\` encodes each int as a list of binary digits of the same length (this is specific to ngn/k)
`+/` sum
`+//` sum until convergence; in this case sum of the sum of all binary digit lists
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~32~~ 30 bytes
*-1 bytes thanks to Brad Gillbert*
```
{[…](@_)>>.base(2).comb.sum}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJKmYKvwvzr6UcOyWA2HeE07O72kxOJUDSNNveT83CS94tLc2v/FiSCFGoYGBjoKRgYGmtZccBGQgOZ/AA "Perl 6 – Try It Online")
Explanation:
```
[…](@_) #Range of parameter 1 to parameter 2
>> #Map each number to
.sum #The sum of
.comb #The string of
.base(2) #The binary form of the number
```
] |
[Question]
[
Given a string as input, output the string with the following algorithm applied:
```
1. Split the String by " " (find the words): "Hello World" -> ["Hello","World"]
2. Find the vowel count of each component: [2,1] ( ["H[e]ll[o]","W[o]rld"] )
3. For each of the components, output the first n letter where n is the number
of vowels it contains: ["He","W"]
4. Join the list to a single string and reverse it: "HeW" -> "WeH"
```
## Specs
* You may take input and provide output by [any standard form](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods?answertab=votes#tab-top), and the only data type allowed for both Input and Output is your language's native String type. Taking input directly as a list of individual words is not permitted.
* You are guaranteed that there will be no consecutive spaces.
* The vowels are `"a","e","i","o","u","A","E","I","O","U"`, but `"y","Y"` *are not considered vowels*.
* You are guaranteed that only letters and spaces will appear in the input, but without any newlines.
* Output *must* be case-sensitive.
* You are not guaranteed that each word contains a vowel. If no vowels appear in that word, you do not have to output anything for it.
## Test Cases
```
Input -> Output
---------------
"" -> ""
"Hello World" -> "WeH"
"Waves" -> "aW"
"Programming Puzzles and Code Golf" -> "GoCauPorP"
"Yay Got it" -> "iGY"
"Thx for the feedback" -> "eeftf"
"Go Cat Print Pad" -> "PPCG"
"ICE CREAM" -> "RCCI"
```
## Scoring
The shortest valid submission for each language wins, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Good luck and have fun!
---
[Sandbox](https://codegolf.meta.stackexchange.com/questions/2140/sandbox-for-proposed-challenges/12896#12896) for those who can see deleted posts.
[Answer]
## Haskell, 59 bytes
```
map fst.reverse.(>>=zip<*>filter(`elem`"aeiouAEIOU")).words
```
[Try it online!](https://tio.run/##VcqxDoIwFAXQ3a@4aRzAgS8QEmOMcZJBd6p9hca2j7wWNfx8nT3zmXR6kfel2DboGTblRuhNkqipuq5d3bzfddb5TFIN5CkMSpPj5XC6XO@qrpsPi0klaBfRwvAGmMXFjC0sVC88ig7BxRH9sq6eEnQ0OLIhnNlb9f9v0xeWBXkiWCLz0M@XKj8 "Haskell – Try It Online")
```
words -- split into a list of words
(>>= ) -- apply a function to every word and collect the results in a
-- single list
zip<*>filter(`elem`"aeiouAEIOU")
-- f <*> g x = f x (g x), i.e. zip x (filter(...)x)
-- we now have a list of pairs of (all letters of x, vowel of x)
-- with the length of number of vowels
reverse -- reverse the list
map fst -- drop vowels from the pairs
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 31 bytes
```
Í /ò
òÄøã[aeiou]
|DJ@"|D-òÍî
æ
```
[Try it online!](https://tio.run/##K/v//3Cvgv7hTVyHNx1uObzj8OLoxNTM/NJYLsYaFy8HpRoXXaBE7@F1XIeX/f8fklGhkJZfpFCSkaqQlpqakpSYnA0A "V – Try It Online")
```
00000000: cd20 2ff2 0af2 c4f8 e35b 6165 696f 755d . /......[aeiou]
00000010: 0a01 7c44 4a40 227c 442d f2cd ee0a e6 ..|DJ@"|D-.....
```
And explanation:
```
Í " Substitute Every space
/ " With
ò " Newlines
" This puts us on the last line of the buffer
ò " Recursively:
Ä " Duplicate the current line
ø " Count:
ã " Case insensitive
[aeiou] " The number of vowels
<C-a> " Increment this number
| " Go to the beginning of this line
DJ " Delete the number of vowels, and remove a newline that was accidentally made.
" Also, my name! :D
@" " Run the unnamed register, which is the number of vowels that we deleted
| " And move to the n'th column in this line
D " Delete everything on this line after the cursor, keeping the first *n* characters
- " Move up a line
ò " End the loop
Íî " Remove all newlines
æ " And reverse:
" (implicit) The current line
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 17 bytes
```
ṇ₁{{∋ḷ∈Ṿ}ᶜ}ᶻs₎ᵐc↔
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@HO9kdNjdXVjzq6H@7Y/qij4@HOfbUPt80B4t3Fj5r6Hm6dkPyobcr//0oBRfnpRYm5uZl56QoBpVVVOanFCol5KQrO@SmpCu75OWlK/6MA "Brachylog – Try It Online")
### Explanation
That's a direct translation of the problem:
```
Example input: "Hello World"
ṇ₁ Split on spaces: ["Hello", "World"]
{ }ᶻ Zip each word with: [["Hello",2],["World",1]]
{ }ᶜ The count of:
∋ḷ∈Ṿ Chars of the words that when lowercased are in "aeiou"
s₎ᵐ Take the first substring of length <the count> of each word: ["He","W"]
c Concatenate: "HeW"
↔ Reverse: "WeH"
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-p040F`, 35 bytes
```
$\=$_.$\for@F[0..lc=~y/aeiou//-1]}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxlYlXk8lJi2/yMEt2kBPLyfZtq5SPzE1M79UX1/XMLa2@v//gKL89KLE3NzMvHSFgNKqqpzUYoXEvBQF5/yUVAX3/Jy0f/kFJZn5ecX/dQsMTAzcAA "Perl 5 – Try It Online")
[Answer]
# [Perl 6](http://perl6.org/), 57 bytes
```
{flip [~] .words.map:{.substr(0,.comb(rx:i/<[aeiou]>/))}}
```
[Answer]
## [Alice](https://github.com/m-ender/alice), 32 bytes
```
/.'*%-.m"Re.oK"
\iu &wN.;aoi$u@/
```
[Try it online!](https://tio.run/##S8zJTE79/19fT11LVVcvVykoVS/fW4krJrNUQa3cT886MT9TpdRB////gKL89KLE3NzMvHSFgNKqqpzUYoXEvBQF5/yUVAX3/Jw0AA "Alice – Try It Online")
### Explanation
```
/....
\...@/
```
This is just a framework for linear code in Ordinal (string-processing mode). Unfolding the program, we get:
```
i' %w.."aeiou".u*&-Nm;Ro.$K@
```
Here's what it does:
```
i Read all input.
' % Split the input around spaces.
w Push the current IP address to the return address stack to mark
the beginning of the main loop. Each iteration will process one
word, from the top of the stack to the bottom (i.e. in reverse
order).
.. Make two copies of the current word.
"aeiou" Push this string.
.u* Append an upper case copy to get "aeiouAEIOU".
&- Fold substring removal over this string. What that means is that
we push each character "a", "e", ... in turn and execute -
on it. That will remove all "a"s, all "e"s, etc. until all
vowels are removed from the input word.
N Compute the multiset complement of this consonant-only version
in the original word. That gives us only the vowels in the word.
We now still have a copy of the input word and only its vowels
on top of the stack.
m Truncate. This reduces both strings to the same length. In particular,
it shortens the input word to how many vowels it contains.
; Discard the vowels since we only needed their length.
R Reverse the prefix.
o Print it.
. Duplicate the next word. If we've processed all words, this
will give an empty string.
$K Jump back to the beginning of the loop if there is another word
left on the stack.
@ Otherwise, terminate the program.
```
[Answer]
## JavaScript (ES6), 76 bytes
```
s=>s.split` `.map(w=>w.split(/[aeiou]/i).map((_,i)=>o=i?w[i-1]+o:o),o='')&&o
```
### Test cases
```
let f =
s=>s.split` `.map(w=>w.split(/[aeiou]/i).map((_,i)=>o=i?w[i-1]+o:o),o='')&&o
console.log(f("" )) // -> ""
console.log(f("Hello World" )) // -> "WeH"
console.log(f("Waves" )) // -> "aW"
console.log(f("Programming Puzzles and Code Golf")) // -> "GoCauPorP"
console.log(f("Yay Got it" )) // -> "iGY"
console.log(f("Thx for the feedback" )) // -> "eeftf"
console.log(f("Go Cat Print Pad" )) // -> "PPCG"
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~54~~ 59+1 = ~~55~~ 60 bytes
Uses the `-p` flag for +1 byte.
```
$_=$_.split.map{|w|w[0,w.count("aeiouAEIOU")]}.join.reverse
```
[Try it online!](https://tio.run/##HY7BSsNAFEX3@YprG1BRR3@gCylSBTFZKEVEymvykoxO5oWZl8bU@u01urp3ce/hhH47HucnYQpcdcd0s0g3JnbOqmmp@z4Mh@Ht5nIwhfRez2bEVvrbu4fsZXb@/mM@xHoTeMch8vS9WKTXmCPzboTngmOkMEIFXa8g56AcFQVFjhCP0lYVB/YKZz1HgydRdBQUUkEbBhXak0MhJR/v2TnBWoIrkzXtOCZ5kDpQ21pfI@/3ezdRyZdYTnOsxFXJK41TUVhNnpsvVBL@sRVzuaXiM1kJlqTIg50cciqTR9bTiFr@nLPGyi8 "Ruby – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt) v2.0a0, ~~12~~ 10 bytes
```
¸®¯Zè\vìw
```
[Try it](https://ethproductions.github.io/japt/?v=2.0a0&code=uK6vWuhcdsOsdw==&input=IlRoeCBmb3IgdGhlIGZlZWRiYWNrIg==)
---
## Explanation
Pretty much does exactly what the spec describes!
```
:Implicit input of string U.
¸ :Split to array on spaces.
® :Map over the array, replacing each element with itself ...
¯ : sliced from the 0th character to ...
Zè\v : the count (è) of vowels (\v) in the element (Z).
à :End mapping.
¬ :Join to a string.
w :Reverse.
:Implicit output of result.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 14 bytes
```
#RʒDžMDu«Ãg£R?
```
[Try it online!](https://tio.run/##MzBNTDJM/f9fOejUJJej@3xdSg@tPtycfmhxkP3//@75Cs6JJQoBRZl5QDIxBQA "05AB1E – Try It Online")
*Darn 05AB1E doesn't have builtin for AEIOUaeiou ಠ\_ಠ*
[Answer]
# JavaScript (ES6), 96 bytes
```
s=>[...s.split` `.map(w=>w.slice(0,(m=w.match(/[aeiou]/gi))&&m.length)).join``].reverse().join``
```
```
f=
s=>[...s.split` `.map(w=>w.slice(0,(m=w.match(/[aeiou]/gi))&&m.length)).join``].reverse().join``
console.log(
f(''),
f('Hello World'),
f('Waves'),
f('Programming Puzzles and Code Golf'),
f('Yay Got it'),
f('Thx for the feedback'),
f('Go Cat Print Pad')
)
```
[Answer]
# [Python 3](https://docs.python.org/3/), 83 81 79 77 bytes
* [Mr. Xcoder](https://codegolf.stackexchange.com/users/59487/mr-xcoder) saved 2 bytes
* [Griffin](https://codegolf.stackexchange.com/users/2501/griffin) saved 2 bytes: Switch from Python 3 to 2
* saved 2 bytes: use of lambda
```
lambda z:''.join(i[:sum(y in'aeiouAEIOU'for y in i)]for i in z.split())[::-1]
```
[Try it online!](https://tio.run/##dY4/C8IwFMR3P8WjS5PBgrgVHEREnXRQRNQhNUn7NM0raSq2X77aDv4ZvOn43R1cUfuM7LjVk1NrRJ5IAU0chtGV0DI8xmWVsxrQhkIhVdP5ar0LNTnoGCA/dx4730RlYdAzzo9xPByd28Kh9UyzYKmMIdiTMzLgfPDme3FXZQCcw4dtHKVO5DnaFDZV0xhVgrASZiQVLMjovv81OIj6xT2gD36DbfaA7pzPFGilZCIut77yT@0T "Python 3 – Try It Online")
[Answer]
# Pyth - 19 bytes
```
_jkm<dl@"aeiou"rd0c
```
[Try it here](https://pyth.herokuapp.com/?code=_jkm%3Cdl%40%22aeiou%22rd0c&input=Hello%20World&test_suite=1&test_suite_input=%22%22%0A%22Hello%20World%22%0A%22Waves%22%0A%22Programming%20Puzzles%20and%20Code%20Golf%22%0A%22Yay%20Got%20it%22%0A%22Thx%20for%20the%20feedback%22%0A%22Go%20Cat%20Print%20Pad%22&debug=0)
Explanation:
```
_jkm<dl@"aeiou"rd0c
c # Split implicit input on whitespace
m # For each word d...
rd0 # ...take the lower-case conversion...
@"aeiou" # filter it to only vowels...
l # and find the length of this string (i.e., the number of vowels in the word)
<d # Take the first # characters of the word (where # is the length from above)
jk # Join on empty string (can't use s, because that will screw up when the input is the empty string)
_ # Reverse the result (and implicitly print)
```
I could have 18 bytes if not for the empty string:
```
_sm<dl@"aeiou"rd0c
```
[Answer]
# Pyth, 31
This took me a long time to write, and I feel like there is probably a better approach, but here is what I have:
```
_jkm<Fd.T,cQ)ml:d"[aeiou]"1crQ0
```
[Online test](https://pyth.herokuapp.com/?code=_jkm%3CFd.T%2CcQ%29ml%3Ad%22%5Baeiou%5D%221crQ0&test_suite=1&test_suite_input=%27%27%0A%27Hello+World%27%0A%27Waves%27%0A%27Programming+Puzzles+and+Code+Golf%27%0A%27Yay+Got+it%27%0A%27Thx+for+the+feedback%27%0A%27Go+Cat+Print+Pad%27&debug=0).
```
Q # input
r 0 # to lowercase
c # split by whitespace
:d"[aeiou]"1 # lambda: regex to find vowels in string
l # lambda: count the vowels in string
m # map lambda over list of words
cQ) # split input by whitespace
, # list of (input words, vowel counts)
.T # transpose
<Fd # lambda to get first n chars of string
m # map lambda over list of (input words, vowel counts)
jk # join on on empty strings
_ # reverse
```
[Answer]
# Ohm, 13 bytes
```
z:αv_K_σh;0JR
```
## Explanation
* First the (implicit) input is split on spaces by `z`.
* Then a foreach loop is started (`:`) with it's associated codeblock being `αv_K_σh`.
+ `av` pushes `aeiou`
+ `_` pushes the current iterated element
+ `K` counts the occurrences of `aeiou` in `_`
+ `_` the element again
+ `σh` Splits the element into slices of length `occurences` and takes the first element.
- Effectively this takes the first `occurences` chars
* `0J` Pushes the stack joined on `''`
+ The `0` is necessary because it requires an argument that will be joined. If that argument isn't an array it joins the stack
* `R` reverses the result
* implicit print of the TOS
[Answer]
# [Java 8](http://openjdk.java.net/), ~~171~~ 151 bytes
-20 bytes thanks to @Lukas Rotter
I feel like it still needs some golfing... let me know in the comments if you have any suggestions.
```
s->{String z="";for(String w:s.split(" "))z+=w.substring(0,w.replaceAll("(?i)[^aeiou]","").length());return new StringBuilder(z).reverse().toString();}
```
[Try it online!](https://tio.run/##hZExb8MgEIV3/4oTE6gJ6lwrrdoM6dLIUitFVZRKxD4nJBgswHbjyL/dxa2z1guCe98d78FJ1GJuStSn7NxHqRLOwZuQ@hoBSO3R5iJFWA9HgHdvpT5ASseNY3God1FYnBdeprAGDQvo3fzxOjLtgpA4N/bW0zw47kolPSVAGGvvFg131d79qvR@1nCLpQqXPitFCX2SbPslUJpqR2aEMK5QH/yRMhZb9JXVoLEZjb1UUmVoacvCjBqtQ8q4N38iZXHXx4PVstqrYHV0XBuZQRESjwa3OxBsjHtxHgtuKs/LIHmlqeYpJa@olIGNsSoLCeJ/2Y2o0U1SiTUHK4pieKCkaluFDoTOYGkyhJVR@eSET3EJoAfpJ9GP4zeEDwF/RMgRs71Iz5NNKwNL4SEZapCIW/Au6vof "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 10 bytes
```
⌈ƛk∨↔LẎ;∑Ṙ
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E2%8C%88%C6%9Bk%E2%88%A8%E2%86%94L%E1%BA%8E%3B%E2%88%91%E1%B9%98&inputs=Hello%20World&header=&footer=)
```
⌈ # Split on spaces
ƛ ; # Map...
↔ # Remove characters not in...
k∨ # 'aeiouAEIOU'
L # Get the length of that
Ẏ # Get that many characters of the original string
∑ # Concatenate all of them
Ṙ # Reverse the whole thing
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
ḲµfØcLḣ@µ€FU
```
[Try it online!](https://tio.run/##y0rNyan8///hjk2HtqYdnpHs83DHYodDWx81rXEL/a9zuD3rUcMcJQVdOwWlRw1zQWwQnQVWEPn/v5KSjpIH0IR8hfD8opwUIC88sSy1GEgHFOWnFyXm5mbmpSsElFZV5aQWKyTmpSg456ekKrjn56QB1UQmVgKZJQqZJUBOSEaFQlp@kUJJRqpCWmpqSlJicjZQ2D1fwTmxRCGgKDMPSCamKAEA "Jelly – Try It Online")
[Answer]
# Mathematica, 145 bytes
```
(s=StringCount[#,{"a","e","i","o","u","A","E","I","O","U"}]&/@(x=StringSplit@#);StringReverse[""<>Table[StringTake[x[[i]],s[[i]]],{i,Tr[1^s]}]])&
```
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~49~~ 46 bytes
```
i`(?=(([aeiou])|\w)+)((?<-2>.)+)\w* ?
$3
O^$`.
```
[Try it online!](https://tio.run/##DcaxDoIwEADQ/b7iBkyKRgZdVQYG3GQwIUY0nPaAxtImpYgS/x1ZXp5jrwxNC5GWkypFvBfiSqxsfwt/xRCuQiHi3XpziOYWwxJjCLZwugdlNE1wZK0t5tZpCTm9uYPM2dpR2ypTY9aPo@YOyUhMrGRMra7gQt85HpWHc/PByjr0DWPFLB/0fEFqMSGPmVNmluQf "Retina – Try It Online") Link includes test suite. Explanation: This is an application of .NET's balancing groups. The lookahead searches the word for vowels, which are captured in group 2. The group is then popped as each letter is matched, thus capturing the number of letters equal to the number of vowels in the word. The rest of the word and any trailing space is then ignored so that the process can begin again with the next word. Finally the remaining letters are reversed.
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), 144 bytes
```
using System.Linq;s=>new string(string.Join("",s.Split(' ').Select(e=>e.Substring(0,e.Count(c=>"aeiouAEIOU".Contains(c))))).Reverse().ToArray())
```
[Try it online!](https://tio.run/##jVDBTsMwDL33K6xclkgj4j5aaZoAgUBMdIhzlrpbRJpAnA42xLeXdK2G4MQ72NKz/Ww/TWfaB@xaMm4D5Z4iNvLOuLdZlkGCtooIlsFvgmqOzOcx9qCootGw86aCe2UcF6fST1OPUfaqdfqCYkibpjDkAmrIs47ywuH7yPEhyVufJBmbkixfrYl8AhMhS7SoI8e8QFm263HifIpy4VsXuc4LptD4dn558/DEEutiOo24Fj3kI@4wEHIhV34egtpzIbrx1z/nplHyFuVzMBGTJchrzkYnmt6tZXs4WCRQroKFrxCuva2ZELN/q622H1D7AHGLUCNWa6Vffgl8ZUPsvgE "C# (.NET Core) – Try It Online")
The worst part is that reversing a `string` in C# returns a `IEnumerable<char>` which you have to convert back to a `string`.
[Answer]
# [PHP](https://php.net/), 96 bytes
```
foreach(explode(" ",$argn)as$w)$r.=substr($w,0,preg_match_all("#[aeiou]#i",$w));echo strrev($r);
```
[Try it online!](https://tio.run/##Hcu9CsIwFEDh3acIaYYEgrjX4uDg2l2kXNvbJJA/blorfflYXA/nyzbX6y3bfBJAJna8p2QIQnDRsH7dd4@FQZzYPU3IHsnPvK1zIoTRSvxmf2TJGdd/rqCITQk6d2V9l4Wk2PRFZ0IzBFhGO4D3kjdPQJfWV@MOtinV4mgTO3bCjxSk2lp/ "PHP – Try It Online")
[Answer]
# Common Lisp, 218 bytes
```
(defun p(s &aux(j 0)c(v 0)r)(dotimes(i(1+(length s))(apply'concatenate'string r))(cond((or(= i(length s))(eql(setf c(elt s i))#\ ))(setf r(cons(reverse(subseq s j(+ j v)))r)v 0 j(1+ i)))((find c"AEIOUaeiou")(incf v)))))
```
**Explanation**
```
(defun p(s &aux (j 0) c (v 0) r) ; j start of word, c current char, v num of wovels, r result
(dotimes (i ; iteration var
(1+ (length s)) ; iteration limit
(apply 'concatenate 'string r)) ; iteration final result
(cond ((or (= i (length s)) ; if string is terminated
(eql (setf c (elt s i)) #\ )) ; or, set current char, and this is a space, then
(setf r (cons (reverse (subseq s j (+ j v))) r) ; push on result from current word chars as number of vowels
v 0 ; reset number of vowels to 0
j (1+ i))) ; reset start of current word to next char
((find c "AEIOUaeiou") ; if current char is a wovel
(incf v))))) ; then increment num of vowels
```
[Answer]
# sed, 133 (132+1) bytes
sed is called with the `-E` flag, which apparently means I add one byte.
Note: I have not really attempted to golf this yet.
```
s/$/\n/
:l
s/(.)(\n.*)/\2\1/
tl
s/\n/ /
h
s/[aoeui]//g
G
:r
s/^(\S*) \S(.*\n\S* )\S/\1 \2/
tr
s/^ //
s/(\n\S*) /\1/
/^\n/!br
s/\s//g
```
[Try it online!](https://tio.run/##HYzBasMwEETv@xVb6ME2xEtyzDUU92hwIZRuA4ol26KKtkhKafPfvVaVc1mGebMvGp1zpEdiT7B3EKlq64p929TEO94SpLUsFAmWkt6UmKt9J5qhg30ozanioamRh6pt2JeMNQ/EW@Rd@b4vkGg132mNtGrpVJwP5xVzLLacn41zgkcJTsNRfZkIfZA5qMvF@hn76@3mTETlNR5EG@zETfCqfkpIaBO8LN84ScC0GJyM0Wc1fkAneFAJ@2B9uUr/yWey4mPePP162YxqXMw/ "sed – Try It Online")
[Answer]
## Clojure, ~~96~~ 94 bytes
```
#(apply str(mapcat(fn[i](take(count(filter(set"aeiouAEIOU")i))i))(reverse(re-seq #"[^ ]+"%))))
```
Well this length is quite ridiculous. `mapcat` saved two bytes.
[Answer]
# Swift 3, 240 bytes
This is a function that can be used with `f(s:"Input")`. Surprisingly, I don't think it can be golfed further:
```
import Foundation
func f(s:String){var c=s.components(separatedBy:" "),r="";for i in c{let b=i.startIndex;r+=i[b...i.index(b,offsetBy: i.characters.filter{"aeiouAEIOU".contains(String($0))}.count-1)]};print(String(r.characters.reversed()))}
```
[Try it at IBM Sandbox!](http://swift.sandbox.bluemix.net/#/repl/5945a5bef5dc584046fa2027)
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 26 bytes
```
qS/{_el"aeiou"fe=:+<}%:+W%
```
[Try it online!](https://tio.run/##S85KzP3/vzBYvzo@NUcpMTUzv1QpLdXWStumVtVKO1z1///cxOxUBa/SvGwF56LEtJJiAA "CJam – Try It Online")
I was proud of coming up with the `el"aeiou"fe=:+` snippet to count vowels.
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 33 bytes
```
" "/-1%{.{"aeiouAIUEO"?)},,<-1%}/
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X0lBSV/XULVar1opMTUzv9TRM9TVX8les1ZHxwYoXqv//79Hak5OvkJ4flFOCgA "GolfScript – Try It Online")
```
" "/ # Split the words ["Hello" "World"]
-1% # Reverse the list ["World" "Hello"]
{ }/ # For each word "World" | "Hello"
. # Copy it "World" "World" | "Hello" "Hello"
{ }, # List all letters that pass this test
"aeiouAIUEO"?) # Is it a vowel? "World" ["o"] | "Hello" ["e" "o"]
, # Get the number of letters in the list "World" 1 | "Hello" 2
< # Get that many letters from the beginning "W" | "He"
-1% # Reverse it "W" | "eH"
"WeH"
```
[Answer]
# k, ~~33~~ ~~28~~ 27 bytes
```
|,/{x@!+/~^"aeiou"?_x}'" "\
```
[Try it online!](https://tio.run/##fcm9CsIwFEDhPU9xzVJFJc4uCh3q2EEogihXc9uGprmQpqXWn1ePPoHL4YPTrLmJ8bVSz3E/W6rPRSIZ7uXuOr4TCfIc53/mItlspdI0qC5o42Q8kLUMBXurRYEDdSL3XHlsW@MqyPtpstQBOg0pa4KMbSlO@PghgAniWI9QsodQE5RE@ob3RmQMKQbIvXG/ov4C "K (oK) – Try It Online")
---
[-5 bytes](https://codegolf.stackexchange.com/questions/126935/make-string-waves/126948?noredirect=1#comment501575_126948) thanks to [coltim](https://codegolf.stackexchange.com/users/98547/coltim), [-1 byte](https://codegolf.stackexchange.com/questions/126935/make-string-waves/126948?noredirect=1#comment577893_126948) thanks to [doug](https://codegolf.stackexchange.com/users/111844/doug).
[Answer]
# [Husk](https://github.com/barbuz/Husk), 17 bytes
```
ṁS↑ṁ#¨aeıuAEIOU¨w
```
[Try it online!](https://tio.run/##yygtzv7//@HOxuBHbROBlPKhFYmpRzaWOrp6@oceWlH@//9/j9ScnHyF8PyinBQA "Husk – Try It Online")
Even without a builtin, does pretty well.
] |
[Question]
[
**This question already has answers here**:
[Composite Number Sequences](/questions/57264/composite-number-sequences)
(17 answers)
[List of first n prime numbers most efficiently and in shortest code [closed]](/questions/6309/list-of-first-n-prime-numbers-most-efficiently-and-in-shortest-code)
(21 answers)
Closed 8 years ago.
# Introduction
Prime numbers are simple, right? Well, now you get your chance to find out!
# Challenge
You must write a program or function that takes an input `n` and outputs the first `n` prime numbers.
# Example Input and Output
Input: `10`
Output: `2,3,5,7,11,13,17,19,23,29`
# Rules
1. You must not include any of the following builtin functions:
* A list of prime numbers
* Primality testing
* Next prime
* Prime factorization
* List of divisors
2. Your output must be in a convenient, unambiguous list format.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in bytes wins.
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), ~~14~~ 11 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
‘²R©’!²%®Oḣ
```
Uses [Wilson's theorem](https://en.wikipedia.org/wiki/Wilson's_theorem) for the primality test. [Try it online!](http://jelly.tryitonline.net/#code=4oCYwrJSwqnigJkhwrIlwq5P4bij&input=&args=MTA)
### How it works
```
‘²R©’!²%®Oḣ Main link. Input: n
‘ Increment. Yields n + 1.
² Square. Yields (n + 1)².
R Range. Yields [1, ..., (n + 1)²].
This range will always contain max(n,2) or more prime numbers.
© Store the range in the register.
’ Decrement. Yields [0, ..., (n + 1)² - 1].
! Factorial. Yields [0!, ..., ((n + 1)² - 1)!].
² Square. Yields [0!², ..., ((n + 1)² - 1)!²].
%® Mod by the range in the register.
This yields [0!² % 1, ..., ((n + 1)² - 1)!² % (n + 1)²].
By Wilson's theorem this gives 1 for primes and 0 for non-primes.
O Find the indices of 1's. This yields all prime number in the range.
ḣ Keep the first n items.
```
[Answer]
# Java, ~~116~~ 113 bytes
Saved 3 bytes thanks to @CamilStaps in a regex reduction!
```
void x(int c){for(int i=2;c>0;i++)if(!new String(new char[i]).matches("(..+?)\\1+")){System.out.println(i);c--;}}
```
Uses regex to test primality, prints if it is, else, it continues. Call on an instance of your class as `.x(10)`.
Output for `x(10)`:
```
2
3
5
7
11
13
17
19
23
29
```
[Answer]
# C, 125 bytes
Most likely I'm not going to win against the Jelly solution haha.
Anyway here's my solution in C. It's not commented and it's very compact to reduce the size of the program.
125 bytes.
```
c,h,i,j;g(n){for(j=2;j*j<=n;j++)if(n%j<1)return 1;return 0;}main(){scanf("%i",&h);for(i=2;c<h;i++)g(i)?:printf("%i ",i,c++);}
```
[Answer]
## Pyth, 12 bytes
```
.fq2/%LZSZ0Q
```
This uses trial division to check primality.
```
.f Q find first Q positive integers that satisfy lambda Z:
/ 0 the number of zeroes
%LZ in map modulo-Z-by
SZ over inclusive range 1 to Z
q2 equals 2
```
Try it [here](http://pyth.herokuapp.com/?code=.fq2%2F%25LZSZ0Q&input=10&debug=0).
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 16 bytes
```
2iq:"t`Qtt:\~z2>
```
This uses [current release (10.1.0)](https://github.com/lmendo/MATL/releases/tag/10.1.0) of the language/compiler.
[**Try it online!**](http://matl.tryitonline.net/#code=MmlxOiJ0YFF0dDpcfnoyPg&input=MTA)
### Explanation
This uses two nested loops. The outer one produces each prime, and the inner one increases 1 by 1 from latest found prime until the next prime is found.
To test for primality a modulo operation is used: x is prime if computing `mod(x,k)` for `k=1,2,...,x` produces no more than *two* zeros; that is, if only *two* numbers of the set `1,2,...,x` divide `x`.
```
2 % push 2 (first prime) to the stack
i % input number, "n"
q: % generate vector [1,2,...,n-1]
" % "for" loop. This runs n-1 times, to find the n-1 primes after 2
t % duplicate top of the stack, which contains the latest found prime, "p"
` % "do...while" loop. This searches for the next prime
Q % increament top of stack by 1. This is the current candidate for next prime, "x"
t % duplicate top of the stack (x)
t: % produce vector [1,2,...,x]
\ % compute mod(x,k) for k=1,2,...,x
~2> % if that gives more than two zeros: x is not prime: we need another iteration
% implicitly end "do...while" loop
% implicitly end "for" loop
% implicitly display stack contents
```
[Answer]
## Dyalog APL, 18 bytes
```
{⍵↑(⊢~∘.×⍨)1↓⍳2*⍵}
```
Generates a multiplication table from `2` to `2^n`. The prime numbers are those that don't occur, so we take the first `n` of those.
Try it [here](http://tryapl.org/?a=%7B%u2375%u2191%28%u22A2%7E%u2218.%D7%u2368%291%u2193%u23732*%u2375%7D%A8%201%202%205%2010&run).
[Answer]
## Haskell, 46 bytes
```
(`take`[x|x<-[2..],mod(product[1..x-1]^2)x>0])
```
Using [@Mauris'/@xnor's prime checker](https://codegolf.stackexchange.com/a/57704/34531).
[Answer]
# [Perl 6](http://perl6.org), ~~39~~ 37 bytes
```
{(2..*).grep({![+] $_ X%%2..^$_})[^$_]} # 39 bytes
{(2..*).grep({none $_ X%%2..^$_})[^$_]} # 39 bytes
{(2..*).grep({all $_ X%2..^$_})[^$_]} # 37 bytes
```
Usage:
```
say {(2..*).grep({all $_ X%2..^$_})[^$_]}( 10 );
# (2 3 5 7 11 13 17 19 23 29)
```
[Answer]
## [Chapel](http://chapel.cray.com/), 108 bytes
This is the simple trial division method. I tried Wilson's theorem but came up with something slightly longer.
```
var n=0;read(n);var f=0;var q=0;while(f<n){q+=1;for i in 2..q{if(i==q){writeln(q);f+=1;}if(q%i==0){break;}}}
```
Chapel is a language designed to run on Cray supercomputers, but I installed it on my laptop. I literally downloaded the language and learned how to write the above program in a total of 2 hours.
The language has some interesting features, there is a pretty through [X in Y minutes](https://learnxinyminutes.com/docs/chapel/) page about it. I'm sure there's some list-based features I haven't seen yet which could cut down on my byte count.
As a bonus stat, this compiles into a 519858-byte executable (based on `wc -c`).
[Answer]
## Python 2, 60 bytes
```
n=input()
k=P=1
while n:
if P%k:print k
n-=P%k;P*=k*k;k+=1
```
Same method as [here](https://codegolf.stackexchange.com/a/27022/20260), Wilson's Theorem, computing the factorial-squared iteratively.
54 bytes as a function:
```
f=lambda n,k=1,P=1:n*[0]and P%k*[k]+f(n-P%k,k+1,P*k*k)
```
[Answer]
## C#, 207 bytes
```
using s=System.Console;using System.Linq;class P{static void Main(){int n=int.Parse(s.ReadLine());s.Write(string.Join(",",Enumerable.Range(2,n*n).Where(x=>!Enumerable.Range(2,x-2).Any(y=>x%y<1)).Take(n)));}}
```
[Answer]
# AppleScript (through osascript), ~~201~~ 158 bytes
If you're wondering how I saved that many bytes: I changed it from AppleScript to osascript (AppleScript from the command line) and used the main method equivalent (`on run x`) to grab arguments at *way* less bytes.
It's back. The most annoyingly verbose yet awesome language that I've used...
AppleScript.
```
on run x
set b to 1
repeat while x>0
set b to b+1
set c to 1
repeat while c<b
set c to c+1
if b mod c=0 then exit
end
if b=c
log c
set x to x-1
end
end
end
```
[Answer]
## [Retina](https://github.com/mbuettner/retina), 43 bytes
Byte count assumes ISO 8859-1 encoding.
```
+m`^((::+)\2+|:?)1
$1:1
)`(:+)1
$1¶$1:
:+$
```
The trailing linefeed is significant. Input and output in unary (input using `1` and output using `:` but any other two printable ASCII characters would work for the same byte count).
[Try it online!](http://retina.tryitonline.net/#code=K21gXigoOjorKVwyK3w6PykxCiQxOjEKKWAoOispMQokMcK2JDE6CjorJAo&input=MTExMTExMTExMQ)
[Answer]
# Pyth - 13 bytes
Wilson's Theorem
```
j.f!%h.!tZZQ2
```
[Test Suite](http://pyth.herokuapp.com/?code=j.f%21%25h.%21tZZQ2&input=10&debug=0).
[Answer]
# Befunge 93, 60 bytes
```
&00p1v<_@#`0p00:-1g00.:<
210pv>1+:
`g01<_v# %p01+1:g01::_^#
```
I didn't feel motivated enough to install Befunge 98 to try and use its features to golf this more, but this works quite well in Befunge 93. [Try it here](http://www.quirkster.com/iano/js/befunge.html). Interestingly, this method also leaves all non-prime numbers on the stack. It works by the method of trial division.
[Answer]
# Python, 72 bytes
To avoid while statements, it simply computes all the prime numbers up to `3**n` and then it returns only the fist `n`. It works, but it is extremely slow for `n >= 7` because of the `3**n`.
```
lambda n:filter(lambda x:all(x%d for d in range(2,x)),range(2,3**n))[:n]
```
[Answer]
## [AutoIt](http://autoitscript.com/forum), 155 bytes
RegEx to the rescue.
```
Func _($n,$i=0,$0=2)
Do
$1=''
For $2=1 To $0
$1&='1'
Next
$0+=1
ContinueLoop StringRegExp($1,'^(1?|(11+?)\2+)$')
$i+=1
MsgBox(0,0,$0-1)
Until $i=$n
EndFunc
```
[Answer]
# Pyth, 14 bytes
```
.f!}0m%Zdr2ZQ2
```
Explanation
```
- Autoassign Q = eval(input())
.f Q2 - First Q where ... returns True, starting from 2
r2Z - range(2, Z)
m%Zd - [Z%d for d in ^]
!}0 - 0 not in ^
```
[Try it here.](http://pyth.herokuapp.com/?code=.f!%7D0m%25Zdr2ZQ2&input=10&debug=0)
[Answer]
## Ceylon, 93 bytes
```
void p(Integer n)=>loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(n).each(print);
```
This is a function which takes an Integer `n` and prints the first `n` primes, each in one line.
Here formatted and with comments:
```
// Print the first n primes.
//
// Question: https://codegolf.stackexchange.com/q/70001/2338
// My answer: https://codegolf.stackexchange.com/a/70021/2338
void p(Integer n) =>
// the infinite sequence of integers, starting with 2.
loop(2)(1.plus)
// filter by primality (using trial division)
.filter((c) => ! (2 : c-2).any((d) => c%d < 1) )
// then take the first n elements
.take(n)
// print each element
.each(print);
```
This uses the same basic prime check as [my answer to the "Is this number prime" question](https://codegolf.stackexchange.com/a/61412) (without the special-casing for 1, which is unnecessary here).
If a full program is needed, we need to incorporate some input, too. With a command line argument it becomes 138 bytes:
```
shared void run(){loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(parseInteger(process.arguments[0]else"")else 0).each(print);}
```
With reading a line from standard input we get 136 bytes:
```
shared void run(){loop(2)(1.plus).filter((c)=>!(2:c-2).any((d)=>c%d<1)).take(parseInteger(process.readLine()else"")else 0).each(print);}
```
[Answer]
# Ruby, ~~75~~ 55 bytes
```
->n{a=[]
t=2
(a<<t if(2...t).all?{|i|t%i!=0}
t+=1)while !a[n-1]
a}
```
Works by trial division
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 63 bytes
```
:2{h0|[N:X],X+1=Y,('(X-1=:2reI,X%I=0),Xw,@Nw,N-1=:Y:1&;N:Y:1&)}
```
`'(X-1=:2reI,X%I=0)` is the part that checks that a number is prime. the rest is basically setting up a recursive predicate that stops after `n` primes founds (the `h0` part).
[Answer]
# Japt, 23 bytes
```
U+1 ²o f_o2 eY{Z%Y}} ¯U
```
[Test it online!](http://ethproductions.github.io/japt?v=master&code=VSsxILJvIGZfbzIgZVl7WiVZfX0gr1U=&input=MTA=)
[Answer]
# Perl 5 - 75
This is actually adapted and golfed from an old perlmonks post.
```
sub p{for(@n=(2..2**20);@p<@_[0]&&push@p,shift@n;){@n=grep{$_%$p[-1]}@n}@p}
```
The output is an array containing the prime numbers, so usage can be:
```
print join(',',p(100));
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
Uses the same algorithm as [Bob's answer](https://codegolf.stackexchange.com/a/70019/34388). Note that also for this, input greater than 7 will take a while to compute. If you aren't really patient, you can also change the `3` into a `2` in the code.
Code:
```
3WmGN<!nN%iN}})Z£
```
Explanation:
```
3Wm # 3 ^ input
G } # For N in range(1, 3 ^ input)
N<!n # Compute (N - 1)!²
N% # mod N
i } # If 1
N # Place N onto the stack
)Z£ # Keep the first Z (auto-assigned to input) elements
```
Uses CP-1252 encoding
[Answer]
# Javascript ES6, ~~82~~ 67 Bytes
```
n=>{for(p=[],i=2;n;i++)!p.some(c=>!(i%c))&&p.push(i)&&n--;return p}
```
Ungolfed version :
```
n=>{
for(p=[],i=2;n;i++) //Loop until n prime found
!p.filter(c=>(i/c|0)==i/c).length //Test if i is not divisible by previous primes
&&
p.push(i) // If prime add to the list
&&
n--; // If a prime found, one less to find.
return p; // Return list of primes
}
```
Changed the function to detect prime number thanks to @neil output.
[Answer]
## C#, 316 315 bytes
```
using System;class P{static void Main(string[]a){int x=int.Parse(Console.ReadLine()),i=0;List<int>b=G(~(2<<30));for(;i<x;i++)Console.WriteLine(b[i]);}static List<int> G(int n){var p=new List<int>();for(var i=2;i<n;i++){var o=0<1;foreach(var k in p){if(k*k>i)break;if(i%k==0){o=1<0;break;}}if(o)p.Add(i);}return p;}}
```
'Cleaner' & ungolfed version that shows what's happening.
```
static void Main(string[]a)
{
int x=int.Parse(Console.ReadLine()), i=0;
List<int> b=G(~(2 << 30));
for(;i<x;i++)Console.WriteLine(b[i]);
}
static List<int> G(int n)
{
var p = new List<int>();
for(var i=2;i<n;i++)
{
var o = 0<1;
foreach (var k in p)
{
if (k * k > i)
break;
if (i%k==0)
{
o = 1<0;
break;
}
}
if (o)
p.Add(i);
}
return p;
}
```
Takes the input from STDIN and prints N primes, each to a new line.
Couple tricks used here are ~(2 << 30), shortened way of saying 2147483647. True and false words have been replaced with 0<1 and 1<0, they'll evaluate accordingly.
] |
[Question]
[
The [Torian](https://googology.wikia.org/wiki/Torian), \$x!x\$, of a non-negative integer \$x\$ can be recursively defined as
$$
x!0 = x \\
x!n = \prod^x\_{i=1} i!(n-1) = 1!(n-1) \times 2!(n-1) \times \cdots \times x!(n-1)
$$
The Torian is then equal to \$x!x\$ for a given \$x\$. This sequence begins \$0, 1, 2, 24, 331776, ...\$ for \$x = 0, 1, 2, 3, 4, ...\$
Alternatively, you can consider the binary function \$!\$ to be instead \$f(x, y)\$. We then have \$f(x, 0) = x\$ and \$f(x, y) = f(1, y-1) \times f(2, y-1) \times \cdots \times f(x, y-1)\$. You should then calculate \$f(x, x)\$.
You are to take a non-negative integer \$x\$ and output \$x!x\$. You may take input and output in any [convenient method](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), and you don't have to worry about outputs exceeding your language's integer limit. This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins
### Test cases
```
x x!x
0 0
1 1
2 2
3 24
4 331776
5 2524286414780230533120
6 18356962141505758798331790171539976807981714702571497465907439808868887035904000000
7 5101262518548258728945891181868950955955001607224762539748030927274644810006571505387259191811206793959788670295182572066866010362135771367947051132012526915711202702574141007954099155897521232723988907041528666295915651551212054155426312621842773666145180823822511666294137239768053841920000000000000000000000000000
```
And [here](https://tio.run/##XY1BCsIwFETXySlm10QjGN0JuUk3gab6QX5K@EJ6@piKRXA3MPPeLKs8Ml9bm9IMyYUim@rA9qYVzWCEgHPPqiR5FUbVSrLEJwK8VnMuIBCjRL4n4x3q0W/od3QIu5O68@St3j2fXut/wWWDl0Is5geSdUg89cth5JEH29ob) is a reference program that produces output for \$0!0\$ to \$11!11\$
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
R×\⁸¡Ṫ
```
[Try it online!](https://tio.run/##AR4A4f9qZWxsef//UsOXXOKBuMKh4bmq/8W7w4figqz//zU "Jelly – Try It Online")
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 bytes
```
{⊃⌽×\⍣⍵⍳⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pRV/Ojnr2Hp8c86l38qHfro97NQLL2f9qjtgmPevuAsofWGz9qm/iob2pwkDOQDPHwDP6fdmgFUKEpV5qCAQA "APL (Dyalog Unicode) – Try It Online")
The main trick is to observe how the computation of `x!y` progresses as `y` increases.
```
1!0=1 2!0=2 3!0=3 4!0=4 ...
1!1=1 2!1=1*2 3!1=1*2*3 4!1=1*2*3*4 ...
1!2=1!1 2!2=1!1*2!1 3!2=1!1*2!1*3!1 4!2=1!1*2!1*3!1*4!1 ...
1!3=1!2 2!3=1!2*2!2 3!3=1!2*2!2*3!2 4!3=1!2*2!2*3!2*4!2 ...
...
```
Basically going to the next row is just a matter of product scan on the previous row. Therefore, to get the value of `x!x`, we can just run product scan on the range `1..x` `x` times, and extract the last element.
One caveat of this approach is that the 0 case must be checked separately. In Jelly, popping from an empty array gives 0. In APL, `⊃` of the empty vector is 0 (`⊢/` does not work in place of `⊃⌽`).
I have 16-byte J and 14-byte ngn/k answers using the same algorithm. Can you find them? (ngn/k code includes converting 0N to 0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
R¡FP
```
[Try it online!](https://tio.run/##y0rNyan8/z/o0EK3gP///5sCAA "Jelly – Try It Online")
```
(Starting from [n],)
R Recursively replace each x with [1..x]
¡ n times
F Flatten
P Product
```
For example `R¡` for the input `4` yields
```
[
[[[1]]],
[[[1]], [[1], [1, 2]]],
[[[1]], [[1], [1, 2]], [[1], [1, 2], [1, 2, 3]]],
[[[1]], [[1], [1, 2]], [[1], [1, 2], [1, 2, 3]], [[1], [1, 2], [1, 2, 3], [1, 2, 3, 4]]]
]
```
and the product of all numbers in that nested list is 331776.
[Answer]
# [Haskell](https://www.haskell.org/), 43 bytes
```
f x=x!x
x!0=x
x!n=product$map(!(n-1))[1..x]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwrZCsYKrQtHAFkTm2RYU5aeUJpeo5CYWaChq5OkaampGG@rpVcT@z03MzFOwVSgoLQkuKfLJU9BTKM7IL1dQUYjWyNTJVMzUVKhRyFSw0VUAqTePjf0PAA "Haskell – Try It Online")
+8 bytes due to the problem needing a function that only takes a single argument. Thanks to @Lynn for pointing that out
Thanks to OVS for pointing out map is shorter than a list comprehension and taking 1 byte off.
My first time ever submitting a haskell answer. I am a beginner so do point out places where I can shorten my code :)
---
# [Haskell](https://www.haskell.org/), 39 bytes
```
f x=x!x
x!0=x
0!_=1
x!n=x!(n-1)*(x-1)!n
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P02hwrZCsYKrQtHAtoLLQDHe1hDIzgOKaeTpGmpqaVQAScW8/7mJmXkKtgoFpSXBJUU@eQp6CsUZ@eUKKgrRGpk6aQqZmgo1CpkKNroK0YZ6euaxsf8B "Haskell – Try It Online")
Thanks to @Alwin for suggesting this version.
[Answer]
# Python 3 48 bytes
```
f=lambda x,y:f(x,y-1)*f(x-1,y)if x*y else(y>0)+x
```
[TIO](https://tio.run/##JYnLCsIwEADv@Yo97tZULIKHgv5LpFldaB7EHLJfH1N6mGFgstZvivfe@bm78N4cNKsr4/C80DRiXqySMLRJwe8/D@2C@rpR51RAQCIUFz8eH7QayEViRbE8ECIjIadSoUrw5nxHXg8hUf8D)
# 55 bytes
if a more conventional input is required. I don't know how to initialize the default 2nd argument to equal the first, so I've rewritten everything as t=x-y without much more thought.
```
f=lambda x,t=0:f(x,t+1)*f(x-1,t-1)if(x-t)*x else(x>t)+x
```
Thanks to Arnauld for saving 3 bytes
[Answer]
# [Factor](https://factorcode.org/), ~~53 45~~ 41 bytes
```
[ dup [1,b] [ cum-product ] repeat last ]
```
[Try it online!](https://tio.run/##Jcw7DsIwEIThPqeYA0AkOgQHQDQ0iMpKsThLsOIX63UBlzeWUn7SP/Miq0na4369XU4IpO9RKC5csLJE9lg4spB3P1KXYtmSol1Fnd2Mwp/K0fZVFlb9ZnFRcR6GI1xSagZzzTCH3XOCga1hnyXN1SomCGcmhafS1QJl9He7ju0P "Factor – Try It Online")
A port of @Bubbler's [answers](https://codegolf.stackexchange.com/a/231277/97916); take the product scan (cumulative product) of `1..x` `x` times and then return the last element.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 43 bytes
Expects and returns a BigInt.
```
f=(x,n=x,g=_=>x?f(x--,~-n)*g():1n)=>n?g():x
```
[Try it online!](https://tio.run/##FYxBCoMwEADvvmILHrI1Kc21dvUpVawJLbIRLWUhpF9PzWWYwzDv8Tvu0/ZaP4bDc87ZkRLNJNrTgzrpnRJj9M8wnr3Cm2Wkjvuikl3YlADBlVsQuBNYW6xpEGIFMAXewzJfluDVUEdJp4Kjr@NxxTRgW6X8Bw "JavaScript (Node.js) – Try It Online")
This actually simplifies down to ...
# [JavaScript (Node.js)](https://nodejs.org), 37 bytes
```
f=(x,n=x)=>n?x?f(x,~-n)*f(~-x,n):1n:x
```
[Try it online!](https://tio.run/##FYzBCoMwEETvfsUWPGSrKc1Vu/VXFGtKi@yKlrIQ4q/HeBnmMY/5Dv9hG9fP8rMsryklT0ZrJkV6cqedz7Rbxqs3u80DNo4bTV5Wo0Bw5xYUHgTOna2qEEIBMApvMk@3Wd6mL4PGyxnZL0M@xNhjW8R0AA "JavaScript (Node.js) – Try It Online")
... which is essentially the same as [Alwin's answer](https://codegolf.stackexchange.com/a/231287/58563).
[Answer]
# [Haskell](https://www.haskell.org/), 41 bytes
```
f n=product$iterate(>>= \x->[1..x])[n]!!n
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7agKD@lNLlEJbMktSixJFXDzs5WIaZC1y7aUE@vIlYzOi9WUTHvf25iZp6CrUJBUWZeiYKKQm5igUKaAkiJaex/AA "Haskell – Try It Online")
Same idea as my Jelly answer: starting from `[n]`, repeatedly replace each `x` by `1..x`, `n` times, then take the product.
```
[4]
→ [1,2,3,4]
→ [1,1,2,1,2,3,1,2,3,4]
→ [1,1,1,2,1,1,2,1,2,3,1,1,2,1,2,3,1,2,3,4]
→ [1,1,1,1,2,1,1,1,2,1,1,2,1,2,3,1,1,1,2,1,1,2,1,2,3,1,1,2,1,2,3,1,2,3,4]
→ product: 331776
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 27 bytes
```
1##&@@#&//@Nest[Range,#,#]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b731BZWc3BQVlNX9/BL7W4JDooMS89VUdZRzlW7X9AUWZeSbSyrl2aA5BbF5ycmFcHlo820DGP/Q8A "Wolfram Language (Mathematica) – Try It Online")
Port of Lynn's solution.
---
### [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
Nest[f1##&@@f~Array~#&,D,#]@#&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73y@1uCQ67f2khYbKymoODml1jkVFiZV1ymo6LjrKsQ7Kav8DijLzSqKVde3SHJRj1eqCkxPz6oIS89JTow10zGP/AwA "Wolfram Language (Mathematica) – Try It Online")
Builds \$x!0...x!x\$:
```
D x => x!0
f1##&@@f~Array~#& (x => x!n) => (x => x!(n+1))
Nest[ , ,#] x => x!#
@# #!#
```
[Answer]
# [K (oK)](https://github.com/JohnEarnest/ok), ~~13 12~~ 14 bytes
Saved 1 byte thanks to ngn
Fixed thanks to Razetime
```
{*|0,x*\/1+!x}
```
[Try it online!](https://tio.run/##y9bNz/7/P82qWqvGQKdCK0bfUFuxovZ/mrqi@X8A "K (oK) – Try It Online")
```
{*|0,x*\/1+!x}
!x Range [0..x-1]
1+ Increment range
x / Repeat x times:
*\ Get the cumulative products of the list
When this is done y times, we get [1!y, 2!y...x!y]
0, Prepend a 0 in case x is 0
*| Get the last number (x!y) by reversing and getting the head
```
[Answer]
# JavaScript (ES6), 46 bytes
```
x=>(g=p=>x>1n?x--**p*g(p*y++/i++):x)(i=1n,y=x)
```
[Try it online!](https://tio.run/##FcpBDsIgEADAe1@xxwWK2pvRLr6lqUDWkIW0jaExvh3raS7zmt7TOi9cNiv56VugVslhpEKuukEe1Vqti45Y9G7MmY1Rt6qQaZB@p6payAtg8hswEFzkfjjC9e9R4dMBzFnWnPwp5YjcQ0BWqvu2Hw "JavaScript (Node.js) – Try It Online")
Use
$$ f\left(n\right) = \prod\_{i=1}^n i^{{2n-i-1}\choose{n-1}} $$
with exception
$$ f\left(0\right) = 0 $$
[Answer]
# [R](https://www.r-project.org/), 46 bytes
```
x=scan();i=1:x;prod(i^choose(2*x-i-1,x-1))*!!x
```
[Try it online!](https://tio.run/##Vc3BCsIwEATQe79ii5fdYsRUPcTaL9CjZ6HGFBdKEpKKEfHbozl6eYcZhgnZ@ZmdjRg1e2N7pRRVIxwEjA@rS4VM8IaoB/uXEsPibOIMzzB4bwJcX3DkwNMEp1VOfRkgddzLfep8cDfki747Fw22TRIs5DIJSdTUdcqfasT17xdloS1sCtvCjvIX "R – Try It Online")
Using formula from [tsh's answer](https://codegolf.stackexchange.com/a/231284/55372) (presumably adapted from [OEIS page](https://oeis.org/A068943)).
---
Straightforward recursion:
### [R](https://www.r-project.org/), 50 bytes
```
f=function(x,n=x)"if"(n,prod(sapply(1:x,f,n-1)),x)
```
[Try it online!](https://tio.run/##Fcs9CoAwDEDh3WM4JRDB@jNU6GFEDRQkDVahnr6a5RsevKsmvWOSDHmLekjw3mPlwI9s1qGQhIJt5BaE9Eo75FX1fMEthZikc4hU/gV6bBicMRijMRkz1g8 "R – Try It Online")
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal), 9 bytes
```
[ɾ?(⁽*r)t
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%5B%C9%BE%3F%28%E2%81%BD*r%29t&inputs=5&header=&footer=)
-1 thanks to @AUsername
[Answer]
# [Julia 0.7](http://julialang.org/), ~~32~~ 29 bytes
-3 bytes by MarcMush.
```
<(x,n=x)=n>0?prod(1:x.<n-1):x
```
[Try it online!](https://tio.run/##BcFRCoAgDADQq/i5QUV@CbLVWQorDJkiBbv9fO/9Sz6CGYFOwoos27q3XhP4qAvJ7DGq3bU7ZR@Daz3LVwQIzvyAIqK7JNkA "Julia 0.7 – Try It Online")
Or if we are allowed to take the input as it appears in Torian notation itself (essentially twice), then it becomes:
# [Julia 0.7](http://julialang.org/), 24 bytes
```
x<n=n>0?prod(1:x.<n-1):x
```
[Try it online!](https://tio.run/##yyrNyUw0//@/wibPNs/OwL6gKD9Fw9CqQs8mT9dQ06rif1p@kUKFraGVuUJBUWZeSU6eRlJmukaFpk2FpkJqXsp/AA "Julia 0.7 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 9 bytes
```
’ߥⱮPðṛḷ?
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLigJnDn8Kl4rGuUMOw4bmb4bi3PyIsIjXFu8OH4oKsIiwiIixbXV0=)
-1 byte thanks to caird coinherinaahing
This is a singular dyadic link. The challenge requires taking one input; however, a single dyadic chain within a monadic link will have the argument supplied to both sides so this works just fine.
```
’ߥⱮPðṛḷ? Dyadic Chain
? If
ḷ The left argument is truthy
-----ð Evaluate on the left argument (this is a variadic chain, and its arity changes between runtimes)
Ɱ For each in range on the right argument
--¥ Call as dyad:
’ - Decrement the left argument
ß - Recurse (the `¥` is only necessary to make this act as a dyad since it's a variadic actor)
P And take the product
ṛ Otherwise, just return x
```
[Answer]
# JavaScript, ~~38~~ 36 bytes
~~I still don't understand the challenge but~~ Thanks to Bubbler I understand the challenge a bit better and this port of [Alwin's solution](https://codegolf.stackexchange.com/a/231287/58974) seems to work - be sure to `+1` them too.
Only handles inputs up to `4` as anything bigger will result in an output exceeding JavaScript's [`MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)
```
f=(x,n=x)=>n?x?f(x,~-n)*f(~-x,n):1:x
```
[Try it online!](https://tio.run/##DctBDkAwEEDRq1h2VIWFTRmu0qZUiMwIIrNy9ery5@Xv/vV3uLbzMcTzklJEJRWhAI40yRRzfYagjOozGcC2VlLkSwk2vQxdr7VAYLr5WOqDVyXaFVg4nU@A9AM)
For just one byte more, though, we can handle larger inputs by using BigInts:
```
f=(x,n=x)=>n?x?f(x,~-n)*f(~-x,n):1n:x
```
[Try it online!](https://tio.run/##DctBDkRAEEbhq1h2aS3DEsVFLFrQMhP5SxCplav39PLly/tNz3TN5/e4HWRZYwxstAArcY9Bh5DqdaA8mNcloKZCozHIaZQ/aLWrarTWKs2CS/a13GUzan3GmbfppsKP8BT/)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 51 bytes
```
f(n){n=g(n,n);}g(x,n){x=n?x?g(x,n-1)*g(x-1,n):1:x;}
```
[Try it online!](https://tio.run/##XVDBboMwDL33KyykSoEGtUC3as1YD9O@Yu2BpgGidaYiTM2G@PUxQylaGymO/fz8Ylv6mZRtmzJ0a4wzhhxd0WTM0lvbGDd20wd@4Hrk@AHh62BtRdNqrOAz0cjcST0BOh1QKVOZ9x3EUC84BBxCDhGHZSNg7kGC31WuMYNcZ7kqYX8szga@TlAgRKG/11UnYsCbj4LKnpSs1OFOM1ySbhSsVo@N6LkyT0qPrJIfqiQydHRna9/CrX16pfvgcPgfR85QmRYlsO4rjQdlqWwhBvcZjP5RRcquTbjzAfBGRMBs1rNduGzh2jiS0mUbfXonbrKGst3Sb1FF6DjwfdmpJErKnOkB/BcgOzVbpKGQg@Hj5CqOzW6QbSZN@yvTY5KZ1j//AQ "C (gcc) – Try It Online")
Port of [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)'s [JavaScript answer](https://codegolf.stackexchange.com/a/231285/9481) (which may be based on [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)'s [JavaScript answer](https://codegolf.stackexchange.com/a/231289/58974)) which, in turn, is based on [Alwin's answer](https://codegolf.stackexchange.com/a/231287/58563).
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
h x=iterate(scanl1(*))(1:[1..])!!x!!x
```
[Try it online!](https://tio.run/##fc2xDsIgEMbxvU/xkTiAkUYmEyM@gZujYSAVLdrShtJ4g@9eW0e1Ltxwv/9R2u7uqmq4gDQxyoit9fQG3cbm3BdpUduWMx6kEuKk8pxMdh2tTy7a5HhX2BAVX45LWpEcgTKMEWProfxg1ZtxtZ3OGPFWNNw0/4vEfq/5OLLa@gCNc5MBbZ@OKR4CcnRl88ACJ@5XnnmBJzx2ElO@MQZSIrqLiy4Ubja84iuctSV@fmKL1Ntqtrp9V8ML "Haskell – Try It Online")
[Product scan method](https://codegolf.stackexchange.com/a/231277/78410) seems to win over other approaches.
[Answer]
# Python 3, 50 bytes
```
t=lambda x,z=0:x*(x-z)and t(x-1,z-1)*t(x,z+1)or x
```
Using the trick of using parameter z=x-y from @Alwin's answer. Before that, I had the 59 byte version
```
t=lambda x,y=-1:x*(y:=(y,x)[y<0])and t(x-1,y)*t(x,y-1)or x
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
≔EN⊕ιθFθUMθΠ…θ⊕λI∧Lθ⊟θ
```
[Try it online!](https://tio.run/##TYw7DsMgEAV7n4JykZwylSuLylIS@QoEiEGC5R8ppyfrVHnlaOYpK4uK0o@x1uoOhLtMsGHq7dHD0xTgM9tQFRMMNqPBcQKZL9MrFgaZM/JFDEGihjyzvUTdVQPxUd4IG9MJ/3vPacu0F4dkydpgpfJm8GiW7ujhbH7SGNdxefsv "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @Bubbler's answer.
```
≔EN⊕ιθ
```
Start with a range from `1` to `n`.
```
Fθ
```
Repeat `n` times...
```
UMθΠ…θ⊕λ
```
... calculate the cumulative products.
```
I∧Lθ⊟θ
```
Output the last one, unless `n=0`, in which case just output `0`.
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/wiki/Commands), 5 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
FL}˜P
```
Port of [*@Lynn*'s Jelly answer](https://codegolf.stackexchange.com/a/231303/52210), so make sure to upvote him/her as well!
[Try it online](https://tio.run/##MzBNTDJM/f/fzaf29JyA//@NAQ) or [verify the first \$[0,7]\$ test cases](https://tio.run/##MzBNTDJM/W9@bJKfvZLCo7ZJCkr2fi7/3XxqT88J@K/zHwA).
**Explanation:**
```
F # Loop the (implicit) input amount of times:
L # Transform each integer `n` into a [1,n] ranged list
# (which uses the implicit input in the first iteration)
}˜ # After the loop: flatten the nested lists
P # And take the product of all integers
# (after which the result is output implicitly)
```
Uses the legacy version of 05AB1E, because [the new version's `˜` doesn't work on a single integer for input \$x=0\$](https://tio.run/##yy9OTMpM/f/fzaf29JyA//8NAA).
[Answer]
# [ayr](https://github.com/ZippyMagician/ayr), 8 bytes (2 methods)
Method 1:
```
:*/,~$:`
```
Method 2 (doesn't work for N=0):
```
]/]*\$:~
```
# Explanation
```
: Non J-style train
~$: 1-range on each scalar val
` Commute input (pass to both sides)
*/, Product of all scalars
```
Dyadic `A u$: B` is call `u` on previous iteration `A` times with starting value `B`
```
~ 1-range of N
*\$: Repeatedly foldl with multiplication
] N times
]/ Rightmost argument
```
[Answer]
# [Uiua](https://uiua.org) [SBCS](https://tinyurl.com/Uiua-SBCS-Jan-14), 12 bytes
```
⬚0⊢⇌⍥\×:+1⇡.
```
[Try it!](https://uiua.org/pad?src=0_8_0__ZiDihpAg4qyaMOKKouKHjOKNpVzDlzorMeKHoS4KCuKItWbih6E2Cg==)
Pretty much a port of Bubbler's [Jelly/APL answers](https://codegolf.stackexchange.com/a/231277/97916).
] |
[Question]
[
Given a standard combination lock like the one in the picture. The way to unlock it is to align the 4 numbers in the code on the combination line. After years of loyal service you have been fired from the lock factory and have decided to exact revenge by not jumbling up the locks before you send them off, thus leaving every lock with the combination to unlock it on the combination line.

You also know that by looking at the order of the numbers in the other lines it is possible to work out what numbers must be on the combination line (and therefore the combination to unlock it is).
If every line on the lock is given a number starting from line 0 for the combination line (the line which unlocks the lock) to line 9. For example, if the numbers on line 4 are `5336`, then the combination to unlock it would be `1992`.
Unfortunately the locks have already been packaged and your view of each lock is obscured, so you can only see numbers on different lines of the lock.
**The Challenge**
Given 4 pairs of digits, where the first digit of the integer represents the line number and the second digit represents the the number which appears on that line, work out the combination to the lock.
For example if you input:
```
57 23 99 45
```
Then it should output:
```
2101
```
Or
```
25 78 63 15
```
and
```
3174
```
Assume the input will always be 4 positive integers in the form `25 64 72 18.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest programs in number of bytes wins.
Also this is my first question, so any feedback is appreciated.
[Answer]
# CJam, ~~9~~ 8 bytes
```
ea9fbAf%
```
Reads the digit pairs as command-line arguments. To [try the code online](http://cjam.aditsu.net/), change `ea` to `lS/` to read from simulated STDIN.
### Example run
```
$ cjam <(echo ea9fbAf%) 57 23 99 45; echo
2101
$ cjam <(echo ea9fbAf%) 25 78 63 15; echo
3174
```
### How it works
The character code of the digit **d** is **48 + d**. Thus, considering the two-digit string **xy** a base 9 number yields **9 \* (48 + x) + (48 + y) = 10 \* (48 + x) + y - x ≡ y - x (mod 10)**.
```
ea " Push the array of command-line arguments. ";
9fb " Mapped base 9 conversion; replace each string 'xy' with (9 * ord(x) + ord(y)). ";
Af% " Take the results modulo 10. ";
```
[Answer]
# CJam, ~~13~~ ~~12~~ 11 characters
Thanks to user23013, its now down to 11 characters :)
```
4{Ar:--A%}*
```
Explanations:
```
4{ }* "Run the code block 4 times";
r "Read the next input token (whitespace separated)";
:- "Subtract 2nd number from the first treating r as a 2 numbered string";
A - "Subtract the result of above from 10";
A% "Take modulus of 10 and store it on stack";
```
[Try it online](http://cjam.aditsu.net/)
I know it can be golfed more. But this is my first real attempt on CJam and I am limited by experience :)
---
Alternatively, the other methods to do the same thing in 1 extra character:
```
l~]{_A/-A%}/ // My previous solution
```
or
```
4{ri_A/-A%}* // As pointed out by Ingo
```
or
```
ea{i_A/-A%}/ // If input is passed through command line
```
[Answer]
# Golfscript (14 ~~13~~)
[Try it online here](http://golfscript.apphb.com/?c=OyIyNSA3OCA2MyAxNSIKfl17LjEwOl4vLV4lfS8%3D)
It's pretty much the same as [Optimizer's solution](https://codegolf.stackexchange.com/a/37790/26765), but in a different language. It's hard to approach it in a different way because the problem is fairly simple~~, so the tie definitely goes to Optimizer, whose entry was earlier anyway.~~
```
~]{.10:^/-^%}/
```
For the same number of bytes you can do
```
~]{.10/- 10%}/
```
[Answer]
# [GNU dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 14 bytes
Borrowing [@Dennis's clever base 9 trick](https://codegolf.stackexchange.com/a/37815/11259):
```
9i[?A%nd]dxxxx
```
Input integers read from STDIN, one per line.
### Explanation:
```
9i # Set input radix to 9
[ ] # push a macro, defined thus:
? # read number from STDIN and push
A # push literal 10
% # calculate number mod 10
n # print, with no newline
d # duplicate macro
d # duplicate macro
xxxx # execute the macro 4 times
```
### Output:
```
$ for i in 57 23 99 45; do echo $i; done | dc ./combolock.dc
2101$
$ for i in 25 78 63 15; do echo $i; done | dc ./combolock.dc
3174$
$
```
---
### Previous Answer, 18 bytes:
Because I thought I could get closer to the "golfing" languages with this (but didn't):
```
[A?A~--A%n]dddxxxx
```
[Answer]
**C 64 63 56 or 61**
If the input can be piped from file
```
main(a){while(scanf("%d",&a)>0)putchar(48+(a-a/10)%10);}
```
If the input should be typed to stdin
```
i;main(a){for(;i++-4;putchar(48+(a-a/10)%10))scanf("%d",&a);}
```
Reads the four numbers in a loop and then processes each by subtracting the first digit from the value and printing the result modulo 10.
Savings thanks to various comments below and also using putchar instead of printf
[Answer]
## Python 3 , 64
Straightforward.
```
print(''.join([(i-i//10)%10 for i in map(int,input().split())]))
```
It can be shorter if I'm allowed to print, say, `[2, 1, 0, 1]` instead (**46**):
```
print([i%10-i//10 for i in map(int,input().split())])
```
[Answer]
# C, 92
```
#define a(n) ,(10+v[n][1]-*v[n])%10
main(int c,char**v){printf("%d%d%d%d"a(1)a(2)a(3)a(4));}
```
Input from commandline. Subtracts the first ASCII code of each argument from the second, adds 10 and takes modulo 10.
I think this is the first time I've written a `printf` with four `%`s and no comma (the comma is in the `#define.`)
[Answer]
## Java - 203 bytes
Just because there *has* to be a Java entry, I saw a nice opportunity to give this code golfing a chance (first submission ever).
```
class M{public static void main(String[] a){String r="";for(int i=0;i<4;i++){int l=Byte.valueOf(a[i].substring(1));int f=Byte.valueOf(a[i].substring(0,1));r+=(l-f<0)?l-f+10:l-f;}System.out.print(r);}}
```
If there's room for some improvements, I'd glad to know about them ;-)
[Answer]
# Lua - 46 characters
```
while''do a,b=io.read(1,1,1)print((b-a)%10)end
```
Reads three characters at a time (grant me the small mercy of inputing a space at the end), and eventhough a and b are string-y... b-a MAGICALUALY allows them to conceive a healthy baby integer. Does the wrap-around check while printing.

[Answer]
# JavaScript ES6 – ~~53~~ 43 bytes
```
f=n=>n.replace(/.. ?/g,a=>(1+a[1]-a[0])%10)
```
Fairly straightforward function, uses regex to get the numbers. Try it out at <http://jsfiddle.net/efc93986/1/>. If functions are not allowed, a standalone program at 52 bytes:
```
alert(prompt().replace(/.. ?/g,a=>(1+a[1]-a[0])%10))
```
As ES6 currently only works on Firefox, the following code works on any modern browser, at 70 bytes:
```
alert(prompt().replace(/.. ?/g,function(a){return(1+a[1]-a[0])%10}))
```
[Answer]
# Python 2 - 33 bytes
```
for i in input():print(i-i/10)%10
```
Accepts comma-delimited user input.
E.g. Input:
```
29,26, 31, 88
```
Output:
```
7
4
8
0
```
If output is required to exactly match the example then it is much longer. 47 bytes:
```
print"%d"*4%tuple((i-i/10)%10 for i in input())
```
[Answer]
## APL, 14
```
10|{--/⍎¨⍕⍵}¨⎕
```
**Explaination**
`⎕` takes input from screen. Space-separated values are parsed as an array.
`{...}¨` for each number, feed it into function.
`⍎¨⍕⍵` takes the argument, create an array of its digits.
`--/` calculates units minus tens.
`10|` mod 10.
[Answer]
## J - 20 15
The non-verb form (as statement instead of function definition) it's 5 characters shorter:
```
10|-~/|:10#.inv
```
The verb form which is a nice [train](http://www.jsoftware.com/help/dictionary/dictf.htm):
```
10|[:-~/[:|:10#.inv]
```
This verb used on the example inputs:
```
10|-~/|:10#.inv 57 23 99 45
2 1 0 1
10|-~/|:10#.inv 25 78 63 15
3 1 7 4
rotd =: 10|[:-~/[:|:10#.inv] NB. verb form
rotd 25 78 63 15
3 1 7 4
rotd 57 23 99 45
2 1 0 1
```
[Answer]
# Haskell 60 58
```
main=interact$show.map((\x->mod(x-x`div`10)10).read).words
```
Single character digits, a real nemesis in Haskell golfing.
[Answer]
# Perl: 38 40
```
print abs($_-int$_/10)%10for split" ",<>
```
Output:
```
% perl code.pl
57 23 99 45
2101
25 78 63 15
3174
```
[Answer]
## Ruby, 35 bytes
```
$*.map{|n|a,b=n.bytes;$><<(b-a)%10}
```
### Explanation
Input is taken as command line arguments. `String#bytes` returns an Array of Integers (ASCII character codes). Only the difference between the last and first character code is of importance, not the Integers themselves.
[Answer]
**C# & LinqPad: 104**
```
Util.ReadLine<string>("").Split(' ').Select(s =>(s[1]-s[0])).Aggregate("",(r,a)=>r+(a<0?10+a:a)).Dump();
```
[Answer]
## C++ 118
```
int main()
{
int a,b,c;
for(int i=0; i<4; i++)
{
cin>>a;
b=a/10;
a=a%10;
c=a-b;
if(c<0)c+=10;
cout<<c;
}
}
```
[Answer]
# PHP - 90 characters
Thought I'd give code golf a try so here it is, my first attempt - can probably be golfed more.
```
<?php $a=array(57,23,99,45);foreach($a as$b){echo abs(substr($b,0,1)-substr($b,1,1)%10);}
```
## 58 characters (courtesy of Ismael Miguel)
```
for($i=0,$a=$_GET[n];$i<8;)echo abs($a[$i++]-$a[$i++]);
```
Access file using
```
file.php?n=57239945
```
[Answer]
# Python 3, 60
```
for x in input().split():print(-eval('-'.join(x))%10,end='')
```
Input and output exactly as specified, although it doesn't print a trailing newline. Two interesting tricks here: 1) replacing two calls to `int()` with one call to `eval()`, and 2) using `join()` to get `a-b`, then negating it for `b-a` as required. Fortunately Python's modulo operator gives positive values even if the first argument is negative!
] |
[Question]
[
Given a string `S` and a list of indices `X`, modify `S` by removing the element at each index of `S` while using that result as the new value of `S`.
For example, given `S = 'codegolf'` and `X = [1, 4, 4, 0, 2]`,
```
0 1 2 3 4 5 6 7 |
c o d e g o l f | Remove 1
c d e g o l f | Remove 4
c d e g l f | Remove 4
c d e g f | Remove 0
d e g f | Remove 2
d e f
```
Your task is to perform this process, collect the values of `S` after each operation, and display each on a newline in order. The final answer would be
```
S = 'codegolf'
X = [1, 4, 4, 0, 2]
Answer:
codegolf
cdegolf
cdeglf
cdegf
degf
def
```
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so make your code as short as possible.
* You may assume that the values in `X` are always valid indices for `S`, and you may use either 0-based or 1-based indexing.
* The string will only contain `[A-Za-z0-9]`
* Either `S` or `x` may by empty. If `S` is empty, it follows that `x` must also be empty.
* You may also take `S` as a list of characters instead of a string.
* You may either print the output or return a list of strings. Leading and trailing whitespace is acceptable. Any form of output is fine as long as it is easily readable.
## Test Cases
```
S = 'abc', x = [0]
'abc'
'bc'
S = 'abc', x = []
'abc'
S = 'abc', x = [2, 0, 0]
'abc'
'ab'
'b'
''
S = '', x = []
''
S = 'codegolfing', x = [10, 9, 8, 3, 2, 1, 0]
'codegolfing'
'codegolfin'
'codegolfi'
'codegolf'
'codgolf'
'cogolf'
'cgolf'
'golf'
```
[Answer]
## Haskell, ~~38~~ 33 bytes
```
s#i=take i s++drop(i+1)s
scanl(#)
```
Straight forward: repeatedly take the elements before and after index i, rejoin them and collect the results.
[Try it online!](https://tio.run/##dYuxDkAwGAZ3T/EFA2kHxNonEUOjxR/V4vf@xUgiN97drHmxzsXIGalTLxYEFsIcYStI1CUnu@JBe1dkZVw1eSiYkADbQf5Ejh3pEIydghtTdLVsbyrZ9L/Jv6nki0/4rPEC "Haskell – Try It Online")
Edit: @Lynn saved 5 bytes. Thanks!
[Answer]
# JavaScript (ES6), ~~57~~ ~~50~~ ~~48~~ ~~45~~ 42 bytes
Takes the string as an array of individual characters, outputs an array containing a comma separated string of the original followed by a subarray of comma separated strings for each step.
```
s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]
```
* 3 bytes saved thanks to [Arnauld](https://codegolf.stackexchange.com/users/58563/arnauld)
suggesting I abuse the loose output spec more than I already was, which led me to abusing it even more for another 3 byte saving.
---
## Test it
```
o.innerText=JSON.stringify((f=
s=>a=>[s+"",a.map(x=>s.splice(x,1)&&s+"")]
)([...i.value="codegolf"])(j.value=[1,4,4,0,2]));oninput=_=>o.innerText=JSON.stringify(f([...i.value])(j.value.split`,`))
```
```
label,input{font-family:sans-serif;font-size:14px;height:20px;line-height:20px;vertical-align:middle}input{margin:0 5px 0 0;width:100px;}
```
```
<label for=i>String: </label><input id=i><label for=j>Indices: </label><input id=j><pre id=o>
```
---
## Explanation
We take the two inputs via parameters `s` (the string array) and `a` (the integer array) in currying syntax, meaning we call the function with `f(s)(a)`.
We build a new array and start it off with the original `s`. However, as the `splice` method we'll be using later on modifies an array, we need to make a copy of it, which we can do by converting it to a string (simply append an empty string).
To generate the subarray, we `map` over the integer array `a` (where `x` is the current integer) and, for each element, we `splice` 1 element from `s`, beginning at index `x`. We return the modified `s`, again making a copy of it by converting it to a string.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 6 bytes
```
åjV uV
```
[Test it online!](http://ethproductions.github.io/japt/?v=1.4.5&code=5WpWIHVW&input=WzEsNCw0LDAsMl0gImNvZGVnb2xmIg==)
### Explanation
```
UåjV uV Implicit: U = array of integers, V = string
Uå Cumulatively reduce U by
j removing the item at that index in the previous value,
V with an initial value of V.
uV Push V to the beginning of the result.
```
Alternatively:
```
uQ åjV
UuQ Push a quotation mark to the beginning of U.
å Cumulatively reduce by
j removing the item at that index in the previous value,
V with an initial value of V.
```
This works because removing the item at index `"` does nothing and so returns the original string.
[Answer]
## [Husk](https://github.com/barbuz/Husk), 7 bytes
```
G§+oh↑↓
```
Takes first the string, then (1-based) indices.
[Try it online!](https://tio.run/##yygtzv7/3/3Qcu38jEdtEx@1Tf7//79SYlJySmpaeobS/2gTHUMdIx2jWAA "Husk – Try It Online")
## Explanation
```
G§+oh↑↓
G Scan from left by function:
Arguments are string, say s = "abcde", and index, say i = 3.
↓ Drop i elements: "de"
↑ Take i elements
oh and drop the last one: "ab"
§+ Concatenate: "abde"
Implicitly print list of strings on separate lines.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
s,i=input()
for i in i+[0]:print s;s.pop(i)
```
[Try it online!](https://tio.run/##PcrBCoAgEATQe1@xN5WWsOhU9CXiqbIWQpe0Q19vGBEMb2AYvtMefJdzRJrI85Wkqlw4gYA8UG20HfgknyCOseHAklR28nvi1yobI2aBIEJhKayF7d@OghMWwbQI/RuN0Fn7AA "Python 2 – Try It Online")
>
> Any form of output is fine as long as it is easily readable.
>
>
>
So this prints as lists of chars.
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
This could be shortened to [43 bytes](https://tio.run/##K6gsycjPM/r/P1EnyTYzr6C0REOTKy2/SCFTITNPIUk72iDWqqAoM69EIdE6Ua8gv0AjU/P//2ilZCUdpXwgTgHiVCBOh/JzgDhNKVZHIdpQR8EEjAx0FIxiAQ), as @LuisMendo pointed out, but that's already @ErktheOutgolfer's solution.
```
a,b=input();print a
for i in b:a.pop(i);print a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P1EnyTYzr6C0REPTuqAoM69EIZErLb9IIVMhM08hySpRryC/QCMTLvf/f7RSspKOUj4QpwBxKhCnQ/k5QJymFKujEG2oo2ACRgY6CkaxAA "Python 2 – Try It Online")
[Answer]
# Java 8, 78 bytes
This is a curried lambda, from `int[]` to a consumer of [`StringBuilder`](https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/StringBuilder.html) or [`StringBuffer`](https://docs.oracle.com/javase/8/docs/api/index.html?java/lang/StringBuffer.html). Output is printed to standard out.
```
l->s->{System.out.println(s);for(int i:l)System.out.println(s.delete(i,i+1));}
```
[Try It Online](https://tio.run/##bY8xT8MwEIXn9lecOsUisShiIiUDIDamjlUH4zjRpY5t2eegKspvD27aBVHphne6907v68QgCuuU6erT7OK3RglSixDgS6CBcb1yHgdBCgIJSscuBXgk1LyJRhJawz9vYrcnj6Z9i6hr5fN71ndrQuyV36Ghw7GqIH039IFBOKfEJQ2vcygqXVTj/hxI9dxG4otLmyywsrE@Swvgi2b3HLxWWpHKMMeHLWPlNK/KBHEluzEMFmvoE192bXw4gvBtYBfc1b9GPCl9zoz6gT@A2UbaWrVWNxvGuJBSOVpcCxuM2xyel3nM4WliqcW0nuZf)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 11 bytes
```
v=ā0m0yǝÏ},
```
[Try it online!](https://tio.run/##MzBNTDJM/f@/zPZIo0GuQeXxuYf7a3X@/4821DEBQgMdo1iuaKVkJR2lfCBOAeJUIE6H8nOAOE0pFgA "05AB1E – Try It Online")
```
v # For each index:
= # Print without popping
ā # Push range(1, len(a) + 1)
0m # Raise each to the power of 0.
# This gives a list of equal length containing all 1s
0yǝ # Put a 0 at the location that we want to remove
Ï # Keep only the characters that correspond to a 1 in the new list
}, # Print the last step
```
[Answer]
# Mathematica, 70 bytes
```
(s=#;For[t=1,t<=Length@#2,Print@s;s=StringDrop[s,{#2[[t]]+1}];t++];s)&
```
[Try it online!](https://tio.run/##y00sychMLv6fZvtfo9hW2dotvyi6xNZQp8TG1ic1L70kw0HZSCegKDOvxKHYutg2uATITHcpyi@ILtapVjaKji6JjdU2rI21LtHWjrUu1lT7D1as4JAWrZScn5Kanp@TpqSjUG2oYwKEBjpGtbH/AQ "Mathics – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~46~~ 32 bytes
```
function(S,X)Reduce(`[`,-X,S,,T)
```
[Try it online!](https://tio.run/##DcgxCoAwDAXQ3WNkSuA7qDh6CesglEKhNiKIFW3PX@Vt76k6VS1XyEe62GCVOW4lRPbWo11hgEWq8puf9z6PzBTSFvd0KoFIrO2cQ@Ae46/DINIoE/0lUj8 "R – Try It Online")
Takes input as a list of characters and `X` is 1-based. `Reduce` is the R equivalent of `fold`, the function in this case is `[` which is subset. Iterates over `-X` because negative indexing in R removes the element, and `init` is set to `S`, with `accum=TRUE` so we accumulate the intermediate results.
# [R](https://www.r-project.org/), 80 bytes
```
function(S,X,g=substring)Reduce(function(s,i)paste0(g(s,0,i-1),g(s,i+1)),X,S,,T)
```
2-argument function, takes `X` 1-indexed. Takes `S` as a string.
[Try it online!](https://tio.run/##PYuxDoUgEAT/xeou7ktEY@lPPC1sFYFcYsAIfD9iY7aZyWTvYqdis9dJgqcZK9wU8x7TLd7x3xxZG/p6hPC1xWQ6clU6yE8xXpRWMdf3DCxcLDU6HMaF0zbQ1GOsUxiYywM "R – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), 33 bytes
```
scanl(\s i->take i s++drop(i+1)s)
```
[Try it online!](https://tio.run/##DcJLCoAgFAXQrVykgWJBRtPaSDUQP/XINHrt3@Kcw/IZUqo1TuxsTnJlUDe/9gwgsNb@KbckbRSrelnKmHA/lF80iBCu@LCXFAUW046/vh22@gE "Haskell – Try It Online")
[Answer]
# q/kdb+, ~~27~~ 10 bytes
**Solution:**
```
{x _\0N,y}
```
**Examples:**
```
q){x _\0N,y}["codegolf";1 4 4 0 2]
"codegolf"
"cdegolf"
"cdeglf"
"cdegf"
"degf"
"def"
q){x _\0N,y}["abc";0]
"abc"
"bc"
q){x _\0N,y}["abc";()]
"abc"
q){x _\0N,y}["abc";2 0 0]
"abc"
"ab"
,"b"
""
q){x _\0N,y}["";()]
""
```
**Explanation:**
Takes advantage of the [converge](https://code.kx.com/q/ref/adverbs/#converge-iterate) functionality `\` as well as drop `_`.
```
{x _\0N,y}
{ } / lambda function, x and y are implicit variables
0N,y / join null to the front of list (y), drop null does nothing
_\ / drop over (until result converges) printing each stage
x / the string (need the space as x_ could be a variable name)
```
**Notes:**
If we didn't need to print the original result, this would be **2** bytes in `q`:
```
q)_\["codegolfing";10 9 8 3 2 1 0]
"codegolfin"
"codegolfi"
"codegolf"
"codgolf"
"cogolf"
"cgolf"
"golf"
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~94~~ 84 bytes
```
param($s,$x)$a=[Collections.Generic.list[char]]$s;$x|%{-join$a;,$a|% r*t $_};-join$a
```
[Try it online!](https://tio.run/##LchBCsIwEADAr@xhS1tZS6sXJQiCBx9RioQY28ialCRgwfr29eIcZw5vG9NkmUVmHfWrwkS41KhP/SUwW5Nd8Km5Wm@jMw27lHsz6TgMmBQua/HZPoPzqBWhXguImwx4@6r/ikhpwt2OgR/Oj6Wcq64lOBIcCPYEO4KOoK1/ "PowerShell – Try It Online")
Takes input `$s` as a string and `$x` as an explicit array. We then create `$a` based on `$s` as a list.
Arrays in PowerShell are fixed size (for our purposes here), so we need to use the lengthy `[System.Collections.Generic.list]` type in order to get access to the `.removeAt()` function, which does exactly what it says on the tin.
I sacrificed 10 bytes to include two `-join` statements to make the output pretty. OP has stated that outputting a list of chars is fine, so I could output just `$a` rather than `-join$a`, but that's really ugly in my opinion.
*Saved 10 bytes thanks to briantist.*
[Answer]
# [Python 2](https://docs.python.org/2/), 50 bytes
* Takes in string and list of indices
```
s,i=input()
for j in i+[0]:print s;s=s[:j]+s[j+1:]
```
[Try it online!](https://tio.run/##HcKxCoAgEADQva@4zUKHlCbDLzmcKuskVDwb@nqDHq@87crJ9M6KHKXytHEaQq4QgRKQxNnbUik14JUdo41eMkapre9dbHk/znwHoVArWP6zAuM/ "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 99 bytes
```
j;f(s,a,i)char*s;int*a;{puts(s);for(j=0;j<i;j++){memmove(s+a[j],s+a[j]+1,strlen(s)-a[j]);puts(s);}}
```
[Try it online!](https://tio.run/##NY7NCsMgEIRfRXLSuIGktKdtniTkINakSozFtb1Int0m/YGBgYFvZnQza12Kw4kTKLBC31WsCe2aaoX58UzESeAUInd9i@5q0Ukpsjfeh5fhJNXgRvia7IBSXMy6I80RCPwXbFvxyq5c5GOA0TD2lQ43M4dlqo41pvYod8DOH7XATtvv1GXHyxs "C (gcc) – Try It Online")
Takes the string, array, and the length of the array.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 7 bytes
```
=svõyǝ=
```
[Try it online!](https://tio.run/##MzBNTDJM/f/ftrjs8NbK43Nt//9Pzk9JTc/PSeOKNtQxAUIDHaNYAA "05AB1E – Try It Online")
---
```
=s # Print original string, swap with indices.
v # Loop through indices...
õyǝ # Replace current index with empty string.
```
-2 thanks to idea from @ETHProductions.
[Answer]
# [Retina](https://github.com/m-ender/retina), 58 bytes
```
¶\d+
¶¶1$&$*
+1`(?=.*¶¶.(.)*)(((?<-1>.)*).(.*)¶)¶.*
$2$3$4
```
[Try it online!](https://tio.run/##K0otycxL/P//0LaYFG2uQ9sObTNUUVPR4tI2TNCwt9XTAonoaehpamlqaGjY2@ga2oHYQBEtzUPbgEhPi0vFSMVYxeT//@T8lNT0/Jy0zLx0LkMDLksuCy5jLiMuQy4DAA "Retina – Try It Online") Explanation:
```
¶\d+
```
Match the indices (which are never on the first line, so are always preceded by a newline).
```
¶¶1$&$*
```
Double-space the indices, convert to unary, and add 1 (because zeros are hard in Retina).
```
+1`
```
Repeatedly change the first match, which is always the current value of the string.
```
(?=.*¶¶.(.)*)
```
Retrieve the next index in `$#1`.
```
( . ¶)
```
Capture the string, including the `$#1`th character and one newline.
```
((?<-1>.)*) (.*)
```
Separately capture the prefix and suffix of the `$#1`th character of the string.
```
¶.*
```
Match the index.
```
$2$3$4
```
Replace the string with itself and the index with the prefix and suffix of the `$#1`th character.
[Answer]
# Pyth, 8 bytes
```
.u.DNYEz
```
[Demonstration](https://pyth.herokuapp.com/?code=.u.DNYEz&input=codegolf%0A%5B1%2C+4%2C+4%2C+0%2C+2%5D&debug=0)
Reduce, starting with the string and iterating over the list of indices, on the deletion function.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~54~~ 58 bytes
```
param($s,$x),-1+$x|%{$z=$_;$i=0;-join($s=$s|?{$z-ne$i++})}
```
[Try it online!](https://tio.run/##DcnRCsIgFADQX7kPN6Z4Ba2XYkj9xxghyzbDdOhDo7Zvt53XM6ePy2VyIdQ622zfDAvhwklqgct6@OHX4L1Fb1QrX8nH/Q2W9bqHjA69EBvfaq2sGyabu75vhvRwYwpPH8eG1xvTiuBCcCY4ERwJNIHifw "PowerShell – Try It Online")
## Explanation
Takes input as a char array (`[char[]]`).
Iterates through the array of indices (`$x`) plus an injected first element of `-1`, then for each one, assigns the current element to `$z`, initializes `$i` to `0`, then iterates through the array of characters (`$s`), returning a new array of only the characters whose index (`$i`) does not equal (`-ne`) the current index to exclude (`$z`). This new array is assigned back to `$s`, while simultaneously being returned (this happens when the assignment is done in parentheses). That returned result is `-join`ed to form a string which is sent out to the pipeline.
Injecting `-1` at the beginning ensures that the original string will be printed, since it's the first element and an index will never match `-1`.
[Answer]
# [Perl 5](https://www.perl.org/), 55 bytes (54 + "`-l`")
```
sub{print($s=shift);for(@_){substr$s,$_,1,"";print$s}}
```
[Try it online!](https://tio.run/##dY7NCoMwEAbveYol5GBgA9ofaAmWvolUa2xAjGTTk/jqTdPQ3irs6ZuB2bn34zEKAzVEerbL7O0UCkE1PawJUhvni2sjl8QoeEEoGqyQc51FQesaNWPCqEvBO3fvBzcajlAhHPKVCDupWbaBK6W4/tq3tktiuQ3/k43517bT8Mmn7BnhhLBP/fxOCsWXm4N1E0U1vgE "Perl 5 – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 8 bytes
```
ii"t[]@(
```
Indexing is 1-based.
[Try it online!](https://tio.run/##y00syfn/PzNTqSQ61kHj/3/15PyU1PT8nDR1rmgjHQVTMDLUUTCOBQA "MATL – Try It Online") Or [verify the test cases](https://tio.run/##y00syfmf8D8zU6kkOtZB43@suq6urnqES8h/9cSkZHWuaMNYLigLzjDWUTAEIiAfJAoA).
### Explanation
```
i % Input string. Input has to be done explicitly so that the string
% will be displayed even if the row vector of indices is empty
i % Input row vector of indices
" % For each
t % Duplicate current string
[] % Push empty array
@ % Push current index
( % Assignment indexing: write [] to string at specified index
% End (implicit). Display stack (implicit)
```
[Answer]
# [C# (.NET Core)](https://www.microsoft.com/net/core/platform), ~~87~~ ~~87~~ ~~74~~ 70 bytes
```
S=>I=>{for(int i=0;;S=S.Remove(I[i++],1))System.Console.WriteLine(S);}
```
[Try it online!](https://tio.run/##XY5BS8NAFITv@yuWnnbpNiR6UbYJiMVS0It78BByCNvX8iB5W/dtWyTkt8coKCJzmoGZbzyvfIgwnRnpKN0HJ@it@OuyZ6T3f9Fj6DrwCQNxtgWCiN4KanvgU@tB0iB81zLL0yA4tQm9fDqTX3OK84h5@G6ukVLdVJXcyHJyZbUrq@EQoppjiWVurStd9gp9uIDa1bhcNqbQ@vcAcegge4uYYD4Iymk7TvYHdwm4ly8tktKD2KiFD3s4hu4w4xdaEVzrZihyc2/uzK25MYXJR23F@KXpEw "C# (.NET Core) – Try It Online")
Just goes to show that recursion isn't always the best solution. This is actually shorter than my original invalid answer. Still prints to STDOUT rather than returning, which is necessary because it ends with an error.
-4 bytes thanks to TheLethalCoder
[Answer]
# [J](http://jsoftware.com/), 23 bytes
```
>@({&.>/\.&.|.@;<^:4"0)
```
[Try it online!](https://tio.run/##y/qfVqxga6VgoADE/@0cNKrV9Oz0Y/TU9Gr0HKxt4qxMlAw0/2tyKekpqKfZWqkr6CjUWimkFXNxpSZn5CuoJ@enpKbn56SpK6QpGCqYAKGBgtF/AA "J – Try It Online")
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `o`, 4 bytes
```
(…n⟇
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJvIiwiIiwiKOKApm7in4ciLCIiLCJbMSwgNCwgNCwgMCwgMl1cbltcImNcIiwgXCJvXCIsIFwiZFwiLCBcImVcIiwgXCJnXCIsIFwib1wiLCBcImxcIiwgXCJmXCJdIl0=)
Prints lists of chars
```
(…n⟇ # 'o' flag forces output of the last value
( # For every number in the list...
… # Print the string without popping
n # Get the current value
⟇ # Remove the char at the index
# The result is printed on next iteration
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 10 bytes
Rule changes saved me 1 byte:
```
V+E0Q .(QN
```
[Try it online!](https://tio.run/##K6gsyfj/P0zb1SBQQU8j0O///2ilZCUdpXwgTgHiVCBOh/JzgDhNKZYr2lBHwQSMDHQUjGIB "Pyth – Try It Online")
# [Pyth](https://pyth.readthedocs.io), 11 bytes
```
V+E0sQ .(QN
```
**[Try it online!](https://tio.run/##K6gsyfj/P0zb1aA4UEFPI9Dv//9opWQlHaV8IE4B4lQgTofyc4A4TSmWK9pQR8EEjAx0FIxiAQ)**
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 9 bytes
```
+⟪Seḥ+⟫⊣ṣ
```
I should really add a "delete at index" function...
[Try it online!](https://tio.run/##S0/MTPz/X/vR/FXBqQ93LAUyVj/qWvxw5@L/qY/aOxSA4FHDHOfEnByFkoxUhbTSvOSSzPw8BSAC8TPzCkpLHjXMjfkPVJWcn5Kanp@TBuQrRBsqmAChgYJRLAA "Gaia – Try It Online")
### Explanation
```
+ Add the string to the list
⟪Seḥ+⟫⊣ Cumulatively reduce by this block:
S Split around index n
e Dump the list
ḥ Remove the first char of the second part
+ Concatenate back together
ṣ Join the result with newlines
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), 12 bytes
```
òdt,GÙ@-|xHx
```
[Try it online!](https://tio.run/##K/v///CmlBId98MzHXRrKjwq/v83NNQxNNCx1DHRMdYx0jHU4UrOT0lNz89Jy8xLBwA "V – Try It Online")
This is 1-indexed, input is like:
```
11,10,9,4,3,2,1,
codegolfing
```
### Explanation
```
ò ' <M-r>ecursively until error
dt, ' (d)elete (t)o the next , (errors when no more commas)
G ' (G)oto the last line
Ù ' Duplicate it down
| ' Goto column ...
@- ' (deleted number from the short register)
x ' And delete the character there
H ' Go back home
x ' And delete the comma that I missed
```
[Answer]
# [Swift 3](https://www.swift.org), 80 bytes
```
func f(l:[String],c:[Int]){var t=l;for i in c{print(t);t.remove(at:i)};print(t)}
```
**[Try it online!](http://swift.sandbox.bluemix.net/#/repl/598df3ef19b65f016ddd76f4)**
[Answer]
# Pyth, 8 bytes
```
+zm=z.Dz
```
[Test suite!](https://pyth.herokuapp.com/?code=%2Bzm%3Dz.Dz&input=%22codegolf%22%0A%5B1%2C+4%2C+4%2C+0%2C+2%5D&test_suite=1&test_suite_input=%5B1%2C+4%2C+4%2C+0%2C+2%5D%0Acodegolf%0A%5B0%5D%0Aabc%0A%5B%5D%0Aabc%0A%5B2%2C+0%2C+0%5D%0Aabc%0A%5B%5D%0A%0A%5B10%2C+9%2C+8%2C+3%2C+2%2C+1%2C+0%5D%0Acodegolfing%0A&debug=0&input_size=2)
# explanation
```
+zm=z.DzdQ # implicit: input and iteration variable
m Q # for each of the elements of the first input (the array of numbers, Q)
.Dzd # remove that index from the second input (the string, z)
=z # Store that new value in z
+z # prepend the starting value
```
[Answer]
# [Python 2](https://tio.run/#python2), 54
```
X,S=input()
for a in X:
print S
S=S[:a]+S[a+1:]
print S
```
[Try It Online](https://tio.run/##K6gsycjPM/r/P0In2DYzr6C0REOTKy2/SCFRITNPIcKKizPYNjjaKjFWOzg6UdvQKparoCgzr0Qh@P//aEMdBRMwMtBRMIrVUU/OT0lNz89JUwcA)
] |
[Question]
[
Write the shortest program possible such that when you combine the first character and every Nth character after it into a new program, the output is N. This must work for N = 1, 2, ..., 16.
Another way to say it is, if you *remove* all the characters from your program *except for* the first one and every Nth one after that, the output of the remaining code should be N.
# Example
If your code was
```
ABCDEFGHIJKLMNOP
```
N = 1 results in `ABCDEFGHIJKLMNOP`. Running this should output 1.
N = 2 results in `ACEGIKMO`. Running this should output 2.
N = 3 results in `ADGJMP`. Running this should output 3.
N = 4 results in `AEIM`. Running this should output 4.
N = 5 results in `AFKP`. Running this should output 5.
N = 6 results in `AGM`. Running this should output 6.
N = 7 results in `AHO`. Running this should output 7.
N = 8 results in `AI`. Running this should output 8.
N = 9 results in `AJ`. Running this should output 9.
N = 10 results in `AK`. Running this should output 10.
N = 11 results in `AL`. Running this should output 11.
N = 12 results in `AM`. Running this should output 12.
N = 13 results in `AN`. Running this should output 13.
N = 14 results in `AO`. Running this should output 14.
N = 15 results in `AP`. Running this should output 15.
N = 16 results in `A`. Running this should output 16.
# Details
* All characters are allowed, ASCII and non-ASCII. (Newlines and unprintable ASCII are allowed as well. Note that carriage return and line feed count as distinct characters.)
* Your score is the length *in characters* of your unaltered program (15 in example). The lowest score wins.
* A score below 16 is clearly impossible because then at least two of the altered programs would be identical.
* Output may be to a file or stdout or anything else reasonable. However, the output of the 16 different programs must all go to the same place (e.g. it's not ok if `AO` goes to stdout but `A` goes to a file). There is no input.
* The output must be in decimal, not hex. The actual output should only contain the 1 or 2 characters that make up the number from 1 to 16, nothing else. (Things like Matlab's `ans =` are ok.)
* Your program does not have to work for N = 17 or above.
[Answer]
# Befunge 93 - Five million seven-hundred sixty-five thousand and seven-hundred and seventy six characters
I demand to be taken seriously...
```
v &(720 720 - 80) X SPACE
"""""""""""""""" &(720 720 - 80) X SPACE
1234567890123456 &(720 720 - 80) X SPACE
"""""""""1111111 &(720 720 - 80) X SPACE
,,,,,,,,,""""""" &(720 720 - 80) X SPACE
@@@@@@@@@,,,,,,, &(720 720 - 80) X SPACE
,,,,,,, &(720 720 - 80) X SPACE
@@@@@@@ &(720 720 - 80) X SPACE
```
3 reasons why. 1st reason: a befunge script is always 80x25, so no matter what, there had to be **something** that got reduced on the lines with code. 2nd reason: why that something is about 5.5 million spaces is because 720 720 is the smallest common multiple of 1 to 16... Means there will be no wrap around mess when we're skipping characters. 3rd reason: wow, this is pretty absurd.
[Answer]
# Python - ~~1201~~ 1137 (generator: ~~241~~ 218) - Long live the hashes!
**Strategy:**
I tried to start every line with as many hashes as the desired output `n`. Then all other versions will skip this line completely.
The main difficulty, however, was to append the correct number of hashes so that the next run will hit the beginning of the next line exactly. Furthermore, interferences with other versions might occur, e.g. version 16 jumping right into the `print` command of line 5 and so on. So this was a lot of trial and error combined with a helper script for rapid testing.
**Statistics:**
* Characters: ~~1201~~ 1137
* Hashes: ~~1066~~ 1002 (88.1 %)
* Non-hashes: 135 (11.9 %)
**Code:**
```
#
print 1#####
#p#r#i#n#t# #2######################
##p##r##i##n##t## ##3###
###p###r###i###n###t### ###4
####p####r####i####n####t#### ####5#########
#####p#####r#####i#####n#####t##### #####6##########
######p######r######i######n######t###### ######7###########
#######p#######r#######i#######n#######t####### #######8###
########p########r########i########n########t######## ########9##
#########p#########r#########i#########n#########t######### #########1#########0##
##########p##########r##########i##########n##########t########## ##########1##########1##
###########p###########r###########i###########n###########t########### ###########1###########2##
############p############r############i############n############t############ ############1############3##
#############p#############r#############i#############n#############t############# #############1#############4##
##############p##############r##############i##############n##############t############## ##############1##############5##
###############p###############r###############i###############n###############t############### ###############1###############6
```
**Test script:**
```
with open('printn.py', 'r') as f:
c = f.read()
for n in range(1, 17):
print "n =", n, "yields",
exec c[::n]
```
**Output:**
```
n = 1 yields 1
n = 2 yields 2
n = 3 yields 3
n = 4 yields 4
n = 5 yields 5
n = 6 yields 6
n = 7 yields 7
n = 8 yields 8
n = 9 yields 9
n = 10 yields 10
n = 11 yields 11
n = 12 yields 12
n = 13 yields 13
n = 14 yields 14
n = 15 yields 15
n = 16 yields 16
```
---
**Update: A generating script!**
I thought about my solution and that there must be a pattern to generate it algorithmically. So here we go:
```
lines = ['#']
for i in range(1, 17):
lines.append(('#' * (i - 1)).join('\nprint ' + `i`))
fail = True
while fail:
while ''.join(lines)[::i].find('print ' + `i`) < 0:
lines[i] = '#' + lines[i]
fail = False
for n in range(1, 17):
try:
exec ''.join(lines)[::n]
except:
lines[i] = '#' + lines[i]
fail = True
break
print ''.join(lines)
```
It builds the program line by line:
1. Start with a hash.
2. Append a new line `i` with the `print i` command and `i - 1` hashes in between each two neighboring characters.
3. While the "i-version" (every i-th character) of the current program does not contain the command `print i` (due to misalignment) or any `n`-version with `n in range(1, 17)` throws an exception, add another hash to the previous line.
It actually returned a shorter program than I found manually this morning. (So I updated my solution above.) Furthermore, I'm pretty sure there is no shorter implementation following this pattern. But you never know!
**Golfed version - ~~241~~ 218:**
```
h='#';L=[h];I=range(1,17);J=''.join
for i in I:
p='print '+`i`;L+=[(h*(i-1)).join('\n'+p)]
while 1:
while J(L)[::i].find(p)<0:L[i]=h+L[i]
try:
for n in I:exec J(L)[::n]
break
except:L[i]=h+L[i]
print J(L)
```
Note that there might be a shorter generator, e.g. by hard-coding the required number of succeeding hashes for each line. But this one computes them itself and could be used for any N > 16.
[Answer]
# 209 characters (Various languages)
I just tried to keep things simple and avoid putting anything in positions with a lot of prime factors. The advantage is an ability to run in many scripting languages. It should work in any language that is not deliberately perverse and has the following features:
* Integer literals
* Basic arithmetic operators +, - (subtraction and negation), \*, /
* Prints the evaluation of a bare expression
* Has a single character that begins a line comment
For example,
## Python 2 command-line interpreter (though not from a file):
```
+ 1 # 4 / 23 # # 5 # 9 # 7 6 * # # - 5 2 * - ## 2 6 #2 * 2 6 4
```
## MATLAB (simply replace '#' with '%'):
```
1 % 4 / 23 % % 5 % 9 % 7 6 * % % - 5 2 * - %% 2 6 %2 * 2 6 4
```
N.B. There should be 17 spaces preceding the first '1'.
You guys know a lot of languages, so please help me list more that it could run in ( :
### EDIT: Added unary + at position 0 for Python to avoid the line being indented.
[Answer]
## APL, 49
```
⌊⊃⍟○7⍟⍟1|/2111118 9⍝×-1 ×○3×4_5_× 1_ _⍝_⍝ __2
```
**Altered programs**
```
1 ⌊⊃⍟○7⍟⍟1|/2111118 9⍝×-1 ×○3×4_5_× 1_ _⍝_⍝ __2
2 ⌊⍟7⍟|21189×1×345× 1 ⍝⍝_2
3 ⌊○⍟/119-××5 1 ⍝ 2
4 ⌊7|18××4×1 ⍝2
5 ⌊⍟21×○5
6 ⌊⍟19×51⍝2
7 ⌊11-4 ⍝
8 ⌊|8×× 2
9 ⌊/9×1
10 ⌊2×5
11 ⌊11 ⍝
12 ⌊1×12
13 ⌊13
14 ⌊14⍝
15 ⌊15
16 ⌊8×2
```
**Explaination**
I'll start from the bottom as it would make explaining easier
There are two language feature of APL to keep in mind. One, APL has no operator precedence, statements are always evaluated right to left. Two, many APL functions behave quite differently depending if it is given one argument on its right (monadic) or two arguments on its left *and* right (dyadic).
Monadic `⌊` is round down (floor function), Dyadic `×` is obviously multiplication, `⍝` comments out rest of the line
This should make these obvious:
```
16 ⌊8×2
15 ⌊15
14 ⌊14⍝
13 ⌊13
12 ⌊1×12
11 ⌊11 ⍝
10 ⌊2×5
```
**9: `⌊/9×1`**
`/` is Reduce. Basically it takes the function of the left and the array on the right, insert the function between every pair of elements of the array and evaluate. (This is called "fold" in some languages)
Here, the right argument is a scalar so `/` does nothing.
**8: `⌊|8×× 2`**
Monadic `×` is the [signum function](http://en.wikipedia.org/wiki/Sign_function) and monadic `|` is the absolute value function
So, `× 2` evaluates to `1` and `|8×1` is of course `8`
**7: `⌊11-4 ⍝`** should be obvious
**6: `⌊⍟19×51⍝2`**
Monadic `⍟` is natural log
So, `⍟19×51` evaluates to `ln(19×51) = 6.87626...`, and `⌊` rounds it down to `6`
**5: `⌊⍟21×○5`**
Monadic `○` multiplies its argument by π
`⍟21×○5` is `ln(21×5π) = 5.79869...`
**4: `⌊7|18××4×1 ⍝2`**
Dyadic `|` is the mod function
`×4×1` evaluates to `1`, and `7|18×1` is `18 mod 7 = 4`
**3: `⌊○⍟/119-××5 1 ⍝ 2`**
Space-separated values is an array. Note that in APL, when most scalar functions are give array arguments, it is an implicit map.
Dyadic `⍟` is log
So `××5 1`, is signum of signum on 5 and 1, which gives `1 1`, `119-1 1` is `¯118 ¯118` (`¯` is just the minus sign. APL has to distinguish between negative numbers and subtraction), and `⍟/¯118 ¯118` is log-118(-118) = 1
**2: `⌊⍟7⍟|21189×1×345× 1 ⍝⍝_2`**
You can work it out yourself
**1: `⌊⊃⍟○7⍟⍟1|/2111118 9⍝×-1 ×○3×4_5_× 1_ _⍝_⍝ __2`**
This one consist of a more complicated use of `/`. If `n` is a number, `F` is a function, and `A` is an array, then `nF/A` takes each group of `n` consecutive entries of `A` and apply `F/`. For example, `2×/1 2 3` takes each pair of consecutive entries (which are `1 2` and `2 3`) and apply `×/` to each group to give `2 6`
So, `1|/2111118 9` just returns `2111118 9` (as it applies `|/` to scalars). Then, `⍟○7⍟⍟` applies ln, then log7 to those numbers, then multiplies them by π and ln again. The numbers that come out the other side are `1.46424... 0.23972...`
Here, `⊃` is just used to select the first element of an array.
[Answer]
# CJam, 89 bytes
```
GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(iiii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-
```
This approach doesn't use any kind of comments.
`i` casts to integer, so it is a noop here. It could be replaced by whitespace, but the letters seem more readable to me...
[Try it online](http://cjam.aditsu.net) by executing the following *Code*:
```
G,{)
"GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(iiiii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-"
%_~}%N*
```
### Example run
```
$ cat nth-char.cjam
G,{)"GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(i
iii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-"%_~}%N*N
$ cjam nth-char.cjam
GiiAHH(5A5(7ii)ii;(;(-i((i(-i)i)ii)i()i((i(i(i
iii(iii(iiiii(iiiii(i-i(iiiiiii(ii(ii(-ii-
1
GiH(A(i)i((i((iii)(i(((
i(i(ii(ii(-(iii(ii(i-
2
GA(5ii(-(-ii(((iii(i(i(iii(((i
3
GHAii((ii(((iii(i-iii(-
4
GH(i(iii(i(i(i(ii-
5
G(i((i((i(((i((
6
G5)-ii(iii(i(
7
GAi(i(iiiii-
8
G5(-(i(ii(
9
G((i((((i
10
G7ii(i(i-
11
Gi((i(i(
12
Gi((ii(
13
G)i(i((
14
Giii(i
15
Giiiii
16
```
[Answer]
# GolfScript, 61 bytes
```
1})_#;#;;00123358_(_};}_}_}} _}_(__6
_})4_)_+)__(__}__;_}___6
```
This takes advantage of comments (`#`) and the undocumented "super-comments" (everything following an unmatched `}` it is silently ignored).
`_` is a noop. It could be replaced by whitespace, but the underscores seem more readable to me...
[Try it online.](http://golfscript.apphb.com/?c=MTYseykiMX0pXyM7Izs7MDAxMjMzNThfKF99O31ffV99fSBffV8oX182Cl99KTRfKV8rKV9fKF9ffV9fO199X19fNiJcJS5%2BfSVuKg%3D%3D "Web GolfScript")
# Example run
```
$ cat nth-char.gs
16,{)"1})_#;#;;00123358_(_};}_}_}} _}_(__6
_})4_)_+)__(__}__;_}___6"\%.~}%n*
$ golfscript nth-char.gs
1})_#;#;;00123358_(_};}_}_}} _}_(__6
_})4_)_+)__(__}__;_}___6
1
1)##;0238(}}}} }(_
}4)+_(__;}_6
2
1_#025(;}}}_
)))(};_6
3
1#;28}} (
4+(_}6
4
1;05}_}64)__6
5
1#2(}}
)(;6
6
1;3; 6)_}
7
1;8}(4(}
8
10(}
);
9
10}}4_6
10
11}_+_
11
12}
(6
12
13})_
13
13 )}
14
15})6
15
18((
16
```
[Answer]
# [Zsh](https://www.zsh.org/), 249 bytes
```
b
y
e
2y
y
yyyy
e
bye 1
e e
e
e
9
1
1
11
1
13
4
5
6
b
b
b
y
y
y
e
6
8
1
0
b
b
y
e
e
7b
y
e
1
5
2
b
b
yy
e
3
4
```
[Verify all slices online!](https://ato.pxeger.com/run?1=ZVBRTgIxEP3ed4pJaLIQA3EAEUk23oALGD_cOsgmuCUgmko4iT-bEA_lUfxz2q77w2v7ZtqZ15nM1_lzv27Otsi_D2-r4fznt4SHgDD26niF3kovxBAS9YWAO2iCbo4MsG5OFjxRwjTQTaAZLlF2JxaJbxKZ4gqaeftfwnWnS4RWlWQSu1DclsHz_wGmrg2ML3rQ6j7mEWGCaTuAbQ5bmKNd8Il6tJNX9y60kafnqn6hWj42VS1YuR0tqX_k0YhnpwH1kbkiz5GFQJUCpmeVlhp1V4WxD9UjMh02DS0Zh0zs2pG5xyDVbZpk_wA)
Every sliced program is of the form:
```
[...junk]
bye N
[junk...]
```
For example, for \$ N = 8 \$:
```
b2y1e
11
6
bye 8
y
e
2
be4
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m724qjhjwUKNpaUlaboWNxWTjCoNU7kUDA25zLi4kipTFSy4uLgqubgUUrmMuJJSTbggCldqcqUmZ-QrqNhD-AsWQGgA)
The only code that matters is the `bye 8`, which exits the program with the exit code of 8.
The rest of the junk is just ignored by zsh, because it's all invalid commands. (Everything after the first valid `bye` also doesn't matter, because it never gets executed).
---
To optimise this answer, we want to interleave the programs `bye 1`, `b y e 2`, `b y e 3`, etc., so that:
* every program starts at an offset that is a multiple of its corresponding value of \$ N \$
* none of the programs "overlap", putting different characters in the same place, which will break the code
* the total length is minimised (of course)
This problem boils down to searching over the permutations of \$ [1, 16] \$, and then inserting each program in the chosen order at the first valid offset in the output code.
I tried various strategies to solve these constraints, including some obvious orderings picked by hand, and a greedy breadth-first search, but the most successful was a crude "Monte Carlo" method:
1. shuffle the range into a particular order
2. arrange the programs in that order
3. if this solution was shorter than the previous iteration, then save it as the current shortest possibility
4. repeat ad nauseam
Here's my optimiser code, in Python:
```
import re, random, time
def valid(code, n):
match = pattern.search(''.join(code))
return match and match[1] == str(n)
pattern = re.compile(r"^\s*bye\s+(\d+)\s*$", re.MULTILINE)
# for repeatability
seed = int(time.time() * 1e6)
print(f"{seed=}")
random.seed(seed)
ns = list(range(1, 17))
# it's pretty much guaranteed we'll find a solution shorter than this fake one
result = "dummy" * 100
while True:
code = ["\n"] * 1000
random.shuffle(ns)
used = set()
for n in ns:
used.add(n)
out = code.copy()
insert = f"bye {n}"
offset = 0
out[offset:offset + len(insert) * n:n] = insert
while not all(valid(out[::i], i) for i in used):
offset += n
if offset >= 250:
# too long
break
out = code.copy()
out[offset:offset + len(insert) * n:n] = insert
# hack to propogate break
else:
code = out
continue
break
else:
candidate = "".join(code).rstrip("\n")
if len(candidate) < len(result):
result = candidate
print("------")
print("length:", len(result))
print(result)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=pVRLbtswEN10pVMM5AKmYkewC_QDoy7QRRcB0naTrmIXYKyhxYYiBZJKagQ5STbZtIfqNXqBDkX5IzddlQtCmjd8M_NmyIef9caXRj8-_mi8OH3z69lvWdXGerA4Bst1YaoxeFlhkhQo4IYrWbCVKQjV2SwBWhX3qxLmUHPv0ercIberkg2H-TcjdeucZa2nRd9Y3R0g7vh1OV3CfA7OW6azJOloiNBivjJVLRUym35duJOrDS7ciC2KUUZ_z9NxcPn45fzi7Pzs04cMkmQAwliy1sg9v5JK-k3iEAtik9qzUEgeNpbBCUzxVZbUNgAivQtu8_s0S2LVefhnYaOctCMCJZ1nBK6RTccwfU1FUTzphw5qqsxvoGqornXDycmHoLc4VAqEpEo5OKMaL40GV5K-aMGXXNMmHQh-jWA0JhZdozzFSoumqjZpSHIySZLbkkSAC9tglDxoSl6X6UKny-g0iQp3uZeNECSbdlH4xrUSOPQsGoJKmiQB7SLj1ivnRRHasLWZJqQT4lEv6g3bI1I7tAEUKfUF7vR9uj8lBMUibHJIdBnNsw4dgULNIk1oh57pZdunYNidi6Vr44ErxeL8Ba7ZTC7HILO2FBlKCeln-2oO8hjNQffsUmyhd3N48XLSPxXWALwxoIxe_wVdWeTX_TD_FOl_Kh9AyVfXlAeNl6nNmns8io3KYT_1bjAo5JFZe6kb3Bn3PH2OFc2PLEIkmsH04ALnlu6nrFmYuIMZEG0lu1MZvG0NcY6PmrEb7p17D44XMT1tV5o9hRH12pczuvcHQZ7y7KAegt8lTX-Qld8YWcD7i8_tw0ZaxbevewK3T-Ef) (but due to ATO's timeout and non-streaming nature, this is probably better run on your actual computer)
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.