text
stringlengths 180
608k
|
---|
[Question]
[
([related](https://codegolf.stackexchange.com/q/6443/42963))
A [*Pythagorean Triple*](https://en.wikipedia.org/wiki/Pythagorean_triple) is a list `(a, b, c)` that satisfies the equation *a2 + b2 = c2*.
A *Primitive* Pythagorean Triple (PPT) is one where `a`, `b`, and `c` are all [coprime](https://en.wikipedia.org/wiki/Coprime_integers) (i.e., the only common divisor between the three elements is `1`). For example, the `(3, 4, 5)` right triangle is a famous Primitive Pythagorean Triple.
## The Challenge
* Given input `n`, output the `n`th PPT. Or,
* Given input `n`, output the first `n` PPTs.
There are multiple ways to order these PPTs to form a well-ordered list, to determine which is the `n`th. You can choose any ordering you want, so long as you can prove (informally is fine) that your algorithm can generate every possible unique PPT. For example, your code should not output both `(3,4,5)` and `(4,3,5)` since those are duplicates of the same triple -- one or the other, please.
Similarly, whether your code is zero- or one-indexed is fine, so long as you state which you're using.
## Examples
For the examples below, I'm using one-indexing, outputting the `n`th PPT, and ordering by smallest `c`, then smallest `a`, then smallest `b`.
```
n | output
1 | (3, 4, 5)
2 | (5, 12, 13)
5 | (20, 21, 29)
12| (48, 55, 73)
```
## Rules
* The input and output can be given [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963).
* In your submission, please state how your entries are ordered, and whether your entries are 0-indexed or 1-indexed.
* Your chosen ordering cannot create duplicates.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* [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]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 25 bytes
*2 bytes thanks to Jonathan Allan.*
```
²IH;Pµ;ÆḊ
+2ḶḤ‘Œcg/ÐṂÇ€Ṣḣ
```
[Try it online!](https://tio.run/##ATwAw/9qZWxsef//wrJJSDtQwrU7w4bhuIoKKzLhuLbhuKTigJjFkmNnL8OQ4bmCw4figqzhuaLhuKP///8xMDA "Jelly – Try It Online")
Outputs the first `n` 1-indexed triples `[b, a, c]`, sorted by increasing `b` and then `a`.
Uses the algorithm from [Wikipedia](https://en.wikipedia.org/wiki/Pythagorean_triple#A_variant):

This generates all primitive triples for all unique coprime pairs of odd integers `m > n > 0`.
### Explanation
```
+2ḶḤ‘Œcg/ÐṂÇ€Ṣḣ Main link. Argument: n
+2 Add 2 to n, to get enough results.
Ḷ Get integers [0, 1, ..., n+1].
Ḥ Double to get [0, 2, ..., 2n+2].
‘ Increment to get [1, 3, ..., 2n+3].
Œc Get all ordered pairs [[1, 3], [1, 5], ..., [2n+1, 2n+3]].
g/ GCD of each pair.
ÐṂ Grab the pairs with minimal GCD (which is 1).
Ç€ Call the helper link on each pair to get the triples.
Ṣ Sort the triples first by a, then by b, then by c.
ḣ Get the last n.
²IH;Pµ;ÆḊ Helper link. Argument: pair [m, n]
² Square to get [m², n²].
I Increments: get [m²-n²].
H Halve: get [(m²-n²)/2], i.e. [b].
P Product: get mn, i.e. a.
; Append to get [b, a].
µ Begin a new monadic chain with argument [b, a].
ÆḊ Get the length of the vector, i.e. c.
; Append to get [b, a, c].
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 36 bytes
```
`@:Ut&+wmR&fZd1Mhw/vXutnGE<]GY)t&2|h
```
Input is 1-based. The output order guarantees that each triple appears exactly once. The order is explained in the following. The explanation requires delving a little into how the program works.
The code keeps increasing a counter `k` in a loop, starting at `1`. For each `k` it generates all pairs with `a = 1,...,k`, `b = 1,...,k`, `a < b`, and picks those that give a Pythagorean triple with `c <= k`. The pairs are obtained in order of increasing `b`, then `a`.
Each pair is then divided by its gcd. The resulting (possibly duplicated) pairs are arranged as a two-column matrix. This matrix is vertically concatenated with a similar matrix containing the accumulated results obtained for smaller values of `k`. The rows of the matrix are then stably deduplicated. This removes *two* types of duplicates:
1. Pairs that have been found more than once for the current `k` (such as `3,4`, which also results from `6,8` when dividing by its gcd);
2. Pairs that were already found with smaller `k`.
In fact, each iteration `k` finds all pairs that were already found for previous iterations. But it may find them *in a different order*. For example, `k=25` will find the triple `7,24,25` and not `20,21,29` (because `c` cannot exceed `k`). Later on, iteration `k=29` will find both, but with `20,21,29` *before* `7,24,25` (order is increasing `b`, then `a`). This is why, instead of keeping all pairs found for the latest `k`, we append them to the previous ones and deduplicate stably. Doing so assures that the order is the same for any input `n`.
The above guarantees that each primitive Pythagorean triple will eventually appear, and it will appear only once. For input `n`, the loop over `k` finishes when at least `n` valid triples have been obtained; and then the `n`-th triple is ouput.
[Try it online!](https://tio.run/##y00syfn/P8HBKrRETbs8N0gtLSrF0DejXL8sorQkz93VJtY9UrNEzagm4/9/QyMA "MATL – Try It Online")
Or use this modified code to see the first `n` triples:
```
`@:Ut&+wmR&fZd1Mhw/vXutnGE<]G:Y)tU&2sX^h
```
[Try it online!](https://tio.run/##y00syfn/P8HBKrRETbs8N0gtLSrF0DejXL8sorQkz93VJtbdKlKzJFTNqDgiLuP/fyMDAA)
[Answer]
# [Haskell](https://www.haskell.org/), 98 bytes
```
f 0=(3,4,5)
f n|let(a,b,c)=f$div(n-1)3;r=mod n 3;d=a*(-1)^2^r;e=b*(-1)^r;s=2*(d+e+c)=(s-d,s-e,s+c)
```
[Try it online!](https://tio.run/##JY5BDoIwFET3nuKHsPilhSBoYtLUE@jKpYoptgQiFNKibrx7LbqbN5OZTCvdQ/e99w3kAku2YVuyasB8ej2jZDW7E9HEqnuhSdek5FYMowIDJVdCJhi8qqgs16L@g@VOFAkqqmlooksVc6lmLpAfZGdAwCCn4w3wYiDdw/ScT7M9GIjBteM7LFMK0ZJEi/p5GP4QAuc8y3b51X8B "Haskell – Try It Online")
### How it works
This interprets the [bijective base-3](https://en.wikipedia.org/wiki/Bijective_numeration) digits of *n* as a path down the [tree of primitive Pythagorean triples](https://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples). It runs with no searching in O(log *n*) operations.
[](https://i.stack.imgur.com/0fuY6.png)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~19~~ 18 bytes
```
*g/²_/
4*œc3UṢÇÐḟḣ
```
The program takes a 1-based index **n** and prints the first **n** PPTs **[c, b, a]** in lexicographical order.
This is a **O(64n)** solution, so TIO will choke on inputs **4** and higher. I'll work on making it faster.
[Try it online!](https://tio.run/##AScA2P9qZWxsef//KmcvwrJfLwo0KsWTYzNV4bmiw4fDkOG4n@G4o////zM "Jelly – Try It Online")
### Alternate version, O(n3), *probably* valid
To find the **n**th triplet – **[cn, bn, an]** – the solution above assumes that **cn ≤ 4n**, which is easy to verify. However, [A020882](https://oeis.org/A020882) proves that **cn ~ 2πn**, so there is a **k** such that **cn ≤ kn** for all **n**.
If we can take **k = 7**, the solution below is also valid (and much, much faster).
```
*g/²_/
×7œc3UṢÇÐḟḣ
```
[Try it online!](https://tio.run/##ASkA1v9qZWxsef//KmcvwrJfLwrDlzfFk2MzVeG5osOHw5DhuJ/huKP///8xNg "Jelly – Try It Online")
### How it works
```
4*œc3UṢÇÐḟḣ Main link. Argument: n
4* Compute 4**n, the n-th power of 4.
œc3 Take all 3-combinations of the set {1, ..., 4**n}, each sorted in
ascending order. The triples themselves are sorted lexicographically.
U Upend; reverse each triple [a, b, c], yielding [c, b, a].
Ṣ Sort the descending triples lexicographically. This ensures that their
order is independent of n.
ÇÐḟ Keep only triples for which the helper link returns a falsy value.
ḣ Dyadic head; take the first n triples.
*g/²_/ Helper link. Argument: [c, b, a]
g/ Reduce [c, b, a] by greatest common divisor, yielding g.
* Elevate the integers to that power, computing [c**g, b**g, a**g].
² Square, yielding [c**2g, b**2g, a**2g].
_/ Reduce by subtraction, yielding c**2g - b**2g - a**2g.
Fermat's Last Theorem assures that this difference will be non-zero
whenever g > 1, so this yields 0 iff g = 1 and c² = a² = b².
```
[Answer]
## JavaScript (ES7), ~~106~~ ~~105~~ 103 bytes
Outputs the Nth PPT. Results are 1-indexed and ordered by the value of ***b***.
```
n=>(g=(a,b)=>b?g(b,a%b):a,F=a=>(x=a*a+b*b,c=x**.5|0)*c-x*g(a,g(b,c))||--n?F(a-b?a+1:!++b):[a,b,c])(b=1)
```
### Demo
```
let f =
n=>(g=(a,b)=>b?g(b,a%b):a,F=a=>(x=a*a+b*b,c=x**.5|0)*c-x*g(a,g(b,c))||--n?F(a-b?a+1:!++b):[a,b,c])(b=1)
for(n = 1; n <= 20; n++) {
console.log('#' + n + ' : ' + f(n));
}
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 63 bytes
```
3lvi:"t"[HlHllO;aOlOHl]!@Y*2eh]]!XuGY)&*tt[lO;Oa]*ssD2)ED2Xy*ss
```
[Try it online!](https://tio.run/##y00syfn/3zinLNNKqUQp2iPHIyfH3zrRP8ffIydW0SFSyyg1IzZWMaLUPVJTTaukJBoo658Yq1Vc7GKk6epiFFEJZP7/bwQA "MATL – Try It Online")
A lesson in golfing gone horribly wrong. I'm posting it anyway because I'm wondering if there are ways to golf this better.
I based this on [this](https://en.m.wikipedia.org/wiki/Coprime_integers) Wikipedia page in combination with Euclid's formula, to constructively generate all triples rather than trial-and-error approaches.
First, odd coprime pairs are generated as a ternary tree. This is done as a big matrix multiplication, accounting for most of the byte count. Then, Euclid's formula is applied, possibly also in a very byte-wasting manner. If anyone has tips for these two parts, I'd love to hear them.
Note that, to save bytes, this program generates a tree the same depth as the input, rather than `log3(n)`. Also, children are generated for each row rather than only for the last row of the tree, and then filtered again with `Xu`. So much for an efficient constructive approach.
```
3lv % Push root node of ternary tree
i:" % Generate a tree of depth of input (WAY too large, but golfy)
t" % loop over all nodes (golfier than looping over last tree row)
[HlHllO;aOlOHl]! % Matrix to generate three children of current node
@Y* % Multiply with current node to get children
2e % Reshape to get node pairs
h]] % Append to tree, exit loops
!Xu % Remove duplicates (more efficient to do it before last ] but golfier this way)
GY) % Select n-th odd coprime pair
&*tt % Multiply with it's own transpose to get [m²,m*n;m*n,n²]
[lO;Oa]*ssD % Sum of matrix multiplication = m²-n² to get a
2)ED % Second element doubled for b=2mn
2Xy*ss % Sum of matrix multiplication with identify matrix to get c=m²+n²
```
[Answer]
## Haskell, 65 bytes
```
([(a,b,c)|c<-[5..],b<-[1..c],gcd c b<2,a<-[1..b],a^2+b^2==c^2]!!)
```
0-based indexing. For a given `c`, `b` runs up to `c` and `a` up to `b`, so `c > b > a` always holds.
[Try it online!](https://tio.run/##y0gszk7Nyfn/P81WI1ojUSdJJ1mzJtlGN9pUTy9WJwnIMNTTS47VSU9OUUhWSLIx0kmEiCXF6iTGGWknxRnZ2ibHGcUqKmr@z03MzFOwVUjJ51JQUCgoyswrUVBRSFMwNETlm1r@BwA "Haskell – Try It Online")
[Answer]
# Python, ~~67~~ ~~50~~ ~~48~~ 46 Bytes
Using the formulas found on wikipedia,
`a=m*n, b=(m^2-n^2)/2, c=(m^2+n^2)/2`
where `m>n>0` and `m` and `n` are coprimes and odd. Here is the code
```
lambda n:[3+2*n,~-(3+2*n)**2-1/2,-~(3+2*n)**2/2]
```
-17 bytes thanks to @Martin Ender
[Try it Online](https://tio.run/##K6gsycjPM/7/P9E2JzE3KSVRIc8q2ljbSCtPp05XA8zQ1NIy0jfS0a1D5sb@LyjKzCvRSNQw0NTkgrENDZB5Jsaamv//AwA)
Works by always having the value of the `n` variable in the equation being 1, meaning that `m` simply is any other odd value, in this case, `3+2*n` where `n` is the number of the primitive Pythagorean triple. This allows us to assume the value of 1 for all `n` values.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 18 bytes
```
↑üOf§=F⌋ȯ¬Ḟ-m□ΠR3N
```
[Try it online!](https://tio.run/##ASkA1v9odXNr///ihpHDvE9mwqc9RuKMi8ivwqzhuJ4tbeKWoc6gUjNO////MQ "Husk – Try It Online")
-4 bytes thank to Zgarb, with inspiration from Dennis
Super-slow brute force approach, won't work on TIO for inputs larger than 1. You can try a more manageable version, limited to a,b≤200 [here](https://tio.run/##AS8A0P9odXNr///ihpHDvE9mwqc9RuKMi8ivwqzhuJ4tbeKWoc6gUjPhuKMyMDD///8yMA)
### Explanation
```
↑üOf§=F⌋ȯ¬Ḟ-m□ΠR3N
ΠR3N Get all triples of natural numbers
f Keep only those triples where
F⌋ their GCD
§= is equal to
ȯ¬Ḟ-m□ the logical negation of c²-b²-a²
üO Remove duplicates by their sorted version
↑ Get the first <input> values of this sequence
```
[Answer]
# Mathematica, 89 bytes
using Solve ordered by c
```
SortBy[{a,b,c}/.Solve[a^2+b^2==c^2&&GCD[a,b]==1&&0<a<b<c<9#,{a,b,c},Integers],Last][[#]]&
```
# Mathematica, 124 bytes
```
(s={};Table[If[IntegerQ[c=Sqrt[a^2+b^2]]&&GCD[a,b]==1,AppendTo[s,{a,b,c}]],{a,9#},{b,9#}];SortBy[Union[Sort/@s],Last][[#]])&
```
[Answer]
# R (+ numbers), 88 bytes
```
n=scan();while(all(nrow(T)<n))T=numbers::pythagorean_triples(5,5+(F<-F+1));T[n,3:5]
```
For using a builtin to generate the numbers, it takes actually a surprising amount of bytes to get what we want. The builtin takes two arguments `c1` and `c2`, and returns those triplets that have `c >= c1 & c <= c2`. This makes it slightly annoying to get to the `n`-th triplet. This will just keep increasing `c2` 1 at a time until the output is just enough rows.
[Answer]
# [PHP](http://php.net/docs.php), 273 Bytes
```
function t($n){$x=[];for($c=3;;$c++)for($b=2;$b<$c;$b++)for($a=2;$a<$b;$a++)if(d($a,$b,$c)&&$a**2+$b**2==$c**2){$x[]=[$a,$b,$c];if(--$n==0)return $x;}}function d($a,$b,$c){for($i=2;$i<$a;$i++)if($a%$i==0&&$b%$i==0||$a%$i==0&&$c%$i==0||$b%$i==0&&$c%$i==0)return 0;return 1;}
```
* `t($n)` returns an array of [a,b,c] with ordering `a < b < c`
* Returns a zero-based index
[Try it online!](https://tio.run/##dZLbTsJAEIav6VNMmlFbQTl4WRZjPEQSA8TgFXCxXRdaD9umbCMGfXac7bZCEG9mu98//@7MTtMo3Wy6l2mUOs3mOAEtlxp0JCHNkkXG3@Ej1hHMk@yday2fIcl1musG5EsJWa4839pecrItpLVmcpm/aUjmxU6RfzQaW4smg7G1O37gzHMldJwooqj8tVPDFZvMAqdG13ko2EUQoKjXjWJRyDoBhl0UFEtuBW4E3sWQYiXU4rn3TFIDwwYK//gY@elpp44hRcZQ0FIm0r2TGZtUqaaC0n92hoqxlm9BLZM6zxTgymZ8N5u3gxvo3znbzd3wER6Gw5FzgOyDav80uB73h4Pte@yUvS5fIzYdxl3kFMsOqT7kR6SwFjUX2q@vrx0mflm4z4qWyn5awd/aKq0d/F@mGSQNDszkKJ0VY6SzpIgScNVU259lqlw7U8lFBJ5JBb4EfJWfwHqAWfJRnGF9BT4Hd6o9l1ajTloz@jppwEkF2vugY4Dr26u2vdxeXd8ffuvL3mbzAw) (code is readable there too)
[Answer]
# C, 158 bytes
I believe this is my first submission here, so you can most probably do better.
```
#include<stdio.h>
void f(n){int i=0,j=3,k,l;while(1){for(k=1;k<j;k++){for(l=k;l<j;l++){if(j*j==k*k+l*l)i++;if(i==n){printf("%d %d %d",j,k,l);return;}}}j++;};}
```
And ungolfed version:
```
#include <stdio.h>
void f(n)
{
int i=0, j=3, k, l;
while (1) {
for (k=1; k<j; k++) {
for (l=k; l<j; l++) {
if (j*j==k*k+l*l)
i++;
if (i==n) {
printf("%d %d %d\n", j, k, l);
return;
}
}
}
j++;
};
}
void main()
{
int i;
scanf("%d", &i);
f(i);
printf("\n");
}
```
For *a2 + b2 = c2*, the ordering is increasing *c* then increasing *a*.
There can no be twice the same PPT as *b* is at leas *a* in this algorithm.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 25 bytes
```
⁽0(ḃs
Ɠḃd2Ḥ’×€Ç
3r5DṭÇæ×/
```
This is an implementation of the tree approach from [@AndersKaseorg's Haskell answer](https://codegolf.stackexchange.com/a/135760/12012), with a different branch order. The program uses 0-based indexing and takes input from STDIN.
[Try it online!](https://tio.run/##y0rNyan8//9R414DjYc7mou5jk0GUilGD3csedQw8/D0R01rDrdzGReZujzcufZw@@Flh6fr//9vaAAGAA "Jelly – Try It Online")
### Background
As mentioned on the Wikipedia page [Tree of primitive Pythagorean triples](https://en.wikipedia.org/wiki/Tree_of_primitive_Pythagorean_triples "Tree of primitive Pythagorean triples - Wikipedia"), every PPT can be obtained by repeatedly left-multiplying the row vector **(3, 4, 5)** by matrices with certain properties.
In each iteration, the previous result can be left-multiplied by either **A**, **B**, or **C**, which can be chosen as follows.

When **A**, **B**, and **C** are fixed, each PPT can be obtained in a unique fashion.
### How it works
```
3r5DṭÇæ×/ Main link. No arguments.
3 Set the argument and the return value to 3.
r5 Create a range from 3 to 5, i.e., [3, 4, 5].
D Decimal; convert each integer to base 10, yielding [[3], [4], [5]].
Ç Call the second helper link with argument 3.
ṭ Tack; append [[3], [4], [5]] to the result.
æ×/ Reduce by matrix multiplication.
```
```
Ɠḃd2Ḥ’×€Ç Second helper link. Argument: 3
Ɠ Read and evaluate one line of input, yielding an integer n.
ḃ Convert n to bijective base 3.
d2 Divmod 2; map each digit d to [d/2, d%2].
Ḥ Unhalve; multiply the results by 2.
’ Decrement the doubled results.
The previous four atoms apply the following mapping to the digits.
1 -> [0, 1] -> [0, 2] -> [-1, 1]
2 -> [1, 0] -> [2, 0] -> [ 1, -1]
3 -> [1, 1] -> [2, 2] -> [ 1, 1]
Ç Call the helper link with argument 3, yielding the following 2D array.
[[ 1, 2, 2],
[ 2, 1, 2],
[ 2, 2, 3]]
×€ Multiply each [-1, 1], [ 1, -1], and [ 1, 1] by that matrix, using
vectorizing multiplication (not matrix multiplication), yielding one
of the following three 2D arrays.
[[-1, 2, 2], [[ 1, -2, 2], [[ 1, 2, 2],
[-2, 1, 2], [ 2, -1, 2], [ 2, 1, 2],
[-2, 2, 3]] [ 2, -2, 3]] [ 2, 2, 3]]
```
```
⁽0(ḃs First helper link. Argument: 3
⁽0( Numeric literal; yield 13041.
ḃ Convert 13041 to bijective base 3, yielding [1, 2, 2, 2, 1, 2, 2, 2, 3].
s Split the result into chunks of length 3, yielding the aforementioned
2D array.
```
[Answer]
# APL(NARS), 90 chars, 180 bytes
```
{a⊃⍨⍵⊃⍋↑¨a←{⍵[⍋⍵]}¨a/⍨{1=∨/⍵}¨a←{(-/k),(×/2,⍵),+/k←⍵*2}¨a/⍨{>/⍵}¨a←,a∘.,a←⍳(⌊2⍟2+⍵)×9+⌊√⍵}
```
if the argument of the function above is ⍵, the above function would return the element of the index ⍵ (1 based)
of the array has elements Pythagorean triples (a,b,c) where a<=b<=c and that array is order first for a,
(the side more short), then for b (the other side not hypotenuse). There would be something wrong because
there is not seen where I order for b too... test:
```
f←{a⊃⍨⍵⊃⍋↑¨a←{⍵[⍋⍵]}¨a/⍨{1=∨/⍵}¨a←{(-/k),(×/2,⍵),+/k←⍵*2}¨a/⍨{>/⍵}¨a←,a∘.,a←⍳(⌊2⍟2+⍵)×9+⌊√⍵}
f¨1..10
3 4 5 5 12 13 7 24 25 8 15 17 9 40 41 11 60 61 12 35 37 13 84 85 15 112 113 16 63 65
```
it is related with <http://oeis.org/A020884> and <http://oeis.org/A020884/b020884.txt>
A020884: Ordered short legs of primitive Pythagorean triangles.
```
↑¨f¨1..23
3 5 7 8 9 11 12 13 15 16 17 19 20 20 21 23 24 25 27 28 28 29 31
f 999
716 128163 128165
f 1000
717 28556 28565
```
I don't know if it is right, it seems function give correct result of first side of triangle until 1000
but I don't know for the remain, and possible could be some triple not right too even <1000.
[Answer]
# JavaScript, 101 bytes
By Euclid's formula all primitive Pythagorean triples can be generated from integers `m` and `n` with `m>n>0`, `m+n` odd `gcd(m,n)==1` ([Wikipedia](https://en.wikipedia.org/wiki/Pythagorean_triple#Enumeration_of_primitive_Pythagorean_triples))
This function enumerates all `m,n` pair incrementing m starting from `m=2` and decrementing `n` by 2 starting from `m-1` (so that `m+n` is odd)
```
c=>eval("g=(a,b)=>b?g(b,a%b):a;for(m=2,n=1;c-=g(m,n)<2;(n-=2)>0||(n=m++));[m*m-n*n,2*m*n,m*m+n*n]")
```
*Less golfed*
```
c => {
g = (a,b) => b ? g(b,a%b) : a;
for( m = 2, n = 1;
g(m,n) < 2 ? --c : c;
(n -= 2) > 0 || (n = m++))
/* empty for body */;
return [m*m - n*n, 2*m*n, m*m + n*n]
}
```
**Test**
```
F=
c=>eval("g=(a,b)=>b?g(b,a%b):a;for(m=2,n=1;c-=g(m,n)<2;(n-=2)>0||(n=m++));[m*m-n*n,2*m*n,m*m+n*n]")
for(i=1;i<=50;i++) console.log(i+' '+F(i))
```
] |
[Question]
[
Write a program or function that takes in a string of the characters `-=o.` where the `-=o`'s and `.`'s always alternate, character to character. The string will have an odd length greater than one and always start and end in one of `-=o`.
Basically, the input will look like a line of emoticon faces that share eyes in various states of sleepiness, e.g.
```
o.=.=.-.-.o.o
```
Your goal is to print or return the face that is either the sleepiest or the most awake (it's up to you which you choose). If there are multiple choices for who is sleepiest/most awake then any one of them may be output.
There are nine distinct faces and five levels of sleepiness:
```
-.- is 100% sleepy
-.= is 75% sleepy
-.o is 50% sleepy
=.- is 75% sleepy
=.= is 50% sleepy
=.o is 25% sleepy
o.- is 50% sleepy
o.= is 25% sleepy
o.o is 0% sleepy
```
In case it's not clear, the sleepiness percentage is computed by assigning `1` to `-` for fully asleep, `0.5` to `=` for half asleep, and `0` to `o` for awake. Then the sum of the two eye values divided by two is the percentage.
**The shortest code in bytes wins.**
# Test Cases
**Sleepiest**
```
-.- GIVES -.-
=.- GIVES =.-
o.o GIVES o.o
o.-.= GIVES -.=
=.-.= GIVES =.- OR -.=
o.-.= GIVES -.=
-.-.= GIVES -.-
o.o.- GIVES o.-
=.=.=.o GIVES =.=
-.=.=.= GIVES -.=
=.o.-.= GIVES -.=
o.-.o.=.= GIVES o.- OR -.o OR =.=
-.o.-.=.= GIVES -.=
o.o.o.o.o GIVES o.o
-.-.-.-.- GIVES -.-
o.=.=.-.-.o.o GIVES -.-
-.=.-.o.o.=.o.-.o.=.-.o.=.o.- GIVES -.= OR =.-
```
**Most Awake**
```
-.- GIVES -.-
=.- GIVES =.-
o.o GIVES o.o
o.-.= GIVES o.-
=.-.= GIVES =.- OR -.=
o.-.= GIVES o.-
-.-.= GIVES -.=
o.o.- GIVES o.o
=.=.=.o GIVES =.o
-.=.=.= GIVES =.=
=.o.-.= GIVES =.o
o.-.o.=.= GIVES o.=
-.o.-.=.= GIVES -.o OR o.- OR =.=
o.o.o.o.o GIVES o.o
-.-.-.-.- GIVES -.-
o.=.=.-.-.o.o GIVES o.o
-.=.-.o.o.=.o.-.o.=.-.o.=.o.- GIVES o.o
```
[Answer]
# Pyth, ~~12~~ 10 bytes
```
hoSN%2.:z3
```
This prints the sleepiest emoticon. Verify all test cases at once in the [Pyth Compiler](https://pyth.herokuapp.com/?code=hoSN%252.%3Az3&test_suite=1&test_suite_input=-.-%0A%3D.-%0Ao.o%0Ao.-.%3D%0A%3D.-.%3D%0Ao.-.%3D%0A-.-.%3D%0Ao.o.-%0A%3D.%3D.%3D.o%0A-.%3D.%3D.%3D%0A%3D.o.-.%3D%0Ao.-.o.%3D.%3D%0A-.o.-.%3D.%3D%0Ao.o.o.o.o%0A-.-.-.-.-%0Ao.%3D.%3D.-.-.o.o%0A-.%3D.-.o.o.%3D.o.-.o.%3D.-.o.%3D.o.-&debug=0).
*Credit goes to @Sp3000 for [the idea to use sorting](http://chat.stackexchange.com/transcript/message/25556328#25556328).*
### How it works
```
hoSN%2.:z3
(implicit) Save the in z.
.:z3 Compute all substrings of length 3.
%2 Keep every seconds substring. This discards non-emoticons.
o Sort the emoticons by the following key:
SN Sort the characters of the emoticon.
This works since '-' < '=' < 'o'.
h Retrieve the first, minimal element.
```
[Answer]
# Python 2, ~~54~~ 53 bytes
```
f=lambda s:s and max((s+' ')[:3],f(s[2:]),key=sorted)
```
This is a function that returns the face that is most awake.
Many thanks to xnor for providing many tactical tricks to shorten my original algorithm.
[Answer]
# CJam, 12 bytes
```
q3ew2%{$}$0=
```
This prints the sleepiest emoticon. Try [this fiddle](http://cjam.aditsu.net/#code=q3ew2%25%7B%24%7D%240%3D&input=-.%3D.-.o.o.%3D.o.-.o.%3D.-.o.%3D.o.-) or [this test suite](http://cjam.aditsu.net/#code=qN%2F%7BS%2F(%3AQ%3B1%3E%0A%20%20Q3ew2%25%7B%24%7D%240%3D%0Ae%3D%7D%2F&input=-.-%20GIVES%20-.-%0A%3D.-%20GIVES%20%3D.-%0Ao.o%20GIVES%20o.o%0Ao.-.%3D%20GIVES%20-.%3D%0A%3D.-.%3D%20GIVES%20%3D.-%20OR%20-.%3D%0Ao.-.%3D%20GIVES%20-.%3D%0A-.-.%3D%20GIVES%20-.-%0Ao.o.-%20GIVES%20o.-%0A%3D.%3D.%3D.o%20GIVES%20%3D.%3D%0A-.%3D.%3D.%3D%20GIVES%20-.%3D%0A%3D.o.-.%3D%20GIVES%20-.%3D%0Ao.-.o.%3D.%3D%20GIVES%20o.-%20OR%20-.o%20OR%20%3D.%3D%0A-.o.-.%3D.%3D%20GIVES%20-.%3D%0Ao.o.o.o.o%20GIVES%20o.o%0A-.-.-.-.-%20GIVES%20-.-%0Ao.%3D.%3D.-.-.o.o%20GIVES%20-.-%0A-.%3D.-.o.o.%3D.o.-.o.%3D.-.o.%3D.o.-%20GIVES%20-.%3D%20OR%20%3D.-) in the CJam interpreter.
*Credit goes to @Sp3000 for [the idea to use sorting](http://chat.stackexchange.com/transcript/message/25556328#25556328).*
### How it works
```
q e# Read all input from STDIN.
3ew e# Push all overlapping slices of length 3.
2% e# Keep every seconds slice. This discards non-emoticons.
{$}$ e# Sort the slices by their sorted characters.
e# This works since '-' < '=' < 'o'.
0= e# Retrieve the first, minimal slice.
```
[Answer]
## Dyalog APL, ~~35~~ 28 bytes
```
{⊃{⍵[⍒{+/'.??o='⍳⍵}¨⍵]}3,/⍵}
```
This is a monadic function that takes the string on the right and outputs the sleepiest face.
```
{⊃{⍵[⍒{+/'.??o='⍳⍵}¨⍵]}3,/⍵}'o.=.=.-.-.o.o'
-.-
```
[Answer]
# Prolog, ~~205~~ 189 bytes
**Code**
```
r([X|T],[N|B],M):-N=M,write(X);r(T,B,M).
p(X):-findall(S,sub_atom(X,_,3,_,S),L),findall(E,(nth1(I,L,E),I mod 2=\=0),R),maplist(atom_codes,R,Q),maplist(sum_list,Q,S),min_list(S,M),r(R,S,M).
```
**Explanation**
```
r([X|T],[N|B],M):-N=M,write(X);r(T,B,M).
p(X):-findall(S,sub_atom(X,_,3,_,S),L), % L = all sublists of length 3
findall(E,(nth1(I,L,E),I mod 2=\=0),R), % R = every other element of L
maplist(atom_codes,R,Q), % Q = list of decimal ascii codes
created from R
maplist(sum_list,Q,S), % S = list of sums of R's lists
min_list(S,M), % M = minimum sum
r(R,S,M). % Prints first element in R with sum M
```
**Example**
```
>p('-.=.-.o.o.=.o.-.o.=.-.o.=.o.-').
-.=
```
**Edit:** Saved 16 bytes by unifying r-clauses with OR.
[Answer]
**Clojure, 82 bytes**
```
(fn[x](println(apply str(apply min-key #(reduce +(map int %))(partition 3 2 x)))))
```
Bonus: the following smaller function prints the same face, but with more style!
```
(fn[x](println(apply min-key #(reduce +(map int %))(partition 3 2 x))))
```
[Test here.](http://www.tryclj.com/)
[Answer]
## Ruby, 59 bytes
Function returns sleepiest face, using the sorting trick.
```
f=->(s){s.split(?.).each_cons(2).min_by{|e|e.sort}.join(?.)}
```
Called like this:
```
f.call("o.=.=.-.-.o.o")
# => "-.-"
```
Works on awkward eye order due to internal sort of eyes:
```
f.call("=.-.o")
# => "=.-"
```
[Answer]
## [Minkolang 0.12](https://github.com/elendiastarman/Minkolang), 119 bytes
At first, I tried doing this short and really golfy. I gave up and went for something a bit more "fun", but still relatively golfy.
```
>2@fv$oI2:[9[i$z3[iciz1+q=]++3=tt"^"3zpt]$x$x]IX3140w
o.o1F
o.=1$
=.o1+
=.=12
o.-1:
-.o11
=.-1+
-.=13
-.-1[
/c0i<
\qO].
```
[Try it here!](http://play.starmaninnovations.com/minkolang/?code=%3E2%40fv%24oI2%3A%5B9%5Bi%24z3%5Biciz1%2Bq%3D%5D%2B%2B3%3Dtt%22%5E%223zpt%5D%24x%24x%5DIX3140w%0Ao%2Eo1F%0Ao.%3D1%24%0A%3D.o1%2B%0A%3D.%3D12%0Ao.-1%3A%0A-.o11%0A%3D.-1%2B%0A-.%3D13%0A-.-1%5B%0A%2Fc0i%3C%0A%5CqO%5D.&input=-%2E%3D.-.o.o.%3D.o.-.o.%3D.-.o.%3D.o.-)
### Explanation
But really, click on the link above and click `Slow`! Anyway...
```
>2@fv
```
This skips over the `fv`, which will be important later.
```
$o Read in whole input as characters
I2: Half the stack length
[ Open for loop (for each face)
9[ Open another for loop - 9 repeats
i$z Stores loop counter in register
3[ Open another for loop - 3 repeats
ic Copy char 1/2/3
iz1+q Retrieve char from lookup table
= 1 if equal, 0 otherwise
] Close for loop
++ Add twice
3= 1 if equal to 3, 0 otherwise
tt t Ternary - executes first part when 0,
second part otherwise
"^"3zp Put a ^ next to the face that matched
] Close lookup for loop
$x$x Dump first two characters
] Close for loop
IX Dump the whole stack
31 Push a 3, then a 1
40w Wormhole to (4,0) in the code
```
What all that did was put a `^` next to the faces that matched. So now the codebox might look like this:
```
>2@fv$oI2:[9[i$z3[iciz1+q=]++3=tt"^"3zpt]$x$x]IX3140w
o.o1F
o.=1$
=.o1+
=.=^2 <-- caret
o.-^: <-- caret
-.o11
=.-1+
-.=^3 <-- caret
-.-1[
/c0i<
\qO].
```
Without the comments, of course. Now, the `40w` wormhole sent the instruction pointer to `v`, which immediately redirects it onto `F`. Now, `F` is a "gosub" command. It's like a goto, but you can return to where you called it. At the time `F` is encountered, the stack is `[3,1]`, so it jumps to the `1` (maybe) on the second row. As the program counter was heading downwards, it continues, pushing `1`s onto the stack along the way. That is...until it hits a `^`, at which point it's redirected back up, where it pushes each `1` again. The instruction pointer then hits `f`, which restores its position and direction (when `F` was encountered earlier). For convenience, I will take the following code and change its layout. (The `</\` serve to redirect the instruction pointer as needed.)
```
$+ Sum up the whole stack
2: Divide by 2 (because each 1 was pushed twice)
1+ Add 1 (shift down one row)
3[ Open for loop - 3 repeats
i Push loop counter
0c Copy top of stack
q Retrieve face character
O Output as character
]. Close for loop and stop when it's done.
```
I'm actually kinda proud of how I used multiple features unique to Minkolang that I haven't often used before. Mainly the ternary and the gosub. Anyway, there you have it!
[Answer]
# C, 70 bytes
```
char*f(char*s){char*p=s[3]?f(s+2):s;return*s+s[2]>*p+p[2]?s[3]=0,s:p;}
```
The function returns the most awake face. It modifies the input string in place, so as to return a null-terminated string.
[Answer]
# Python 2/3, 54 ~~56~~ bytes
```
lambda x:".".join(max(zip(x[::2],x[2::2]),key=sorted))
```
Just wanted to take an alternative tack to xsot's recursive answer.
This takes the best (or worst?) tuple of adjacent pairs of eyes and joins them together.
Replace max with min to return the most sleepy (as is this returns the most awake)
Seems to work, using the following test:
```
for line in """-.- GIVES -.-
=.- GIVES =.-
o.o GIVES o.o
o.-.= GIVES o.-
=.-.= GIVES =.- OR -.=
o.-.= GIVES o.-
-.-.= GIVES -.=
o.o.- GIVES o.o
=.=.=.o GIVES =.o
-.=.=.= GIVES =.=
=.o.-.= GIVES =.o
o.-.o.=.= GIVES o.=
-.o.-.=.= GIVES -.o OR o.- OR =.=
o.o.o.o.o GIVES o.o
-.-.-.-.- GIVES -.-
o.=.=.-.-.o.o GIVES o.o
-.=.-.o.o.=.o.-.o.=.-.o.=.o.- GIVES o.o""".splitlines():
inp, _, opts = line.partition(" GIVES ")
optst = opts.split(" OR ")
act = f(inp)
print(inp, "expected", opts, "got", act, "equal?", act in optst)
```
Which gives the following result:
```
-.- expected -.- got -.- equal? True
=.- expected =.- got =.- equal? True
o.o expected o.o got o.o equal? True
o.-.= expected o.- got o.- equal? True
=.-.= expected =.- OR -.= got =.- equal? True
o.-.= expected o.- got o.- equal? True
-.-.= expected -.= got -.= equal? True
o.o.- expected o.o got o.o equal? True
=.=.=.o expected =.o got =.o equal? True
-.=.=.= expected =.= got =.= equal? True
=.o.-.= expected =.o got =.o equal? True
o.-.o.=.= expected o.= got o.= equal? True
-.o.-.=.= expected -.o OR o.- OR =.= got =.= equal? True
o.o.o.o.o expected o.o got o.o equal? True
-.-.-.-.- expected -.- got -.- equal? True
o.=.=.-.-.o.o expected o.o got o.o equal? True
-.=.-.o.o.=.o.-.o.=.-.o.=.o.- expected o.o got o.o equal? True
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
s₃ᶠġ₂hᵐoᵒh
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6k4O4Z5hqsoFRu/6htw6Ompoe7Omsfbp3wv/hRU/PDbQuOLASKZQAF8h9unZTx/3@0kq6erpKOgpIthMrXy4dQunq2UGEIAy6iixDJh2kFwXyIJJgDEc1H1psPE9eFiCPMAEOYyWAIkQGZpAvWCTcazNGDmJwP5YN5SrEA "Brachylog – Try It Online")
Translated from Dennis' Pyth answer.
[Answer]
# Mathematica, 61 bytes
```
"."
Sort[Partition[#~StringSplit~%,2,1]][[1]]~StringRiffle~%&
```
Goes for the sleepiest one.
[Answer]
# F# 60
```
fun s->Seq.max[for n in 0..2..String.length s-2->s.[n..n+2]]
```
Returns the most awake face (change `max` by `min` for the sleepest)
[Answer]
## Perl 5, 127 bytes
```
%h=qw[- 2 = 1];sub r{$b=0;$b+=$h{$_}for split'',pop;$b}($_)=<>;@a='o.o';while(/.../g){push@a,$& if(r$&)>r$a[-1];--pos}say$a[-1]
```
(I'm sure it's doable more briefly.) How it works:
1. Grab each three-character string from the string, with overlap by one (that's what the `--pos` does).
2. Append that three-character string to an array if its value exceeds that of the last element of the array; here, "value" is just the sum of its characters' values in sleepiness.
3. Print the last element of the array.
[Answer]
## ES6, ~~81~~ 72 bytes
```
a=>"-.-,-.=,=.-,-.o,=.=,o.-,=.o,o.=,o.o".split`,`.find(b=>a.includes(b))
```
Probably requires Chrome 45 or Firefox 41.
Thanks to @ETHproductions for saving 9 bytes.
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 55 bytes
[try it here!](http://fishlanguage.com/playground/ZMePES245vyjACmfR)
```
<v~i:i&0"."0
>i:@+:&:@)?v&~i0(?v
^?)0i:r~r&~<;ooo$r<
```
Outputs most awake face.
Since the ASCII values for -, =, and o increase respectively, I could use that to my advantage. Basically it adds the values of the current and previous eye part, check if it's a higher value than before, if it is it saves the new value and updates what face that represents, then loops until the end of the input. Then outputs the face that remains. (I'm very pleased at how nicely all the code fits in place)
[Answer]
# [Perl 5](https://www.perl.org/) `-MList::Util=max -p`, 68 bytes
```
s|..(?=(.))|$t=max$t,ord($&)%15%4+ord($1)%15%4 .$&.$1|eg;$_=$t;s/.//
```
[Try it online!](https://tio.run/##K0gtyjH9/7@4Rk9Pw95WQ09Ts0alxDY3sUKlRCe/KEVDRU1T1dBU1UQbzDGEcBT0VNT0VAxrUtOtVeJtVUqsi/X19PX//7fV09XL/5dfUJKZn1f8X9fXVM/A0ABI@2QWl1hZhZZk5oBM/q9bAAA "Perl 5 – Try It Online")
Grabs each set of three characters, ignores the `.` in the middle, maps the addition of the other two to an integer in the range 0-4, concatenates that to the front of the emoticon face, then sorts by that. Grabs the last entry (most awake), removes the number from the front, and outputs it.
] |
[Question]
[
`your shift key is broken. wheNever you type two lines, the cApitaL`
`LetteRs in them get swappeD. you must write a program to fiX THIS!`
## Description
The input is two strings, `s1` and `s2`, equal in length. They will each contain only printable ASCII and be at least one character in length. You may input these as two strings, an array of two strings, or a single string with `s1` and `s2` separated by either a tab or newline.
The output is the following:
* For each character `c` in `s1`:
+ If the character is not a letter, output it unchanged.
+ Otherwise, if `c` is a letter:
- Find the matching character (the one at the same index) in `s2`.
* If it is a capital letter, output `c` capitalized.
* If it is a lowercase letter, output `c` in lowercase.
* Otherwise, output `c` unchanged.
* Then do the same thing, except with `s1` and `s2` switched.
Essentially, all letters in `s1` for which the matching character in `s2` is capital should be capitalized, and all letters in `s1` with a lowercase letter at the same index in `s2` should become lowercase (and vice versa).
## Test cases
Input:
```
ABCDEfghijKlMnOpqrstuvwxyz
aaaaaaaaaaaaaaaa----------
```
Output:
```
abcdefghijklmnopqrstuvwxyz
AAAAAaaaaaAaAaAa----------
```
---
Input:
```
PRogrammiNG puzZLes & CODe golf
SdlkhkfaladlKsdlalksdg7ldklDgsl
```
Output:
```
Programming Puzzles & Code Golf
SDlkhkfalADlksdLAlksdg7LDkldgsl
```
---
Input:
```
AAAbbb111
Cc2Dd3Ee4
```
Output:
```
AaABbb111
CC2dd3Ee4
```
[Answer]
# CJam, 25 bytes
```
{z{_el_eu&\__:^32&f^?}%z}
```
This is an anonymous function that pops an array of strings from the stack and leaves one in return.
In supported browsers, you can verify all test cases at once in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%2F2%2F%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Read%20input%20and%20split%20into%20arrays%20of%20two%20strings.%0A%0A%7Bz%7B_el_eu%26%5C__%3A%5E32%26f%5E%3F%7D%25z%7D%0A%0A%25%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Map%20the%20block%20over%20all%20string%20arrays.%0A%3A%2BN*%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20%20e%23%20Separate%20the%20strings%20by%20linefeeds.&input=ABCDEfghijKlMnOpqrstuvwxyz%0Aaaaaaaaaaaaaaaaa----------%0APRogrammiNG%20puzZLes%20%26%20CODe%20golf%0ASdlkhkfaladlKsdlalksdg7ldklDgsl%0AAAAbbb111%0ACc2Dd3Ee4).
### Test cases
**Code**
```
qN/2/ e# Read input and split into arrays of two strings.
{z{_el_eu&\__:^32&f^?}%z}
% e# Map the block over all string arrays.
:+N* e# Separate the strings by linefeeds.
```
**Input**
```
ABCDEfghijKlMnOpqrstuvwxyz
aaaaaaaaaaaaaaaa----------
PRogrammiNG puzZLes & CODe golf
SdlkhkfaladlKsdlalksdg7ldklDgsl
AAAbbb111
Cc2Dd3Ee4
```
**Output**
```
abcdefghijklmnopqrstuvwxyz
AAAAAaaaaaAaAaAa----------
Programming Puzzles & Code Golf
SDlkhkfalADlksdLAlksdg7LDkldgsl
AaABbb111
CC2dd3Ee4
```
### How it works
```
z e# Zip to transform the array of strings into an array
e# of character pairs.
{ }% e# For each character pair:
_el e# Push a copy and convert to lowercase.
_eu e# Push a copy and convert to uppercase.
& e# Intersect. The result will be an empty string if
e# and only if both characters are letters.
\ e# Swap the character pair on top of the stack.
__ e# Push two copies.
:^ e# XOR both characters.
32& e# Logical AND with 32. This pushes 32 for letters of
e# different cases and 0 for letters of the same case.
f^ e# XOR each character with the result.
? e# Select the original copy for non-empty intersection
e# and the modified one otherwise.
z e# Zip to turn the characters pairs back into two strings.
```
[Answer]
# C, 126 bytes
This is my first attempt at a code golf, ever. Let me know if I did anything wrong.
I'm using bitwise operations to perform the switching
Golfed:
```
main(u,a,s,t)char**a,*s,*t;{for(s=a[1],t=a[2];*t;s++,t++)isalpha(*s)*isalpha(*t)?u=(*t^*s)&32,*t^=u,*s^=u:0;*s=10;puts(a[1]);}
```
Ungolfed:
```
main(u,a,s,t) char**a,*s,*t; { // K&R style arguments
for(s=a[1],t=a[2];*t;s++,t++) // initialize loop.
isalpha(*s) * isalpha(*t) ? // ensure both characters are letters (if)
u = (*t^*s) & 0x20, // check if characters have swapped case
*t^=u, // if so, xor the bit which represents case
*s^=u // for both characters in the string.
:0; // end ternary statement (endif)
*s=10; // replace null terminator in first string
puts(a[1]); // with newline. This allows both output to
} // be printed out all at once
```
edit: replaced && with \*
[Answer]
# Pyth, ~~19~~ 18 bytes
```
LCmrW&@dG@drG1d2Cb
```
This defines a function **y** that accepts and return a list of strings.
Verify all test cases at once in the [Pyth Compiler/Executor](https://pyth.herokuapp.com/?code=LCmrW%26%40dG%40drG1d2Cb%0A%0Ajb%2BFmydc.z2&input=ABCDEfghijKlMnOpqrstuvwxyz%0Aaaaaaaaaaaaaaaaa----------%0APRogrammiNG+puzZLes+%26+CODe+golf%0ASdlkhkfaladlKsdlalksdg7ldklDgsl%0AAAAbbb111%0ACc2Dd3Ee4&debug=0).
*Thanks to @Jakube for golfing off 1 byte.*
### How it works
```
" (implicit) Initialize G to 'abcdefghijklmnopqrstuvwxyz'.
L " Define y(b):
Cb " Zip to turn the two strings into an array of char pairs.
m " Map (implicit variable d):
@dG " Intersect d with G.
@drG1 " Intersect d with G.upper().
W& " If both are non-empty:
r d2 " Apply swapcase() to d.
C " Zip to turn the character pairs back into two strings.
```
[Answer]
# SQL (PostGreSQL), 427 Bytes
Despite it's huge size, this ended up being quite a bit smaller than I expected. I wasn't quite sure I was going to be able to do it to be honest. I suspect there is a lot that still can be done:)
```
CREATE FUNCTION F(TEXT,TEXT)RETURNS TABLE(S TEXT) AS'SELECT unnest(array[string_agg(CASE WHEN T~''[A-Z]''THEN upper(S)WHEN T~''[a-z]''THEN lower(S)ELSE S END,''''),string_agg(CASE WHEN S~''[A-Z]''THEN upper(T)WHEN S~''[a-z]''THEN lower(T)ELSE T END,'''')])FROM(SELECT ROW_NUMBER()OVER()N,S FROM regexp_split_to_table($1,'''')X(S))A JOIN(SELECT ROW_NUMBER()OVER()M,T FROM regexp_split_to_table($2,'''')Y(T))B ON N=M'LANGUAGE SQL
```
Formatted and commented
```
-- Declare the function spec
CREATE FUNCTION F(TEXT,TEXT)RETURNS TABLE(S TEXT) AS
'SELECT unnest( -- turns array into a table
array[ -- build array of the column results
string_agg( -- Aggregate the result into a string
CASE
WHEN T~''[A-Z]''THEN upper(S) -- uppercase it if corresponding char is uppercase
WHEN T~''[a-z]''THEN lower(S) -- lowercase it if corresponding char is lowercase
ELSE S END
,''''),
string_agg( -- Same as the previous but swap strings
CASE
WHEN S~''[A-Z]''THEN upper(T)
WHEN S~''[a-z]''THEN lower(T)
ELSE T END
,'''')
])
FROM
-- split the first string
(SELECT ROW_NUMBER()OVER()N,S FROM regexp_split_to_table($1,'''')X(S))A
JOIN
-- split the second string
(SELECT ROW_NUMBER()OVER()M,T FROM regexp_split_to_table($2,'''')Y(T))B
ON N=M
'
LANGUAGE SQL
```
Test run
```
SELECT F(A,B) AS Result
FROM (VALUES
('AAAbbb111', 'Cc2Dd3Ee4'),
('ABCDEfghijKlMnOpqrstuvwxyz', 'aaaaaaaaaaaaaaaa----------'),
('PRogrammiNG puzZLes & CODe golf', 'SdlkhkfaladlKsdlalksdg7ldklDgsl')
)A(A,B)
Result
-----------------------------
AaABbb111
CC2dd3Ee4
abcdefghijklmnopqrstuvwxyz
AAAAAaaaaaAaAaAa----------
Programming Puzzles & Code Golf
SDlkhkfalADlksdLAlksdg7LDkldgsl
```
[Answer]
# Julia, 140 bytes
```
f(s,t)=(C(x,y)=(i=0;z="";for c=x i+=1;z*=string(isalpha(c)?isupper(y[i])?uppercase(c):islower(t[i])?lowercase(c):c:c)end;z);(C(s,t),C(t,s)))
```
This creates a function that accepts two strings and returns a tuple of strings. Nothing particularly clever is going on here; we simply define an inner function that directly implements the algorithm in the spec and call it twice.
Ungolfed:
```
function f(s, t)
C(x, y) = begin
i = 0
z = ""
for c in x
i += 1
if isalpha(c)
if isupper(y[i])
z *= string(uppercase(c))
elseif islower(y[i])
z *= string(lowercase(c))
else
z *= string(c)
end
else
z *= string(c)
end
end
return z
end
return (C(s, t), C(t, s))
end
```
[Answer]
# JavaScript ES6, ~~128~~ 108 bytes
```
s=(a,b,t)=>[...a].map((l,i)=>/[^a-z]/.exec(b[i])?l.toUpperCase():l.toLowerCase()).join``+(t?'':`
`+s(b,a,1))
```
JavaScript's `toUpperCase()` and `toLowerCase()` take up a lot of bytes but `String.fromCharCode()` is even longer
[Answer]
## Mathematica, ~~173~~ ~~169~~ 155 bytes
```
f=0>1;t=!f;c=Characters;u=ToUpperCase;StringJoin/@MapThread[#@#2&,{Reverse[{LetterQ@#,#==(u@#)}&/@c@#/.{{f,_}->(#&),{t,t}->u,{t,f}->ToLowerCase}&/@#],c/@#},2]&
```
This is a function taking an array of two strings, e.g. `{"Foo","bAR"}` and outputting an array of two strings. Un-spatially-compressing it, rewriting the scheme `f@x` as `f[x]` wherever it appears, expanding the notation abbreviations (`f=0>1` a.k.a. `False`,`t=!f` a.k.a. `True`, `c=Characters`, and `u=ToUpperCaseQ`), and un-replacing UpperCaseQ[#] with `#==u@#` (this character equals its uppercased version), it is:
```
StringJoin /@ MapThread[#[#2] &, {
Reverse[
{ LetterQ[#], UpperCaseQ[#] } & /@ Characters[#] /.
{ {False, _} -> (# &), {True, True} -> ToUpperCase,
{True, False} -> ToLowerCase } & /@ #
],
Characters /@ #
}, 2] &
```
Interfacing: the trailing `&` makes this a function. Its argument is inserted as the "#" at both instances of `/@ #`. For instance `f=0>1; ... & [{"AAAbbb111", "Cc2Dd3Ee4"}]` produces the output `{AaABbb111,CC2dd3Ee4}`.
Processing: Told in usual outside in order:
* The output of the `MapThread[...]` is a list of two lists of characters. StringJoin is applied to each of these two lists of characters to produce a list of two strings, the output.
* `MapThread[#[#2]&, ... , 2]` acts on an array of two 2-by-n element lists. The first list is a 2-by-n array of functions. The second list is a 2-by-n array of characters, `Characters /@ #`, the lists of characters in the two input strings. It works at depth 2, i.e., on the functions and individual characters.
* `Reverse[...]` swaps the two sublists of functions so that MapThread will apply the second string's functions to the first string and vice versa.
* `{ ... } &` is an anonymous function that is applied to each of the two input strings.
* `{LetterQ[#], UpperCaseQ[#]} & /@ Characters[#]` splits a string into a list of characters, then replaces each character with two element lists. In these two element lists, the first element is `True` if the character is a letter and `False` otherwise, similarly, the second element indicates whether the character is upper case. `UpperCaseQ[]` cannot return true if it does not receive a letter.
* `/. {{False, _} -> (# &), {True, True} -> ToUpperCase, {True, False} -> ToLowerCase}` replaces these two element lists with functions. (Expansion of the abbreviations `t` and `f` occurs before any matching is attempted.) If a two element list has `False` as its first element, it is replaced with the function `(# &)`, the identity function. (The parentheses are necessary, otherwise the arrow binds more tightly than the ampersand.) Otherwise the two element list starts with `True`, the character was a letter, and we output the functions `ToUpperCase` and `ToLowerCase` corresponding to its case. (Checking for this last `False` is unnecessary, in fact `{_,_}->ToLowerCase` would work, catching anything that hadn't been replaced yet, but this would be no shorter and more obscure.)
The only challenge was figuring out a succinct way to zip a two dimensional array of functions to an array of arguments.
Edit: Thanks to @Martin Büttner for catching "helpful" cut/paste linebreak backslashes, the `1>0` and `1<0` abbreviations, and also for the guidance to count length in bytes not characters (whatever those are :-) )
Edit2: Further thanks to @Martin Büttner for pointing out that polluting the global namespace is acceptable golf, reminding me of one character function application, and suggesting replacing the two uppercase functions with an abbreviation for one and using the one to emulate the other (saving four characters). (I think he's done this before. :-) )
[Answer]
# Python 3, 131 bytes
```
def j(s,g):p=lambda s,g:''.join(i.upper()if j.istitle()else i.lower()if j.islower()else i for i,j in zip(s,g));return p(s,g),p(g,s)
```
Function returns strings in a tuple
[Answer]
# Erlang, 157 bytes
```
f(A,B)->S=string,G=fun(A,B)->[if Q>64andalso Q<91->S:to_upper(P);Q>96andalso Q<123->S:to_lower(P);true->P end||{P,Q}<-lists:zip(A,B)]end,G(A,B)++"\n"++G(B,A).
```
Zips the two strings (actually, lists) into a two-character-tuple list and maps each character to the appropriate case using a list comprehension.
[Answer]
# Python 2, 101 bytes
```
lambda*I:["".join([a.upper(),a.lower(),a][~-b.isalpha()or"Z"<b]for a,b in zip(*X))for X in I,I[::-1]]
```
An anonymous function which takes two strings and returns the output strings in a list. I've marked this as Python 2 because Python 3 doesn't allow `I,I[::-1]` to sit alone at the end like that.
[Answer]
# Python, 126 bytes
```
t="".join;s="low","upp";y=lambda a,b:eval("a"+".%ser()"%s[b.isupper()]*b.isalpha());f=lambda a,b:(t(map(y,a,b)),t(map(y,b,a)))
```
Function `f` returns strings in a tuple
[Answer]
# C, 181 bytes
```
char*x,*y;main(int a,char**_){a?x=_[2],y=_[1],main(0,0),putchar(10),x=_[1],y=_[2],main(0,0):(*x?putchar(!isupper(*x)?!islower(*x)?*y:tolower(*y):toupper(*y)),x++,y++,main(0,0):0);}
```
Had trouble shortening standard library names in a worthwhile way, (#define'ing them takes 11 characters of overhead). Uses main recursion and global variables x and y as arguments.
main(<non-zero>,argv) = call main(0,{argv[1],argv[2]}) then print newline then call main(0,{argv[2],argv[1]})
main(0,{x,y}) = if x is end of string return 0, else print correct case of first character of x and call main(0,{x+1,y+1}).
Run with the two strings as arguments.
[Answer]
# C - ~~164~~ 153 Bytes - GCC
```
#define r z[_][w]
main(_,z,w)char**z;{while(--_)for(w=0;r;r+=r<25?97:r<91&&r>64?z[!(_-1)+1][w]-=32,_-1?z[_-1][w]-=97:0,32:0,w++);puts(z[1]),puts(z[2]);}
```
gcc prog.c
./a.out AfdgF a2dfsd
Will update if I can get wc -c down. Works very well actually
[Answer]
# F#, 211 chars
```
let n x y=List.fold2(fun a i j->a@match j with|c when c>='A'&&c<='Z'->[Char.ToUpper i]|c when c>='a'&&c<='z'->[Char.ToLower i]|_->[i])[](x|>Seq.toList)(y|>Seq.toList)|>String.Concat
let m a b =n a b+"\n"+n b a
```
could be better ...
[Answer]
## Matlab, 140
```
function [s,t]=f(s,t)
c=s>96&s<123;C=s>64&s<91;d=t>96&t<123;D=t>64&t<91;s(c&D)=s(c&D)-32;s(C&d)=s(C&d)+32;t(d&C)=t(d&C)-32;t(D&c)=t(D&c)+32;
```
Ungolfed:
```
function [s,t] = f(s,t)
c = s>96 & s<123; % letters that are lowercase in 1st string
C = s>64 & s<91; % letters that are uppercase in 1st string
d = t>96 & t<123; % letters that are lowercase in 2nd string
D = t>64 & t<91; % letters that are uppercase in 2nd string
s(c&D) = s(c&D) - 32; % make uppercase in 1st string
s(C&d) = s(C&d) + 32; % make lowercase in 1st string
t(d&C) = t(d&C) - 32; % make uppercase in 2nd string
t(D&c) = t(D&c) + 32; % make lowercase in 2nd string
```
Example:
```
>> [s,t]=f('PRogrammiNG puzZLes & CODe golf','SdlkhkfaladlKsdlalksdg7ldklDgsl')
s =
Programming Puzzles & Code Golf
t =
SDlkhkfalADlksdLAlksdg7LDkldgsl
```
[Answer]
# C, 164 bytes
Pretty much implementing the algorithm as described in the problem. Takes 2 strings as input parameters.
```
char*a,*b;main(c,v)char**v;{for(a=v[1],b=v[2];*a&&*b;++a,++b)isupper(*a)&&islower(*b)?*a+=32,*b-=32:isupper(*b)&&islower(*a)?*b+=32,*a-=32:0;puts(v[1]);puts(v[2]);}
```
Ungolfed:
```
char *a, *b; /* Helpers */
main(c, v)
char **v;
{
/* While strings not terminated... */
for (a = v[1], b = v[2]; *a && *b; ++a, ++b)
isupper(*a) && islower(*b)
? *a += 32, *b -= 32 /* Make first string lowercase, second uppercase */
: isupper(*b) && islower(*a)
? *b += 32, *a -= 32; /* Make second string lowercase, first uppercase */
puts(v[1]); /* print out first string */
puts(v[2]); /* print out second string */
}
```
[Answer]
## Ruby, 102
```
$><<gets.chars.zip(gets.chars).map{|i|/[a-z][A-Z]|[A-Z][a-z]/=~i*''?(i.map &:swapcase):i}.transpose*''
```
Takes the original strings, pairs off letters in arrays. If they are either lower/cap or cap/lower, then swapcase on both. Then transpose the arrays back into our ordered array.
This requires a trailing newline in input.
[Answer]
# Perl 5.10+, 101 99 bytes
```
perl -p00e '/\n/;s/([a-z])(?=.{$-[0]}([a-z]))/$x=($1^$2)&" ";$s{$-[2]}=$2^$x;$1^$x/egis;s|.|$s{$-[0]}//$&|eg'
```
96 bytes + 3 bytes for the command line flags `p00`. Takes a single newline-delimited string as input:
```
$ echo -e "AAAbbb111\nCc2Dd3Ee4" | perl -p00e '...'
```
Or you can enter input on STDIN:
```
$ perl -p00e '...'
AAAbbb111 <Enter>
Cc2Dd3Ee4 <Ctrl+D>
```
## Broken down:
```
perl -p00e' # Slurp everything into $_, print $_ automatically at the end
/\n/; # Match first newline, setting $-[0] to length(s1)
s/
([a-z]) # Match a single letter in s1
(?=
.{$-[0]} # Match n chars where n is length(s1) (until corresponding char in s2)
([a-z]) # Corresponding letter in s2
)
/
$x=($1^$2)&" "; # Check whether bit 6 is the same for both chars.
# (Only difference between a lowercase and uppercase ASCII letter
# is bit 6; ASCII space is 100000 in binary)
$s{$-[2]}=$2^$x; # Swap case of corresponding char in s2 and store in %s,
# with position as the key
$1^$x # Swap case of current char
/egis;
s|.|$s{$-[0]}//$&|eg # Do a second pass through $_. If there's a value stored in %s
# corresponding to this position, use it
'
```
[Answer]
# First attempt in scala, 138 chars
```
def f(s:String,t:String)={val g=(a:Char,o:Char)=>if(o.isUpper)a.toUpper else a.toLower;s.zip(t).map(c=>(g.tupled(c),g(c._2, c._1))).unzip}
```
f is a function that take the two input strings and do the job, with a local function, used two times, for changing case of strings.
The same code, with indentation and just a litte more readable names :
```
def f_ungolfed(first : String, second : String) = {
val aux = (c1: Char, c2: Char) => if (c2.isUpper) c1.toUpper else c1.toLower
first.zip(second).map(
c => (aux.tupled(c), aux.tupled(c.swap))
).unzip
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 13 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
=Œu=/ị"Ɱż"Œs$
```
A monadic Link accepting and returning lists of two "strings" (lists of characters in Jelly).
**[Try it online!](https://tio.run/##ATUAyv9qZWxsef//PcWSdT0v4buLIuKxrsW8IsWScyT/4bu0w4dZ//9Db2RlR29sZgp4eFBQQ0d4eA "Jelly – Try It Online")**
[Answer]
# [Python 2](https://docs.python.org/2/), 97 bytes
```
lambda a,b:''.join([x,chr(ord(x)&95|ord(y)&32)][(x+y).isalpha()]for x,y in zip(a+'\n'+b,b+' '+a))
```
[Try it online!](https://tio.run/##XZDBT8IwFMbP@lf0RNtskjA0RhIPY1t2QGTBmBiBQ0vXraysswPpFv/3SZ148J2@933v/Q5f1RxyVXodf1x3kuwpI4C4dALhcKdEiVbG3eYaKc2QwYOHuy@rGjwYe3izQsZp8FDURFY5QXjDlQbGbYAoQSsqRBy4LqFDXepAAB2CcWcvznh7sULQnwZhxLNc7GZyXi6qD10fjp8n07TQBZD8m5u/gdgFCCZLlWmy34vnGFTH9v0prcEABIswBZmS3CJemCzyghNJmJzVTBJZ1Cy7l6yQYVbLnuP7PqV0NBrZj2DrhWwcpbd9FiiWxmfYT2ZMkgSxZ0yfSXVKtfVfkyRa9t5cvKWh9fqw59vd/9XTLbNrxOMc4s3k@qrSojwAchH0Ijg694Rd22D3DQ "Python 2 – Try It Online")
[Answer]
# [Tcl](http://tcl.tk/), 194 bytes
```
proc C a\ b {proc L x\ y {expr [[set S string] is u $y]?"[$S tou $x]":"[$S is lo $y]"?"[$S tol $x]":"$x"}
lmap x [split $a ""] y [split $b ""] {append s [L $x $y]
append t [L $y $x]}
list $s $t}
```
[Try it online!](https://tio.run/##XZBBT4NAEIXv@yteNsSbh6qJiReD0HgoWmNvUg5LFygywMouCm347bjQ1oNz@@blvckbs6NxVE29gwexRYzjDAG6LXock041CEOdGGygTZNXWYRco4XTR488dDYwtYUu4g8zWY3qSeQXlc6q0/GBUSkUOoRaUW7gCHAe2TsXjmc@CqWSSkIjDKx5SmPnlZlX/RRpw3JtPRqOGcY5@FSAuU@ev0yzff65opdqrb4abdrvn64/MPFvrv@GMf72XmeNKMv89RmqPXwEicYVvLWfIKsp5WwjqdgXqSAhaaUlCSq0zO5JFuRnmhhzXTeO48ViwbzdjS9vl8kdG@xLW2O7eFNfJ4621TD@Ag "Tcl – Try It Online")
[Answer]
# [Haskell](https://www.haskell.org/), ~~109~~ 91 bytes
```
import Data.Char
(!)=zipWith f
f c|isUpper c=toUpper|isAlpha c=toLower|1<3=id
a#b=[b!a,a!b]
```
Thanks to @Laikoni for 16 bytes!
[Try it online!](https://tio.run/##XYxBS8NAEIXv@RWTFKSFKsQKXppDTIqHplYsIrQUmc0m2TWTZN3dWg3973FpwYPvMo9veJ9AUxdEwyAb1WkLKVq8SQRqb@xPol6qN2kFlF4J@UmaV6UKDXlku3NzJCYl8Eyy7uhIOJ9Fkns4YtGO@ThFn@2HBmULETSoVu8wvhx1sBurs3biwQ6C@CFJF2Ul5MeSVu1afWpjD1/H758@GAX4L9d/CTyYQvD80lUam0Y@PTptv80KA1eQrNMCqo5KZ9hwqkVdIiGnpeGEVBte3ROvKa0MXTRxHDPGwjB0gyS/TflsUdy51374BQ "Haskell – Try It Online")
] |
[Question]
[
# Input
An alphanumeric string `s`.
# Output
The shortest string that occurs exactly once as a (contiguous) substring in `s`.
Overlapping occurrences are counted as distinct.
If there are several candidates of the same length, you must output all of them in the order of occurrence.
In this challenge, the empty string occurs `n + 1` times in a string of length `n`.
# Example
Consider the string
```
"asdfasdfd"
```
The empty string occurs 10 times in it, so it is not a candidate for unique occurrence.
Each of the letters `"a"`, `"s"`, `"d"`, and `"f"` occurs at least twice, so they are not candidates either.
The substrings `"fa"` and `"fd"` occur only once and in this order, while all other substrings of length 2 occur twice.
Thus the correct output is
```
["fa","fd"]
```
# Rules
Both functions and full programs are allowed, and standard loopholes are not.
The exact formatting of the output is flexible, within reason.
In particular, producing no output for the empty string is allowable, but throwing an error is not.
The lowest byte count wins.
# Test cases
```
"" -> [""]
"abcaa" -> ["b","c"]
"rererere" -> ["ererer"]
"asdfasdfd" -> ["fa","fd"]
"ffffhhhhfffffhhhhhfffhhh" -> ["hffff","fffff","hhhhh","hfffh"]
"asdfdfasddfdfaddsasadsasadsddsddfdsasdf" -> ["fas","fad","add","fds"]
```
# Leaderboard
Here's the by-language leaderboard that I promised.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
```
<script src='https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js'></script><script>site = 'meta.codegolf',postID = 5314,isAnswer = true,QUESTION_ID = 45056;jQuery(function(){var u='https://api.stackexchange.com/2.2/';if(isAnswer)u+='answers/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJeRCD';else u+='questions/'+postID+'?order=asc&sort=creation&site='+site+'&filter=!GeEyUcJFJO6t)';jQuery.get(u,function(b){function d(s){return jQuery('<textarea>').html(s).text()};function r(l){return new RegExp('<pre class="snippet-code-'+l+'\\b[^>]*><code>([\\s\\S]*?)<\\/code><\/pre>')};b=b.items[0].body;var j=r('js').exec(b),c=r('css').exec(b),h=r('html').exec(b);if(c!==null)jQuery('head').append(jQuery('<style>').text(d(c[1])));if (h!==null)jQuery('body').append(d(h[1]));if(j!==null)jQuery('body').append(jQuery('<script>').text(d(j[1])))})})</script>
```
[Answer]
# Python 3, ~~124~~ ~~123~~ ~~111~~ 96 bytes
```
f=lambda s,n=1:[x for x in[s[i:i+n]for i in range(len(s)+1)]if s.find(x)==s.rfind(x)]or f(s,n+1)
```
Looks for strings such that the first occurrence from the left is the same as the first occurrence from the right. The `+1` in the `range` is to accommodate for the empty string case.
Now if only Python had a `.count()` which counted *overlapping* matches, then this would have been a fair bit shorter.
[Answer]
# Mathematica, ~~95~~ ~~94~~ 79 bytes
```
Cases[Tally@StringCases[#,___,Overlaps->All],{s_,1}:>s]~MinimalBy~StringLength&
```
`StringCases` gets me all possible substrings, the `Tally` and `Cases` filter out those that appear more than once and `MinimalBy` finds those that are shortest.
[Answer]
## GolfScript, 44 bytes
```
:S;-1:x{;S,x):x-),{S>x<}%:^1/{^\/,2=},.!}do`
```
Takes input as a string on stdin and outputs in a double-array syntax: e.g. `[["b"] ["c"]]`. [Online demo](http://golfscript.apphb.com/?c=IyMgVGVzdCBmcmFtZXdvcmsKOycKYWJjYWEKcmVyZXJlcmUnbi97CiMjCgo6UzstMTp4eztTLHgpOngtKSx7Uz54PH0lOl4xL3teXC8sMj19LC4hfWRvYAoKIyMgVGVzdCBmcmFtZXdvcmsKcHV0c30vCiMj)
### Dissection
```
:S; # Store input in S and pop it
-1:x # Store -1 in x
{ # do-while loop
; # Pop x the first time and [] every subsequent time
S,x):x-), # Increment x and build an array [0 1 ... len(S)-x]
{S>x<}% # Map that array to [substr(S,0,x) substr(S,1,x) ...]
:^ # Store in ^ (to avoid the token coalescing with the next char)
1/ # Split by length 1 to iterate over 1-elt arrays rather than strings
{^\/,2=}, # Filter to arrays which occur exactly once as a subarray of ^
.! # Duplicate and test emptiness
}do # end do-while loop: loop if the filtered array is empty
` # Stringify for output
```
This is arranged such that no special case is required for the empty string (which I've included as a test case in the online demo linked above).
[Answer]
# Pyth, ~~27~~ 26 bytes
```
&zhfTmf!/>zhxzYYm<>zkdUzUz
```
[Try it here.](https://pyth.herokuapp.com/)
Note that due to a bug in the online compiler, the empty string case only works correctly on the command line version, which can be found [here.](https://github.com/isaacg1/pyth)
You can also cure the bug by giving a newline as the input for the online compiler.
### Explanation:
```
z = input(), implicit.
&z Prints empty string if input is empty.
hfT Take the first non-empty list from
m Uz A list of list of substrings of z, divided by length
m<>zkdUz with some shorter strings repeated later, to no effect.
f Where the substrings are filtered on
!/ Y There being 0 occurrences of the substring in
>z The slice of z
hxzY from the character after the first character
of the first occurrence of the substring in z
to the end of z.
```
[Answer]
# CJam, ~~52 43~~ 40 bytes
```
]]q:Q,,{)Q,1$-),f{Q><}:R{R\a/,2=},}%{}=p
```
Input is the string without quotes
**Explanation**:
```
]] "For empty string input case";
q:Q "Read the input and store in Q";
,, "Take length of input and 0 to length array";
{ }% "Map the above array on this code block";
)Q "Increment the number in the current iteration, L";
Q,1$ "Take input's length and copy the above number";
-) "Get upper limit of next loop to get substrings";
,f{ } "Get 0 to above number array and for each";
Q>< "Get the L length substring at Ith index where";
"I loops from 0 to Q, - L + 1";
:R "Store this list of substring of length L in R";
{R\a/,2=}, "Filter to get unique substrings";
{}= "Get the first non empty substring array";
"This leaves nothing on stack if all are empty";
p "Print the top stack element. At this point, its";
"Either the first non empty substring array or";
"the ]] i.e. [""] which we added initially";
```
Example:
```
asdfdfasddfdfaddsasadsasadsddsddfdsasdf
```
Output
```
["fas" "fad" "add" "fds"]
```
[Try it online here](http://cjam.aditsu.net/)
[Answer]
# Scala, 120 bytes
```
readLine.inits.flatMap(_.tails).toList.groupBy(l=>l).filter(x=>x._2.length<2).map(_._1).groupBy(_.length).minBy(_._1)._2
```
I started off with 140 which at least already fits into a tweet.
```
( // added for comments
readLine // input
.inits.flatMap(_.tails).toList // get all substrings of that string
.groupBy(l=>l).filter(x=>x._2.length<2) // remove substrings that occur more than once
.map(_._1).groupBy(_.length) // take the substring and group by length
.minBy(_._1)._2 // take the list of shortest substrings
)
```
[Answer]
# JavaScript (ES6), 109 ~~110~~
**Edit** search instead of indexOf, as the input string is alphanumeric. Thanks @IsmaelMiguel
Recursive function, looking for substrings starting with length 1 and going up.
```
F=(s,n=1,r)=>
s?[...s].map((a,i)=>~s.indexOf(a=s.substr(i,n),s.search(a)+1)?r:r=[...r||[],a])&&r||F(s,n+1):[s]
```
**Ungolfed** and explained
```
F = function(s, n=1) { // start with length 1
var i, a, p, r;
if (s == "") // special case for empty input string
return [s];
for (i = 0; i < s.length; i++)
// for each possibile substring of length n
// (should stop at s.length-n+1 but going beyond is harmless)
// Golfed: "[...s].map((a,i)" ... using i, a is overwrittem
{
a = s.substr(i, n); // substring at position i
p = s.search(a); // p is the first position of substring found, can be i or less
p = s.indexOf(a, p + 1) // p is now the position of a second instance of substring, or -1 if not found
if (~p) // ~p is 0 if p is -1
{
; // found more than once, do nothing
}
else
{
r = r || []; // if r is undefined, then it becomes an empty array
r.push(a); // save substring
// Golfed: "r=[...r||[],a]"
}
}
if (r) // if found some substring, saved in r
{
return r;
}
return F(s, n+1) // recursive retry for a bigger length
}
```
**Test** In FireFox/FireBug console
```
;["", "abcaa", "rererere", "asdfasdfd", "ffffhhhhfffffhhhhhfffhhh",
"asdfdfasddfdfaddsasadsasadsddsddfdsasdf"]
.forEach(x=>console.log(x,F(x)))
```
*Output*
```
[""]
abcaa ["b", "c"]
rererere ["ererer"]
asdfasdfd ["fa", "fd"]
ffffhhhhfffffhhhhhfffhhh ["hffff", "fffff", "hhhhh", "hfffh"]
asdfdfasddfdfaddsasadsasadsddsddfdsasdf ["fas", "fad", "add", "fds"]
```
[Answer]
# Java, 168 ~~176 233~~
Here's a pretty basic nested loop example.
```
void n(String s){for(int l=0,i=0,t=s.length(),q=0;l++<t&q<1;i=0)for(String b;i<=t-l;)if(s.indexOf(b=s.substring(i,i+++l),s.indexOf(b)+1)<0){System.out.println(b);q++;}}
```
Or a *bit* more readable:
```
void t(String s){
for(int l=0,i=0,t=s.length(),q=0;l++<t&q<1;i=0)
for(String b;i<=t-l;)
if(s.indexOf(b=s.substring(i,i++ +l),s.indexOf(b)+1)<0){
System.out.println(b);
q++;
}
}
```
[Answer]
# Haskell, 169 162 155 153 151 138 120 115
```
import Data.List
l=length
q k=filter$(==)k.l
p y=q(minimum.map l$y)$y
f x=p$concat$q 1$group$sort$(tails x>>=inits)
```
To use it:
```
f "asdfdfasddfdfaddsasadsasadsddsddfdsasdf"
```
Which gives:
```
["add","fad","fas","fds"]
```
Btw. I hate the last line of my code (repetition of `h y`). Anyone hints to get rid of it?
[Answer]
## J, ~~61~~ ~~58~~ ~~44~~ ~~42~~ ~~40~~ ~~38~~ 37 bytes
```
[:>@{.@(#~#@>)#\<@(~.#~1=#/.~)@(]\)]
```
Here is a version split up into the individual components of the solution:
```
unqs =. ~. #~ 1 = #/.~ NB. uniques; items that appear exactly once
allsbsq =. #\ <@unqs@(]\) ] NB. all unique subsequences
shrtsbsq =. [: >@{.@(#~ #@>) allsbsq NB. shortest unique subsequence
```
* `x #/. y` computes for each distinct element in `x` how often in occurs in `y`. If we use this as `y #/. y`, we get the for each distinct element in `y` its count. For instance, `a #/. a` for `a =. 1 2 2 3 4 4` yields `1 2 1 2`.
* `1 = y` checks which items of `y` are equal to `1`. For instance, `1 = a #/. a` yields `1 0 1 0`.
* `u~` is the *reflexive* of a monadic verb `u`. This is, `u~ y` is the same as `y u y`. Thus, `#/.~ y` is the same as `#/.~ y`. When applied to a dyadic verb, `u~` is the *passive* of `u`. That is, `x u~ y` is the same as `y u x`. These are used in quite a few other places which I do not explicitly mention.
* `~. y` is the *nub* of `y`, a vector with duplicates removed. For instance, `~. a` yields `1 2 3 4`.
* `x # y` (*copy*) selects from `y` the items at the indices where `x` contains a `1`.
* Thus, `(1 = y #/. y) # (~. y)` creates a vector of those elements of `y` which appear only once. In tacit notation, this verb is written as `~. #~ 1 = #/.~`; let's call this phrase `unqs` for the rest of the explanation.
* `x ]\ y` creates an `x` by `1 + y - x` array of all *infixes* of the vector `y` of length `x`. For instance, `3 ]\ 'asdfasdfd` yields
```
asd
sdf
dfa
fas
asd
sdf
dfd
```
* `# y` is the *tally* of `y`, that is, the number of elements in `y`.
* `u\ y` applies `u` to each *prefix* of `y`. Incidentally, `#\ y` creates a vector of integers from `1` to `#y`.
* `< y` puts `y` into a box. This is needed because arrays cannot be ragged and we compute an array of suffixes of different lengths; a boxed array counts as a scalar.
* Thus, `(i. # y) <@:unqs@(]\) y` generates a vector of `#y` boxed arrays of the length *k* (for all 0 ≤ *k* < `#y`) infixes of *y* that occur exactly once. The tacit form of this verb is `i.@# <@unqs@(]\) ]` or `i.@# <@(~. #~ 1 = #/.~)@(]\) ]` if we don't use the `unqs` name. Let's call this phrase `allsbsq` for the rest of this explanation. For instance, `allsbsq 'asdfasdfd'` yields:
```
┌┬─┬──┬───┬────┬─────┬──────┬───────┬────────┐
││ │fa│dfa│sdfa│asdfa│asdfas│asdfasd│asdfasdf│
││ │fd│fas│dfas│sdfas│sdfasd│sdfasdf│sdfasdfd│
││ │ │dfd│fasd│dfasd│dfasdf│dfasdfd│ │
││ │ │ │sdfd│fasdf│fasdfd│ │ │
││ │ │ │ │asdfd│ │ │ │
└┴─┴──┴───┴────┴─────┴──────┴───────┴────────┘
```
* `(#@> y) # y` takes from vector of boxed arrays `y` those which aren't empty.
* `{. y` takes the first element of vector `y`.
* `> y` removes the box from `y`.
* Thus, `> {. (#@> y) # y` yields the unboxed first non-empty array from vector of boxed arrays `y`. This phrase is written `>@{.@(#~ #@>)` in tacit notation.
* Finally, `[: >@{.@(#~ #@>) allsbsq` assembles the previous phrase with `allsbsq` to create a solution to the problem we have. Here is the full phrase with spaces:
```
[: >@{.@(#~ #@>) i.@# <@(~. #~ 1 = #/.~)@(]\) ]
```
[Answer]
# Haskell, 135 Bytes
```
import Data.List
f ""=[""]
f g=map(snd)$head$groupBy(\a b->fst a==fst b)$sort[(length y,y)|[y]<-group$sort[x|x@(_:_)<-tails g>>=inits]]
```
[Answer]
# PHP, ~~171~~ ~~152~~ ~~134~~ 125
```
function f($s){while(!$a&&++$i<strlen($s))for($j=0;$b=substr($s,$j++,$i);)strpos($s,$b)==strrpos($s,$b)&&($a[]=$b);return$a;}
```
<http://3v4l.org/RaWTN>
[Answer]
# Groovy (Java regex on Oracle implementation), 124
```
c={m=it=~/(?=(.*?)(?=(.*))(?<=^(?!.*\1(?!\2$)).*))/;o=m.collect({it[1]});o.findAll({it.size()==o.min({it.size()}).size()});}
```
Tested on Groovy 2.4 + Oracle JRE 1.7. The regex should work for Java 6 to Java 8, since the bug that allows the code above to work is not fixed. Not sure for previous version, since there is a look-behind bug in Java 5 which was fixed in Java 6.
The regex finds the shortest string which doesn't have a duplicate substring elsewhere, at every position in the input string. The code outside takes care of filtering.
```
(?=(.*?)(?=(.*))(?<=^(?!.*\1(?!\2$)).*))
```
* Since the strings can overlap, I surround the whole thing in look-ahead `(?=...)`.
* `(.*?)` searches from the shortest substring
* `(?=(.*))` captures the rest of the string to mark the current position.
* `(?<=^(?!.*\1(?!\2$)).*)` is an emulation of variable-length look-behind, which takes advantage of the implementation bug which allows `(?<=.*)` to pass the length check.
* `(?!.*\1(?!\2$))` simply checks that you can't find the same substring elsewhere. The `(?!\2$)` rejects the original position where the substring is matched.
The limit of the outer look-around construct doesn't apply to the nested look-around construct. Therefore, the nested negative look-ahead `(?!.*\1(?!\2$))` actually checks for the whole string, not just up to the right boundary of the look-behind.
[Answer]
# Rebol, 136 bytes
```
f: func[s][repeat n length? b: copy s[unless empty? x: collect[forall s[unless find next find b t: copy/part s n t[keep t]]][return x]]]
```
Ungolfed:
```
f: func [s] [
repeat n length? b: copy s [
unless empty? x: collect [
forall s [
unless find next find b t: copy/part s n t [keep t]
]
][return x]
]
]
```
Usage example:
```
>> f ""
== none
>> f "abcaa"
== ["b" "c"]
>> f "rererere"
== ["ererer"]
>> f "asdfasdfd"
== ["fa" "fd"]
>> f "ffffhhhhfffffhhhhhfffhhh"
== ["hffff" "fffff" "hhhhh" "hfffh"]
>> f "asdfdfasddfdfaddsasadsasadsddsddfdsasdf"
== ["fas" "fad" "add" "fds"]
```
NB. I suppose the heart of the code is how the [`find`](http://www.rebol.com/r3/docs/functions/find.html) part is working. Hopefully this will help explain...
```
>> find "asdfasdfd" "df"
== "dfasdfd"
>> next find "asdfasdfd" "df"
== "fasdfd"
>> find next find "asdfasdfd" "df" "df"
== "dfd"
>> ;; so above shows that "df" is present more than once - so not unique
>> ;; whereas below returns NONE because "fa" found only once - ie. bingo!
>> find next find "asdfasdfd" "fa" "fa"
== none
```
[Answer]
# Haskell, 119
```
f s=[r|n<-[1..length s],l<-[map(take n)$take(length s-n+1)$iterate(drop 1)s],r<-[[j|j<-l,[j]==[r|r<-l,r==j]]],r/=[]]!!0
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 10 bytes
```
sᶠ≡ᵍ~gˢlᵍt
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/jhtgWPOhc@3Npbl356UQ6QLvn/P1pJSUcpMSk5MRFIF6VCIEioOCUNhFOA7DQgyACCNBgjA0JDlYEVgqmUlOLE4kQokZICFi0GKVGKBQA "Brachylog – Try It Online")
```
sᶠ The list of every substring of the input
≡ᵍ grouped by identity,
~gˢ with length-1 groups converted to their elements and other groups discarded,
lᵍ and grouped by their length,
t has the output as its last group.
```
Although `ᵍ` doesn't naturally sort by the value it groups by, instead ordering the groups by the first occurrence of each value, the first occurrences of every length are in decreasing order. I'm not 100% sure that the uniqueness filtering can't mess this up, but I haven't come up with a test case this fails yet.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 10 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
Œʒ¢}é.γg}н
```
Outputs nothing for an empty string.
[Try it online](https://tio.run/##yy9OTMpM/f//6KRTkw4tqj28Uu/c5vTaC3v//08sTkkD4RQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@PTjo16dC64kOLag@v1Du3Ob32wt7/Ov@jlZR0lBKTkhMTgXRRKgSChIpT0kA4BchOA4IMIEiDMTIgNFQZWCGYSkkpTixOhBIpKWDRYpASqB1JySAGCCjFAgA).
**Explanation:**
```
Œ # Get all substrings of the (implicit) input-String
ʒ # Filter it by:
¢ # Count how many times the current substring occurs in the (implicit) input-String
# (only 1 is truthy in 05AB1E, so the filter will leave unique substrings)
}é # After the filter: sort the remaining substrings by length
.γg} # Then group them by length as well
н # And only leave the first group containing the shortest substrings
# (which is output implicitly as result)
```
This takes advantage of 05AB1E's only having `1` as truthy value, and everything else as falsey. The shortest unique substring is always guaranteed to occur exactly once for all possible input-strings. (For an input-string containing only the same characters (i.e. `aaaaa`), the input-strings itself as substring occurs just once, so the result is `["aaaaa"]`. For an input-String with repeating pattern (i.e. `"abcabc"`), there are still unique substrings that only occur once (`["abca","abcab","abcabc","bca","bcab","bcabc","ca","cab","cabc"]`), so this will result in `["ca"]`.)
[Answer]
# Python 2, 150
```
import re
a=input()
r=range
l=len(a)
d=0
for i in r(l):
if d:break
for j in r(l-i):
k=a[j:i+j+1]
if len(re.findall("(?="+k+")",a))<2:d=1;print k
```
[Answer]
# [Perl 5](https://www.perl.org/) `-a`, ~~114~~ 87 bytes
```
map{//;(grep$' eq$_,@q)-1||($l||=y///c)-y///c||say}@q=map{"@F"=~/(?=(.{$_}))/g}1..y///c
```
[Try it online!](https://tio.run/##K0gtyjH9/z83saBaX99aI70otUBFXSG1UCVex6FQU9ewpkZDJaemxrZSX18/WVMXTNXUFCdW1joU2oJ0KTm4KdnW6WvY22roVavE12pq6qfXGurpgVX@/5@YmJT0L7@gJDM/r/i/rq@pnoGhwX/dRAA "Perl 5 – Try It Online")
Old method:
[114 bytes](https://tio.run/##JYxBCoMwEAC/0oZFFGNWD55CMKfe@oYirdWAJCGrlCL5etOUznWG8VNY@5Qe7oB7XUu4KaYvTL4Ws04lCqwOFFlFlMAVFNLvtOjAgZvnibAcFPAKcVaqK4rzHCaPwJFr@oeUQ0l5gzHudjOrDpLGN9OBpTT@@Di/GWcpNddetF2bGjt@AQ "Perl 5 – Try It Online")
] |
[Question]
[
[Stack Exchange doesn't know how to transpose tables.](https://meta.stackexchange.com/a/357504/317948) Let's help.
**Given a markdown table, transpose it.**
Input assumptions:
* There will be at least two rows (including header) and two columns
* Either all cells have no leading space or all cells have exactly one leading space (you must handle both)
* If the cells have a leading space, then the widest cell in every column has exactly one trailing space, otherwise, the widest cell in every column has no trailing spaces
* All pipes line up
* The header-body separator lines of dashes extend the full width of their column, except a leading and tailing space if the table uses this
* Cell alignment (`-:`, `:-:`, etc.) is not used
* No other extraneous spaces appear (this includes between words)
* Either all rows have a trailing pipe or no rows have a trailing pipe (you must handle both)
* Cells contain only printable ASCII, but no pipes (`|`), dashes (`-`) or any characters that need special treatment (`\`, `**`, etc.)
* All cells will have at least *some* non-space content
Output requirements:
* Trailing pipe on every row or no trailing pipes (must be consist for any one result)
* Either no leading spaces, or exactly one leading space in every cell (must be consist for any one result)
* If you produce leading spaces, then the widest cell in each column must have exactly one trailing space
* All pipes must line up
* The header-body separator must extend to the full width of the column, save for leading and trailing spaces, if used in that result
* Trailing spaces (and up to one trailing line break) are acceptable
# Test cases
## A
### Test inputs (you must handle every one of these)
```
| A header | Another header |
| -------- | -------------- |
| First | row |
| Second | row |
```
```
| A header | Another header
| -------- | --------------
| First | row
| Second | row
```
```
|A header|Another header|
|--------|--------------|
|First |row |
|Second |row |
```
```
|A header|Another header
|--------|--------------
|First |row
|Second |row
```
### For any of the above inputs, output must be any one of the below (not necessarily corresponding 1:1)
```
| A header | First | Second |
| -------------- | ----- | ------ |
| Another header | row | row |
```
```
| A header | First | Second
| -------------- | ----- | ------
| Another header | row | row
```
```
|A header |First|Second|
|--------------|-----|------|
|Another header|row |row |
```
```
|A header |First|Second
|--------------|-----|------
|Another header|row |row
```
## B
### Test inputs (you must handle every one of these)
```
| A header | Another header | Last column here |
| -------- | -------------- | ----------------- |
| First | 0 | more content here |
| Second | row | that's it! |
```
```
| A header | Another header | Last column here
| -------- | -------------- | -----------------
| First | 0 | more content here
| Second | row | that's it!
```
```
|A header|Another header|Last column here |
|--------|--------------|-----------------|
|First |0 |more content here|
|Second |row |that's it! |
```
```
|A header|Another header|Last column here
|--------|--------------|-----------------
|First |0 |more content here
|Second |row |that's it!
```
### For any of the above inputs, output must be any one of the below (not necessarily corresponding 1:1)
```
| A header | First | Second |
| ---------------- | ----------------- | ---------- |
| Another header | 0 | row |
| Last column here | more content here | that's it! |
```
```
| A header | First | Second
| ---------------- | ----------------- | ----------
| Another header | 0 | row
| Last column here | more content here | that's it!
```
```
|A header |First |Second |
|----------------|-----------------|----------|
|Another header |0 |row |
|Last column here|more content here|that's it!|
```
```
|A header |First |Second
|----------------|-----------------|----------
|Another header |0 |row
|Last column here|more content here|that's it!
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 218 bytes
```
n=[(t:=[x for s in l.split('|')if(x:=s.strip())],max(map(len,t)))for l in open(0)]
del n[1]
j=''.join
f=lambda c:j(f'|{l[c]:{w}}'for l,w in n)
print(f(0),j('|'+w*'-'for _,w in n),*map(f,range(1,len(n[0][0]))),sep='\n')
```
[Try it online!](https://tio.run/##VY5Ba8QgFITv/gpv6taEXXopAQ972T/QYxqKTbQxmKeokJR1f3tqUgrt8JjTfPPGf6XRwfOLD9sGoqWpEe2KtQs4YgPY1tFbkyjJhBlN10bEOqZgPGWs47Nc6Sw9tQp4YoztmN0x5xXQM@vQoCyG9tKhSRBST84A0sLK@WOQuG8mqkm@27bvmvvyeJCD58veAAz5YCBRXXr4tA94Wk6kOjLvvxl@2t9rHiR8KnrhZQiF9tyVK3N4VF6QNyBs2/IVj0oOKuBD@WZCTPlV9Q4GlKt/yn@8QvkKLo0F/OFzcEvhD8foGw "Python 3.8 (pre-release) – Try It Online")
-12 bytes thanks to basic code golfing advice by @cairdcoinheringaahing :)
-25 bytes thanks to @ovs by using `open(0)` instead of `sys.stdin`!
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~84~~ ~~73~~ ~~67~~ 59 bytes
-6 bytes from @rak1507's trim implementation (`2(|(&\^:)_)/`)
-19 bytes from golfing
```
{,'/("|",'++?[;1;"-"]{(|/#'x)$x^,""}2(|(&\^:)_)/'"|"\)'x_1}
```
[Try it online!](https://ngn.bitbucket.io/k/#eJyVk71ugzAUhXc/xa1b1bZCRPiZ8FDZQ6duHZsmRQkRkRqQiKsixXn3GlLUOCBT7mTdA/7OEYddcvKIT7HGHpnNnt54wPEcv5+o9u9JzR7qlYfxOaSaPi5XCVszn5hnl4zU6+CMkAgS8y4IyLN0m1VgjkWpcnPqFpgbff478HfsFq3+vK+OCsxoqMpvuJqL/pptymI7rDMkQrcJtwW3gRE8ZhyJqMF3dG2zW/8dStvkVuvI2r651TrurQZN6NhBdUAdTAfSABGSox8bXlJz8ab8/DoUZlllMF6Am8VgKRZgjYZDae42TlVWqAtotCig8lSRI+zV3XV55Eh5hkJNjzQ90PQ4TRhnFXs5nOXsZbDraifQPf/OAve8t1/C1eie+UnWJzn/n/Hmj/iAReL5dEeoCLgIuYi4iLkMuAy5jLiMGfMIXhYY/QC3xGYe)
Takes a list of strings, one for each row. Returns a list of strings, without leading/trailing spaces, and without trailing pipes.
* `x_1` drop the row at index 1 (i.e., the one with all the `-`'s)
* `(...)'` run the code in parenthesis on each row of the input
+ `"|"\` split each row on pipes (i.e. get the cells)
+ `2(|(&\^:)_)/'` strip leading and trailing whitespace from each cell's contents
+ `{...x^,""}` remove empty cells
+ `{(|/#'x)$x...}` pad the cells (of each row) with spaces so they are all the same length
+ `?[;1;"-"]` insert a cell containing the character `"-"` in the proper place
+ `++` transpose each row to generate the correct number of `"-"`s, then transpose back
+ `"|",'` prepend a `"|"` to each cell
* `,'/` concatenate the result by column
[Answer]
# [Ruby 2.7](https://www.ruby-lang.org/), 144 bytes
```
->a{(a=(a.map{_1.scan /\| ?\K[^|
]*[^|
-]/}-[[]]).map{|l|l.map{_1.ljust l.map(&:size).max}}.transpose.map{?|+_1*?|}).insert 1,a[0].tr("^|",?-)}
```
[Try it online!](https://tio.run/##pZJNT8MwDIbv/RWmB@jG2o0r0qi4cIEbx66TwpZpRV06Jan4mPvbi1foRlalIsOHynplx@9TW5YvH/VqWod3bBewacCiDdvuMMc8UgsmYDxDiGePyRy9dEhf8MJ0XIVJkqaDY2mTKFRR/loqDY0QXN6q7JPvq96rKtKSCbUtFG@7YrzOhzFWgygTiksNNyOWTFIqDPw5@qM4HFT1ttQKVomPcA9rzpZcAqWi0GvKDsITo6GLIi83gkTJAdBDCH8CjqlFaDTqeMgkPUSBMAEjEDYFvbsohOZCfw/ZdzxzkpZNgSzezA69ZvpKQaYvDpof5ZngKvX2XJ53Jp0rmyuZK5eNqoVCEwk7QPQnW69oWscODNW2MGiiYAeEalsQNDGwA4H/pXBgcED4C8E5V9V/Q@bFnF5A/324u@nz0uek14frOu3r@7WtkxXYl3OmC6sJqwerBWNy/QU "Ruby – Try It Online")
Takes in an array of lines, and outputs array of lines through the last output format. TIO uses an older version of Ruby, whereas in Ruby 2.7, we've numbered parameters, which saves *six* bytes!
[Answer]
# JavaScript (ES8), 204 bytes
Expects and returns an array of lines. Uses the last output format.
```
s=>(m=[,0]).map((r,y)=>m[r&&y].map((s,x)=>(r?s:"").padEnd(w[x],"-"[r])).join`|`,s.map(w=(s,y)=>s.replace(/\| *(.+?) *(?=\||$)/g,(_,s)=>((v=s.length)<w[y]?0:w[y]=v,m[x+=x==1]=m[x++]||[])[y]=s,y+=y<2,x=0)))
```
[Try it online!](https://tio.run/##tZGxbsIwEIZ3nsK1Kmo3JtCOCIM6tFO3jsEqETEkKLEj24Ug3btTBxqqNOoAVW@502//d/7Om3gb26XJSjdQOpGHFT9YPiUFj9hI0LCIS0IM21M@LSLT7@/FSbKs8hIxMzvGmIZlnDyrhOyiSjA8wJERlIYbnakFLJg9Wnbcm@o@NjSyzOOlJMM5oHsSBjPq04zPAW7pcM3IO7N1c7LlNsylWruUTnbRXsxG4zrxLSuiKuAV5w@C12UgACJB6zM/I@D7ySOr@IhSelhqZXUuw1yvyYpEPYQwoCeUyjiRBvlSaZf66iy8xtahpc4/CuVFIxECzE62wVeg7/IX4ag1tpfM@JY@AI1QKwAV2k/wb3RSudO4s@1Nej053jJ617a5NHZ3FmXu5qzhnjitnOC5whQF6Jh7f1/AVfhXwV@Ffgl4ww1taugwN7/Q4ECbDjq8jaHhhTYtdFgbQ8MKbVLocMK/gF7KeSnmpZQ/IOnhEw "JavaScript (Node.js) – Try It Online")
## Commented
### Step 1
Extracting the content of all cells and saving them into the matrix `m[]`.
```
s.map(w = // w is an object used to store the max. width in each row
(s, y) => // for each string s at position y in the input array:
s.replace( // match in s all occurrences of:
/\| *(.+?) *(?=\||$)/g, // "\|" a pipe
// " *" followed by optional whitespace
// "(.+?)" followed by a non-greedy string
// (this is the payload)
// " *" followed by optional whitespace
// "(?=\||$)" followed by either a pipe or the end of
// the line (not captured)
(_, s) => // for each payload string s found in there:
( (v = s.length) // define v as the length of this string
< w[y] ? // if it's smaller than w[y]:
0 // do nothing
: // else:
w[y] = v, // update w[y] to v
m[x += x == 1] = // increment x if x = 1
m[x++] || [] // if undefined, initialize m[x] to an empty array
// increment x afterwards
)[y] = s, // save s in m[x][y]
// initialization:
y += y < 2, // increment y if y = 0 or y = 1
x = 0 // start with x = 0
) // end of replace()
) // end of map()
```
### Step 2
Building the output.
```
(m = [, 0]) // initialize m[] with m[1] = 0 (reserved for the separator lines)
// (this is actually done before step 1)
.map((r, y) => // for each row r[] at position y in m[]:
m[r && y] // use m[0] if r = 0, or m[y] otherwise
.map((s, x) => // for each string s at position x in this row:
(r ? s : "") // use an empty string if r = 0, or s otherwise
.padEnd( // pad it with:
w[x], // w[x] characters
"-"[r] // using hyphens if r = 0, or spaces otherwise
) // end of padEnd()
).join`|` // end of inner map(); join with pipes
) // end of outer map()
```
[Answer]
# [PHP](https://php.net/), ~~429~~ 420 bytes
```
$a=preg_split("/
(\W*
)?/",$argv[1]);foreach($a as&$v)$v=array_values(array_filter(explode('|',$v)));for($i=-1;++$i<max(count($a),count($a[0]));)for($j=-1;++$j<=$i;){$t=trim($a[$i][$j]);$u=$a[$i][$j]=trim($a[$j][$i]);$a[$j][$i]=$t;$m[$i]=max(strlen($t),$m[$i]);$m[$j]=max(strlen($u),$m[$j]);}for($k=-1;$b=$a[++$k];print$k?"
":"
$s
")for($l=-1;$b[++$l]!=null;){printf("|%-$m[$l]s",$b[$l]);$s.='|'.str_repeat('-',$m[$l]);}
```
[Try it online!](https://tio.run/##dVLLTsMwELznK0y0EBtSHldSq@LCiRsHDiWqTOsSp85D9qaACN9e1gm0IMEerPHs7M7ESlu0u@mspROUbJ1@XvjWGuTxRcQfH04jMbuIU1DueTu/ykW2bpxWy4KDYsqfwFbAVirn1Ntiq2ynPR8va2NRO65fW9usNE/6JCWtGOY5GDm5ys7OwEwr9cqXTVcjLRTpN5pf5iQVg7b80pZTCSYT74ASnamCCkw@h5JCQScP10O7zANH7T2WgBlUAwrOHp3VNQcU6ciKoVv@7nZjNxh9DJE2IRI8BU8Ktsmz1pkaYTOLo/g6jsBH8ZjdjsKgsvmRrDtr6QsG9ZrH/fEk7LW5pwd@CoDs/bmkxzon74XTrVbIk0mSjjry3@12PbthhVYr7RjBusGC0J64Ux7ZsrFdVRPpNGN91LPJV7ED/IcYOJq4NY4WUfXMNS/sR/Wson@APGrUNY4mYeJeE7X6ewILhYlnBo/23Cc "PHP – Try It Online")
I'm pretty sure it could be golfed a bit more, when I have time I'll try to max it
EDIT: saved 9 bytes by using an alias for `$a[$k]` and using double quotes for the `printf`. Still work to do but 420 is a good number ;)
ungolfed explanation (the outputted newlines also replaced by `\n` for readability):
```
$a=preg_split("/\n(\W*\n)?/",$argv[1]); //split input by line removing the dashes under the headers
foreach($a as&$v)$v=array_values(array_filter(explode('|',$v))); //split each line at the pipes, remove empty cells and rearrange indexes if needed
for($i=-1;++$i<max(count($a),count($a[0]));) //looping on largest array dimension
for($j=-1;++$j<=$i;){ //swapping array values, trimming strings and we keep the largest length for each column
$t=trim($a[$i][$j]);
$u=$a[$i][$j]=trim($a[$j][$i]);
$a[$j][$i]=$t;
$m[$i]=max(strlen($t),$m[$i]);
$m[$j]=max(strlen($u),$m[$j]);
}
for($k=-1;$b=$a[++$k];print$k?"\n":"\n$s\n") //output of the result with the line
for($l=-1;$b[++$l]!=null;){
printf("|%-$m[$l]s",$b[$l]);
$s.='|'.str_repeat('-',$m[$l]);
}
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~79~~ ~~71~~ 61 bytes
```
WS¿¬⁼ιη«≔⟦⟧υFΦ⪪ι|κ«≔⁻Eκμ⌕Aκ ζ≔✂κ⌊ζ⊕⌈ζ¹κP⁺|κM⊕¬υ↓⊞υLκ»MLυ↑|⌈υ↑
```
[Try it online!](https://tio.run/##bVA9b8IwEJ3Jr7hmqS2FgblThiJRQYWablUHKzH4VMcG2ymImt@eniGhldqbfO/ex/lqJVxthe77g0ItgS3MrgtVcGi2jHPYWAfs2Qb2uO@E9gwLUJzwr2xSeo9bw97eC9jzh2xyoc5RB@lYtdMYEjmPOS9AXxWjZIWm82wldkwXYGg@R9OUWqc2h5wTckqOk3XnFdsXUGmsZZqSEtuuZSeiLEztZCtNkA15HQecKilxA@PKS2m2gWxIMqM9Rs9D4p3Hb5RhYRp5TINZAa/YSs/yaU6Jg3PaloaDmeZD0MWtu17gnK3pbGGkPlk0LI8xH54JJuZaNC@4VYGNkfStD35z/oXOUsb1hCms72MJSopGulgaG5R0Y7sUPkBtddcagpzM4nSo2@PfliqLc3SkBojOHuCnYmudJFO6rwmDayWpb/5SgxLh3gOGu6yffupv "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
WS¿¬⁼ιη«
```
Loop over the input rows, skipping the separator row.
```
≔⟦⟧υ
```
Start collecting the output column cell widths.
```
FΦ⪪ι|κ«
```
Split the row on `|`s and loop over the non-empty cells.
```
≔⁻Eκμ⌕Aκ ζ
```
Remove the positions of the spaces from the list of all character indices.
```
≔✂κ⌊ζ⊕⌈ζ¹κ
```
Get the trimmed cell text.
```
P⁺|κ
```
Print the vertical line and text without moving the cursor.
```
M⊕¬υ↓
```
Move down one or two lines depending on whether this is the first cell.
```
⊞υLκ
```
Push the width of the trimmed text to the list.
```
»MLυ↑
```
Move up to the separator row.
```
|⌈υ
```
Print the separator with its vertical line.
```
↑
```
Move to the first row.
[Answer]
# [Perl 5](https://www.perl.org/), ~~269~~ 228 bytes
```
sub f{@t=map[split/\s*\|\s*/],pop()=~/^.\s?(.*?)\s*$/mg;@T=map{$c=$_-1;[map$$\_[$c],@t]}1..@{splice@t,1,1};@w=map{max map y///c,@$\_}@t;splice@T,1,0,[map'-'x$\_,@w];join'',map{(map{sprintf'|%\*s',-$w[$\_],$$r[$_]}0..$#{$r=$_}),$/}@T}
```
[Try it online!](https://tio.run/##pVVdk5owFH3nV9y66QBOBO1MZzrLssvuQ592n2qf1DoUo9Lha0gYdQz96zZBRQVZS5uHEO5Hzj03Z5KEpMHnXUYJvPqU3d9/Z34AauiuVQvuXPDilEAYz7KAYGBLkpJ5nELipgziuTRA4EaLzF0QJdwAijOWZGz6bD88qKql8GdYEndGUigG/@qnlPFvxIujmcJ7F4OfzT2RGcUS7pDP03gl8osZlHOol@tQRzA4GwdguayCl8DXLdVyylLOdz9ZFP7qCmgvDrIwAtk0Hso@CnRGIra3sKXLVAo@@1DwcRihzNYUmS8Zgf14aidWOJT8xPKyGC68x0rhtDwahLdsBYdK3dJbtuWK9x/qea@aWi01@GbEI2BVGqezrCpKKTVQOS7hOaLWPG3xG@Ev0RsRrwO@3DhyqCoMbskAagK/JQ2oifaWXOAk6hsNbc@vLbu23Noya@bVJNQapXekW7@NmsVcv1ua5V2jwf@fRwsWLUj8DYd97bqlyPdrSOT79Sb3kXcptR@/WMpq6QdEKy5XfVtEhxsN@VGCEVknuk2TwPdI4cd9/Mk6hABaxMyeF5H63uhTrTOOpL2D5UKkd4Qr39HsJ8y3DrNDNxnJ/Zg5pt0xF5M5wUmcaLr92/xhjOmTZnSfdGFHZriwnKHM2CLPRtPewBqJH4SmI@RNsMMm@cAwnO2xPDzAg9xyVkWGeJxBfGFjmqaHHTTNHWYdIociso/lXmpPXaMpdlYT61fsR6qKZa4mJ5qkfsTmKv/YpSruodUITScYoVR@875hoLstSkVZuY6RmTvDfLf7Aw "Perl 5 – Try It Online")
```
sub f{
@t=map[split/\s*\|\s*/], #split at |, trim away spaces before and after
pop()=~/^.\s?(.*?)\s*$/mg; #pick part of each line that matter from input
@T=map{$c=$_-1;[map$$\_[$c],@t]}#transpose input table @t
1..@{splice@t,1,1}; #cols
@w=map{max map y|||c,@$\_}@t; #find max width of cols in transposed table
splice@T,1,0,[map'-'x$\_,@w]; #insert second line with --- of each width
join'', #join pieces of output into single string
map{ #for each line in transposed table @T
(
map {
sprintf '|%\*s', #string right padded...
-$w[$\_], #...to width of this column
$$r[$_] #info in column number $_
}
0..$#{$r=$_} #0..last index of current line in @T
),
$/ #newline \n (default)
}
@T #for each line in transposed table @T
}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 45 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ā2ÊÏε'|¡õÚðδÚ}©øćU®ε€gà}©'-ךXšεεR®NèjR„| ì]»
```
Input as a list of lines. Outputs with spaces, and without trailing `|`.
[Try it online](https://tio.run/##yy9OTMpM/V/z/0ij0eGuw/3ntqrXHFp4eOvhWYc3nNtyeFbtoZWHdxxpDz207tzWR01r0g8vAIqo6x6efnRhxNGF57ae2xp0aJ3f4RVZQY8a5tUoHF4Te2j3//81Co4KGamJKalFCkBmXn5JBpAFF/BJLC5RSM7PKc3NAwoWpSoo1HDVKOhCgQKCiUMALAbU4ZZZBDQICGoUDBRQQI1Cbj7Q3OT8vJLUvBKIJSAdwalAoRSwgqL8clQdJRmJJerFCpklinAxAA) (the header `|` is to convert the input into a list of lines).
**Explanation:**
```
ā # Push a list in the range [1, (implicit) input-length]
2Ê # Check for each that they're NOT equal to 2
Ï # And only leave the lines in the input at truthy indices
# (so we've removed the second line with the dashes)
ε # Map each remaining line to:
'|¡ '# Split it on "|"
õÚ # Remove leading/trailing empty strings, if the line started and/or ended
# with a "|"
δ # Map over each part:
ð Ú # Remove leading/trailing spaces
}© # After the map: store the result in variable `®` (without popping)
ø # Zip/transpose, swapping rows/columns
ć # Pop and push remainder-list and first item separated to the stack
U # Pop this first item, and store it in variable `X`
® # Push the list of variable `®` again
ε # Map over each list:
€ # Map over each part:
g # Pop and get the length of the part
à # Pop and only leave the maximum length
}© # After the map: store this as new value `®` (without popping)
'-× '# Transform each integer in the list into that many "-" as string
š # Prepend this list to the remainder-list
Xš # And then prepend the extracted head `X` back as well
ε # Map over each list:
ε # Map over each part inside the list:
R # Reverse the current part
® # Push the list of integers `®`
Nè # Pop and index the map-index into it
j # Pad leading spaces up to that many characters to the reversed part
R # Then reverse it back so the spaces are trailing
„| ì # And prepend "| " to the part
] # Close the nested maps
» # Join each inner list by spaces, and then each string by newlines
# (after which the result is output implicitly)
```
[Answer]
# [Julia 1.0](http://julialang.org/), ~~146~~ 144 bytes
```
x->["|"*join(rpad.(i,l),"|") for i=zip(insert!.((n=[strip.(split(i,"|";keepempty=0>1)) for i=x[[1;3:end]]];),2,"-".^(l=maximum.(length,n)))...)]
```
input and output are arrays of strings
[Try it online!](https://tio.run/##bY8xT8MwEIX3/IprFmyUWi1sVKnEwsTGGAXJatzmimNbzkWkyP89uKUGgrjp@d3z6XvHQaNcj9O@nMbltspDfnu0aJh3shEMC82L6HHYWw9YfqBjaHrlaSEYM2XVk0cnWO80UkzH6OZNKac6R6dytV3z9HOsqvXm/kGZpq7rDS/uinyZi1emy06O2A2dYFqZA7WF4ZwLIXg9oXEDQQlVlgd4hFbJRnmI0lhqo0pGXpwDy@vAj0zGV@AJfU8QJ4C37/BrroEXtbOm@T@Q1VnWYOwpT@zCxTPn0ZA2jH8v9tcVn0LCDXPY8Cwjw87qoTPR8gpCFhJomHP/eZ6dLKQSYQUzwM7GWxGflKHL4ZhNfcK8TaBW0k0PSIvkfAI "Julia 1.0 – Try It Online")
[All tests!](https://tio.run/##pVQ7T8MwEN7zKw4v2Ci1eGxUqcTCxMYYghRRlxoSJ3JcUZD/e7kAbmKnLaR4iXPnu@@@e72sCplfrDeLZLOezFJiydlLJRXVdT7nVMYFi1HGYFFpkMmHrKlUjdDmhFOqkrQxWtacNnUhDb7Gp9NXIWpR1uY9WeRFI5izXafpxfTqWqh5lmVTFl/GZEL4Iy2SMl/LclVyWgj1bJaxYoxxzlm2kapemQYSSCNCSGThBpYinwsNeFWVWeLNCVA7@TnQXZ0AtbdSNwbwWNDVG/ROq70XT5Wa79QidBzib5Wd255s6wy8uPbGF8q@rAKCrd9zCI8XbWt1l2M0T1WxKhVaaoEvygo/GJARyjiZWebmtAFpTnbzC@EPZfdQbg9mtgN2uNZHRUIOxPqYqHGY1veKGocYan7HC7O3H39QwF5AfpnsIP/7I@zK8p@mO6bljmm4Y9ptWIOt5wEp21HqdcL@ElivP0I6dkCml318H1IZ1q1XHnskj5E0RrIYSaINP4uir/0MUsH3uo1aT7WWyhSKSub9EkhmQDwZp4tu/z8ogsvbN2llEa79zZ@nDuyIubMjBs/@ZfKc5BM "Julia 1.0 – Try It Online")
Edit: -2 bytes by replacing `false` by `0>1`
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 40 bytes
```
⊃1(,/↑,2↓⊢){'|','-'⍪⍢(1∘⊖)↑⌂deb⍵⊆⍨⍵≠⊃⍵}¨
```
[Try it online!](https://tio.run/##nZDBSsNAEIbvfYrxtC0kaPUJRBAFT8YXiM02KaSJpCsqHS8qQaMpiigepacighd9gT7KvEicbEwlBMF0DruTn/kn37/2kW86Z7YfuqY8VTJwpJNllFx228YqxQ/GOsWPlEw7Y4HCEKag9I3SabtL1y@UPHd4hO4uHHlI6RclMaWzvLl55Q3cnM9nWZ/ie0onWnin9HP@sZGbJk/W/hafBzu7VubyzJg/@BKCbq/6kJtbLgiETfCk7cgIuA1C5XG3EPbskYJe6B8PAxYjCYAi95g/Bb/tH4LWtGd7EPEyLoQ1qBTCMOTdvTDg91HFjwqPJVl09EgUnlQ9yrOVECMYqJWFKJaI1DxQ8zhLhCmilEmwmgNrKfR7lYBY5cVaAj1dJsAqP9bo9XRJj1V2rJNjM/RG4I24/4ktWt8 "APL (Dyalog Extended) – Try It Online")
Adám's method.
**64 bytes(old)**
```
{↑,/⍉↑{'|',¨¯1⌽(m∘↑¨1⌽⍵),⍨⊂'-'/⍨m←⌈/≢¨⍵}¨¯1⌽1↓1⌽⌂deb¨'|'(≠⊆⊢)¨⍵}
```
[Try it online!](https://tio.run/##nVBNS8NAEL33V4ynbaGhFn@BCKLgyfoHYrP9gCaRdEWl46VKaGNTFBE8Sk85CL3o0Ut@yvyRONmYSgiC6Rx2Z9@@N/vemhcjw7oxR27fkNdKOpa0kmRC/lOzReGc94lA0YyjeN2mxVfdptkrg3GUnij8bDQpjCiYCkMwP7LJf6TFrEXzVRzx9W0ubJP/rCWLqSXP44iH1mn@RoFPwaqRcZNeqg6XFNxR@E7hR7ze47do@dI5PeD17Oi4k/SZM@EDb0LQw30PUmmtDwJhHwbStKQH3DquGnC3AU7MsYKuO7q0HQY9CYAi1Rg/Bb/tH4DGtOZw6PEwLoRdKBSC7fLsruvwV6rsoUzTkQxamuK5V0WNGphKiDEM1c4GFFtEqh6oepwtwmRR8iRYzIGlFPq/coNY9IulBJqdJ8Cifyy51@zcPRa9Y9k5VrNeyXgl3/@0LWrf "APL (Dyalog Extended) – Try It Online")
Takes the input as a list of lines, outputs a character matrix.
-9 bytes using `dfns.deb`.
## Explanation
`'|'(≠⊆⊢)¨⍵` split each line on pipes(`|`)
`⌂deb¨` trim whitespace from both sides of each cell
`¯1⌽1↓1⌽` drop the row with hyphens
`{'|',¨¯1⌽(m∘↑¨1⌽⍵),⍨⊂'-'/⍨m←⌈/≢¨⍵}¨` do the following for each row:
`m←⌈/≢¨⍵` set m to the maximum cell length
`⊂'-'/⍨` create a cell of hyphens that long
`,⍨` join with
`m∘↑¨1⌽⍵` input shifted by 1, with each cell padded to length m.
`¯1⌽` shift back to original position
`'|',¨` prepend a pipe to each cell
Finally,
`⍉↑` convert to matrix, and transpose
`↑,/` join each row's cells, and convert to matrix again
] |
[Question]
[
# Problem
Recreate the UI from a torrent program
Given no input, output the following:
```
+----------+----------+----------+
|a.exe |##########|seeding |
+----------+----------+----------+
|b.exe 10% |# |leeching |
+----------+----------+----------+
|c.exe |##########|seeding |
+----------+----------+----------+
|d.exe 20% |## |leeching |
+----------+----------+----------+
|e.exe |##########|seeding |
+----------+----------+----------+
|f.exe 30% |### |leeching |
+----------+----------+----------+
|g.exe |##########|seeding |
+----------+----------+----------+
|h.exe 40% |#### |leeching |
+----------+----------+----------+
|i.exe |##########|seeding |
+----------+----------+----------+
|j.exe 50% |##### |leeching |
+----------+----------+----------+
|k.exe |##########|seeding |
+----------+----------+----------+
|l.exe 60% |###### |leeching |
+----------+----------+----------+
|m.exe |##########|seeding |
+----------+----------+----------+
|n.exe 70% |####### |leeching |
+----------+----------+----------+
|o.exe |##########|seeding |
+----------+----------+----------+
|p.exe 80% |######## |leeching |
+----------+----------+----------+
|q.exe |##########|seeding |
+----------+----------+----------+
|r.exe 90% |######### |leeching |
+----------+----------+----------+
|s.exe |##########|seeding |
+----------+----------+----------+
|t.exe |##########|seeding |
+----------+----------+----------+
|u.exe |##########|seeding |
+----------+----------+----------+
|v.exe |##########|seeding |
+----------+----------+----------+
|w.exe |##########|seeding |
+----------+----------+----------+
|x.exe |##########|seeding |
+----------+----------+----------+
|y.exe |##########|seeding |
+----------+----------+----------+
|z.exe |##########|seeding |
+----------+----------+----------+
```
progress for programs are:
`b=10% d=20% f=30% h=40% j=50% l=60% n=70% p=80% r=90%`
amount of `#`'s for leeching programs is `progress/10`
the rest are all `seeding` with full progress bars.
# Rules
* Leading and trailing newlines allowed.
* Leading and trailing spaces allowed as long as it doesn't change shape of output.
* stdout and functions for output allowed.
* **Shortest code in bytes win**
[Answer]
# [Perl 5](https://www.perl.org/), 130 bytes
```
print$e=("+"."-"x10)x3 ."+
";printf"|$_.exe%4s |%-10s|%-9s |
$e",$|--&&$@++<9?("$@0%","#"x$@,leeching):("","#"x10,seeding)for a..z
```
[Try it online!](https://tio.run/##JYnLCsIwFAX3/YpwvC0peZCiLuoD8yciequFUkvjIkj@PVbdDMPMxPOwzXma@/FFfJRQsDCIjavjWlioAvvf7JDobDlyuQkilaZxYWG7eEEMTcmYqiKv1KE9SZB3JTRWiOT1wHx99OO93kn8Y@N0YL59W/ecxcXad84f "Perl 5 – Try It Online")
I expect that there are a few bytes that can be golfed, but I've ran out of inspiration.
Short explanations:
`$e` contains the separation line (`+----------+----------+----------+`); its construction is straight forward (`("+"."-"x10)x3 ."+\n"`).
Then, I loop over the characters from `a` to `z`:
Every time, print `"|$_.exe%4s |%-10s|%-9s |\n$e`; this is a standard `printf` with placeholders for strings (`%s`) and left-padded strings (`%-9s`).
if `$|--&&$@++<9` is true (`$|` is a special variable that contains either 0 or 1, and decrementing it toggles its value), then the percentage is not 100%, and the three values in the print are `"$@0%","#"x$@,leeching` (`$@0%` is actually just `$@ . "0" . "%"` - remember that `$@` was incremented earlier), otherwise, the three values are `"","#"x10,seeding`).
[Answer]
# [SOGL V0.12](https://github.com/dzaima/SOGL), ~~90~~ ~~89~~ 88 [bytes](https://github.com/dzaima/SOGL/blob/master/chartable.md)
```
ēz{L┌* +3ΟQķ|;o".exe ”oēI»L*"% |”e» #*lLκ@*"┌5%8'Ω⅞█≡θ¹‘++++e'³>e2\+?X"⅓m÷Ko→∆)№(¤^▒«‘}o
```
[Try it Here!](https://dzaima.github.io/SOGLOnline/?code=JXUwMTEzeiU3QkwldTI1MEMqJTIwKzMldTAzOUZRJXUwMTM3JTdDJTNCbyUyMi5leGUlMjAldTIwMURvJXUwMTEzSSVCQkwqJTIyJTI1JTIwJTdDJXUyMDFEZSVCQiUyMCUyMypsTCV1MDNCQUAqJTIyJXUyNTBDNSUyNTglMjcldTAzQTkldTIxNUUldTI1ODgldTIyNjEldTAzQjglQjkldTIwMTgrKysrZSUyNyVCMyUzRWUyJTVDKyUzRlglMjIldTIxNTNtJUY3S28ldTIxOTIldTIyMDYlMjkldTIxMTYlMjglQTQlNUUldTI1OTIlQUIldTIwMTglN0Rv)
Explanation:
```
ē push variable E (default = input, which default is 0) and increase it after (next ē call will result in 1, or next e call - 2)
z{ iterate over the lowercase alphabet
L┌* push 10 dashes
+ push "+"
3Ο encase 3 copies of the dashes in pluses
Q output in a new line, without popping and without disabling auto-output
ķ| output in a new line "|"
;o output the current iteration (the alphabet letter)
".exe ”o output ".exe "
ē push E and increase the variable after
I increase it
5* multiply by 5 (every 2 ē calls this gets called)
"% |” push "% |"
e» push (E)/2
#* get that mant "#"s
l get the length of that string
Lκ push 10-length
@* push that many spaces
"..‘ push "|leeching |"
++++ add all those strings on the stack together ((e+1)*5, "% |", "#..#", " .. ", "|leeching |") (done this way to leave the "+-+-+-+" on the stack)
e'³> push e>19
e2\ push e divides by 2
+ add together (here works like OR)
? if that then
X remove the added-together string
"..‘ push " |##########|seeding |"
} END
o output POP (either the added string or full/seeding version)
implicitly output POP (since none of tTpP were called), which is the separator line
```
[Answer]
## Charcoal, ~~98~~ ~~85~~ 83 bytes
```
F³B⁻³⁴×¹¹ι³M↘ .exeM⁶→×#χ|seeding⸿F²⁵C⁰¦²↗Fβ↓⁺ι-F⁹«J⁷⁺³×⁴ι⁺⁺ι¹0% |#P⁺× ⁹|leeching×#ι
```
I thought copying a template would save me a lot of code but it all seems to add up somehow, although I managed to save 13 bytes by using a single loop to fix the 9 leeching rows. Explanation:
```
F³B⁻³⁴×¹¹ι³ Make the top row of boxes
M↘ .exeM⁶→×#χ|seeding⸿ Print .exe, the 10 #s and seeding
F²⁵C⁰¦² Make 25 copies of the boxes
↗Fβ↓⁺ι- Put the letters in at the start
F⁹« For the 9 leeching files
J⁷⁺³×⁴ι Move the cursor to the percentage column
⁺⁺ι¹0% |# Print the percentage and the first # of progress
P⁺× ⁹|leeching Erase the rest of the progress and change the status
×#ι Print the desired amount of progress
```
(Side note: I seem to have discovered a bug in Charcoal; `|` is an ASCII character, but it's also counted as an arrow for the purposes of `Multiprint`, so you can't `Multiprint` it.)
[Answer]
# [Python 2](https://docs.python.org/2/), 182 177 bytes
Thanks to @officialaimm for shaving off 5 bytes by changing the format of the condition.
```
r=("+"+10*"-")*3+"+"
for i in range(26):z=i/2+1;print r+"\n|"+chr(97+i)+".exe "+[" |"+10*"#"+"|seeding ",`10*z`+"% |"+z*"#"+(10-z)*" "+"|leeching"][i%2and i<19]+" |"
print r
```
[Try it online!](https://tio.run/##LY3RCoIwGIXvfYqfP4TNP8stKKx8EhMUXTqIKcuLGr77mtW5Opxz@M70nofRSO9twZCQRJZgijw5BI/RfbSgQRuwjekVk0d@doXeSxKXyWozgyW8mQWpHSzLT6Q54U69FCCVCEHLj7gJsOWpVKdND7itQ@Zqwnjt3bdmIksdTxDW5UOpdghTrEody8Z0oK8irwhXYPR/9v4D "Python 2 – Try It Online")
[Answer]
# Javascript, ~~232~~ ~~230~~ ~~228~~ 226 bytes
```
(s='+----------'.repeat(3),p=0)=>[...'abcdefghijklmnopqrstuvwxyz'].map((c,i)=>(b=i%2,p=b?p+10:p,x=b&p<91,`${s}+'
|${c}.exe ${x?p+'%':' '} |${'#'.repeat(x?p/10:10).padEnd(10)}|${x?'leeching':'seeding '} |`)).join`
`+`
${s}+`
```
* -2 Bytes thanks to @Stephen S - Using default function parameters
* -2 Bytes thanks to OP - Replacing some spaces
* -2 Bytes thanks to @Shaggy - Destructuring alphabet string
## Demo
```
f=
(s='+----------'.repeat(3),p=0)=>[...'abcdefghijklmnopqrstuvwxyz'].map((c,i)=>(b=i%2,p=b?p+10:p,x=b&p<91,`${s}+'
|${c}.exe ${x?p+'%':' '} |${'#'.repeat(x?p/10:10).padEnd(10)}|${x?'leeching':'seeding '} |`)).join`
`+`
${s}+`
console.log(f());
```
```
.as-console-wrapper { max-height: 100% !important; top: 0; }
```
[Answer]
# [Braingolf](https://github.com/gunnerwolf/braingolf), ~~673~~ 655 bytes
```
9..#+[#-]#+[#-]#+[#-]"+
|"!&@V"a.exe |"!&@V9[##]"|seeding |
"!&@v!&@v<1+>!&@V8##[# ]"|leeching |
"!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@vv<<$_##>>!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@vv<<<$_##>>>!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@vv<<<<$_##>>>>!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@vv<<<<$_##>>>>!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@vv<<<<<$_##>>>>>!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@vv<<<<<<$_##>>>>>>!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@vv<<<<<<<$_##>>>>>>>!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@vv<<<<<<<<$_##>>>>>>>>!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@vv<<<<<<<<<$_##>>>>>>>>>!&@v!&@v<1+>!&@v!&@vv!&@v<1+>!&@v!&@vv!&@v<1+>!&@v!&@vv!&@v<1+>!&@v!&@vv!&@v<1+>!&@v!&@vv!&@v<1+>!&@v!&@vv$_!&@;
```
[Try it online!](https://tio.run/##SypKzMxLz89J@//fUk9PWTtaWTcWmVTS5qpRUlRzCFNK1EutSFUAAYiAZbSycqxSTXFqagrQBJAwF0i8DIRtDLXtQGoslJWjlRWAqnJSU5MzwMowVYHZKAJlNjYq8crKdnbEqIQqJU4tTDFNVMOVE6seoYFoHUhaiNeDrIkEXSjaCOujmoBKPJCy/v8fAA "Braingolf – Try It Online")
I've said it before and I'll say it again: Braingolf is bad at ASCII art.
At least this is only 1/3rd of the bytes it would take to actually hardcode the output
[Answer]
# [PHP](https://php.net/), 179 bytes
without input
```
for($a=a;$x<53;++$x&1?:$a++)printf($x&1?"
|$a.exe%4s |%-10s|%-10s|
":str_pad("",34,"+----------"),($y=$x%4>2&$x<36?++$z:"")?$y."0%":"",str_repeat("#",$y?:10),$y?leeching:seeding);
```
[Try it online!](https://tio.run/##PY1BDoIwFET3nMJ8f0mbFgKCLgrYo5hGipAYbFoWYLg7FmOcxbzJLGZsb7da2eDdy1HUja5wrs9FxTnOca4kas6ZdcM4dfTbQLSiTs1sSOkPK0nyzP88Auknd7O6pQCiKAXw5C9gguLS4EzK6ykOH8VFhY@3BGAKlxQyAiGLfcEZa/RE4QgCFyXzjO18GnPvh/EhvTFtIKu27QM "PHP – Try It Online")
# [PHP](https://php.net/), 176 bytes
with input
```
for($a=a;$x<53;)printf($x&1?"
|$a.exe%4s |%-10s|%-10s|
":str_pad("",34,"+----------"),($y=strstr($argn,++$x&1?:$a++)[2])?$y."0%":"",str_repeat("#",$y?:10),$y?leeching:seeding);
```
[Try it online!](https://tio.run/##Pc7dqsIwDAfw@z2FxExaWmVz86sz7EEOB6muc4rM0u1iA999RjmcEH7/myTEN346lr7xEdpwbQnOlCbxrKI1W1PGNpSzd9qwD9qyLe1YT3s20CGJoZjqZxBoyRY4HDdZIX24tX0tcFikJUQvtCs3uDjvZq94mSbdnxGYrg8nbysBoLNcg1r@F0gtcCQe4Bbf/7RS34sGrVLyZ/0rSxxXwB8Y3v@cCs472wuYg8axNGkiP/lw7tLc2qvpnKs4ZTFNbw "PHP – Try It Online")
[Answer]
# [V](https://github.com/DJMcMayhem/V), 107 bytes
```
¬azÓ./|&.exeò
ddÎAµ |±°#|seeding³ |
ÙÒ-4ñr+11lñddç^/P
jp4G9ñ8|R00%3l10r llRleeching4jñV{10g
çä/WylWl@"r#
```
[Try it online!](https://tio.run/##AYEAfv92///CrGF6w5MuL3wmLmV4ZcOyCmRkw45BwrUgfMKxwrAjfHNlZWRpbmfCsyB8CsOZw5ItNMOxcisxMWzDsWRkw6deL1AKanA0RznDsTh8UjAwJRszbDEwciBsbFJsZWVjaGluZxs0asOxVnsxMGcBCsOnw6QvV3lsV2xAInIj//8 "V – Try It Online")
Hexdump:
```
00000000: ac61 7ad3 2e2f 7c26 2e65 7865 f20a 6464 .az../|&.exe..dd
00000010: ce41 b520 7cb1 b023 7c73 6565 6469 6e67 .A. |..#|seeding
00000020: b320 7c0a d9d2 2d34 f172 2b31 316c f164 . |...-4.r+11l.d
00000030: 64e7 5e2f 500a 6a70 3447 39f1 387c 5230 d.^/P.jp4G9.8|R0
00000040: 3025 1b33 6c31 3072 206c 6c52 6c65 6563 0%.3l10r llRleec
00000050: 6869 6e67 1b34 6af1 567b 3130 6701 0ae7 hing.4j.V{10g...
00000060: e42f 5779 6c57 6c40 2272 23 ./WylWl@"r#
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 121 bytes
```
;'++(-p10 +'+ ³
1
U+R+C£W=Yv ªY>20?10:Y¥1?1:V±1"|{X}.exe {4î hW>9?S:W+"0%"}|{10î h'#pW}|{10î hW<10?`äƒÊA`:`Ð:ˆg`}|"+R+U+R
```
[Try it online!](https://tio.run/##y0osKPn/31pdW1tDt8DQQEFbXVvh0GYuQ65Q7SBt50OLw20jyxQOrYq0MzKwNzSwijy01NDe0Crs0EZDpZrqiFq91IpUhWqTw@sUMsLtLO2DrcK1lQxUlWprqg0NQILqygXhcE64jaGBfcLhJYeaD3c5JlglHJ5gdagjPaG2RgloF9C@//8B "Japt – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 141 bytes
```
puts s=(?++?-*10)*3+?+,(?a..?z).map{|c|["|#{c}.exe%4s |%-10s|%-9s |"%(c.ord%2>0||($.+=1)>9?["",?#*10,:seeding]:["#$.0%",?#*$.,:leeching]),s]}
```
[Try it online!](https://tio.run/##HYzdCoIwGEBfRaaDzc2PrbpxoN@DiBc2RwX9iEuonM@@VjeHAwfOvBzfMU7L02e@YSgEVqVWvNwLFJLhAIAfDrdhWoMNHQn5ajdwL0cPPgu00son1skJZRYe80h3rQqBFSAazdsaO0Ik5ukpjXduvNxPvelIXoCi/1CANFfn7PlXuPT9FuMX "Ruby – Try It Online")
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~244~~ ~~229~~ ~~228~~ ~~227~~ ~~226~~ ~~224~~ ~~222~~ ~~218~~ 217 bytes
```
o->{String x="----------+",z="+"+x+x+x,s=z;for(int c=96,p;++c<123;s+=s.format("%n|%c.exe%4s |%-10s|%-10s|%n"+z,c,p>9?"":p+"0%","##########".substring(0,p),p>9?"seeding":"leeching"))p=(p=c/2-48)>9|c%2>0?10:p;return s;}
```
[Try it online!](https://tio.run/##PVBNb8IwDL3zK6xMlVIlzQpD06Ck3HabduA47RBCytKFNGpSxEf57V0LjGfJtt57tiyXYi@Syilbbn4716yNliCN8B4@hLbnEcCd9EGEvuwrvYFdL@FVqLXdfn2DqLc@HpwAZb@NNUEbVjRWBl1Z9n5vFp/rUslA4TaXQwEcuirJzzcCDhwlDxBETxwRRA5DUM9PWVHVWNsAks9eqcsIkYvx5CXzhHvWazsRMIpsG0mmDiqaemijZJz6/2wROVFJXT5bIjR3BKURoujpAcR8s/bXU3BKXXxzeqU2PYPmyCglf4Y2jh3HjsvnSTJ9i/NZK6NJni7H6dxltQpNbcFnly67PmR19EHtWNUE5vrVwVhcMOGcOWLbGBPHg@0yuoy6Pw "Java (OpenJDK 8) – Try It Online")
-2 bytes thanks to @KevinCruijssen!
[Answer]
# Plain TeX, 306 bytes
```
\let\a\advance\def\b{+\r{\r-9-+}3\par}\def\s{\r~5|\r\#9\#|seeding\r~3|}\def\r#1#2{{\i0\loop#1\a\i1
\ifnum\i<#2\repeat}}\newcount\i\i`a\newcount\j\j1\tt\loop\b|\char\i.exe\ifodd\i\s\else\ifnum\i<`s\
\the\j0\%~|\r\#\j{\j-\j \a\j10 \r~\j}\a\j1|leeching\r~2|\else\s\fi\fi\endgraf\a\i1 \ifnum\i<`\{\repeat\b\bye
```
Ungolfed with some explanations:
```
\let\a\advance
\def\b{+\r{\r-9-+}3\par}% The bar between rows: '+' + 3*(9*'-' + '-' + '+') + '\n'
\def\s{\r~5|\r\#9\#|seeding\r~3|}% The common part for seeding lines, similar to \b
\def\r#1#2{{% Macro for repeating #1 #2 times
% Note the local grouping here which is needed for nested \loops and allows us to reuse the global \i
\i0%
\loop
#1%
\a\i1 %
\ifnum\i<#2%
\repeat%
}}%
\newcount\i \i`a% Counter for ASCII values of letters, start with 'a'
\newcount\j \j1% Counter for percentages; shorter than modulo tricks
\tt
\loop
\b|\char\i.exe%
\ifodd\i
\s% Odd lines are seeding lines
\else
\ifnum\i<`s\ % Even line up to 'r'
\the\j0\%~|\r\#\j% Print percentage and progress bar
{\j-\j \a\j10 \r~\j}% 10-\j spaces after the progress bar
\a\j1%
|leeching\r~2|%
\else
\s% There's no \ifeven, hence the repetition here
\fi
\fi
\endgraf% Print '\n'. \par doesn't work here, because \loop isn't a \long macro
\a\i1
\ifnum\i<`\{% Repeat until \j <= 'z'
\repeat
\b
\bye
```
[Answer]
# [Python 3](https://docs.python.org/3/), 255 bytes
I'm sure this can be golfed, updating soon:
```
e,l='.exe ',('+'+10*'-')*3+"+";print(l)
for i in zip(['|'+chr(z)+e+' |'+"#"*10+'|seeding |'if z%2or z>115else'|'+chr(z)+e+str((z-96)//2*10)+'% |'+(z-96)//2*"#"+(10-(z-96)//2)*" "+"|leeching |"for z in range(97,123)],[l]*26):print(i[0],i[1],sep="\n")
```
[Try it online!](https://tio.run/##VY9BasMwEEX3PYVQCKPRyIll04S0pBdxvSjpJBYIxchetMJ3d@UEEjrLB///N/3v2F1DPc9s/BE2/MMCjAICsqWGAlDXJEm@99GFUXl8OV@jcMIFkVyvGpiATl1UCYkJRL4M5EpqWxJMA/O3C5cbdWeR1lUOpw9rX9kP/C87jFGpVBx2uN1WOY0E66XryXIrKVsWD4Jaiqw2eeZTd5uZ5GKXFrv4FS6sDntjqxpb0/hWVzt8u7/hmrI1rrGtGbg/ys8gcZ7/AA "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 98 bytes
```
;27Æ4î+ ¬q-pU=10ÃíC¬£'|²¬q[X+".exe {W=Yu ©°T<U©T*U ?W+'%:P}"'#pW/UªU `äÊA Ð:g`¸g!W]m!hUî)q|})c ·
```
Doesn't work in the latest version due to a bug that messes up `4î+`, `q-p10`, and `q|`, but it does work in [commit `f619c52`](https://github.com/ETHproductions/japt/tree/f619c52d28277eaf279903146e832360384acb02). [Test it online!](http://ethproductions.github.io/japt/?v=f619c52d28277eaf279903146e832360384acb02&code=OzI3xjTuKyCscS1wVT0xMMPtQ6yjJ3yyrHFbWCsiLmV4ZSB7Vz1ZdSCpsFQ8ValUKlUgP1crJyU6UH0iJyNwVy9VqlUgYOSDykEg0DqIZ2C4ZyFXXW0haFXuKXF8fSljILc=&input=)
[Answer]
# T-SQL, 238 bytes
```
DECLARE @ INT=1,@D CHAR(11)='+----------'L:PRINT @D+@D+@D+'+
|'+CHAR(@+96)+'.exe '+IIF(@%2=0AND
@<20,CONCAT(@/2,'0% |',REPLICATE('#',@/2),SPACE(10-@/2),'|leeching |'),' |##########|seeding |')SET @+=1IF @<27GOTO L
PRINT @D+@D+@D+'+'
```
Procedural solution, formatted:
```
DECLARE @ INT=1, @D CHAR(11)='+----------'
L:
PRINT @D + @D + @D + '+
|' + CHAR(@+96) + '.exe ' +
IIF(@%2=0 AND @<20,
CONCAT(@/2,'0% |',REPLICATE('#',@/2),SPACE(10-@/2),'|leeching |'),
' |##########|seeding |')
SET @+=1
IF @<27 GOTO L
PRINT @D + @D + @D + '+'
```
Everything in the loop (up until the SET) is part of the same PRINT statement, including a line break inside the first string literal.
I'm working on a set-based solution (create and populate a table, then SELECT from it), but I'm not sure if its going to be smaller or not.
[Answer]
# Java 8, ~~271~~ ~~263~~ 262 bytes
```
o->{String a="+----------",b=a+a+a+"+\n",r=b;for(int c=96,t;++c<123;r+="|"+(char)c+".exe "+(t>0?(c/2-48)+"0%":" ")+" |##########".substring(0,t>0?c/2-46:12)+" |".substring(t>0?c/2-49:9)+(t>0?"leeching":"seeding ")+" |\n"+b)t=c<115&c%2<1?1:0;return r;}
```
All this trouble for nothing.. >.> ;)
([Shorter Java answer by *@OliverGrégoire*](https://codegolf.stackexchange.com/a/128624/52210).)
**Explanation:**
[Try it here.](https://tio.run/##TVDRTsIwFH33K25qMF26zW0qkZXCF4gPPKoPXSkyHB1pO6JhfPu8g0k8bZPe3nNzTs9WHmRU77XZrr46VUnn4EWW5ngDUBqv7VoqDYu@BFh6W5pPUPS12GrloQ44vp/w4HZe@lLBAgwI6OpodhzoUhAWXUHCQkjWL8LeDQmtKPi6thTFQInJOPScMTVNswdumSAtYVRtpA0UI7H@1oC1nyVzqu6z6PE5YCQZkZygOYJ3aG@vILFrCne2QJOwnzmPjPM065l/aP/zrqxJPgkuQqTSWm2wiSpO61X/o7MUtGifFYEX6DZ9ulOjbJrO0zzhVvvGGrD81PFLNvumqDCbIaJDXa5ghyHTS0JvHyCDIeEf5/Uurhsf77HlqYkVNU1VBUPUp@4X)
```
o->{ // Method with unused Object parameter and String return-type
String a="+----------",b=a+a+a+"+\n",
// Temp String "+----------+----------+----------+\n"
r=b; // Result-String
for(int c=96,t;++c<123 // Loop from 'a' to 'z':
; // After every iteration:
r+= // Append the result-String with:
"|" // A literal "|"
+(char)c // + the character
+".exe " // + literal ".exe "
+(t>0? // If the current character is below 's' and even unicode:
(c/2-48)+"0%" // + the percentage
: // Else:
" ") // + the spaces
+" |##########" // + the progress bar
.substring(0, // By using a substring from 0 to
t>0? // If the current character is below 's' and even unicode:
c/2-46 // 'b' = 3; 'd' = 4; 'f' = 6; etc.
: // Else:
12) // 12 (the entire progress bar)
+" |" // + spaces after the progress bar
.substring( // By using a substring from
t>0? // If the current character is below 's' and even unicode:
c/2-49 // 'b' = 0; 'd' = 1; 'f' = 2; etc.
: // Else:
9) // 9 (all the spaces)
+(t>0? // If the current character is below 's' and even unicode:
"leeching" // + literal "leeching"
: // Else:
"seeding ") // + literal "seeding "
+" |\n" // + literal " |" + new-line
+b) // + `b` ("+----------+----------+----------+\n")
t=c<115&c%2<1? // If the current character is below 's' and even unicode:
1 // `t` = 1
: // Else:
0; // `t` = 0
// End of loop
return r; // Return the result-String
} // End of method
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 154 149 143 130 103 bytes
```
A⁵δFβ«F³«+χ»+⸿A∨﹪δ²›δ⁹⁵θ|ι.exe⎇θ… ⁵⁺⁺ δ% ⁰|⎇θ…#χ⁺…#∕δχ… ⁻χ∕δχ⎇θ|seeding |⸿↧|leeching |⸿A⁺⁵δδ»F³«+χ»+
```
[Try it online!](https://tio.run/##jVFNSwMxEL3vrxgiQgZTqcoeZE8FwYtFEY9e4mbcBpaEJm1Vuv3tcbJdIUUEDwMz7828@WpXOrRe9yktYrSdk7UCg0317gPIN4R9BcC@vMH9U7BuI8WFwOboXs2xOfygr4FxTp5kHoNcerPtvTTqGtV9IL2hwMFtjahgPeZOtYMoIlsyl/RJJflCwenwJdcKnrXrSAoQCmoWXBgjs2XAoBLnIBCLyvmfDX9rnrEm73YULbA7u7OGeAcmURUDLK3bRj6HOsnAkwGKNmKIRMa6DgAGvpuCB/9BodWR9YaeqF2NZOYmjemqeaA67zf@6FD96zOMppRmuzSL/Tc "Charcoal – Try It Online") (Link to verbose version.)
* 27 bytes saves thanks to Neil's master Charcoaling techniques.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 120 bytes
```
AS".exe"«'A17×S9L‚ζJJðK€H©T*т%εD0Q_i'%«ëð3×}}‚ζεðýð«}®'#×T®-úí"leeching seeding "Tô®TQè)ζ'|ýε'|.ø}õ.ø'-T∍'+«3×'+ì¶.øý
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fMVhJL7UiVenQanVHQ/PD04MtfR41zDq3zcvr8AbvR01rPA6tDNG62KR6bquLQWB8prrqodWHVx/eYHx4em0tWOG5rYc3HN57eMOh1bWH1qkrH54ecmid7uFdh9cq5aSmJmdk5qUrKBSnpqaAGQpKIYe3HFoXEnh4hea5beo1h/ee26peo3d4R@3hrUBSXTfkUUevuvah1UDz1bUPrzm0DSh6eO///wA "05AB1E – Try It Online")
---
There's way too much golfing to do here, will post explanation when I'm below 90 bytes.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~53~~ ~~68~~ 64 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
â"{≤╞c~£ÿτδ¬│∙}Dgoô₧»öÖ#9▌ó♂i◘ÿkùâGCå`è╙/♠Gδb,φW0EqΔ┘δth½àJZ¿l╦#
```
[Run and debug it](https://staxlang.xyz/#p=83227bf3c6637e9c98e7ebaab3f97d44676f939eaf94992339dda20b6908986b9783474386608ad32f0647eb622ced57304571ffd9eb7468ab854a5aa86ccb23&i=)
Unpacked and ungolfed it looks like this.
```
'+'-A*+34:mQ
VaF
'|p
".exe "+
|;i^hA?X
$.0%+
xA<Y*+G
'#x*G
`Qz/"D?d=T"`jy@G
zP
Q
}A(p'|p
```
Note that if you use the "Golf" button to remove whitespace and comments from the expanded solution, it incorrectly doubles the `}`. If you remove the extra character, it continues to work correctly.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~172~~ ~~170~~ 162 bytes
-8 bytes thanks to Lynn
```
for i in range(2,28)+[id]:print('+'+'-'*10)*3+'+';a=i/2;b=i%2*(i<20);print('|'+'%-10s|'*3)%('%c.exe '%(95+i)+'%d0%%'%a*b,'#'*(a*b or 10),'sleeeedcihnign g'[b::2])
```
[Try it online!](https://tio.run/##LY7NCoMwEIRfJVCWTWJs40qh1fok4sGfVBdKFPXQgu@eptCZy8A3DLN89mn2FMJzXgUL9mJt/egkGbqppOahKZaV/S4xiU5RZ1bp/JfLtuILlV3FQFryg6wq/9UjYkgzux2ocwUSoT@7txMI8n5NWEU6WACEVncGT6hlDCIeiOMGt5eLGnqePI9ejFh3RUGNCuEL "Python 2 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~217~~ 211 bytes
-6 bytes thanks to ceilingcat
```
#define B"+----------"
f(p){for(char*a,*l=" bdfhjlnpr",i=97;puts(B B B"+"),i<'{';printf("|%c.exe %.*d%s |%-10.*s|%s |\n",i++,!!a,p%10,a?"0%":" ",p=a?a-l:10,"##########",a?"leeching":"seeding "))a=index(l,i);}
```
[Try it online!](https://tio.run/##PU/BCsIwFLv7Fc8nxXbrxjyJziHsO7zU9nWr1Fo2BcH57bO7mFMISUh00Wk9zxtD1gWCFvPiD1xZHsXHPgauezVkSma@Qbga2998iANK1xz2dXw9R95Cu4RRSHfafrZ1HFx4Wo4T0yW9CViZGTbCxIpdVWbjlDhMl5Aq8lyu10pGtqukOmPF8IgAgDI26qwKf0w6bv7AxeSJdO9Cl6wjkUkMUAjVuGDozb10ov7OaQDclQs8XeCL8AM "C (gcc) – Try It Online")
[Answer]
# [///](https://esolangs.org/wiki////), 264 bytes
```
/~/\/\///!/---~@/!!!-~$/@+@+@~</+
|~>/|
+~(/###~*/ ~}/|leeching*~[/.exe ~;/0% |~{/[**|(((#|seeding* ~]/>$</+$<a{]b[1;# ****}]c{]d[2;##****}]e{]f[3;( ***}]g{]h[4;(#***}]i{]j[5;(## **}]k{]l[6;((**}]m{]n[7;#((* }]o{]p[8;##((*}]q{]r[9;((( }]s{]t{]u{]v{]w{]x{]y{]z{>$+
```
[Try it online!](https://tio.run/##JczZTsNADAXQ937FRBOk0UTB7Iumivof5j6UdmgKoSxhKXjiXw@T4vt05Gv33bJvYz@OpHSXQ1RQXde6oKIoai1pUeXonKpZ0obSrFJH1lr1ZIwOlLoYV@12t/HKdBz30WigkyOTVIi9T845m/oY11PFKKgp869yvhTc82mwxucZsBKs@SxY@88oeODz4MxBG0HLF8HZg7aCR77Mmm4HPAk6vgrOTXgW7Pg62Cwz4EXwyjf5aeaAN8E73@aiy6te8CH4FHwJvgV7wY/gV5qyGsc/ "/// – Try It Online")
Works by defining a bunch of replacements and using them to replace more characters than they are.
[Answer]
# Mathematica, 274 bytes
```
a=Alphabet[];n=StringPadRight;o=ToString;Column@Join[Row/@Table[{g="+----------+----------+----------+\n","|"<>o@a[[i]]<>".exe ",If[EvenQ@i&&i<20,s=o[5i]<>"% ";k="|"<>Table["#",i/2];f="leeching";,k="|##########";f="seeding";s=" "];s,n[k,11]<>"|",n[f,10],"|"},{i,26}],{g}]
```
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 150 bytes
```
00000000: e007 3d00 8c5d 0015 8b71 ec14 6414 8031 ..=..]...q..d..1
00000010: 7fc3 2b24 3568 ca81 7ab5 363e c3b7 f500 ..+$5h..z.6>....
00000020: c926 d3f0 55d9 926f 75a8 f8d0 806f 1f12 .&..U..ou....o..
00000030: d71f b824 7e75 a7f2 544f 0364 ee5e 98be ...$~u..TO.d.^..
00000040: a327 c36c 2ff1 8e6e df94 858e 82d0 d9da .'.l/..n........
00000050: 77d6 fac6 5548 64aa 7a29 78fa 6886 3c85 w...UHd.z)x.h.<.
00000060: 0494 905e 74de a209 e927 42c8 418d 8250 ...^t....'B.A..P
00000070: ee39 c16b a4c2 9add 0b17 f8b0 9984 9aa8 .9.k............
00000080: defb 2875 31a9 c136 0ec2 6f28 9f8c 9990 ..(u1..6..o(....
00000090: 10d4 0000 0d0a ......
```
[Try it online!](https://tio.run/##ddG7alZBFAXg3qdYRTARYTv32SMqaGWnhSkNzDWBRIPgj5LCV/9dJzmGNO7iwBTnmzVrt0NrN/Py8O14NPu8xjQmww9joD0OGGMjtGWL2W1ACvyo8RYQeSvyVUR@iAwR@@xBsDTy6h6uuQAfk6JXtci1RfjkJ7pvGSvyBhovT@KVyJ2kd5RkNxyNXlzC8MsgxlHA00KOVbF0MJvh0S7raDwXORe5PWzA7aPhaYxsF5oyR545oublEENYMD4FzBknira55ZCTPwS@fOJTLh6NQKN6lxk5dbi1LHSmibEKW4g6oY5hRhmVxqncvBL5LvvsRtz6yCNh1Z74lqAssVb24QqyroqkmuC7RuAX/zv/OOTuxW@5kjf/jETDBN5ZDCPnMCaqMwWzMFtwXRGsDoaJ953Kxc8twOkHeS/yeTfyttvpC7pNDTV0h1IHF9wst6HNoBTlDZUVQ4pcy5PZDd06navBKev0tm6aTzCTWlpOUZZ2QuU@x9nBiiQu5eyJUWhYMwK2A8wwrO6/83D78fgX "Bubblegum – Try It Online")
[Answer]
## Perl6, ~~225~~ 219
```
my&f={say ("+"~"-"x 10)x 3~"+"};my&g={f;my$b=$^c>9??" "!!$c*10~"%";say "|$^a.exe $b |{'#'x$c}{' 'x(10-$c)}|$^d |"};my \s="seeding ";for 1..9 {g chr(95+2*$_),10,s;g chr(96+2*$_),$_,"leeching"};g $_,10,s for "s".."z";f
```
[Answer]
# Lua, 380 bytes
```
s=string.gsub
r=string.rep
function l(i)return".exe "..i.."0% |"..r("#",i)..r(" ",10-i).."|leeching |\n"end
print((s(s("Z|aY|b"..l(1).."Z|cY|d"..l(2).."Z|eY|f"..l(3).."Z|gY|h"..l(4).."Z|iY|j"..l(5).."Z|kY|l"..l(6).."Z|mY|n"..l(7).."Z|oY|p"..l(8).."Z|qY|r"..l(9).."Z|sY|tY|uY|vY|wY|xY|yY|zY","Y",".exe |##########|seeding |\nZ"),"Z","+----------+----------+----------+\n")))
```
Uses `gsub` to create the row dividers and the seeding rows. `l` generates the leeching rows. Renaming `gsub` and `rep` saves more bytes.
[Answer]
# [Jstx](https://github.com/Quantum64/Jstx), 126 [bytes](https://quantum64.github.io/Jstx/codepage)
```
►-○EO.♥/(:►+:1►+;+₧D0%4►|22♫♥φézï2♂bdfhjlnpr♀*U!↑)☺:♣<!,♂% |♀:2&₧#=-₧#/')▬►#◙')§► ◙21♫♠~√╫WσΓÇ2◙↓♫♥¿Ç~√₧#/►#:1♫♣~√▐┬╞¿:2◙►|41%
```
[Try it online!](https://quantum64.github.io/Jstx/JstxGWT-1.0.2/JstxGWT.html?code=4pa6LeKXi0VPLuKZpS8oOuKWuis6MeKWuis7K%24KCp0QwJTTilrp8MjLimavimaXPhsOpesOvMuKZgmJkZmhqbG5wcuKZgCpVIeKGkSnimLo64pmjPCEs4pmCJSB84pmAOjIm4oKnIz0t4oKnIy8nKeKWrOKWuiPil5knKcKn4pa6IOKXmTIx4pmr4pmgfuKImuKVq1fPg86Tw4cy4peZ4oaT4pmr4pmlwr_Dh37iiJrigqcjL%24KWuiM6MeKZq%24KZo37iiJrilpDilKzilZ7Cvzoy4peZ4pa6fDQxJQ%3D%3D)
Explanation
```
►- # Push literal -
○ # Push literal 9
E # Push the second stack value the absolute value of the first stack value times.
O # Collapse all stack values into a string, then push that string.
. # Store the first stack value in the d register.
♥ # Push literal 3
/ # Enter an iteration block over the first stack value.
( # Push the value contained in the d register.
: # Push the sum of the second and first stack values.
►+ # Push literal +
: # Push the sum of the second and first stack values.
1 # End an iteration block.
►+ # Push literal +
; # Push the difference of the second and first stack values.
+ # Store the first stack value in the a register.
₧D # Push literal abcdefghijklmnopqrstuvwxyz
0 # Enter an iteration block over the first stack value and push the iteration element register at the beginning of each loop.
% # Push the value contained in the a register.
4 # Print the first stack value, then a newline.
►| # Push literal |
2 # Print the first stack value.
2 # Print the first stack value.
♫♥φézï # Push literal .exe
2 # Print the first stack value.
♂bdfhjlnpr♀ # Push literal bdfhjlnpr
* # Push the value contained in the iteration element register.
U # Push a true if the second stack value contains the first stack value, else false.
! # Push a copy of the first stack value.
↑ # Enter a conditional block if first stack value exactly equals true.
) # Push the value contained in the iteration index register.
☺ # Push literal 1
: # Push the sum of the second and first stack values.
♣ # Push literal 5
< # Push the product of the second and first stack values.
! # Push a copy of the first stack value.
, # Store the first stack value in the b register.
♂% |♀ # Push literal % |
: # Push the sum of the second and first stack values.
2 # Print the first stack value.
& # Push the value contained in the b register.
₧# # Push literal 10
= # Push the quotient of the second and first stack values.
- # Store the first stack value in the c register.
₧# # Push literal 10
/ # Enter an iteration block over the first stack value.
' # Push the value contained in the c register.
) # Push the value contained in the iteration index register.
▬ # Enter a conditional block if the second stack value is less than the top stack value.
►# # Push literal #
◙ # End a conditional block.
' # Push the value contained in the c register.
) # Push the value contained in the iteration index register.
§ # Enter a conditional block if the second stack value is greater than or equal to the top stack value.
► # Push literal
◙ # End a conditional block.
2 # Print the first stack value.
1 # End an iteration block.
♫♠~√╫WσΓÇ # Push literal |leeching
2 # Print the first stack value.
◙ # End a conditional block.
↓ # Enter a conditional block if first stack value exactly equals false.
♫♥¿Ç~√ # Push literal |
₧# # Push literal 10
/ # Enter an iteration block over the first stack value.
►# # Push literal #
: # Push the sum of the second and first stack values.
1 # End an iteration block.
♫♣~√▐┬╞¿ # Push literal |seeding
: # Push the sum of the second and first stack values.
2 # Print the first stack value.
◙ # End a conditional block.
►| # Push literal |
4 # Print the first stack value, then a newline.
1 # End an iteration block.
% # Push the value contained in the a register.
# Implied println upon termination.
```
I'm sure this can get significantly shorter.
[Answer]
# [///](https://esolangs.org/wiki////), 226 bytes
```
/;/ "//:/$$$+//,/0% |//*/###//)/ //(/!
|//'/,*//&/.exe //$/+----------//"/ |leeching |
:
|//!/&) |***#|seeding)|
:/:
|a(b&1,#)) ;c(d&2,##));e(f&3'))"g(h&4'#) ;i(j&5'##);k(l&6'*)"m(n&7'*# ;o(p&8'*##;q(r&9'**"s(t(u(v(w(x(y(z!
```
[Try it online!](https://tio.run/##PctJVsMwEATQfU7Rlkyr1TEphjBFpwmJiAMmA2IIPN3dNBtqVa/@qzIsS5/LOCKBHLBA27ZToMPFGVVA4b0HIogIEDQTGwM6BRizfMq2tpie/wdwoDrkvOq3uw1RnSz@Lg04UlVVX0vOa6NoArOlPPJl52OktJI1X3XeesryxNchRreRnufBm27lmW@CaXqRgW@DRvcqO74L6int5cD31nw6yhs/BFVX5F0@5FO@5CTf8tOM4y8 "/// – Try It Online")
A bit more sophisticated approach to defining replacements. [Try it interactively here!](http://conorobrien-foxx.github.io/slashes?JTJGJTNCJTJGJTIwJTIyJTJGJTJGJTNBJTJGJTI0JTI0JTI0JTJCJTJGJTJGJTJDJTJGMCUyNSUyMCU3QyUyRiUyRiolMkYlMjMlMjMlMjMlMkYlMkYpJTJGJTIwJTIwJTIwJTJGJTJGKCUyRiElMEElN0MlMkYlMkYnJTJGJTJDKiUyRiUyRiUyNiUyRi5leGUlMjAlMkYlMkYlMjQlMkYlMkItLS0tLS0tLS0tJTJGJTJGJTIyJTJGJTIwJTdDbGVlY2hpbmclMjAlMjAlN0MlMEElM0ElMEElN0MlMkYlMkYhJTJGJTI2KSUyMCU3QyoqKiUyMyU3Q3NlZWRpbmcpJTdDJTBBJTNBJTJGJTNBJTBBJTdDYShiJTI2MSUyQyUyMykpJTIwJTNCYyhkJTI2MiUyQyUyMyUyMykpJTNCZShmJTI2MycpKSUyMmcoaCUyNjQnJTIzKSUyMCUzQmkoaiUyNjUnJTIzJTIzKSUzQmsobCUyNjYnKiklMjJtKG4lMjY3JyolMjMlMjAlM0JvKHAlMjY4JyolMjMlMjMlM0JxKHIlMjY5JyoqJTIycyh0KHUodih3KHgoeSh6IQ==)
[Answer]
# [Pascal (FPC)](https://www.freepascal.org/), ~~294~~ ~~286~~ ~~266~~ 263 bytes
```
const m='----------+';Q=#10'+'+m+m+m+#10;S='.exe |##########|seeding |'+Q;var i:word;begin write(Q);for i:=1to 9do write('|',chr(95+i*2),S,'|',chr(96+i*2),'.exe ',i,'0% |',StringOfChar('#',i),'|leeching |':22-i,Q);for i:=115to 122do write('|',chr(i),S)end.
```
[Try it online!](https://tio.run/##ZY5RCoMwDIavUpARXevQggMtPu0AQzyBq1ELakeVbQ@9u6tzyGB/nvIl4cu9mmTVh81dLovU4zSTIYdwDwVR5F4cAQU6fMo1oszhhC8ka6y3x06ItRrblQItxKMyRGVPbWpxw1aN5GnUjH4RiEavkzyeNUlr/eVggcnO@GlC1ZEHrGQ7OW9kswJTDKKDc7ByNs53bS5dZXzw3MQt2R5Rdp8/LGSch4r9KOPESWPO/7TutAxwrE/L8gY "Pascal (FPC) – Try It Online")
So... I ended up with both leading and trailing newline :D
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~224~~ ~~210~~ ~~181~~ ~~174~~ ~~169~~ 160 bytes
```
$l=("+"+"-"*10)*3+"+
"
0..25|%{"$l|$([char](97+$_)).exe "+(" |$("#"*10)|seeding ",("$(++$c/2)0% |{0,-10}|leeching"-f("#"*($c/2))))[$_%2-and$_-lt18]+" |"}
$l
```
[Try it online!](https://tio.run/##HU5dC4JAEHz3VxzbCnueZ6cR1UO/RERENw0OCw0KPH@7Lc68DMwH8359eZoH9n7b0N8JjNBCkjudnERHELksK84hXgB9QCrboZkqul0M1lpn/GMFhkAJxIXDXg0zc/ccewUpAZIx2B4L7WIVFpfa3K3BM7eDJMA@9hLtCUGJdVzYZuywtv6TXysj2wHWCOXhHw "PowerShell – Try It Online")
Now 64 bytes less terrible
Some Neat tricks: Combining a lot of "$(stuff)" to save on parens. We want only odd numbers which makes $\_%2 = 1 so we don't need an -eq for it. Now uses list indexing instead of an if-else to save 5 bytes. Also gets rid of an `n for another byte. I couldn't get "$c`0%" to separate the var and zero so the current route was 1 byte shorter than gluing two strings together. Now with -f formatting.
] |
[Question]
[
A mortality table or life table is an actuarial tool that gives the probability that a person aged \$A\$ years will die in the next year, and is used to help calculate the premiums for life insurance, among other things. One of the first people to compile a life table was [Edmond Halley](https://www.york.ac.uk/depts/maths/histstat/halley.pdf), of cometary fame. These probabilities also allow you to estimate the life expectancy for a given age, which is the goal of this challenge.
# Input
* An integer from 0 to 119, inclusive.
* An indicator for Sex M/F.
# Output
* An approximation for the life expectancy for that Age/Sex according to the [Social Security Administration's 2016 Mortality Table](https://www.ssa.gov/oact/STATS/table4c6.html), aka the Actuarial Life table, the relevant part of which can be found below.
```
Age M F
0 75.97 80.96
1 75.45 80.39
2 74.48 79.42
3 73.50 78.43
4 72.52 77.45
5 71.53 76.46
6 70.54 75.47
7 69.55 74.47
8 68.56 73.48
9 67.57 72.49
10 66.57 71.50
11 65.58 70.50
12 64.59 69.51
13 63.60 68.52
14 62.61 67.53
15 61.63 66.54
16 60.66 65.55
17 59.70 64.57
18 58.74 63.59
19 57.79 62.61
20 56.85 61.63
21 55.91 60.66
22 54.98 59.69
23 54.06 58.72
24 53.14 57.75
25 52.22 56.78
26 51.31 55.82
27 50.39 54.85
28 49.48 53.89
29 48.56 52.93
30 47.65 51.97
31 46.74 51.01
32 45.83 50.06
33 44.92 49.10
34 44.01 48.15
35 43.10 47.20
36 42.19 46.25
37 41.28 45.30
38 40.37 44.36
39 39.47 43.41
40 38.56 42.47
41 37.65 41.53
42 36.75 40.59
43 35.85 39.66
44 34.95 38.73
45 34.06 37.80
46 33.17 36.88
47 32.28 35.96
48 31.41 35.04
49 30.54 34.13
50 29.67 33.23
51 28.82 32.33
52 27.98 31.44
53 27.14 30.55
54 26.32 29.68
55 25.50 28.81
56 24.70 27.94
57 23.90 27.09
58 23.12 26.24
59 22.34 25.39
60 21.58 24.56
61 20.83 23.72
62 20.08 22.90
63 19.35 22.07
64 18.62 21.26
65 17.89 20.45
66 17.18 19.65
67 16.47 18.86
68 15.77 18.07
69 15.07 17.30
70 14.39 16.54
71 13.71 15.79
72 13.05 15.05
73 12.40 14.32
74 11.76 13.61
75 11.14 12.92
76 10.53 12.23
77 9.94 11.57
78 9.37 10.92
79 8.82 10.29
80 8.28 9.68
81 7.76 9.09
82 7.26 8.52
83 6.79 7.98
84 6.33 7.45
85 5.89 6.95
86 5.48 6.47
87 5.08 6.01
88 4.71 5.57
89 4.37 5.16
90 4.05 4.78
91 3.75 4.43
92 3.48 4.11
93 3.23 3.81
94 3.01 3.55
95 2.81 3.31
96 2.64 3.09
97 2.49 2.90
98 2.36 2.73
99 2.24 2.58
100 2.12 2.42
101 2.01 2.28
102 1.90 2.14
103 1.80 2.01
104 1.70 1.88
105 1.60 1.76
106 1.51 1.65
107 1.42 1.54
108 1.34 1.44
109 1.26 1.34
110 1.18 1.24
111 1.10 1.15
112 1.03 1.06
113 0.96 0.98
114 0.90 0.91
115 0.84 0.84
116 0.78 0.78
117 0.72 0.72
118 0.66 0.66
119 0.61 0.61
```
For convenience, here they are in wide form (ages 0-119 in order):
```
M: [75.97, 75.45, 74.48, 73.5, 72.52, 71.53, 70.54, 69.55, 68.56, 67.57, 66.57, 65.58, 64.59, 63.6, 62.61, 61.63, 60.66, 59.7, 58.74, 57.79, 56.85, 55.91, 54.98, 54.06, 53.14, 52.22, 51.31, 50.39, 49.48, 48.56, 47.65, 46.74, 45.83, 44.92, 44.01, 43.1, 42.19, 41.28, 40.37, 39.47, 38.56, 37.65, 36.75, 35.85, 34.95, 34.06, 33.17, 32.28, 31.41, 30.54, 29.67, 28.82, 27.98, 27.14, 26.32, 25.5, 24.7, 23.9, 23.12, 22.34, 21.58, 20.83, 20.08, 19.35, 18.62, 17.89, 17.18, 16.47, 15.77, 15.07, 14.39, 13.71, 13.05, 12.4, 11.76, 11.14, 10.53, 9.94, 9.37, 8.82, 8.28, 7.76, 7.26, 6.79, 6.33, 5.89, 5.48, 5.08, 4.71, 4.37, 4.05, 3.75, 3.48, 3.23, 3.01, 2.81, 2.64, 2.49, 2.36, 2.24, 2.12, 2.01, 1.9, 1.8, 1.7, 1.6, 1.51, 1.42, 1.34, 1.26, 1.18, 1.1, 1.03, 0.96, 0.9, 0.84, 0.78, 0.72, 0.66, 0.61]
F: [80.96, 80.39, 79.42, 78.43, 77.45, 76.46, 75.47, 74.47, 73.48, 72.49, 71.5, 70.5, 69.51, 68.52, 67.53, 66.54, 65.55, 64.57, 63.59, 62.61, 61.63, 60.66, 59.69, 58.72, 57.75, 56.78, 55.82, 54.85, 53.89, 52.93, 51.97, 51.01, 50.06, 49.1, 48.15, 47.2, 46.25, 45.3, 44.36, 43.41, 42.47, 41.53, 40.59, 39.66, 38.73, 37.8, 36.88, 35.96, 35.04, 34.13, 33.23, 32.33, 31.44, 30.55, 29.68, 28.81, 27.94, 27.09, 26.24, 25.39, 24.56, 23.72, 22.9, 22.07, 21.26, 20.45, 19.65, 18.86, 18.07, 17.3, 16.54, 15.79, 15.05, 14.32, 13.61, 12.92, 12.23, 11.57, 10.92, 10.29, 9.68, 9.09, 8.52, 7.98, 7.45, 6.95, 6.47, 6.01, 5.57, 5.16, 4.78, 4.43, 4.11, 3.81, 3.55, 3.31, 3.09, 2.9, 2.73, 2.58, 2.42, 2.28, 2.14, 2.01, 1.88, 1.76, 1.65, 1.54, 1.44, 1.34, 1.24, 1.15, 1.06, 0.98, 0.91, 0.84, 0.78, 0.72, 0.66, 0.61]
```
# Scoring Rules
For this challenge, **the submission with the lowest score wins**. Your score will be equal to \$(1+L)\times(1 + M)\$, where \$L\$ is the length of your code in bytes and \$M\$ is the mean-squared error of your estimates, rounded to two decimal places. [This](https://tio.run/##dZTNalRBEIX39yka3RhIiv7/QXEjuBN8AmFMLiSgE5mZoD59POeUutJNF/d2V3XVqfr69PwjvLkJt69GszWuA0xtMNXqhCnGj2wtwyRrBSZaq9ehL2vY69Navw5bH9bg3rubZg3uvVpbMMVwpGfrCSZZR5QereNnW4bjW5s2ELMNGzjfuk2EbsgIDq3amjKRDsUST2bLSKklK4n@0Qoc61LW1XOqwzrC1K7YtdnEvRXRskyEY0U0uNdsie7JMt0RDEkVBKPxYMWDFQSjacqwIBjMVjy3gmj0yApTklUELy5XXtaxl6dNXJ@HaoJhMVvuVvi3Ue1cKUkutrQmbmQrjJGkao6qBCbiKy0rzCFN6ziahs0lk7jZVUNqNtxEmiqxUrGRZKL8s@GKlGx0GSaWojq@bFWuVMXzn6pw6OywrAFQ61AIHJpyaGpGU5ZVd1WFqLqwuJA6UywXyqieZJtaOyu2ShWsdK5ZfySITiZKlIx1aooSxwwaaatSDMmWlGByQUybEddFW10rl8k2RBuTHyNz7drlyE4/On3IxlLsMa2ShuG8QGiqQHyG4zOEjyjyMsiP4@P0JKcHsQgPBSA91elpTs8QPYLoP/h0Kj2V80Z@mvhhIeCHvQI4oql4U7KtInBIOwyFBD6c3w38JOGTmvDJoic30ePwsBOghpMNalhk9WcB1DDNDdgwM2AzirCZomZOUUMdYWIVPKkIGjYf0BTNADpXnZrm1EynJjk1VSZyKroPRFNXQI3eIRAznJillQOffQIADFsFYEgyeJldRkwM1rclbwB5Wc5Lc16yQGEDwAkfEBimDVDYI4DCnxtsXkSFWS@l6R123n1Wuh4NJ7O7/gqyNUtdqAgYThck4hOi6osUKXrwiiugGqVz1suwZY2mvz9ZCP8hZTolAkHle6ES@y8mVRAlbUeHQ0DwGXZG/o3IVbgJ59vD8dXV6/B1h/3xKV89b9vzy/Dx6RJ@Pj6dwmk/P325nMPDMVzu9/Di3ePd/iKc99vLw@Pxz9/H091@CvFDuHkLadeHcDjeceMY4vvf/95fw@nb4XS47Hfh88/w/f7hsp@/HW53e/4F) is a scoring program for \$M\$.
# Other rules
* Standard loopholes are forbidden.
* Input is pretty flexible. You can specify any two distinct values for M/F: `'M'/'F'`,`0/1`. If you really wanted, you could even take a single integer, with the sign representing M/F, but note that `0` is an input for both. Or the real and imaginary parts of a complex number.
+ You don't have to take any input if you don't want, which should allow you to post answers that just always return 4 or whatever.
* In case there was any confusion, the output *cannot* be random.
* Please include a means of verifying your score.
* Builtins that have this exact mortality table are not banned, but do please implement your own solution as well.
* Explanations are encouraged.
# Additional Bonuses:
Since R is the [language of the month for September 2020](https://codegolf.meta.stackexchange.com/questions/19304/language-of-the-month-for-september-2020-r?cb=1), I will be awarding a 500 rep bounty to the R answer with the best score at the end of the month.
[Answer]
# JavaScript (ES6), Score: ~~59.51~~ 59.10
**L = 52 bytes, M ≈ 0.1150638**
Expects `(n)(m)`, where **m** is **1** for Male or **0** for Female.
```
n=>m=>81-5*m-(.9+m/51+(70-27*m-(.92-m/7)*n)/2e4*n)*n
```
[Try it online!](https://tio.run/##hZRNbxs5DIbv/hVzCOAZu2ZE6rupu6fm1lOPbYEWiZPNIhkXrhEsEOS3p@TLdrdBu9iD9XokkiIpPfrr8/3nrxeHmy/Hzby/3D1dbZ/m7eu77evGm7y624zU13enmddjDRupPiObu9M6rebpVHZJZTU/vR22w/uaqdcXg0rKKolSU4lkH0JZVJhyVAmU04uhdMq6VhrlolIpq3cpLpmyepdEuatEMguhwipMRYOUQEUncyc1z42qRsyVqprnQk0DZ81H7XOi3iDB7COxWQqJJpSZopkEiuqXOlJOnlCqVDRKKgidMjXdNWkwgQT1SxpMRyE2byYxb42lGUWNZeKxoseKGsskI7@osVwssaixzEEQJTIlDR29U9Kp6Jo0arq5VBSkYpVIoWiT2fosybohkTpGtgWhaGaMhkpAGSpBv7hTVC9uVNSSK7UOYVsrKIAzVZdgktAojlQZEsxdSDdgploglhUHnHSnnmy0jnjyDeVV2FYSO1acmVah9hkZZBxDRooJOyVESNgueg9hE0mijXYYQg1jsWopWQcoFhsFM2gGLNnaw2RFWrvYLpe2ByvJGoGOMbJjbwZhMehmgXrBaENLNtaGUWwsWCz88WyxODcqmjs0v2K1Y4faKBkI1VHRVhcHpzo4FeCAHy/FyHFwnBt2bsS5ic5Ncm6yc1PBDfD5D3BKd3LEyckgx4pRcuysFBlwFP1UhHoEMka5SnBy7PIqOQxwOAMcATeSwY1jY0ehvCQHxipM/hooMJakAmNpKTA1ApgGXloDL9ZClZDAC0fwgrMXXBzjJTkv2Xlpzgs7LwkSOnjBfcg4DwXG@FRWqrPSMdpdF78AioqdkaJSHJVWIMChWnHsrTdSupOSnRQBItZ6RcSeDRXLWRmx01FGMBlIukFiKXfk6CfrmPsVKXgqHMninUeMTFwACVCxO6XdsYcDlUd0I@KNi149CkSLxR8E3Ed/dMQflO@MNOcDDKB0rxJ9/ocQjIzV4FiABXt3/4@Oq/1h3B0Oysisv3Cm8ko7ZH/W62l4WAzDfdCVq3GeRp7O7Jt/fAd8X9q6Gm2Gt@/nj5gxCzXbDOffZ2yL9dZMV6tBhrWZ2D9bu9jPX/e3O7rdX4@fTh7mxw/Hk4f7QMf9@c3fu8tRpsdhPHkY1fnVEIY/huVyeDks18vJ4jyzm@DKv7ry71yf2U2fpsXj4udclh/mN4fD/qAOam0VnOpNtZqfWb272B92bjOOrOOVhn13PNzM1@NEt7v5@vjnNKwGrP0bZfpp8@ns6Rs "JavaScript (Node.js) – Try It Online")
or [Get the raw data](https://tio.run/##Tci7DoIwFAbgnac4my21hTYSNFhGNp6AMBAEhdBTAupifPZaooPLf/nG5tms7TLMd4720rleO9S50flR8iQ0nIgTM1EiGUljrtKvKG6ilIZII9UdfIXoStBQ1VlQ/Dro7ULQnzgDhDNItQ3GKLwCgFLMj/VGeoKUSEozT8UfxRu9g9biaqdOTPZKKiFEuQefRS1GOyDZwY5S9wE) in the format expected by the [scoring program](https://tio.run/##dZjJjiS5EUTv9RV1nAZ6CNIXLpC@RYAw0FE6SJf5@9YzZ24HKRuTrGREMJzmZubO@fevP7//@vv3H7@tbGf9/GaIZIgWm8GbflhLYxgtnaG3jJ/f87Tk2twt58/vr7la8vicd8iWPD6j5WHwxi3T2hwMo01Wmb1NJvM0bv/K3RZr5mqL@3O2zdJJRDyQ0c6uoesBb0N3WjNCytF86PnenAfjVNRxY4rVJsvErLUj2@a9wWpWQ@fBYDUeD2tDj49mepzFCMpZTMNdzO9izmIasiJ0FmP48hubs5qesFrGRwsW9wuXnTa5ZrttXm@r9sSgzXzZbK7ZFNoWgsS8nfoeumDNtcYoVK3XThg6v8ZprhjGbpNbx2r71DB0cdYeRrZ1h64hCqzhbY0aej1vjVeM0dasQYGNXhk/7YS@hcqNf9cOV927mhUBKnVshAeyYshKRlaUUe@KWiLqhX6BrHu8mQvGyom1Xd9TO24hFJpPfVvNFCB15xBEo2mfxaIhmoFRXQqBUbCNCnBcQFpd7LyutzPrW19baehtbf1Ypu9ZV0XZfW/dl2Tr1Nprt5Aa1tULQAsFyWdd@ayST6nobkP6ufK56hlXPawl8QgAqSeuevKqZ5V6SkT/Rz5TSO@K@Uv6ydKPNoJ@lCuEU2rymxRrx0s4UjuDgEQ@4u8X@hkln5ElHyv1WJZ6rniUCVQjZqMabTKuLaAahfmFbBQZsllestmlmr1LNcKRoUeJZ3iJRslHNF4cIHNxVZNXNfuqZlzVRA1drJiXEFlZQTXlQyhmXcWc@hbh7TIAwShVCEZKRi971lCaWNrf17gJkF7O1UtevVgJRQlAJzIQBoWNUJQjhKLJL0Y7koqiPhXmzfDV@@XKLNO4ypwX/1rkK9uYJZUSjNgFRLKQ2r0XIl6G5xeB2mPhbOUMX1bUvP5jJeGnUvZVSQmhtn83WmC/ZBIlolGX@xVHCUI2fDXyvyXy4/v37//88fd//fbjL9///Afjn3@zH7/WVDXpa9sefUTvOSWMkRYnx@p7bk9pxMz2yjk8In1LLrbPzIwdeXyHlOPpfa5jSw8uqSiGe8y@o7tPCSpWX@b97O7H7Gorw20M6xF7lMzWWn3a3KfzRpWraUztNQZvm5LeXLm35bbp3lMqXASYo1va6H1LkGvywBrbeON2aZMtrhHjTPYbLpnudFv3EUKckuw@SbA@54m5ttR7fJqN3U@aEyFCPgS4fG52azY10wcQ2jAHNztTVbLnXr3b7rU3Cb6fc2IY/401Q9onGjbmfevJlA2MHfrMODu5W5YA8mNZgeHdqqwuZxdPSG6FPYs3E8HeaTKLCs997ZGDGFV2x3bAPzZy7ikLIRunn@hzTANY3IRsPF8ELHKW3D57FzG6GRDhMjPCxtkAnH3JcEg3dxADaC6X96wFeyLWHKfHkg2JJyvj9MI/ZUnHiHBmD@tjbrkTAPnpc46ud6Sm@rZgm2QnRqQqPuziN/td@5wRsjGbYhFgVt7kaBX0yBVGOo7cLWDR2OKNpx05XLJ9W9pX9H1kdnPHnmPlqffJ9zbh5w2QuKY88JAv32KVnUGQTAnpmDmysFRbYQAI7uLHPkNe6bFzHpC3FTlkmwlrQPBJElnohGqbFMJT25nyUegRyv9ZYA6RZa3C7TzkSeKwWXD2tR76XOW4qGOhpV70KvPlZmgD9wdECHUui80sX2ff5GmKUKafk1nSkT/DGaJxWA8wcmry@tgZmUSiJrMB8bgSzSMDR@MB2opwgY6myKREdTMAl4bkD@KBlXhuBa7eSCRG1l50zuqTUAxec1KRWrVMhrbzIVN0qnIQgJQPneIK1UrhEefM6RuvUpUglZEP/yFd1WGB0RmIrXa4NAXTDkRQBnuiuaHuWuSS1zmOsVRVWCHmfGq1ppyAx35KyFV0VmCc6xJ6rdAUyELmfjMBz6hFdsoXLUgspqy6RFCr7OTgNqpRIgdkHlJeGDM9cx9/qBXXQ78TF7enWgczHUOGABI4cVLM4AheIwdaWBQeTEWzZVepkB8/IZtcjkrcJiZmxPlhpbg8JJiuukOmeGoVY6Bbwsv8KVUygJ1BiQeK2M/@LsZRXaQBJCwS0KgQ7TxyLgkIipMAJ8wsLu/BoI7ToYjvvUTNhcrIibizHnJVIVBVGtr7Q6@m2spuMQfoxYaoObh@H1vWaLKjDtrq2cG/F0sCDEL19nLy2gpbVfE1Fu7XmZ2sVgkmIf0p2K1CDE74wtUr2lJVhqmslLMqFjHAioGmbgqQw9CDk9wjkEdB1U26RuqE5kxYp6kk3/aoqL0fTcFb/PgKFt5qKuaTz9DINaPiLSAmpYwF9T4rsVxHcgBl6gD3ftRVYlGg4hvcP1Lf1m5O13sehXUUMNwLG56SnYKPGKevh2THBdSBeKaJM1kYawflq/qgjm/qKy18p7PA1ujilShKw5LFH5GeXh7HOxHVzhNE1nEYd/LqXOAMLK1DsTzM1KlQYrpXh4L/qi0hKxBe/QgABbSkDykoTP0H2FIR1HdsrCXVb0gEAESfQcFBRv1@hvqMA6uWqb/AeFCf@gpsXr3EIbw@q4eQMVU3QatB1LdnOEeNARp11RF1CGFiWqqpdeR/Hp95j9ZgaeoIcA5XbwC5NUE72CdOq7JPI4EHqdzTWyCEOimgbTq00HkzVHrpyun2VhVzvFINHVXcVlUhqjdSkgZCR9pQpUYYm@JHOUYOnZZDB2/xxOrsTdQqGfeTdQ7vKt9UXZowyKtqSzuAnlRlITz/Hhj2KrNwCrnzV1VToo1HFUWFHyiojKJseED5DEeX/r5oskh4rgq5MF/Pd0hUSLaOmegvEocpPS9uFUuVPPePKc4TEIpyKKeEK5RBNUtwhfqH4uHwx@pkgHJIG/H4mEqiB92Uyh66wQHegepYQwk8r42te8TBLqxOOYHoPjY21AFXicPK6TD0F91u9P1@3xD1yfwL1lQd2wi7f2SGKeQv48I8F/V7ftzOvtSerY/bybyLiM@pUwWNfvi8tjqqoOXrvTXFnjcyzPdzEJ8Dg70Wd8oXb1v9Y@0l3dRZQs0aSnjjw3kMu17zTRrUDzb@WlDHNBgxPtajU6XurI@skOj9gkMLZx3lqAGqX44DxGvB0P8EUczjPcPxcsvXPiJDLRLLa0Zkbyp2@abf0gkwEcI6H6RBQbD@BdxURTOV8ufyIpsOhLR2kR9PyjfVw78Adx0SXV3aKwVbFrzpN167V78lnmNJH0nHVXSUec2Uwavpfa1Or6qTs85JLyCrqG1V@7dkmHnnRyna9yb8/jm1/S4195sH94US2SvQqLDou/yNPKFThd6hUyuGfMpewqLWCgbE@vLnrl6Rupp0Ie9A69i3XwKjK//1678).
### Method
This is based on two cubic regressions, with a trade-off between code size and accuracy.
For women, this computes:
$$f\_0(x)=81-\frac{9}{10}x-\frac{7}{2000}x^2+\frac{23}{500000}x^3$$
And for men:
$$f\_1(x)=76-\frac{469}{510}x-\frac{43}{20000}x^2+\frac{17}{437500}x^3$$
### How accurate is it?
Below is a graph of the errors produced by the function according to the age and the sex.
[](https://i.stack.imgur.com/9WSaa.png)
[Answer]
# [R](https://www.r-project.org/), score=~~67.47~~ 47.92
30 bytes, MSE = 0.54587
-1 byte (and -1.47 in score) thanks to Dominic van Essen.
```
pnorm(scan(),31,41,F)*scan()-2
```
[Try it online!](https://tio.run/##dZVNjhw3DIX3OoXgbLqcGqKofxnwNqcIDDR62s4AcbXd3QPP7cePj7aTRbIRq0oSi3zkJ11fX7/sl@vnw@103A/LmnUtuv6xvPX3h/SaawxhjhB@i0/7l@d7/Ijlx3t8usXjp/Ma9/O3v592PNzOL2s876fL4/kxzmHr4ufzHo/7Y9St8f3bBV9CuF@f73/F9/F06FVmXyNMqTBFyoDJYi9JaoJRqRlmk1rW2KZUzLUhta0xtC4V21tzU6VieytSJ0wWLGlJmsKoNHhpmzR8rFOwPNQhHT5rl471tcmA64qIsKEWmYNmsw1Z1FYmSQipqkAn7N8kY2OZjLp4TKVLg5vS6LtUGfhvgbdEs2FjgTdsL0nUtqsk2w5nCCrDmRl3lt1ZhjMzlRFmOIMJ2WPL8GY7Et1kFRQwZpcrTWmYS0MGfp86c4KxZEJqku1rNbVTMUlSlslRbSJJNh9KVdPGTGA2vOmUbDHokIal2mVMGrXJxhy0SnezmSkUS7N0pdm4Pwl@oSq90VhgurHiU2ax0VTx@Acz7FzbJbEBWDokgg2VMVQWozLKwn8Vuij8YXYhuSZLyiYja5JkcGyWsRRTQXKzMfELBeFKNYlULE92kVqbQSNOFRODsikDVBdEOLnhd5vMxtGGYWXYpA976cnGxllr2eFLhzdZn/TdhxSjoTsvENpUMHy649OJDynyNIwfx8fpUacHvgweE8DoKU5PdXo66SFE/4NPM6UHYw7GTyU/lgj4sVoBHNKUvShJZiY4RjuMCQl8rH8D@FHio5X4JNKTKulxeKwSoMY6G9RYksWPBVBjYQZgY5EBm56JzSA1Y5Aa0xFmK4RHM6Gx4gOazB5A5YpTU52a4dSoU1NoNuuK5g1RWRVQw3MIxHQnZnK0hk/eAQDGSgVgjGTwMhoNmeiWX1AvgPEynZfqvCSCYgUAJ3aAwFjYAMVqBFDsY4BN01CxqCfD9Ao7794rjYeGk9lcfzoJVbQRFQJj3QWJ7Ahh9pmKZB542RVgjtQ58WQIia3p508iwj9JGU4JQWD6nijF/oVJIUTK6c3hIBB2DDsj/43IEsL5/ohr5OPzfro/XfbDy3pb/Dp7@ddN9pCw8HrF9fMeFxKutYPfPw@4f@DgsL1TO4fnWHB//fOOO2tZlg9pCbfT5XrG5kPefo@6xLfx4P7sLZyO98Mb8xtvX5@PV1x@nHz3ZvWHHyv@3OnGPvNhef0O "R – Try It Online")
The input format is: age as an integer, then a newline, then sex, then a newline. Sex is encoded as 98 for men and 106 for women.
Approximates the actuarial tables by the survival function of a normal distribution (the survival function is 1 - the cumulative distributions function). I tried a few families of distribution, and the normal minimized the MSE.
Let \$\phi(x;\mu,\sigma)\$ be the density of a \$\mathcal N(\mu,\sigma^2)\$ distribution. The approximation used is
\$f(x)=a+m\int\_x^\infty\phi(t;\mu,\sigma)\,dt\$
I tried using different parameter values for men and women, but the best score is obtained by using the same values of \$a\$, \$\mu\$ and \$\sigma\$, and picking only different values for \$m\$. Since \$m=98\$ for men and \$m=106\$ for women are the optimal values, I use those to encode the sex directly.
(Actually, the optimal values would be \$m=98.25528\$ for men and \$m=106.34315\$ for women, but using such values to define the sexes really feels like cheating. It would lead to a score of 47.49, a slight improvement.)
Plot of the approximation for men:
[](https://i.stack.imgur.com/SG1js.png)
Plot of the approximation for women:
[](https://i.stack.imgur.com/CSBFe.png)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), Score 151.8,
# 32 bytes, 3.6 MSE
```
#-Cos[x(Pi-.02)/238]~Sum~{x,#2}&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X1nXOb84ukIjIFNXz8BIU9/I2CK2Lrg0t666QkfZqFbtf0BRZl5JtJKju6sCDPg6@iA4CODmCpJQiuWCaKlW1lFSUFDSSY82N9NRjoVzLIGc2lg1fYegxLz01GgDHUNDy9j//wE "Wolfram Language (Mathematica) – Try It Online")
I noticed that the differences of the values were similar to `Cos(x) [0,pi/2]`
So, accumulated Cos(x) works pretty good on men...
***MALE***
**MSE 0,90**
[](https://i.stack.imgur.com/yP6hJ.png)
***FEMALE***
**MSE 6,29**
(*I guess Cos(x) understands men better...*)
[](https://i.stack.imgur.com/HBhqS.png)
Special thanks to @att for golfing my code down to 33 bytes
[Answer]
# [Ruby](https://www.ruby-lang.org/), score ~~56.12...43.94~~ 43.92
\$L=35\$, \$M\approx0.220060\$
```
->x,f{f.*1.87e6-(21676+(66-x)*x)*x}
```
[Try it online!](https://tio.run/##fZVdaxtZDIbv/SuGbAu2E2vn6HxDs/cLLfsDjCneeEwNu7VxEnA3yW/PvnqV9q6FIGXmSBp9Pcfnx7@/ve5uX1d/XG72T3tZBml1Kqu5hlLL9byU1WWxtL@X1932YTvcDuuapdebASplqCSpQUWxB5WsUEFyhBolp5uhdMk4K01ygaqS4V2KqywZ3iVJ7lBRzEKlBKggBUHKKAUvcxeY5yYVEXOVCvNcpCFwRj6wz0l6oxrNPkowSxVFQjlINJNRIvxSZ8rJE0pVCqKkwtApS8NXE4Ip1Qi/hGCQKsG8g6h5IxYyiohlymNFjxURy1RmfhGxXFliEbHMQRklBkkIHb1T2qXgTJs0fFwrC4KySrRItJfZ@qzJuqFROmWwA5VoZoEN1ZFlQI14Cl0ivEKTAstQpXWqYGeFBYQs1dVoKrFRIUoNVKO5q@ADIUgtVJZVGDnpLj2ZtI548o3lVdpWURsrZ4YqYJ@ZQeYYMlNM/FJihMTPRe8hbaJoNGnDUGmUxaqVZB2QWEwq37AZtAzWHiy0CSvKlgvt4UmyRrBjgdkFb4bwcMTHRumF0kRLJmujVJOFh7anzS2b71btDF2bJCOgOiPocXFiqhNTSQzB8RoMGSfGgQkOjDow0YFJDkx2YCqBITc/IaZ0R0YdmUxkrAogY0MCKwQo@jhUeiQrhjfU6MjY1gKZQGJCJjFKYDQTGOfFZgBQkpNiFSa/BkCKJQlSLC2QUiNJaQSlNYJiLYQaE0EJkaBw6MqNMVCSg5IdlOagBAclUY2doHARMucBUgxMQFIdkk5pS64@eTBiMwIjxRlphYocVCsueOsNke6IZEdEyYa1HmzYfQFlOQMOmw7g4MtRtBsdlnJnjj5Z59tXpPCOcBaLd54xsoRCOsiI7RS6YzcGK4/sRuTlFr16FsgWq98E3Ee/bdRvkjc4moPB5WfpXiX7/AMNysDT0XkgBHbh/gqLzWy2PZ3Ox4v9YGxmayCtdVplIl4U/21k2t59eRqe98/weDw9HOch9AVeXJ6HN98PH4bd@nIz7DfDy/Aym87n4xkBsZIz@zFihM@Hr7vpArfD8@AG17fD3AOsD5uVGUIvlkv9EeL324H@94f/ptnsI0L@@Zecp@3un8PX6X7@blysw0buvhz/PbnNJ5jQdXZ/dzxPeJqH64@LJeSnxez0@HA/XH3P7rcn/vdy9fb@u8d70f3Vez69/g8 "Ruby – Try It Online")
Input is an age \$x\$ and a float \$f\$, which is `4.027e-5` for male and `4.362e-5` for female. (See below for an alternative version that takes \$f\$ as an integer instead.) The approach is to fit a cubic polynomial to the life expectancy averaged across both sexes, then scale this polynomial by a *sex factor* to recover sex-specific approximations. The polynomial selected for the average life expectancy is
$$
\frac{x^3-66x^2-21676x+1870000}{23840}
$$
and the sex factor is
$$
\begin{cases}0.96,\;\text{male}\\1.04,\;\text{female}.\end{cases}
$$
In other words, the life expectancy of a male is approximately \$0.96\$ times that of an average human (male or female). Similarly, the life expectancy of a female is approximately \$1.04\$ times that of an average human.
The plot below shows the squared error as a function of age for each sex. The dashed grey line represents the mean squared error for both sexes.
[](https://i.stack.imgur.com/At9kh.png)
One point of interest in the code is the explicit call to the `*` method of the float `f`. Everything to the right of `f.*` is interpreted as the method argument, so the polynomial [doesn't need to be enclosed in parentheses](https://codegolf.stackexchange.com/a/101857/92901).
---
# [Ruby](https://www.ruby-lang.org/), score 50.06
\$L=40\$, \$M\approx0.220981\$
```
->x,f{f/9e3*(56541-(656+(2-x/33r)*x)*x)}
```
[Try it online!](https://tio.run/##fZXdahtJEIXv5ykGZwOSbJen@r8h3vuFhDyAEIvWkoggGwnZBiW2n905dcrJ3S6YOp7p6pr66a91evzn@@vm9vX6z/PV7ml307dxMcslJ72elVwuZ@H6fBPjab4429/L62b9sB5vx2XN0uvVCEkZkiQ1SBR7CJIDRCVHyCQ5XY2lS8ZaaZILpErG7lJcsmTsLklyh0QxjyBFISoFQcokBS9zF7jnJhURc5UK91ykIXBGPvDPSXqjTOYfRc0zSEBCWSWayyQR@1JnyskTSlUKoqTC0ClLw1cTggXKhH0JwWCDqO1WCbYbsZBRRCwTjxU9VkQsk8z8ImK5WGIRsWxDYJSokhA6eqdCl4K10KTh46GyIIhVEopEe5mtzyFZN0KUTqu2ECSam7KhYWIZkAlP2iVilzYp8NQqrVPU1goL0CzVZTJJbJRGqUqZbHsQfEBVaqFYVjpx0l16Mmsd8eQby6v0rRJsrJwZqoB/ZgaZY8hMMfFLiRESPxe9h/SJEqJZG0aQRlusWknWAYnFbOAbNoOeau1RsSKtXWqHC@3hSrJGsGPK7NSbIVyc8LFJeqE105LZ2miD2cJFO6fNPZufrdoZujZJRkB1RtDj4sRUJ6aSGILjNRgyTowDow5McGCiA5McmOzAVAJDbv6DmNIdmeDIZCJjVQAZGxJYIUDRxxGkR7JieEMmR8ZOLZBREqOZxAQCEzKBcV5sBgAlOSlWYfJrAKRYkiDF0gIpNZKURlBaIyjWQsiUCIpGgsKhB54YAyU5KNlBaQ6KOiiJMnWCwoOQOQ@QYmACkuqQdFo75MEnD0ZsRmCkOCOtUMhBteLUW2@IdEckOyKBbFjrwYbdFxDLGXDYdAAHX04SutFhKXfm6JN1vv2IFN4RzmLxzjNGFi2kg4zYmUJ37MZg5ZHdiLzcolfPAtni4DcBz6PfNsFvkjc4moPBw8/SvUr2@TcatMrVyXkgBHbh/h8Wq2FYH4@nw9l@MFbDUtmqlWzXd1@exufdM7wejw@HmWqf48X5eXzz//Bh3CzPV@NuNb6ML8P2dDqcEATHcLAfIEb4e/9tsz1j2/55dIfL23HmAZb71bU5QueLRfgd4uZ25P77/Y/tMHxEyL8@y2m73nzdf9vez/6Y5ktdyd2Xw79H9/kEF24d7u8Opy2eZnr5cb6A/TQfjo8P9@PFr@zePfG/l4u39792vJewu3jPp9ef "Ruby – Try It Online")
Despite being within the rules, taking \$f\$ as a float (as above) feels more than a little 'cheaty'. This version uses the same general approach, but here \$f\$ is an integer: \$12\$ for male and \$13\$ for female. The polynomial used for the average life expectancy is
$$
\frac{x^3/33-2x^2-656x+56541}{720}.
$$
[Answer]
# [J](http://jsoftware.com/), score 53.76 52.78
`L = 46`, `M = 0.122983`
Takes M/F as 1/0 on the right side and age on the left side. A simple third degree polynomial approximation. The J polynomials read from left to right, so `81 - 0.9x - 347e-5x² + 455e-7x³` for the 1 case. The 0 case just modifies the numbers a little bit to `76 - 0.92x - 207e-5x² + 385e-7x³`. `p.` evaluates the polynomial at `x`, in this case the age.
```
p.~81 _0.9 _347e_5 455e_7-5 0.02 _14e_4 7e_6&*
```
[Try it online!](https://tio.run/##dZTLbptHDIX3fgrCRmzLF2bIuaspULRAV0UX2aatYLi/nRSubUgO0EXhV3fOoZVdstCRNBfOIfnN/PNyqCc38uNaTuRCdvhOws@lyi/vf/v15VGfh8km6ZRNLn3ZVCm1Lpt@WSVpctlYWTZFMNOOz15WB7//rIJNvcUmzHuKXXlw1/m3dh08XW1vlyea6FVnp5YqvWgZ0rPip2t16aY1S09ai7SptUobWpu0rrVLa6FV65BWtE5pWTHp2kyaacvSkrYmdWqXOrQXqV37lNp0VKk42qQWnYOasDCrYY2ru1TTjNmkeUqZNFbi7NK1oSSN0UrVkaUUpg1NJgURpLgaNpk6NiFAl4wA0AiQI0BGAGilkYwAobCQEQArnXuzaTHJkb5PbV186HDxTstQmPWmGSMognhBmp7ROIhh0DVjgbE@nugUmobY1FzFhjYX6zom1TDeaNKq9tAELczesnajJuxyLWKm6DYU51tii6bOAkGmYXDQfeeiro6OsObwmaXytMpiVjopDFy4rTB4jpJwNqtnCArqOigNiWhBZpobxPmXKXKJIWNT@Ef66Do@lYMF2bEARgsWCSrHUwaRs1HwGQXSB8UlaEnEZ8SSEd3vk7H60AIWe4CKSrWAtge0ndAS3fBIagPaYNaCWQ9mczBbgtkazHYyS3K/BW2bQa0HtZXUwiioRYXBKwnOUU/XmckrLhI0BbVACdQaobVKaJ3MOi@zBrKoI2AtQSsSKHHVQCvMgFYYAK09k9ZBWMcgrKgJNBXCapmwsk/O1hLWErDWgHUErBawFmqahJWdq6wqaMVlAKk9SJ0UIOfRLoCKMgPUFqCORiWQHeYtakhOZ3Bag1MnoaghCMVthMIZEEWFLZ4lqE8JY5NeoilxkaKljVcwLkCLCnJjVWtklKCi90gZt5E5ZSaZ@T7kSIvuWSyPq0Za4v56XNBXREfwSRCZUiTAen0llGKcSAEmecTb9D08D7YPn@//5vP5YX1qKb15fqfnqPy7tR3/v8LA2Z8vy/XHBzlZ/rv69/FuWZ9cHK7RLjm9@OFmJXawn91uH7ZrkZiNP4y5f5xPj@TNMw44fyt/Hfvqp/WlbJfd57t4ti8E7uTm@TC9lU@4iWkf8W65v336uH6NeLTbj@6uH7bL13NevZ/a@dFuJWf8ESev9ms3lyeye9p@ur/dLo93V9fLoQl2bSzJhz/2Dr4A "J – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), score 94.40, 58 bytes, 0.60 MSE
Just simple linear approximations. `True` for *female* and `False` for *male*.
```
lambda a,g:[75+5*g-(.89+g/30)*a,12-a/11][a>81]+(70<a<90)*2
```
[Try it online!](https://tio.run/##hVXLbhtHELzzK@ZiaJeiWvN@CE6AIJBPMQIkuQk6rM0lI0CihCUVwF@vVNcwCQzYyGVqd6anp7umavfly@nP50N4@/y8nc0P5uLi4u1xevq0ncy02d/clXSZ1vurQWq73F8HO66njfNX07Vz93fTj9XdXw7Fvp/eNyz5N2yX42l5eBnG1WqHfPNf0@OgufH@4fbjT7/cYvKuWml5YwChbUxpEj2gSgyAIjEBskSElCSxAGKHILECvETd50QDrY65SXKAKgmpcpGEVDlLioAkSUOiJOTIQRI2Zy9ZNzjJGmkl47TUJGMtVSnIkooU7EtZCg5NSapORqk6GcAIwEvD9uSkFYJFzmTFIllsgpdYxSE@FsHmmMXrSxJsilGChqEnjfPsMDpWHi2LDI1lBdSDyVAEdYQsVSGRQoBFiyGK04ggXsFLUHASdc2yfY9c2OerVBzni7RIsDjHoy59S7wPD6KQ2gey4NEiR4vyvBOvS5Z35JBSASkzQUNc0eZcp94lKY1gNRAdI6MLpN4hsSdozc7xdpztk1Y89vWSG2vsN4uyVQA8PkvjqLzlzjxzJHHKK28tUlNgB6uBnQeyESTwmd2zQVLsJSlH1CPq4rNTZpjekXknRbvtrfcuybOTwNFzdFxVHViWjNHpWKOOhTNKbxceRne/Wv3jD6he9aTiT138leJP1D556DpR8ceu/tTVn7v6S1d/6eqvXf2N6s/fF3/p2o9d@43ap9oTq4f2tRWA9gULKDWwgPfUfujaVwlB@1py7AVB/EoW1K@pof7a5a83DVBq4YJuAtdoAqUeJgiFJtAbDj1X6LngAvUm5K/1Qf6tgxYGF7hCF2gWdYHrLojdBaW7wHcXVAIvOVOecEGiCQo90Di67gS9YXiAIrFsA2ArrRC6FbKnB/TrAHCVXtAG1AsdaJNIouCF4gg0CJRHK1BhjlXBCnrTjX5tZKQXX9leYWyhLTPvLNP8qX@feA2JJUaeFJkh8rjQOWTM@cvBy/D9EyGZyo90h36qfP9KdDLOjmi0BV1BU9ATXFEP/esJzpMM4aINtES3x//6YjvvzGla9vNpmPbzxuznw3ZexpuVMQ@785u@GLPMp9flYPqv5g7B95ieH4/zV8v/LTL10zwdhkemOwccX58wYa7N46wrq9XTUf@Oy/PrYTsw/A7Bw@6rcszVt4oc12uP2N3zYjBtHg5mmQ77eXDejuf5HqlLwx/LK7Z@mFDxuLofwfO4@vTlNB9xutZy/pUePz8vWtDgLrk6mrU@P@mu1cvycDgNF7///Otvtzc6/U78blzrw3bEJn29MO/MgPCN4f6NYcZxfPsb "Python 3 – Try It Online")
Visual representation of the approximation:
[](https://i.stack.imgur.com/dVqs2.png)
[](https://i.stack.imgur.com/6uz36.png)
[Answer]
# [R](https://www.r-project.org/), score 46.00036
*Pushing the limits of 'any two distinct values' as input more than somewhat...*
45 bytes, mean-squared-error 7.9e-6
```
function(a,s)s%/%gmp::as.bigz(1e4)^a%%1e4/100
```
[Try it online!](https://tio.run/##nZXfblw3Dsbv/RSDFFnMtI7K/5IC@NZ3foUGE@c4O4Bjez0OtunLpx@pIIsU6GKxNo44cyRRJD/@NM9f709327vt96ft9uX4cPvl6uvd54fbl9Pjw/54eT6cX//6@uOnp7dvj@f2/vTxjz1vdvjt@Po17K9M9PWn3Xn7fXc6787wcLo7bR9277/sXv657e4e7@8f/316@LjDxnZ6eNk@bs/ntxc3Vz84fBVwE0HUBc8gGkY0CU8QkxJjmnkQC76rEZsQOxNjC3c82MJYj90kLCRiJBokNkkCn0d5IRUltUHanYzwaCfrjE@DHO99TApVij4RSlDvQUM6jSE04W9Ow2JlZmPuwTiGlZy1441OdursvXPAaefBfUweITzVpZIbKuxDRE2UYRCedRJ3hKkiHYn1OQTnyYwO16Y4CjNDlTsyD7Xp6sM1umsP1@Gh07qRhrEMw2nYRJZVsinmQy26GdYa1trESDoRNLuIIBtz@HWbwx0pBEzv00c3n50CugSHhtRIgbfhPiI8EEJgecTEFsSK5LWLS1cUwmx0N@9w8upwcf2/CI53EyLjTJSTVnUrDYiNJxxiY26Mb0JDWIgjaAZxvEO9BE2g6BxUixRVVQgPqVANhdAQGB2TsWZbQSRC5IgUD84d0Gjmf2CTIJgpDDVTJhZ81kiRoR@8eJ8IxyBJ9h6kHsEzEIg5@i9EkBhiEZQDCgSqPPEW4sJpnwaB4TIGBM76w6viL9uCVbMtUWONMRRC6OjoExxGju5zdA7ExkLsghZIC94NZbSBIs3sZYjJicfsLug8HTOVh2bi0QfExUfINGP@KC7eIFaIm4Nlf0FcQYmAWHU2koKoACjbCeICDwiM@vUBkjItNNag6RD84qfd7fH@9vP98WXb/WP34XR@uj9@2d3g8/Xu@1Vz2s4XuezdzdX5@PR0/2VPb5nn5X/unwNa5sPj5/f32/4vt1TeTVc3h8Nhebj@Pz1cf/dw883Rj7F/2o4Pb87/@nx83j682Z6fH58vnrc7BHy7795mv9zBmMNYswGjLb9Ic4Hh5gpDze1yF7M55mI0D5jeHLsjlvHm2B3WfMJoyxXSgmG4BZwEtcBLnw3LfbQOj95bx3KPNuDYEQ/Wu7U5ylCu18a5UpogIOemuYSaYp/NCtlWQNZbwItFuTZvA6canEkZwj6DM4zSOHdzk9wNX4hI4SvN8qXLl8JXGq/4FL6WycAUvnKDlBflZnCtq1IyW2BORhs4XHolBJOZSDTNl551FstqiLZZI@eENM1lXAUVqjRgCN94NsUuHi2wknsbswznXFQC7K0vQ2msCsXaOpeh3C4NBzC3HmUyKqZSerZpOWZFVvCj0uu1tjdJWUszZIH1XhF4yeAVotVJVh6sjtNVw1qjTTTHFEPaqDEy22ZZgaaRo9SbKkat5CwPt0wyy8XZXChPzVgWoirGFR2vYrSaJBxGbUaNOQzLsY8aJceoyeBDYXENLMbaMVaP9VlH9NEsSeiLFdQ6Fjl9kdOLnAJo5ZLoLHIWOLzAkQWOLnBsgeMLnF7gFD9/Q07MhY4sdLzQyWyATooFZgokXbJIm1rMJOYwtNDJ7gU6XOSwFzlS4IgXOIub1ALA2CImM7R1HYCYDBLEZFggpmsRMwqYMQqYLCEMWQHDWsCU@FKdk8DYAsYXMGMBwwsYK0OzgKmG8NIDxCSggKUvWGaN2eyyOgCspEZgJRYrI8oUDz2T41X6RGUuVHyhIsVIlh6M5L0BkzEDklQHkNRLajKTkgx5VoxL2cX5apGou2IxGavy5cMbR1FSrGRPoTp5c1TmWtXQuuR0ZV8JVoll3QjVj@vWkXWjfINkLEAKgkp9ZVl1/o5IjVyztLgoGPLi/e94fDpvV/ljst/f7usX5M361bksbtYX/Bj9JrX0xx@h8@3j83axN/@FDz/vMQ379U8 "R – Try It Online")
Input is an integer `a` as age, and one of two 'big integer' values `s` to specify M/F sex.
Output is a 'big rational' number.
As (presumably) encouraged by the generously-flexible input rules, the sex-specifying values are integral for the calculation (although in this case probably more so than intended...).
Each of M,F big integers are constructed as the 1...120th power of 1e4 multiplied by 100x the life expectancy at each age: essentially, a base-10000-encoding.
The `life_expectancy` function simply decodes the `a`th base-10000 digit and divides by 100.
Even though the function uses the arbitrary-precision `gmp` library for calculations, a small number of the decoded values still contain inaccuracies at the 2nd decimal place, for reasons that I don't understand.
Nevertheless, the mean-squared-error is (as expected) sufficiently close to zero that this doesn't matter, since we need to add 1 to it anyway to get the score.
[Answer]
# [R](https://www.r-project.org/), score 75.74445
61 bytes, mean-squared-error 0.222
```
function(a,s)s*predict(loess(c(82,58,35,14,3,1)~c(0:5*24)),a)
```
[Try it online!](https://tio.run/##nZVNj9s2EIbv/hUCAhTSVjvQ8JsBfPXNf6GBopVbAYrtWnabvfSvb2feCbZIgebQC19bHA7ngw95e1uX0/xp/nqdp/t4nl73b6fHebovl3M79lu3PV1v88sy3dv1Mm9bO7XF9bH0PvYcet9z99fUDh/jkwtd14/d24dmm782y9Zs4nE5LfNL8/m1uf82N6fLul7@XM6/Nn@M62PePu6O@4Gq2x32vNt9aKZxnR7reJ@bn5qXZbuu42tzlN@H5j26Zd52avbpuN/G63V9la2Za/9PyN240cvl8Xmd238lpunsj13XmYfD//RwePdw/Obo@9i/zOP5efv9MUrZnufb7XLb3eaTBDy1OVLNfSMSokigUEQ86R9H0YkwRS8yUAx9kypFmUuFYhLJFGV1SiaRpAtNChSriCe1cJRYhCmJkzRQko@xkpjHQlk8xkxZzGOiIo6jxCP2MVAtkEHtPbFaOnISUGTyajKQl3WhIuRgAYVMSbyEBNchUpFdgzhzkEHWBXEmoyPW1UxOV4sviciLLxXz5c2XF18qEfF58WWigXnxpQscvHimIK69VcpVSjLnCsnpbFxGQiKaiUvk9WPUOrug1XCeKkbWCUdezRgFdQPSEBnkH1eSg95woSSWnKlUCOtcQgIcKZsMKgGFYk@ZIYMudyQbMFNOEI2KB3S6Ug06akUs@IL0MmwzOW0reiZZiH1EBBFtiAgxYKcADwHbeashbDw5r6M2w1HBmDRbCloB8klHhy8oBixZy8OkSWq5WA@XlAczQQuBijGiYysGYXKQzQTphFGHEnTMBaPTMWEycQcsDoJFsRXFzliu2CIXCkpCNlak1snIyUZOBjkAyHJRdIwcA4cNHGfgeAMnGDjRwMkAB/z8BzmpGjrO0IlAR7MRdLRZwgxA8tYWR9WDGcVcZDB09PQKOgxyOIIcB3BcBDjGjfZCgAlGjGYY7DoQYjRIIUbDEmKyBzEFwJQCYLSEIkMAMOwBDJrvcHIUmGDARAOmGDBswATIUAEMDkREP4QYBVRgyQZLxaiH3dkJEFa0R8JKMlZKgoCHrMmxlV5RqYZKNFQcGNHSCyN6b4hozAKJdocH@ziQq0qJhlwRo3XWOLcjknBXGJPJKg8fkTiBErCiZ0qqozcHMveohscl5y17JIgSO7sRcB7t1nF2o3yDpBgggACpW5ao8zsiGBmzg3EBGPTi/TEeX7Z5r49JK28uXpBne3V6cGN/5DH6xcH0@0domy63edcm/pm7p1amRd/@Bg "R – Try It Online")
Uses loess smoothing to interpolate between hard-coded data points.
The M and F curves are remarkably similar to each other after scaling (by 0.92x) - see the black & grey points on the graph - so the hard-coded points are taken from the mean of the two (scaled) curves, and then rounded to nice, short values. The red line on the graph shows the interpolated values.
[](https://i.stack.imgur.com/9Szon.png)
Unfortunately (for me), the scoring system of adding 1 to the mean-square-error strongly rewards reasonably-close fits, but doesn't give very much more reward for a *very*-close-fit, so the extra code-length here means that the overall score is still worse than Robin Ryder's looser fit to a normal distribution.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), score 34.16
## 27 bytes, mean square error 0.21676 (rounded to 0.22)
```
#3(#2-#+Sqrt[(#2-#)^2+#4])&
```
[Try it online!](https://tio.run/##hY1BC4IwGIbv/oqhEIlrbXOaEkInb0Vkt7Fg6SwhDUVP0W9fMyHoUt/le@F9eN5a9ldVy77Kpa6aIgUJyFQ7qCZXPPJRgEMIMGKrmEFAKUWRWFuG235xGAXxxIW@@ZRFKDBcmWjHnzt04XhZ2/X8Hd0T9Rwm3Jned1XT86M83xS3ANhtDvehKTgoubwoOI4IAMmSYCxMPR58jA2GhMRPYQYmg21/4g9Z@kemXw "Wolfram Language (Mathematica) – Try It Online")
An unnamed function (which we will call `f` for the purposes of discussion) which takes two arguments (in this order), the age (an integer from 0 to 119) and the indicators for female or male in this form:
* indicator for "female": `Sequence[83.506,0.4794,222.8]`
* indicator for "male": `Sequence[80.596,0.4636,248.5]`
In Mathematica, `f[a,Sequence[b,c,d]]` is the same as `f[a,b,c,d]`; so `Sequence[b,c,d]` is almost exactly an ordered triple, except it's better for plugging into functions.
The above code implements the mathematical function
\$
f(a,b,c,d) = c\big( b-a + \sqrt{(b-a)^2+d} \big),
\$
where \$a\$ is the age and \$b,c,d\$ are numerical parameters used to optimize the fit with the data.
This specific form was motivated by my perception that the graphs of the data for each sex looked like a hyperbola with a slant asymptote to the left and a horizontal asymptote to the right, which can be brought into the above parametric form (here \$(b,0)\$ are the coordinates of the center of the hyperbola, \$2c\$ is the slope of the slant asymptote, and \$d\$ controls how far from the center the hyperbola bends). An evolutionary algorithm was then used to fine-tune the parameters for each sex separately; experiments suggest that there is a single local minimum for each set of data, as all attempts converged to very similar values for \$b,c,d\$.
(Technically, the entire function could have been used as the sex indicator, leading to the 4-byte solution `#2@#` with **score 6.1**. But many of the submissions could have done similar things.)
] |
[Question]
[
Given the spiral of size `S` and the step `N`, output the "square" `S*S` spiral having `N` asterisks, built from the outer to inner radius clockwise.
Test cases (examples) below.
1. Input: `4 3`
Output:
```
***
```
2. Input: `4 6`
Output:
```
****
*
*
```
3. Input: `4 11`
Output:
```
****
*
* *
****
```
4. Input: `6 18`
Output:
```
******
*
*
* *
* *
******
```
5. Input: `6 22`
Output:
```
******
*** *
* *
* *
* *
******
```
6. Input: `6 27`
Output:
```
******
******
* **
* **
* **
******
```
7. Input: `1 1`
Output:
```
*
```
It's not necessary to handle the cases when:
* provided `N` asterisks can't "fit" in the spiral of given `S*S` dimensions.
* either `N` or `S` is zero.
The challenge is code-golf, shortest bytes answer wins, any languages can be used.
Your output may have as many trailing (but not leading) spaces/newlines as you wish.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes
```
UGlYLGoQ&P->42*c
```
[Try it online!](https://tio.run/##y00syfn/P9Q9J9LHPT9QLUDXzsRIK/n/fzMuIyMA)
### Explanation (with example)
Consider inputs `4` and `11` as an example.
```
U % Implicit input: S. Push S^2
% STACK: 16
G % Push S again
% STACK: 16, 4
lYL % Outward, clockwise, east-first spiral of that size
% STACK: 16,
[ 7 8 9 10;
6 1 2 11;
5 4 3 12;
16 15 14 13]
GoQ % Push S, compute parity, add 1. Gives 1 for even S, 2 for odd
% STACK: 16,
[ 7 8 9 10;
6 1 2 11;
5 4 3 12;
16 15 14 13],
1
&P % Flip along that dimension (1 is vertical, 2 is horizontal).
% This corrects for the orientation of the spiral
% STACK: 16,
[16 15 14 13;
5 4 3 12;
6 1 2 11;
7 8 9 10]
- % Subtract, element-wise. The upper-left corner becomes 0
% STACK: [ 0 1 2 3
11 12 13 4
10 15 14 5
9 8 7 6]
> % Implicit input (below): N. Greater than?, element-wise.
% This transforms the first N entries, starting from
% upper-left, inward, east-first, into 1, and the rest
% into 0
% STACK: [1 1 1 1;
0 0 0 1;
1 0 0 1;
1 1 1 1]
42* % Multiply each entry by 42
% STACK: [42 42 42 42;
0 0 0 42;
42 0 0 42;
42 42 42 42]
c % Convert to char. Char 0 will be displayed as space.
% Implicit display
% STACK: ['****';
' *';
'* *';
'****']
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
±♪☺ÿzMæ¡♠à╣♂7☼V♀§9↓
```
[Run and debug it](https://staxlang.xyz/#p=f10d01987a4d91ad0685b90b370f560c153919&i=6+22)
It starts by building a string that has all the characters in the result with all the asterisks left-aligned. Then it it takes increasingly large slices off the end of the string, and "wraps" them around a grid as it rotates the grid.
Here's the same program, unpacked, ungolfed, and commented.
```
'** repeat "*" specified number of times
,J( square the top of the input stack, and right-pad string to that length
z push an empty array - this is the result grid built up in the loop
{ begin a block to loop
~ push grid to the input stack
ihNv push -(i / 2) - 1 where i is the 0-based iteration index using integer division
:/] split the string at that index and wrap the second half in a singleton array
, pop the grid from the input stack
rM+ rotate the grid clockwise, then prepend the split string as the new first row
n copy what's left of the original string to top of stack for the loop condition
w while; execute block until condition is truthy
m display resulting grid
```
[Run and debug it](https://staxlang.xyz/#c=%27**+++%09repeat+%22*%22+specified+number+of+times%0A,J%28+++%09square+the+top+of+the+input+stack,+and+right-pad+string+to+that+length%0Az+++++%09push+an+empty+array+-+this+is+the+result+grid+built+up+in+the+loop%0A%7B+++++%09begin+a+block+to+loop%0A++%7E+++%09push+grid+to+the+input+stack%0A++ihNv%09push+-%28i+%2F+2%29+-+1+where+i+is+the+0-based+iteration+index+using+integer+division%0A++%3A%2F]+%09split+the+string+at+that+index+and+wrap+the+second+half+in+a+singleton+array%0A++,+++%09pop+the+grid+from+the+input+stack%0A++rM%2B+%09rotate+the+grid+clockwise,+then+prepend+the+split+string+as+the+new+first+row%0A++n+++%09copy+what%27s+left+of+the+original+string+to+top+of+stack+for+the+loop+condition%0Aw+++++%09while%3B+execute+block+until+condition+is+truthy%0Am+++++%09display+resulting+grid&i=6+22&a=1)
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), 65 bytes
```
' *'[1+⎕>⊖∘⌽⍣o(⊖×⍨-,⍨⍴∘(⍋+\)×⍨↑(⌈2÷⍨×⍨),(+⍨⍴1,⊢,¯1,-)(/⍨)2/⍳)o←⎕]
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKM97b@6gpZ6tKH2o76pdo@6pj3qmPGoZ@@j3sX5GkDe4emPelfo6gCJR71bgFIaj3q7tWM0wcKP2iZqPOrpMDq8HcgBi2jqaGhDlBrqPOpapHNovaGOrqaGPkjKCEhu1sx/1DYBaFEsyOb/aVwmXMZcXCDKDEIZGoJoUyhtxmVoAaGNjKC0OYg25DIEAA "APL (Dyalog Unicode) – Try It Online")
The code for the spiral matrix is taken from [another answer of mine](https://codegolf.stackexchange.com/a/125974/65326).
[Answer]
# [Python 2](https://docs.python.org/2/), 117 bytes
```
n,k=input()
i=0;d=1
l=(' '*n+'\n')*n
exec"l=l[:i]+'*'+l[i+1:];d=[~n/d*cmp(d*d,2),d][' '<l[i+d:]<'*'];i+=d;"*k
print l
```
[Try it online!](https://tio.run/##Fcu9DsIgEADgnadouhx/iZahQylPgky9Jl6KJ2kw0cVXR9y/r3zq/cmuNbZHIC6vKpWgcPUYJpGDhAE0G7gxKM1if@/bmEOOCyUDGkyOZKYldR2/fEG9PYpEjdYpiyn2vP4FLmntOnkyAf2oD1FO4jrk1mbr5h8 "Python 2 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 34 bytes
```
NθFE⮌E⊗N∨ι¹÷⁺鬬겫F‹θι≔θι×ι*≧⁻ιθ↷
```
[Try it online!](https://tio.run/##TU47DoMwDJ3hFBGTU9GhDF2YKrEgFYpQL8AnBauQQD4sVc@ehrB0sOX3s92NjexEM1mb88Xo0swtk7DSNHwJSaBoFqjZxqRifs6EaSfWw7@Z0pg8JGBMLnSfc64z3LBnUE1G7XwpNOz19nriOvmEgT9wZ0rBGhN03E0pHPiB0jCoJHINT5yZXxKdIrrT7o3DWOMwaiiQG@USMVl9CDehD8XBr7VJEl7teZt@ "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Nθ
```
Input `N`.
```
FE⮌E⊗N∨ι¹÷⁺鬬겫
```
The lengths of the spiral arms (excluding corners) are `S-1`, `S-1`, `S-1`, `S-2`, `S-2`, `S-3`, ..., `3`, `2`, `2`, `1`, `1`, `1`. This is formed by starting with the range from `0` up to but excluding `2S`, changing the 0 to 1, reversing it, adding 1 to each element after the first, and finally integer dividing all the elements by 2. This list is then looped over.
```
F‹θι≔θι
```
If there are fewer stars left to draw than the length of the next arm, reduce the arm to that length.
```
×ι*
```
Draw the appropriate number of stars.
```
≧⁻ιθ
```
Subtract from the number of stars remaining.
```
↷
```
Rotate the drawing direction by 90° clockwise.
[Answer]
# PHP, 118 bytes
adjusted and golfed [my solution for the Alphabet Spiral](https://codegolf.stackexchange.com/a/94794/55735).
```
for($w=$n=$argv[$s=1],$r="*";--$argv[2];$r[$p+=$s*$d+$s]="*")if(!$c=++$c%$n)($d^=$w)?$n--:$s=-$s;echo wordwrap($r,$w);
```
Run with `php -nr '<code>' <S> <N>` or [try it online](http://sandbox.onlinephpfunctions.com/code/4f67ff1bbfaaa67e1c0d5e61f281614639ae67fa).
[Answer]
# [Python 2](https://docs.python.org/2/), 150 bytes
```
S,N=input()
X=y=n=0
Y=x=c=-1
s=eval(`[[' ']*S]*S`)
exec"if n%S<1:S-=c%2<1;X,Y=-Y,X;c+=1;n=0\nx+=X;y+=Y;s[y][x]='*';n+=1\n"*N
for i in s:print`i`[2::5]
```
[Try it online!](https://tio.run/##DczdCoMgGIDhc69CgrBfWMI20L5b6KSTxAKHFBPGV1QbevUueM8eeLdwvlfkMfZVBw6375nlZIAACDeiwIOFuiEHzL/XJzNaM8qmor8yOZn9bBO3UEz7thF9DTblbSOHSkGtqkHaEhp5fUb0JQwylKDkocOk/QSsYBIvHzEpOrKsO3XUIT3Etjs8jTOaC3GfYnxUlD// "Python 2 – Try It Online")
[Answer]
# J, ~~60~~ 56 Bytes
-4 Bytes by modifying the build proccess for the spiral so that subtracting it from y^2 was unnecessary
```
4 :'''* ''{~x<|."1|.(|:@|.,<:@{:@{:-i.@#)^:(+:<:y),.*:y'
```
[Try it online!](https://tio.run/##JY3BCsIwEAV/5VEPm7Rxy0apZY2QLxGKCFYKir1YGvrr0Soz55l7zuOzf3UDToo9lIhKEM3LOyQuJLFJGhO7oHFe3fYcN/asptKgk3Vc6kT5erk9YByO@MdsXQjMDg1EIC28hz9ALBx/JyvND8kf "J – Try It Online")
Explanation coming ~~soon~~ now.
### Explanation:
```
4 :'''* ''{~x<|."1|.(|:@|.,<:@{:@{:-i.@#)^:(+:<:y),.*:y' | Explicit dyad definition
(|:@|.,<:@{:@{:-i.@#)^:(+:<:y),.*:y | Generate a y by y inward spiral
,.*:y | The matrix [[y^2]]
( )^:(+:<:y) | 2*(y-1) times...
|:@|. | Rotate
, | Append
i.@# | [0..len(n)-1]
<:@{:@{:- | Subtracted from the previous value and decremented
|."1|. | Flip around antidiagonal
x> | Test if each entry is less than x
'' *''{~ | ' ' for 0, '*' for 1
```
Examples:
```
3 :'(|:@|.,<:@{:@{:-i.@#)^:(+:<:y),.*:y' 4
7 8 9 10
6 15 16 11
5 14 13 12
4 3 2 1
3 :'|."1|.(|:@|.,<:@{:@{:-i.@#)^:(+:<:y),.*:y' 4
1 2 3 4
12 13 14 5
11 16 15 6
10 9 8 7
11(4 :'x<|."1|.(|:@|.,<:@{:@{:-i.@#)^:(+:<:y),.*:y') 4
0 0 0 0
1 1 1 0
0 1 1 0
0 0 0 0
11(4 :'''* ''{~x<|."1|.(|:@|.,<:@{:@{:-i.@#)^:(+:<:y),.*:y') 4
****
*
* *
****
```
[Answer]
# [Kotlin](https://kotlinlang.org), ~~361~~ ~~355~~ ~~353~~ 334 bytes
6 bytes saved thanks to Jonathan
2 bytes saved changing to when
19 bytes saved switching to lambda & tracking outer edges
```
{s:Int,n:Int->var a=Array(s,{_->Array(s,{_->' '})})
var r=0
var c=0
var d=0
var e=0
var f=1
var g=s-1
var h=g
for(i in 1..n){a[r][c]='*'
when(d){0->if(c<g)c++
else{d=1
r++
g--}
1->if(r<h)r++
else{d=2
c--
h--}
2->if(c>e)c--
else{d=3
r--
e++}
3->if(r>f)r--
else{d=0
c++
f++}}}
for(i in 0..s-1){for(j in 0..s-1)print(a[i][j])
println()}}
```
[Try it online!](https://tio.run/##nVdbb9s2FH7Xr2Dz0FiOr0nRDUZsoFi3oUDXAkvzMARBQEuUzEamPFKK4xr@7dl3SOqSxLmsfrAoniu/c@HRdV5kUt0Nu@w3LXghYpbkmhULaViUx4KleZawaMGzTKhUTIJFUazMZDgkItEGpuDRtbgFC@iDKF8O/y2FKWSuzHD8fjwaj4fcFEJLc903K6l5Fvwpb4SCDcE0j2VpWJ4wI38Idsa4ii0BEiv2pcfysliVhd06MP@WXIsDdtY9Y04TW/AbqVL2hVUmTI/NS5kVLNH50opBg8CBciaVwsJbjLI8ul5LIwZB8A3usogbYVhH3PLlKhMmZHOR5WtQGX6fFJyYsHfsxL1/tV5N3Eu3233A9X4/V9cuaN0s7guOx6@S7NaLh7bfs/GvT6holLQcaGnct@zuMXB8/LwBPF/Q@pKBX140UC/t63PLxwbGbC/IQfCpODRM5QVTIhLGcL2hrEFax5mwmeRSZL0QygutdH4jY5RMK//ApQ4LdpDI4gAp55LZJSuyPLWZTwkcy6VQhqrE55iQYNVQhfI7Yyi/H0LnlJ1kuao/5suyT6XXY2aR64Kyd77BA8Vj1lCxlgplwNWGZajJkqfCeoWMZqURMXT@k5e6Kq0l31AZCRwBawgVmsuMqqozB5kAyQSKRqUhDsIBzVCJNRjIoGGbvIRBsxgE3WEQDIfs99sVIAMoN0LT@Sbs3EC5YkKVS6E5dQYAA7x4DEhIZERAn9jaT0oVWQ5gS1Fw@NnCr4RIIuPLecwHAelELXMwfpRaONHt3zJdFD32MV@rHvssEqzPV7sAuv2hO9RtJsgIUKBhLrR9CdmWYgH9HwWUamFdkkoWkmfUn3w/IdiOmwiio1khrjXf9Fxfy9fsLSKVlUuFXsZ1QYCuciPJQwpO7GSIOa48H2DvhmuniE3ZB3paX3tse8X6s/aOL2G3f8gOd@Eu9PJkfcpG/s170WzU9rBXozawoN0T@UtaKXJTNJrd7ph2k/vs/BYE8q1vqWlLxpIaNlAXHuk/kO6CRwtUrRKC8ga5gExdZUi1uMfinJncpYZMSy2cVO7vBCVuC2RlXhB0dHF1JHLvlgpvPBi40PqoWrmzItcujN2qOKNSa6EaLczBfwG3Ly@cy5dw/rB7WGv5lLQwREVqgs7lSkI6ta1TpHypqOAqMbJAp0tz/PfYMkfRWdEB@0pSdB2hpteyiBaVDNhjpLFzjFoP69Sm6WAuCR5EERlRN3h41PEZcNpEIGwuAL95dFRviQwFu21x7E8YKq8WE/Bq6WCNrX6/3t3RkWTyJJB01J/D0YL0LIwZ@sDgEV50iIdwUfmc@rQNnzzhK1Gi9vMIlRYkzBv6HyjRSX4OJYvBsyiVq8cY0RGeSKlZ0yrC5075SrDOV/dxuYdTbakVhJegKlc/BxRgeBampuJbVfwIuPPVvtSa@S4aPnnWV6JVdewnC5l5S3sAq9fUUwK/RgN92JXJYTqm031vHrdt0rGLTCyph7o2rTAO4Ga3mDM7KODCS2gKxxTj@3fCJI1bTi2CoukaNGj6GxpQfC@H8Stq06PBwF0r6HjWf@u@ZXEKHnKB57s/8kpLVXTqln5V9fSryzCo6ZnqhG0Qdv6OwVHtTGO/EGKN4U37z6PWTDawg8WSSwUzqZm4S/r0rIDmdOaaNN2D1UQzJY0nJ@/c0Bbcbc2EBhFF//2Zvf@n/p7vba/6s/a6uuftvTod2Wfkn7F/Cv9MpmP7TKem71aLaRrA/Y6s7sdwyy80ELmc0vVGqdCJw@2oP5NJJzpNwwiZQ8m4jaFL4yXt93fB2NL16SLUDf04iJDBC6IfO/mZCGnL008CTS9HR7vgxMnPklA39FFAxhLQd7vGSYopArqlje@tDR/VC3l58R2BrIO42929OMDZL03ad@NBNXTZ7WZIckS74TR@KAqxXNlOoWl03aMKUzbaBKLu50EM0wlmaUwthqwU@KJwVe1tkZ7PqI9O@ObNoMgR/45Lytr4Xo6ganW8Us/yCGMMjUsyVTThSNuNds6hjtA6x4T7bYEC4PNMNHPulxyJW1BprhccwzASXCab5mxvK1fmAiFohi8UBg20zXA@AOIJL/HhbeUA0njUTLleif2cypK2mPUSLQO1VIFDfdIqeeOydDyqOqWHbTyq@bxiz0n0Lv1VAjWONWV4XH25US362drPiVUHQJxcB6CaDu7@Aw "Kotlin – Try It Online")
[Answer]
# Java 10, ~~284~~ ~~282~~ ~~281~~ 263 bytes
```
s->n->{var c=new char[s][s];for(var d:c)java.util.Arrays.fill(d,' ');for(int i=0,j=0,y=0,x=1,u=s-1,l=0;n-->0;c[j][i]=42,i+=x,j+=y,l+=i==l&x==0?1:0,u-=i==l&j==l&y<1?1:0)if(x!=0){var b=x>0?i<u:i>l;y=b?0:x;x=b?x:0;}else{var b=y>0?j<u:j>l;x=b?0:-y;y=b?y:0;}return c;}
```
A fun challenge!
Try it online [here](https://tio.run/##jdJNb5swGAfwM/0U3mUF8SKTVl0FMdEulXrYqUfEwXFIas91kG0yrIrPnj28lGqaolQCbPz8jI31F/REY7H7fW7areQMMUmNQb8oV@j9xpsHjaUWmtOR79AblPwXq7k6lBWi@mCCQXoCPpS0lstk3ypm@VElT3Nn/axsfah1hL6E2CvVZVVWRYFMwzWViKCziQsVF@8nqhEjqv4zKVPBle@P2h8Ku4wFnyv81Jo6k@y5lP4uukW3wQi5sogTHAm4HdwdSaOWmDiNJMG5iuMC56wUVckrcr@KeEi6SITERTIknBD5vSMEb9IMR208DYjh4dbpMBjwvd99IzgYd7olXYE3fN1mvJC5I9sNzrq8g7bLcN7X0tSzc@AEOAGuG13sxglugLq2rVaI5f3Z83I47AaO3/rT6SS0aaTz74O5cxcE18jDdZKmF83DYh6vm9XqC@bHRZMua10kj8tf4dH0N4M6UVv/k9tp5ke2EJtSuyQCMoZzaNaIJbJWB/sKb2E4qYWJiYmBQUAWKUAOzntxxtZvybG1ybwgMEjTuPn/qlL5Y6Efdt2f/wI).
Thanks to [Kevin Cruijssen](https://codegolf.stackexchange.com/users/52210/kevin-cruijssen "Kevin Cruijssen") for golfing 18 bytes.
Ungolfed version:
```
s -> n -> { // lambda taking two integer arguments in currying syntax
var c = new char[s][s]; // the matrix containing the spiral
for(var d : c) // for every row
java.util.Arrays.fill(d, ' '); // fill it with spaces
for(int i = 0, j = 0, // the coordinates of the next '*'
y = 0, x = 1, // the direction to move in
u = s-1, l = 0; // the upper and lower bounds
n-- > 0; // decrecement the length of the spiral and repeat as many times
c[j][i] = 42, // draw the '*', 42 is ASCII code
i += x, j += y, // move to the next cell
l += i == l & x == 0 ? 1 : 0, // adjust lower bound if necessary
u -= i == l & j == l & y < 1 ? 1 : 0) // adjust upper bound if necessary
if(x != 0) { // if moving in x direction
var b = x > 0 ? i < u : i > l; // if we hit the bounds
y = b ? 0 : x; // flip directions,
x = b ? x : 0; // turning around
} else { // if moving in y direction
var b = y > 0 ? j < u : j > l; // if we hit the bounds
x = b ? 0 : -y; // flip directions,
y = b ? y : 0; // turning around
}
return c; // return the matrix
}
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 167 164 163 bytes
* thanks to @Erik the Outgolfer and @nicael for spaces (3 bytes)
* thanks to @micha for join``split`,` instead of map (1 byte)
```
(l,s)=>{a=(b=[...Array(l)]).map(x=>b.map(_=>" "))
for(d=1,x=y=D=0;s--;x+=d,y+=D)a[y][x]="*",(a[y+D]||[])[x+d]!=" "?[d,D]=[-D,d]:0
return a.join`
`.split`,`.join``}
```
[Try it online!](https://tio.run/##JYzRCoIwFEDf/YryaTfnsB4KimsE@4sx2moaynKyWUyyb7eot3POw2n1U4erb/oh75yp5hpnYmkALF8ayQUFY@zkvR6JBQnsrnsSsbz84IxlukgBktp5YnBNI47IsTiEPD/EDA0dM@SgxShFlJiuUkq@knE5TUKCiJmRS/wujsJQLlHknBq5LxJfDQ/fLTRrXdOpRLHQ22ZQVP2Des9X1wVnK2bdjdRkSzc7gPkD "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Suppose we have a matrix like this:
```
11111
12221
12321
12221
11111
```
This matrix represents a terrain, and each cell represents a portion of terrain. The number in each cell represents the time the portion of terrain needs to be completely burnt (in minutes, if a measurement unit is needed), according to its [combustibility](https://en.wikipedia.org/wiki/Combustibility). If a fire starts at any given position (cell), that cell needs to be completely burnt before the fire propagates to the adjacent cells (horizontal and vertical only, not diagonal). So, if a fire is started at the center position, the fire needs:
```
11111 11111 11111 11011 10001 00000
12221 3 m. 12221 2 m. 12021 1 m. 11011 1 m. 00000 1 m. 00000
12321 -----> 12021 -----> 10001 -----> 00000 -----> 00000 -----> 00000
12221 12221 12021 11011 00000 00000
11111 11111 11111 11011 10001 00000
```
Explanation:
* Fire starts at [2,2] (0-based), which has a burn time of 3.
* After 3 minutes, [1,2],[2,1],[2,3],[3,2] start to burn.
* After 2 minutes, those cells end burning and fire propagates to all adjacent cells, but [0,2],[2,0],[2,4],[0,4] need only 1 more minute to burn, so
* After 1 minute, those cells are burnt and the cell propagates to their adjacent cells.
* After 1 more minute, the rest of cells from step 3 end burning and fire propagates to their adjacent cells (that are already burnt, so nothing happens).
* After 1 last minute, fire ends burning the whole terrain.
So the solution to that case is 8 minutes. If the fire starts in the top leftmost cell [0,0]:
```
11111 01111 00111 00011 00001 00000
12221 1 12221 1 02221 1 01221 1 00121 1 00011 1
12321 --> 12321 --> 12321 --> 02321 --> 01321 --> 00321 -->
12221 12221 12221 12221 02221 01221
11111 11111 11111 11111 11111 01111
00000 00000 00000 00000 00000
00000 1 00000 1 00000 1 00000 1 00000
00221 --> 00110 --> 00000 --> 00000 --> 00000
00221 00121 00020 00010 00000
00111 00011 00001 00000 00000
```
So now the total time is 10 minutes.
### The challenge
Given a NxM matrix (N>0, M>0) of integer values that represent the time every cell needs to be completely consumed, write the shortest program/function that takes that matrix and a pair of integers with the position the fire starts in, and returns/prints the time needed for the fire to completely consume the whole terrain.
* Every cell will have a positive (non-zero) burn time. You cannot assume a maximum value for the cells.
* The matrix does not need to be square nor symmetric.
* The matrix can be 0-indexed or 1-indexed, as you like.
* The position can be given as a single parameter with a tuple of integers, two separate parameters of whatever other reasonable format.
* The dimensions of the matrix cannot be specified as input parameters.
* You do not need to output every intermediate step, just the amount of time asked. But I won't complain if the steps are visualized in any way.
### Another example:
```
Fire starts at [1,1] (a '>' represents a minute):
4253 4253 4253 4153 4043 3033 2023 0001 0000
2213 > 2113 > 2013 > 1003 > 0002 > 0001 > 0000 >> 0000 > 0000
1211 1211 1211 1111 1001 0000 0000 0000 0000
Output: 9
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so may the shortest program for each language win!
[Answer]
## Matlab, ~~235~~ ~~257~~ ~~190~~ ~~182~~ 178 bytes
Input: Matrix `A`, 1x2 vector `p` containing the starting coordinates.
```
function t=F(A,p)
[n,m]=size(A);x=2:n*m;x(mod(x,n)==1)=0;B=diag(x,1)+diag(n+1:n*m,n);k=sub2ind([n m],p(1),p(2));t=max(distances(digraph(bsxfun(@times,((B+B')~=0),A(:))'),k))+A(k)
```
### Explanation:
Instead of simulating the the fire propagation, we can also understand this as a "find the longest shortest path" problem. The matrix is converted into a weighted directed graph. The weights of the paths to a single node correspond to the time to burn said node. E.g. for a matrix
```
5 7 7 10
5 2 2 10
4 5 2 6
```
we get the connected graph:
[](https://i.stack.imgur.com/0lELM.jpg)
Where node 1 is the upper left matrix element and node 12 the lower right element. Given starting coordinates `p`, the shortest path to all other nodes is calculated. Then the length of the longest path of those shortest paths + the time to burn the initial node equals to the time to burn the whole matrix.
Ungolfed and commented version with sample starting values:
```
% some starting point
p = [3 2];
% some random 5x6 starting map, integers between 1:10
A = randi(10,5,6);
function t=F(A,p)
% dimensions of A
[n,m] = size(A);
% create adjacency matrix
x=2:n*m;
x(mod(x,n)==1)=0;
B = diag(x,1)+diag(n+1:n*m,n);
B = B+B';
B = bsxfun(@times,(B~=0),A(:))';
% make graph object with it
G = digraph(B);
% starting node
k = sub2ind([n m], p(1), p(2));
% calculate the shortest distance to all nodes from starting point
d = distances(G,k);
% the largest smallest distance will burn down last. Add burntime of initial point
t = max(d)+A(k);
```
[Answer]
## JavaScript (ES6), ~~156~~ ~~152~~ ~~146~~ ~~144~~ 143 bytes
*Saved 1 byte thanks to Kevin Cruijssen*
A rather naive implementation. Takes input in currying syntax `(a)(s)`, where ***a*** is a 2D-array and ***s*** is an array of two integers [***x, y***] representing the 0-based coordinates of the starting position.
```
a=>s=>(g=t=>(a=a.map((r,y)=>r.map((c,x)=>(z=(h,v)=>(a[y+~~v]||[])[x+h]<1)(-1)|z(1)|z(0,-1)|z(0,1)|x+','+y==s&&c?u=c-1:c),u=-1),~u?g(t+1):t))(0)
```
### Formatted and commented
```
a => s => ( // given a and s
g = t => ( // g = recursive function with t = time counter
a = a.map((r, y) => // for each row r of the input array:
r.map((c, x) => // for each cell c in this row:
( // z = function that takes
z = (h, v) => // 2 signed offsets h and v and checks
(a[y + ~~v] || [])[x + h] < 1 // whether the corresponding cell is 0
)(-1) | z(1) | // test left/right neighbors
z(0, -1) | z(0, 1) | // test top/bottom neighbors
x + ',' + y == s // test whether c is the starting cell
&& c ? // if at least one test passes and c != 0:
u = c - 1 // decrement the current cell / update u
: // else:
c // let the current cell unchanged
), // end of r.map()
u = -1 // start with u = -1
), // end of a.map() --> assign result to a
~u ? // if at least one cell was updated:
g(t + 1) // increment t and do a recursive call
: // else:
t // stop recursion and return t
) // end of g() definition
)(0) // initial call to g() with t = 0
```
### Test cases
```
let f =
a=>s=>(g=t=>(a=a.map((r,y)=>r.map((c,x)=>(z=(h,v)=>(a[y+~~v]||[])[x+h]<1)(-1)|z(1)|z(0,-1)|z(0,1)|x+','+y==s&&c?u=c-1:c),u=-1),~u?g(t+1):t))(0)
console.log(f([
[1,1,1,1,1],
[1,2,2,2,1],
[1,2,3,2,1],
[1,2,2,2,1],
[1,1,1,1,1]
])([2, 2]))
console.log(f([
[1,1,1,1,1],
[1,2,2,2,1],
[1,2,3,2,1],
[1,2,2,2,1],
[1,1,1,1,1]
])([0, 0]))
console.log(f([
[4,2,5,3],
[2,2,1,3],
[1,2,1,1]
])([1, 1]))
```
[Answer]
# Octave, 67 bytes
```
function n=F(s,a)n=0;do++n;until~(s-=a|=imdilate(~s,~(z=-1:1)|~z')
```
[Try it online!](https://tio.run/##VY5BCoMwFET3OYVZmWCEJtVSKn/bS4iLT7QQ0C@YpFDx7qmtdNHZPIYHw8w24HNI6RHJBjdTRnAXXqEkODX9XBTURApu5MKXgBu4qXcjhkFwr7hYodQ3LTe@5lKmgfrfDGMeoqNwqUTLcv1JvtMYc/Bs/vrXd2V1lYwhcI7WxgmXBV@i1ZnulFZtndXdro936Q0 "Octave – Try It Online")
To visualize intermediate results you can [Try this!](https://tio.run/##VY5BCoMwFET3OYVZmWCEJtVSKn/bS4iLT7QQ0C@YpFDx7qmtdNHZPIYHw8w24HNI6RHJBjdTRnAXXqEkODX93HhVFNRECm7kwpeAG7ipdyOGQXCvuFih1DctN77mUqaB@t8SYx6io3CpRMty/Um@0xhz8Gz@@td3ZXWVjCFwjtbGCZcFX6LVme6UVm2d1d2uj4PpDQ "Octave – Try It Online")
A function that take as input matrix of terrain `a` and initial coordinate as a matrix of 0&1 with the same size as terrain.
Actually there is no need to `endfunction` however to run the example in tio it should be added.
Explanation:
Repeatedly apply morphological image dilation on the terrain and subtract the burned areas from it.
Ungolfed answer:
```
function n = Fire(terrain,burned)
n = 0;
mask = [...
0 1 0
1 1 1
0 1 0];
while true
n = n + 1;
propagation = imdilate(~terrain, mask);
burned = burned | propagation;
terrain = terrain - burned;
if all(terrain(:) == 0)
break;
end
end
end
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~26~~ 25 bytes
>
> I really wanted to see some more answers using the golfiest languages around here
>
>
>
```
`yy)qw(8My~1Y6Z+fhy0>z}@&
```
Input format is:
* First input is a matrix using `;` as row separator.
* Second input is a single number which addresses an entry of the matrix in 1-based [column-major order](https://en.wikipedia.org/wiki/Row-_and_column-major_order) (allowed by the challenge). For example, the column-major coordinate of each entry in a 3×4 matrix is given by
```
1 4 7 10
2 5 8 11
3 6 9 12
```
So for instance 1-based coordinates (2,2) correspond to `5`.
[**Try it online!**](https://tio.run/##y00syfn/P6GyUrOwXMPCt7LOMNIsSjsto9LArqrWQe3//2hDBSi0BhJGYAhlGiOYcFEojOUyNAYA "MATL – Try It Online") Or [**verify all test cases**](https://tio.run/##y00syfmf8D@hslKzsFzDwreyzjDSLEo7LaPSwK6q1kHtf4RLWUXI/2hDBSi0BhJGYAhlGiOYcFEojOUyNOYiWytXtAlQ0FTB2BoiC2IYghlAWVMA).
### Explanation
The code maintains a list of entries that are burning. At each iteration, all entries of that list are decremented. When an entry reaches zero, its neighbouring entries are added to the list. To save bytes, entries that reach zero are not removed from the list; instead, they keep "burning" with negative values. The loop is exited when none of the entries have positive values.
See the program [**running step by step**](https://matl.suever.net/?code=%60T%26XxyyyD%29qw%288My~1Y6Z%2Bfhy0%3Ez%7DT%26Xxx%40&inputs=%5B1+1+1+1+1%3B+1+2+2+2+1%3B+1+2+3+2+1%3B+1+2+2+2+1%3B+1+1+1+1+1%5D%0A1&version=20.1.1) with slightly modified code.
Commented code:
```
` % Do...while
yy % Duplicate top two arrays (matrix and array of positions to be decremented)
% In the first iteration this implicitly takes the two inputs
) % Reference indexing. This gives the values that need to be decremented
q % Decrement
w % Swap. This brings the array of positions that have been decremented to top
( % Assignment indexing. This writes the decremented values back into their
% positions
8M % Push array of positions again
y % Duplicate decremented matrix
~ % Negate. This replaces zeros by 1, and nonzeros by 0
1Y6 % Push predefined literal [0 1 0; 1 0 1; 0 1 0] (4-neighbourhood)
Z+ % 2D convolution, maintaining size
f % Find: gives column-major indices of neighbours of totally burnt entries
h % Concatenate. This updates the array of positions to be decremented
y % Duplicate decremented matrix
0> % This gives 1 for positive entries, and 0 for the rest
z % Number of nonzeros. This is the loop condition (*)
} % Finally (execute before exiting loop)
@ % Push iteration number. This is the output
& % Specify that the final implicit display function will display only the top
% of the stack
% Implicit end. If the top of the stack (*) is not 0 (i.e. there are entries
% that have not been totally burnt) the loop proceeds with the next iteration.
% Else the "finally" branch is executed and the loop is exited
% Implicit display (only top of the stack)
```
[Answer]
# [Python 3](https://docs.python.org/3/), ~~277~~ 266 bytes
```
def f(m,s):
p={s};w=len(m);t=0
while sum(sum(m,[])):
t+=1;i=0
for x,y in p:
try:m[x][y]=max(0,m[x][y]-1)
except:0
for v in sum(m,[]):
if v<1:
for l in[(1,0),(-1,0),(0,1),(0,-1)]:a,b=max(0,i%w+l[0]),max(0,i//w+l[1]);p.add((a,b))
i+=1
print(t)
```
[Try it online!](https://tio.run/##vU9Nb4MwDL3nV1iaJsWquyb0BuNf7BblwEZQIxEaQVZA0347Syjd532SHcfPz8@2n8Pp3B2XpTYNNNzRgDkDX74N78VYtqbjDotQCgbjybYGhlfHkztSGhMVwq6UhU0MaM49TDSD7cCnEoR@zp2atJp16aqJC9qyvcRUN9OL8SG/9V5S56f6qmAbuDzK9btS2khRXJJA4vtrECTXN2rqvKLnbZK9H3etEhppyw@HBEiNhX@o6przyMV1DRtPiEf3tgs84MLu4MkMYWANVwyUJPgyTVcku9l35PgH@cX5qZM8LiaQIfuXWRllcdbyAQ "Python 3 – Try It Online")
Defines a function `f` that takes a 2D matrix and a tuple of points. The first thing the function does is define a set of tuples containing the initial tuple value passed in: `p={s}`. The function then goes through every tuple of points in `p` and subtracts one from the matrix `m` at that point, unless the value is already zero. It then loops through `m` again finding all points with the value zero and adding the four neighbors of that point to the set `p`. This is why I chose to use a set, because sets in Python don't allow duplicate values (which would screw up the subtraction a lot). Unfortunately, due to list index wrapping (e.g: `list[-1] == list[len(list)-1]`) the indices need to be constrained so they do not go negative and add the wrong coordinates to `p`.
Nothing special, still getting used to golfing. Definitely room for improvement here, I'm going to keep cracking at it.
[Answer]
# [Python 2](https://docs.python.org/2/), 170 bytes
```
s,m=input()
t={s}
r=0
while max(sum(m,[]))>0:
r+=1
for a,b in t|t:
try:a<0<x;b<0<x;m[a][b]-=1;t|=m[a][b]==0and{(a+1,b),(a-1,b),(a,b+1),(a,b-1)}or t^t
except:0
print r
```
[Try it online!](https://tio.run/##XYzbCsIwEESfzVfsY0K3kNS3avyRECHRigWTlnTFSuu31zteYJhhDsO0Z9o3sZimDoOuY3skLhjpobuwpCU77etDBcH1vDsGHtBYIVayZJAyrRjsmgQOPdQRaKSSzSidS7eUy37hHx6Ms8bbXKsFjfrVtJYubgfuMoVeIHf5K9Fn6pm5EpfbN62Jzap@U7VUStamOhKkaeISC4HGKISPLMIdFG99gfk/@F18fdgr "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~93~~ ~~66~~ 57 bytes
```
{⍵{^/,0≥⍺:0⋄1+x∇⍵∨{∨/,⍵∧⍲/¨2|⍳3 3}⌺3 3⊢0=x←⍺-⍵}(⊂⍺)≡¨⍳⍴⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1Hf1EdtE4Bk9aPerdVx@joGjzqXPurdZWXwqLvFULviUUc7UOJRx4pqINbXAbOXP@rdpH9ohVHNo97NxgrGtY96dgGpR12LDGwrQIb17tIFqqvVeNTVBGRrPupceGgFUOmj3i0gYaBdQGvbJmqYKBgpmCoYa2oYARmGIIYhmGGoyQUUAQA "APL (Dyalog Classic) – Try It Online") or [Visualize it online!](https://tio.run/##jZVRS9tQFMff@yku7OEmGGujmw8FX8YYDCaC7E0cxPbWZou94SZqqlZEpba1EZ26@TLYBsMiA2FOBoUx6L7J/SLunHvbVGtlS0lv0uT@7v@c8z@3ju@N5suOxxdv8m7ge05ZVg/X5cHpixkC39Mv4TZDbPLAIeOP5CmPWJ50ZxNeII4QTjmdSuELCzxCIPn3gSh4m6y6YZGEZZ8Rp5QnTsSCVO@VFRGSolgDoNG5tEdk/EPG1yYMnRaVJ9vyZIsOga4wEaYVrMiFu5Ymnlu6BQ25D0CYvyUb72X1HZ0Dtqweybg9b8FqQ4Uu@z4TIFfkYVCKncjtMxd4iCJlYwco5lDKLZjHVwdgGH4CE4uhFngIMVILkmDBzRl9CCfcxWJIAjfPNCzHRYmJvjjPiTRvWzZ/yepxN@BjPFXQnZZsbGOu7wllBQ02ArMXNQusPrmASmVcB3iTWgZkERYzUe4JHao1ndaVuaexEFoGVia@gBLDN2TUtCATQymFZc8ro3nAh8p8ilPRDsyzHFeejtswKGNxn5Vg4jWR@7swti0MA3@o3MHeMSHYKBdyoZB4j0hjdFw2a8qG2onVI3vkzwd9V3mgPEqgsotaQMeMipBoT2azht2DKm9DLeicYIV5quQOPtULIZhFPg@WBcMWLEFG@r0TCndJ6d20iS3jn7J2Lpu/YeoUJdQcGypWOYkt8RXHQyCLQuGQBc8pvYVieV0u6EfuumFP9SQ1dugIRaKsXVi5oiPATQN8RAfuku@xbjISu@P7ulbfZP2zRmap6msVu2qoa1lr0M4ltWB/eqYWfLRJYbkzGZ8O4IOc4zmiz8fOV4mYlPVPdmYDCbOQg55yMkorQ5q9BI2JU0mBC@KEfEk76392tX4qc8sicFcY2tQtLSb7ZJBNTJ@ZUkFDxKjowtA2PTh9Pv2K6HJfKBXo3HuZ1KEmLJvoHBoaaRrd@kA2a3uUZOCDm22fnvD4whtwOgj2s/h4ZrbP7OkzsKeUJGTclpl01v0qJxiDYgHvINCgiZbaXqc1wIH9Orzb2/AsVbmBKbjhHJyCY67XX49ZGVn/Cg2dzYBd9MPevxp0Pzhnf9ceiWAF5aLWOpxjlro@l/H3sU5rfEPGVxNkoiKbbRhk40tmKlJ7WnsUbQwO3MYtHRKBvr7qdiAsdXMD3W88JuPkCZkwjXG4sPHCVhe2mYJf/gI "APL (Dyalog Classic) – Try It Online")
---
This function takes the terrain matrix as right argument and the coordinates (1-based) of first fire as left argument. Returns the number of minutes needed to burn everything.
---
# Updates
Finally found a way to golf down the spread function.
\*Sigh\* it would be so much easier if the world was [toroidal](https://en.wikipedia.org/wiki/Wraparound_(video_games)).
---
TIO just [upgraded to Dyalog 16.0](https://chat.stackexchange.com/transcript/message/38468346#38468346), which means now we have the shiny new stencil operator
[Answer]
# [Python 2](https://docs.python.org/2/), 268 bytes
```
def f(m,y,x):t,m[y][x]=m[y][x],0;g(m,t)
def g(m,t):
n,h,w=map(lambda r:r[:],m),len(m),len(m[0])
for l in range(h*w):r,c=l/h,l%h;n[r][c]-=m[r][c]and not all(m[r][max(c-1,0):min(c+2,w+1)]+[m[max(r-1,0)][c],m[min(r+1,h-1)][c]])
if sum(sum(m,[])):g(n,t+1)
else:print t
```
[Try it online!](https://tio.run/##ZVLbboMwDH0mX2GtmpSsrla6t0z8x6YsDxl3NReapmr79V0IsLUaAdkcHx/sI4Zr6Jzd3W5V3UBDDV7xwnhAI65SXGQxR9y@72MxMDLy2pRyklns8FwYNVCtzHelwHMvuETDUNeWLkFsJSNZ4zxo6C14Zduadi9nxj2WhX7tUD9371Z4KUq5id9MibIVWBdAaU0TZNSFlpsct4yb3tJyvcPzOmdyLUyq@VQbW@P4I8Ovc@w2eYLGCfoGjidDx8egkIzxPbUYogbJan2s@eB7GyAkMw40rThDWbxWU96cbBl6ZyEt5Nq2t22yZXKIJ6qqqqUGwUHrdFNXv62L7NOX/bJPJBsdPETXSDZZmyTKuDioMpyU/tdPjAq@vyAcg/LhY46fUER/h1OgLFu1dZheRvIoD1PPJB5nm6ozSg6UPmox9shLKJTO@epISPxV7if4XCaJTauJOXjXemVuQuQ4H4kx36Wz5G93@R@@8CXCNt4/ "Python 2 – Try It Online")
Recursively iterate over time steps in which every tile's number is reduced if it is cardinally adjacent to a 0. Very straightforward algorithm that, I believe, can still be golfed for boolean efficiency...
\*note: my 'Try it online!' code includes bonus debug logging in the footer. I like to watch the algorithm progress.
[Answer]
# [Haskell](https://www.haskell.org/), 138 133 bytes
```
u#g|all((<=0).snd)g=0|2>1=1+(u:[[(x+1,y),(x-1,y),(x,y-1),(x,y+1)]|((x,y),0)<-n]>>=id)#n where n=d<$>g;d p|elem(fst p)u=pred<$>p|2>1=p
```
[Try it online!](https://tio.run/##XZDBboMwDIbveQpL9BCLgJLuthFeJMoBNRmNRrMogAaId2ehZVI7@WB//v3HVq5N/2W7btvGrF2brqO0khzL3htsJV/PtZAip@O7UnTKBZuR0ak4MpsL8ci5QL3SvULGsSq8rmvpDGYefq42WvDSVKe6/TAQVtvZG/3sBwg4yhDtroT7prAtcnFB8bLUJCmhSVYHEsw3AaAziwhVAQu4HSd2OTAmjHYYo4fjiAsS0kZnkvd4J40oUIIdoROznc/3eOa3f/yqP/k1IbfG@b/7QnR@gBMomhyos33/S5unv3m0t18 "Haskell – Try It Online")
Assumes input is a list of ((x,y),cell). Ungolfed:
```
type Pos = (Int, Int)
ungolfed :: [Pos] -> [(Pos, Int)] -> Int
ungolfed burning grid
| all ((<=0).snd) grid = 0
| otherwise = 1 + ungolfed (burning ++ newburning) newgrid
where
newgrid = map burn grid
burn (pos,cell) | pos `elem` burning = (pos, cell - 1)
| otherwise = (pos, cell)
newburning = do
((x,y),cell) <- newgrid
guard (cell <= 0)
[(x+1,y),(x-1,y),(x,y-1),(x,y+1)]
```
] |
[Question]
[
Most everyone here is familiar with Pascal's Triangle. It's formed by successive rows, where each element is the sum of its two upper-left and upper-right neighbors. Here are the first `5` rows (borrowed from [Generate Pascal's triangle](https://codegolf.stackexchange.com/q/3815/42963)):
```
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
```
We're going to take Pascal's Triangle and perform some sums on it (hah-ha). For a given input `n`, output the columnar sum of the first `n` rows of Pascal's Triangle. For example, for input `5`, the output would be formed by
```
1
1 1
1 2 1
1 3 3 1
[+] 1 4 6 4 1
----------------------
1 1 5 4 9 4 5 1 1
```
So the output would be `[1, 1, 5, 4, 9, 4, 5, 1, 1]`.
Note that you don't necessarily need to generate Pascal's Triangle to calculate the summation - that's up to your implementation if it's shorter to do so or not.
## Input
A single positive integer `n` with `n >= 1` [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963).
## Output
The resulting array/list of the column-wise summation of the first `n` rows of Pascal's triangle, as outlined above. Again, in any suitable format.
## Rules
* Leading or trailing newlines or whitespace are all optional, so long as the characters themselves line up correctly.
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* If possible, please include a link to an online testing environment so other people can try out your code!
* [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.
### Examples
```
[input]
[output]
1
[1]
2
[1, 1, 1]
3
[1, 1, 3, 1, 1]
5
[1, 1, 5, 4, 9, 4, 5, 1, 1]
11
[1, 1, 11, 10, 54, 44, 155, 111, 286, 175, 351, 175, 286, 111, 155, 44, 54, 10, 11, 1, 1]
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 16 bytes
```
tZv=Gq:"t5BZ+]vs
```
[Try it online!](https://tio.run/nexus/matl#@18SVWbrXmilVGLqFKUdW1b8/7@hIQA "MATL – TIO Nexus")
### Explanation
This repeatedly applies convolution to generate the rows. For example, for input `n=5` we start with the first row
```
0 0 0 0 1 0 0 0 0
```
Convolving with `[1 0 1]` gives
```
0 0 0 1 0 1 0 0 0
```
Repeating the operation gives
```
0 0 1 0 2 0 1 0 0
```
then
```
0 1 0 3 0 3 0 1 0
```
etc. Concatenating these arrays vertically and computing the sum of each column gives the result.
```
t % Input n implictly. Duplicate
Zv % Symmetric range. Gives [1 2 3 4 5 4 3 2 1] for input 5
= % Equal to (element-wise). Gives [0 0 0 0 1 0 0 0 0]. This is the first row
Gq: % Push [1 2 ... n-1]
" % For each. This executes the following code n-1 times
t % Duplicate
5B % Push 5 in binary, that is, [1 0 1]
Z+ % Convolution keeping size
] % End
v % Concatenate all results vertically
s % Sum. Display implicitly.
```
[Answer]
## [CJam](https://sourceforge.net/p/cjam), ~~32~~ ~~25~~ 24 bytes
*Thanks to Luis Mendo for saving 1 byte.*
```
{(_0a*1+\{_(2$+.+}*]:.+}
```
[Try it online!](https://tio.run/nexus/cjam#K8r8X60Rb5CoZagdUx2vYaSiraddqxVrBST/1xX8NzQEAA "CJam – TIO Nexus")
### Explanation
```
( e# Decrement input N.
_0a*1+ e# Create a list of N-1 zeros and a 1. This is the top row with
e# the required indentation.
\{ e# Run this block N-1 times.
_ e# Duplicate the last row.
( e# Pull off a leading zero, shifting the row left.
2$+ e# Copy the full row and prepend that zero, shifting the row right.
.+ e# Element-wise addition, which results in the next row.
}*
] e# Wrap all rows in a list.
:.+ e# Add up the columns by reducing element-wise addition over the rows.
```
[Answer]
# [Octave](https://www.gnu.org/software/octave/), ~~84~~ ~~67~~ 45 bytes
*22 bytes saved thanks to [Neil](https://codegolf.stackexchange.com/users/17602/neil)!*
```
@(n)sum(spdiags(flip(tril(flip(pascal(n))))))
```
[Try it online!](https://tio.run/nexus/octave#@@@gkadZXJqrUVyQkpmYXqyRlpNZoFFSlJkDYRUkFicn5gDVgMH/NAVbhcS8YmuuNA1TTSBhaKj5HwA)
### Explanation
The `pascal` function gives a matrix that contains the values in the Pascal triangle:
```
>> pascal(5)
ans =
1 1 1 1 1
1 2 3 4 5
1 3 6 10 15
1 4 10 20 35
1 5 15 35 70
```
To extract the desired values we flip vertically (`flip`), keep the lower triangular part (`tril` ), and flip again. This gives
```
ans =
1 1 1 1 1
1 2 3 4 0
1 3 6 0 0
1 4 0 0 0
1 0 0 0 0
```
`spdiags` then extracts the diagonals as columns
```
ans =
1 1 1 1 1 0 0 0 0
0 0 4 3 2 1 0 0 0
0 0 0 0 6 3 1 0 0
0 0 0 0 0 0 4 1 0
0 0 0 0 0 0 0 0 1
```
and `sum` computes the sum of each column, which gives the result.
[Answer]
## JavaScript (ES6), 83 bytes
```
f=
n=>[...Array(n+--n)].map(g=(j=n,i,a)=>j--?g(j,i-1)+g(j,i+1)+(a?g(j,i,a):0):i-n?0:1)
```
```
<input type=number min=1 oninput=o.textContent=f(+this.value)><pre id=o>
```
1-indexing cost me a byte. Explanation: `g(j-1,i-1)+g(j-1,i+1)` recursively calculates Pascal's triangle until it reaches the first row, which is the base case. To obtain column sums, I use the fact that `map` actually passes a third parameter, so there is an extra recursive step when this is the case.
[Answer]
## JavaScript (ES6), ~~90~~ ~~87~~ ~~86~~ ~~84~~ 82 bytes
*Saved 3 bytes thanks to ETHproductions*
```
f=(n,a=[1],b=a)=>n--?f(n,[...(F=x=>a.map((n,i)=>n+~~x[i-d]))(a,d=2),0,d=1],F(b)):b
```
### Test cases
```
f=(n,a=[1],b=a)=>n--?f(n,[...(F=x=>a.map((n,i)=>n+~~x[i-d]))(a,d=2),0,d=1],F(b)):b
console.log(JSON.stringify(f(1)))
console.log(JSON.stringify(f(2)))
console.log(JSON.stringify(f(3)))
console.log(JSON.stringify(f(5)))
console.log(JSON.stringify(f(11)))
```
[Answer]
# Mathematica, ~~59~~ 57 bytes
*Thanks to Martin Ender for finding a two-byte savings!*
```
Binomial[i,(j+i)/2]~Sum~{i,Abs@j,b,2}~Table~{j,-b,b=#-1}&
```
Pure function taking a positive integer input and returning a list of integers. Literally produces all the relevant entries of Pascal's triangle and sums them appropriately.
Previous submission (which is a bit easier to read):
```
Table[Sum[Binomial[i,(j+i)/2],{i,Abs@j,b,2}],{j,-b,b=#-1}]&
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~34~~ ~~32~~ ~~28~~ ~~25~~ 24 bytes
*-4 thanks to Emigna.*
```
FN©ƒ®Ne0})¹®-Å0.ø˜¨ˆ}¯øO
```
[Try it online!](https://tio.run/nexus/05ab1e#ASgA1///Rk7CqcaSwq5OZTB9KcK5wq4tw4UwLsO4y5zCqMuGfcKvw7hP//82 "05AB1E – TIO Nexus")
---
```
FN©ƒ®Ne0}) # Generate, iteratively, the current pascal row, interspersed with 0's.
¹®-Å0 # Calculate the number of zeros to middle pad it.
.ø˜¨ˆ}¯øO # Surround with the zeros, transpose and sum.
```
---
Basically all it does is generate this:
```
0 0 0 0 0 0 1 0 0 0 0 0 0
0 0 0 0 0 1 0 1 0 0 0 0 0
0 0 0 0 1 0 2 0 1 0 0 0 0
0 0 0 1 0 3 0 3 0 1 0 0 0
0 0 1 0 4 0 6 0 4 0 1 0 0
```
Transpose it:
```
0 0 0 0 0
0 0 0 0 1
0 0 0 1 0
0 0 1 0 4
0 1 0 3 0
1 0 2 0 6
0 1 0 3 0
0 0 1 0 4
0 0 0 1 0
0 0 0 0 1
0 0 0 0 0
```
Then sums each row:
```
0
1
1
5
4
9
4
5
1
1
0
```
---
If a leading and trailing 0 are not acceptable, `®>-Å` isntead of `®-Å` fixes it for a +1 byte penalty.
---
Result for `50`:
```
[0, 1, 1, 50, 49, 1224, 1175, 19551, 18376, 229125, 210749, 2100384, 1889635, 15679951, 13790316, 97994765, 84204449, 523088334, 438883885, 2421229251, 1982345366, 9833394285, 7851048919, 35371393434, 27520344515, 113548602181, 86028257666, 327340174085, 241311916419, 851817398634, 610505482215, 2009517658701, 1399012176486, 4313184213360, 2914172036874, 8448367214664, 5534195177790, 15139356846901, 9605161669111, 24871748205410, 15266586536299, 37524050574849, 22257464038550, 52060859526501, 29803395487951, 66492351226050, 36688955738099, 78239857877649, 41550902139550, 84859704298201, 43308802158651, 84859704298201, 41550902139550, 78239857877649, 36688955738099, 66492351226050, 29803395487951, 52060859526501, 22257464038550, 37524050574849, 15266586536299, 24871748205410, 9605161669111, 15139356846901, 5534195177790, 8448367214664, 2914172036874, 4313184213360, 1399012176486, 2009517658701, 610505482215, 851817398634, 241311916419, 327340174085, 86028257666, 113548602181, 27520344515, 35371393434, 7851048919, 9833394285, 1982345366, 2421229251, 438883885, 523088334, 84204449, 97994765, 13790316, 15679951, 1889635, 2100384, 210749, 229125, 18376, 19551, 1175, 1224, 49, 50, 1, 1, 0]
```
[Answer]
# [PHP](https://php.net/), 119 bytes
columns numbers from 1-input to input -1
```
for(;$r<$argn;$l=$t[+$r++])for($c=-$r;$c<=$r;$c+=2)$s[$c]+=$t[+$r][$c]=$r|$c?$l[$c+1]+$l[$c-1]:1;ksort($s);print_r($s);
```
[Try it online!](https://tio.run/##LY69CoMwFIV3H0POYLg4WOjSa3AoDl3apZsEKcGqKBqujqWvnsbQ6XznZzhucL6s3OCSTmSVVjq3yj4uffat2/vjebvWihO8pF90ek7Zv1fJGFLGiDFr7A1BiIw6KlidQxi21FFInxS2BtbQf2kOE8oPbIU5GCoMRcgLcyl42sKBDJtiJ@OytxLZ@x8 "PHP – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 bytes
```
Ḷµc€j€0Ṛṙ"NS
```
[Try it online!](https://tio.run/nexus/jelly#@/9wx7ZDW5MfNa3JAmKDhztnPdw5U8kv@P/hdiDf/f9/Qx0FIx0FYx0FUx0FQ0MA "Jelly – TIO Nexus")
### How it works
```
Ḷµc€j€0Ṛṙ"NS Main link. Argument: k
Ḷ Unlength; yield A := [0, ..., k-1].
µ New chain. Argument: A
c€ Combinations each; compute nCr for each n and r in A, grouping by n.
j€0 Join each resulting array [nC0, ..., nC(k-1)], separating by zeroes,
yielding, [nC0, 0, ..., 0, nC(k-1)].
Note that nCr = 0 whenever r > n.
Ṛ Reverse the resulting 2D array.
N Negate A, yielding [0, ..., -(k-1)].
ṙ" Zipwith rotate; for each array in the result to the left and the
corresponding integer non-positive integer to the right, rotate
the array that many units to the left.
S Take the columnwise sum.
```
[Answer]
# Python 3, ~~201~~ 184 bytes
```
def f(n):x,z,m=[1],[0],n-1;l=[z*m+x+z*m];exec("x=[*map(sum,zip(z+x,x+z))];l.append(z*(n-len(x))+[b for a in zip(x,z*len(x))for b in a][:-1]+z*(n-len(x)));"*m);return[*map(sum,zip(*l))]
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~140~~ 137 bytes
```
n=input()
x=[]
a=[0]*n+[1]+n*[0]
z=n%2
exec'x+=[a];a=[(i%2^z)*sum(a[i-1:i+2])for i in range(2*n+1)];z^=1;'*n
print map(sum,zip(*x))[1:-1]
```
[Try it online!](https://tio.run/nexus/python2#DYzLCsMgEADvfoWXEB8NdD1G/BLZgBRb9pCt2ATEn7fe5jAzgwNxuS@lRQsRRQrxiYZtBLRsJoseeHEit/xamw0xoZ@OosUdXZvffaoUaYOdrEP9/lZJkljWxJ@s3ByBRt@PAH41LEolvuSZiprho1NRpmkdYd8AxwD4Aw "Python 2 – TIO Nexus") or [Try it online!](https://tio.run/nexus/python2#PYxLCsMgFAD3nuJtQvwF@izdGDyJGJBWi4u8BptA8PKpq@5mMTPXK2XInIRlcDofGETnb0GS8hgUyc4MmqPBMEhneo6ncj6GuVu8DGZpQn6PlUdfJrRFmSDyp0KBQlAjvRM3fYUizG1xOI@SGNS0H5VgjRvvqW5l4/IUwqOdMFz/vNB27FzYzIu4PGqj7/qhEcMP "Python 2 – TIO Nexus")
For `n=3`
Starts with a list with `n` zeros surround an one - `[[0, 0, 0, 1, 0, 0, 0]]`
Generate the full pyramid
```
[[0, 0, 0, 1, 0, 0, 0],
[0, 0, 1, 0, 1, 0, 0],
[0, 1, 0, 2, 0, 1, 0]]
```
Rotate 90º and sum each row, discarding the first and the last one (only zeros)
```
[[0, 0, 0],
[0, 0, 1],
[0, 1, 0],
[1, 0, 2],
[0, 1, 0],
[0, 0, 1],
[0, 0, 0]]
```
[Answer]
# Haskell, 118 112 104 bytes
*6 14 bytes saved thanks to @nimi*
```
z=zipWith(+)
p n|n<2=[1]|m<-p(n-1)=z(0:0:m)(m++[0,0]) -- Generate the nth triangle row.
f n=foldl1 z[d++p x++d|x<-[1..n],d<-[0<$[1..n-x]]] -- Pad each row with 0s and then sum all the rows.
```
[Answer]
# Python 3.9+, ~~124~~ 115 chars
```
s=range;f=lambda k:[sum([(q:=(lambda t:(k>(u:=n+x+t)>=0)*(t<1or u/t*q(~-t))))(x)for x in s(2*k)])for n in s(1-k,k)]
```
My previous answer didn't seem to work. Future me using python3.9+. The solution still uses the fact that the Pascal Triangle can be defined with binomial coefficents. Expanding it and defining the negatives as 0.
Also this is my first time golfing so I hope you forgive any faux-pas.
The binomial is not mine and was taken from [here](https://codegolf.stackexchange.com/questions/102868/evaluate-the-binomial-coefficient?noredirect=1&lq=1).
[Answer]
# [Python 3](https://docs.python.org/3/), 100 bytes
```
f=lambda n,r=0:r and[r]+(n and[r+n[0]+(r==n[0])]+f(n[1:],n[0]))or(n*[1]and[1]+f(f(n-1)[2::2],1))+[1]
```
[Try it online!](https://tio.run/##JYpBDgIhDEX3nqLLVjCZjrsmnISwwIwoiZZJMxtPj6C79/77@@d4Nr32XsIrv29bBvUWFjHIukVLDvVPTuMyzEKYQMkV1MiS/E@pGeo5cppfnnHkC1NcRdbkmciNuZdmUKEqWNbHHZlJTrBb1QOrL1iJ@hc "Python 3 – Try It Online")
This is really ugly mostly because I mashed together two separate functions. The outer one gets selected when r=0. It recursively calls itself to generate the previous row and then does the following: Discard every other entry. Add a 1 at the end and the beginning. Then have the inner function: Fill the gaps with the sums of the neighbouring entries and if the middle entry was among the discarded ones increment it by one.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 31 bytes
```
n->Vec(((y=1+x^2)^n-x^n)/(y-x))
```
[Try it online!](https://tio.run/##FcdBCoQwDAXQq3xcJUyC1MGlHsONWCiiIgwhiIv29B3dvefpOvXwumOopuO0rURUhvDJseNomqNxS0Uzc03uv0IGHeHXaffD5k2DnYxZMAdBJ/gKekEIC9c/ "Pari/GP – Try It Online")
The sum of first \$n\$ rows is the coefficients of the polynomial \$\frac{(x^2+1)^n-x^n}{x^2+1-x}\$.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 40 bytes
```
(((y=x^2+1)^#-x^#)/(y-x)+O@x^(2#))[[3]]&
```
[Try it online!](https://tio.run/##BcFBCoAgEAXQq3wYiBlSQqNl0Q1qLwoSRS1qES6M6Oz23hnTvp4xHUssG/rCzE@fg62NBNI5kDT86Cz1NObAlkSca72vynwfV3IEPWBz5D0qNCNeo2AVWoVOwZiv/A "Wolfram Language (Mathematica) – Try It Online")
] |
[Question]
[
Write a function that contains five lines.
If you run the function as-is, it should return 0.
If you remove any one of the five lines and run the function, it should tell you which of the lines has been removed (e.g., if you remove the final line it should return 5).
Brevity, novelty, and elegance all deserve consideration. Highest upvoted solution (after a reasonable amount of time) wins.
[Answer]
## Ruby
Eschewing magic numbers since it's not code golf.
```
def f
r=2^3^4^5
defined?(r) ? r^=2 : r=1^3^4^5
r^=3
r^=4
r^=5
end
```
Each line strips its own number out of `1^2^3^4^5`. It's Ruby, so the last line defines the return value.
[Answer]
## JavaScript ( ~~134~~ ~~77~~ ~~69~~ ~~65~~ 60 chars)
## [→ live demo ←](http://xem.github.io/miniCodeEditor/1.1/#w=function%28n%29%7B%0A%0A%20%20a=n-=1%0A%20%20n-=2%0A%20%20+3%0A%20%20+4;if%28this.a%29return%205%0A%20%20return%20n;var%20a%0A%0A%7D%0A%0Adocument.write%28w%2810%29%29%7F%7F%3Ch3%3EComment%20one%20of%20the%20lines%20of%20the%20function%20w,%20it%20will%20return%20the%20number%20of%20the%20commented%20line%3C/h3%3E%0A%0ARemoved%20line%3a%201)
```
function(n){
a=n-=1
n-=2
+3
+4;if(this.a)return 5
return n;var a
}
```
call this function with n = 10.
* If no line is missing, line 5 returns n == 0.
* If line 1 is missing, line 5 returns n == 1.
* If line 2 is missing, line 5 returns n == 2.
* If line 3 is missing, line 5 returns n == 3.
* If line 4 is missing, line 5 returns n == 4.
* If line 5 is missing, the var "a" becomes global and line 4 detects that to return "5".
* If line 5 is present, the JS engine performs "variable hoisting", "a" becomes a local var, and line 4 doesn't return "5".
## Previous versions:
## 65 chars
```
function(n){
a=n-=1
n-=2
+3
+4;if(this.a)return 5
n-=5;return n;var a
}
```
(must be called with n = 15)
## 69 chars
```
function(n){
n-=1
n-=2
n-=3
a=n-=4;if(this.a)return 5
n-=5;return n;var a
}
```
(must be called with n = 15)
## 77 chars
```
function(){
a=
b=
c=
d=1;if(this.a)return 5
1;var a,b,c,d;return d?c?b?a?0:1:2:3:4
}
```
## 134 chars
```
function w(){
a=1;e=1;if(this.e)return 5
b=1;if(!a)return 1
c=1;if(!b)return 2
d=1;if(!c)return 3
var a,b,c,d,e;return d?0:4
}
```
## non-golfed
```
function whichlineisremoved(){
/* 1 */ var a = 1; e = 1; if(window.e) return 5;
/* 2 */ var b = 1, a; if(!a) return 1;
/* 3 */ var c = 1, b; if(!b) return 2;
/* 4 */ var d = 1, c; if(!c) return 3;
/* 5 */ var e = 1, d; if(!d) return 4; return 0;
}
```
[Answer]
## Python
If parameters are allowed, then this will work:
```
def f(n=10):
n -= 1
n -= 2
n -= 3
if n == 4: return 0 if f(7) else 5
return n - 4 or 4
```
[Answer]
## R
```
f <- function() {
T <- FALSE
F <- TRUE
month.abb <- TRUE
(pi <- 5)
T + (!F) * 2 + (!isTRUE(month.abb)) * 3 + (pi != 5) * 4
}
```
The function uses built-in "constants" and assigns another value to each of them. If all of these variables are equal to the new value, the function returns 0. Logical values are transformed to numeric ones because of the mathematical operators. The parentheses around the 4th line allow visibly returning its result (if it's the last command).
[Answer]
# Lua 5.2+
55 chars in the function body excluding newlines.
I couldn't come up with anything better but this:
```
function f()
return 7--[[
return 1--[=[]]-2
--[[
-2--[=[]]
-5--]=]--]]-1
end
```
Hoping to get extra points for comments abuse :P
The reason it does not work in 5.1 is that nested `[[]]` were removed, and in 5.1 it gives a compilation error instead of ignoring it like 5.2 does.
* If none of the lines are removed, the function body is eqivalent to `return 7-2-5`
* If the first line is removed, `return 1`
* If the second, `return 7-5`
* If the third, `return 7-2-2`
* If the fourth, `return 7-2-1`
* If the fifth, `return 7-2`
[Answer]
## Ruby
I tried doing it with bitwise operations and then I realized there is a much simpler solution using lists! This challenge is best served by a programming language that automatically returns the last value it sees, such as Ruby.
```
def tellMe(x=[1,2,3,4,5])
x.delete(1)
x.delete(2)
x.delete(3)
x.delete(4);x[0]
x.delete(5);x==[]?0:x[0]
end
```
[Answer]
Befunge doesn't have explicit functions, but here is what I'd call a function in Befunge:
```
v^ <
>v
1>v
2>v
##3>5v
$0v4 >
>>>>>>^
```
The first and last lines are function start and function end. It does the closest thing to "return", that is, it pushes the correct value onto the stack.
[Answer]
# New Answer
I found another solution. That's so bad, I liked the math one so much. This solution uses recursion and global variables (yuck!) to tell if every line has been run or not. I wanted to do something different from the other solutions, so this isn't much elegant, but it works properly :)
### PHP
```
function LOL($a) {
if (!$a) { LOL(true); if (!$GLOBALS['b']) return 2; if (!$GLOBALS['c']) return 3; if (!$GLOBALS['d']) return 4; if (!$GLOBALS['e']) return 5; return 0; }
if ($a) $GLOBALS['b'] = true; else return 1;
$GLOBALS['c'] = true;
$GLOBALS['d'] = true;
$GLOBALS['e'] = true;
}
```
I really enjoyed this challenge, thank you! :)
---
# Old Answer
I solved it using maths. If each variable is seen as an unknown, and we do one declaration per line, there are five unknowns and five lines of code: this leads us to the following 5x5 system:
```
b+c+d+e = 1;
a+c+d+e = 2;
a+b+d+e = 3;
a+b+c+e = 4;
a+b+c+d = 5;
//Solutions are displayed in the code below.
```
Once I found the values, I hardcoded them and added some basic stuff.
### PHP
```
function LOL(){
$a = 2.75;
$b = 1.75;
$c = 0.75;
$d = -0.25; if ($a+$b+$c+$d == 5) return $a+$b+$c+$d;
$e = -1.25; return $a+$b+$c+$d+$e;
}
```
**Note:** The Old Answer won't work if left as-is.
[Answer]
# Bash, 131 chars
```
#!/bin/bash
# the function:
function f(){
a=1;
b=2;
c=3;
d=4;[ ! $1 ]&&f 1&&return 5||true
[ $1 ]&&return 6;e=5;s=$((a+b+c+d+e));return $((15-$s))
}
# call it:
f
# report the result:
echo Removed line $?
```
It's all straightforward up to line 5. Then it needs to detect if the final line is gone. This takes advantage of permitted function parameters by calling itself recursively, once, to test its own success value when it's being told to fail on line 5, and if line 5 is removed, line 4 returns `5` instead.
(Note: it's down to a minimum of 131 characters if stripping out everything but the function, ditching whitespace, and changing /bin/bash to /bin/sh)
[Answer]
# [beeswax](http://esolangs.org/wiki/Beeswax), 86 bytes
Trying out my first invented esolang.
After initial confusion I found that the solution is so simple.
```
_1 p
_^v>~2+p
> >~3+p
> >~4+X@7~8+~@$^^{;
> >~5+@7~8+~@${;
```
Explanation:
**beeswax** programs work on a 2D hexagonal grid. Programs are stored in a rectangular format.
```
a — b — c — d
/ \ / \ / \ /
e — f — g — h
/ \ / \ / \ /
i — j — k — l
```
is stored as
```
abcd
efgh
ijkl
```
The instructions for moving in certain directions are:
```
b — d
/ \ / \ bd
< —IP — > or in compact form (β=IP): <β>
\ / \ / pq
p — q
```
Short explanation
`_1 p` Create an IP, add 1, then redirect IP to line 2
`_^v>~2+p` Create another IP, just in case line 1 is missing, slow down IP to make sure IP from line one is ahead, then add 2, then redirect to line 3
`> >~3+p` Add 3, then redirect to line 4
`> >~4+X@7~8+~@$^^{;` Add 4, then set 2nd lstack value to 15, then XOR lstack top and 2nd values, slow down IP (to make sure IP in line 5 is ahead, if line 5 exists) and output the result, then terminate the program.
`> >~5+@7~8+~@${;` Add 5, then do the same as in line 4, except the slow down.
Basically the program just calculates a sum xor 15
* Program intact: (1+2+3+4+5) xor 15 = 0
* Line 1 missing: (2+3+4+5) xor 15 = 1
* Line 2 missing: (1+3+4+5) xor 15 = 2
* Line 3 missing: (1+2+4+5) xor 15 = 3
* Line 4 missing: (1+2+3+5) xor 15 = 4
* Line 5 missing: (1+2+3+4) xor 15 = 5
The additional `>` in lines 3 to 5 just guarantee that if one of lines 2 to 4 are missing, the IP still gets redirected properly and doesn’t leave the program.
You can clone my beeswax interpreter, written in Julia, from **[my GitHub repository](https://github.com/m-lohmann/BeeswaxEsolang.jl)**
The readme on GitHub is more up to date and better structured than the esolangs page.
[Answer]
## MuPAD, 57 chars
```
subs(()->
-d(1)
-d(2)
-d(3)
-d(4)
-d(5)
,d=Dom::IntegerMod(15))
```
[Answer]
Common LISP:
```
(defun which-line-is-removed (&aux (x 30))
(decf x 2)
(decf x 4)
(decf x 8)
(decf x 16) 5
(if (zerop x) 0 (log x 2))
)
```
NB: Having ending parenthesis on it's own line is considered bad style, but since other languages has `end` and `}` I assume it is allowed.
[Answer]
# Javascript
```
function(){
/*aa*/if(arguments.callee.toString().indexOf("*"+"a".repeat(6)+"*")==-1)return 5;
/*aaa*/if(arguments.callee.toString().indexOf("*"+"a".repeat(5)+"*")==-1)return 4;
/*aaaa*/if(arguments.callee.toString().indexOf("*"+"a".repeat(3)+"*")==-1)return 2;
/*aaaaa*/if(arguments.callee.toString().indexOf("*"+"a".repeat(4)+"*")==-1)return 3;
/*aaaaaa*/return +!~arguments.callee.toString().indexOf("*"+"a".repeat(2)+"*");
};
```
] |
[Question]
[
We start with a blank 1-indexed sequence:
```
_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,_,...
```
In the nth step, we fill in every a(n) blanks with the integers greater than 1 starting at the first remaining blank, where a(n) is the nth entry in the sequence.
After the first step:
```
2,_,3,_,4,_,5,_,6,_,7,_,8,_,9,_,10,_,11,_,12,_,13,_,...
```
Note that a(1) has to be 2 because the first integer greater than 1 is 2.
In the second step, we fill in every a(2) blanks. It will be apparent that a(2) must be 2.
```
2,2,3,_,4,3,5,_,6,4,7,_,8,5,9,_,10,6,11,_,12,7,13,_,...
```
In the third step, we fill in every a(3) blanks. From the sequence, a(3) = 3.
```
2,2,3,2,4,3,5,_,6,4,7,_,8,5,9,3,10,6,11,_,12,7,13,_,...
```
In the fourth step, we fill in every a(4) blanks. From the sequence, a(4) = 2.
```
2,2,3,2,4,3,5,2,6,4,7,_,8,5,9,3,10,6,11,3,12,7,13,_,...
```
Eventually:
```
2,2,3,2,4,3,5,2,6,4,7,2,8,5,9,3,10,6,11,3,12,7,13,2,...
```
## Task
Given n, return the nth element of the sequence.
The first 10,000,000 terms of the sequence can be found [here](https://drive.google.com/file/d/0B-UzTw21ElCwNWYxdVpjX1NDOTg/view?usp=sharing).
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"). Shortest answer in bytes wins. [Standard loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) apply.
[Answer]
# [Haskell](https://www.haskell.org/), ~~80~~ 67 bytes
```
g~(a:b)|let k!l=k:take(a-1)l++(k+1)!drop(a-1)l=2!g b
m=g m
(!!)$0:m
```
[Try it online!](https://tio.run/##JchBCsIwEADAe1@xAQ8bgiHxGMgTfEER2WIay@7WUHMUvx4PznGe9OYiMkb9IqXFfqR0YCOZUycuSOdoxTlkF615HK/2n3wxFZZJcwWd1ozG2FNIOpS2HTIotesdsB3b3sHDamGO3scQbuMH "Haskell – Try It Online")
Haskell is the perfect language for defining an infinite list in terms of itself.
[Answer]
## C, 123 bytes
```
f(n){int*p=calloc(n,4),i=0,j,k;for(*p=p[1]=2;i<n;++i)for(j=0,k=i/2?0:2-i;j<n;++j)p[j]||k++%p[i]||(p[j]=k/p[i]+2);n=p[n-1];}
```
[Try it online!](https://tio.run/##RY09DoMwDIX3nsJCQkqaIP461UQ9CGVAqagcaIhQN@Ds1GGpF9vvs9@z2dva4xiElyv57zUY20/TbIXXN6nJFNrpEYd5EYxCW3amQmo8KkUyqo4vRkN59SjuVUboTuZkaF23baNSaWiJJxEFM@ZxU5VEz2Y@KzvcD46FT09eSFgvwMW@IKJKYKBEbg3UBULMhLAwGUSSvnSiYRAkJZ5ff/D0J6mLiPbjBw "C (gcc) – Try It Online")
## Walkthrough
```
f(n){int*p=calloc(n,4),
```
Allocate an array of *n* integers to store the first *n* elements of the sequence. This hardcodes `sizeof(int)` as `4`, which is a safe assumption in most cases and certainly one I'm willing to make in the context of code golf. :)
```
i=0,j,k;
```
These are all counters: `i` for the index of the step we're on, `j` to loop through the sequence looking for empty spaces, and `k` to count how many empty spaces have been seen.
```
for(*p=p[1]=2;i<n;++i)
```
Before we start our main loop, we sneak in an initialization of the first two elements of the sequence to `2`. (`p[0]` = `*(p + 0)` = `*p`.) This throws off the count for `k`, though, but...
```
for(j=0,k=i/2?0:2-i;j<n;++j)
```
... we also do a sneaky initialization of `k`, which tests to see if `i` is less than `2` and corrects the starting value of `k` if so. The inner loop also starts here, which iterates over the entire sequence-so-far during each step.
```
p[j]||k++%p[i]||(p[j]=k/p[i]+2);
```
This line could really use some explaining. We can expand this to:
```
if (!(p[j] || ((k++) % p[i]))) {
p[j] = k / p[i] + 2;
}
```
by short circuiting, and then by De Morgan's laws and the fact that `0` is falsy in C:
```
if (p[j] == 0 && ((k++) % p[i]) == 0) {
p[j] = k / p[i] + 2;
}
```
This essentially states: "if this space is empty, increment `k`. And if `k` was previously a multiple of the step size, run the following statement." Hence, we run the statement on every *step size* elements, which is exactly how the sequence is described. The statement itself is simple; all it does is generate `2`, `3`, `4`, ....
```
n=p[n-1];}
```
Using the tricky-return-without-a-return that works with `gcc`, we "return" the last element of the first *n* terms in the sequence, which happens to be the *n*th term.
[Answer]
# Pyth, 29 bytes
```
M?tH?eJ.DtHg1GghG-tHhJ+2hJ2g1
```
[Try it online](https://pyth.herokuapp.com/?code=M%3FtH%3FeJ.DtHg1GghG-tHhJ%2B2hJ2g1&test_suite=1&test_suite_input=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20)
### How it works
Instead of fooling around with lists, this uses a plain recursive formula.
```
M def g(G, H):
?tH if H - 1:
J.DtHg1G J = divmod(H - 1, g(1, G))
?e if J[-1]:
ghG-tHhJ return g(G + 1, H - 1 - J[0])
else:
+2hJ return 2 + J[0]
else:
2 return 2
g1Q print(g(1, eval(input())))
```
[Answer]
# [Haskell](https://www.haskell.org/), 67 bytes
```
0%j=2
i%j|d<-div i$f j=last$d+2:[(i-d-1)%(j+1)|d*f j<i]
f=(%1).pred
```
[Try it online!](https://tio.run/##NVHLboMwELzzFT4ECZqH2LW9QBW@o4coByRIY0oiBLSHqv9Od1z1gD14d@dh39vlox/HbSvSoeEkpMNPdz524cuE3c0Mzdgu667b8@slC8fuSHmaDXvKf7oXrZ7DNbk1WUr5aZr7bpv75XNcF9OYRzuZm7nQ6XRN1nZ@71c9vPCBD1Y/p6vXXRSVulf6V@sZFXpEBMRaIPSS0zJ57STRJiqBKrRSrWUuMMAEPsYYR2oXh6HBAgoulZkjEdcKbQE6CynLILVWBW2kth5QwG9LNFRQsbX6cAWkHAEyBF2M46DqkMEJtF0JWMGAQy5fwIYnuPYMMz6G9Q6ePMJ5gTFfIo2v4M/XwFLApajoQRheJV6OODgWH7HAuOAiJbqXGunL4pokjzY89eanOTxXszPts9P1O0xvYb1nTZOb/yf7e6TtFw "Haskell – Try It Online")
A recursive arithmetical solution that turned out basically the same method as [Anders Kaseorg's Pyth answer](https://codegolf.stackexchange.com/a/127586/20260).
This code is covered in warts -- ugly parts that look like they could be golfed away, but I didn't see how.
The function `i%j` really wants to use a guard to check whether `mod i(f j)>0` and evaluate one of corresponding two expression. But, both expressions use `div i(f j)`. Binding that in a guard won't make it apply to both sides. As far as I know, a guard can't be made to "distribute" over other guards. `let` and `where` are too long. So, the code uses `last` to pick one of two expressions while the guard binds the variable. Ugh.
Ideally we'd use `divMod` because both the `div` and `mod` are used, but `(d,m)<-divMod ...` is a long expression. We instead hackily check of the mod is nonzero by seeing if the `div` value times the divisor falls short of the original value.
The `0%j=2` case would not be needed if Haskell short-circuited `div 0`, which it doesn't. The `.pred` converts the 1-indexed input to zero-indexed, or else there would be `-1` corrections everywhere.
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~20~~ 16 bytes
```
!ƒψΣz`:tNΘC←←¹²t
```
[Try it online!](https://tio.run/##yygtzv6vkPuoqdHvv@KxSec7zi2uSrAq8Ts3w/lR2wQgOrTz0KaS//8B "Husk – Try It Online")
A golfed port of the mind-bending [Haskell answer by Anders Kaseorg](https://codegolf.stackexchange.com/a/127458/62393)
### Explanation
This answer builds this meta list with a self-referential process.
Let's get a few things out of the way before we can look at how the list is actually built: `!` simply takes an item from the list, since the challenge asks to return the element at a given list. `ƒ` is the fixpoint operator, it takes a function and applies the function to itself ad infinity, i.e. `ƒg` = `g(g(g(g(g(g(...`; this is what allows us to define the list in terms of the list itself. `ψ` is a way to write a recursive function in Husk: the following commands define a function of one argument where `⁰` (or `¹`) marks the argument, and `²` marks the function itself.
The inner code (with implicit parameters made explicit) is this:
```
Σz`:tNΘC←←⁰²t⁰ Takes an infinite list as input, returns an infinite list
² Apply the function recursively
t⁰ to the tail of the list
←⁰ then take the head of the input list
← -1
C and cut the resulting list in groups of that length
Θ Prepend an empty group
z For each group
`: append
tN a natural number (starting from 2)
Σ Then concatenate all groups together
```
What this function does is taking the current `a(n)` and the list of values that are marked as blanks in step `n`, and add `2,3,4,5...` at the right locations between those "blanks".
It would be shorter (and more natural) to prepend a number to each group (each value 2,3,4... goes at the *beginning* of the group of a(n) blanks, after all), but to do that we wouldn't be able to generate the first element of the list until we generate the first group of blanks, and since this definition is self-referential we couldn't generate the first element of the first group of blanks until we generate the first group of blanks after that, and so on forever. By adding an empty group at the beginning and putting values at the end of groups instead, we can generate the initial `2` without having to look at the rest of the list, and this is enough to kickstart the whole process that will generate the infinite list recursively.
[Answer]
# JavaScript (ES6), ~~98 93 91~~ 87 bytes
*Saved 4 bytes thanks to @l4m2*
A recursive function that stops as soon as the result is available.
```
f=(n,p,a=[])=>a[n-1]++||f(n,-~p,[...a].map(c=>c?c:i?i++%(a[p]||2)?c:++v:(i=1,v=2),i=0))
```
[Try it online!](https://tio.run/##FY1BDoMgFET3nuJvGiEfiZp0o/16EMKCUG1oWiDauCnt1Sndzby8ydzNYXa7ufhqfLguOa/EvIjCkNKcJqN802nElNaCm28USkpptHyayCxNdraDmx3iiRkVdUo9LwTxGJijThzUc@Go5TyvYWMeCLoRPFwIzm0JiBzeFYANfg@PRT7CjdVG1YBFQqh1GfxLOed8rD75Bw "JavaScript (Node.js) – Try It Online")
[Answer]
# Java 8, 124 bytes
```
(i)->{int j=1,a[]=new int[i+1],k,s,n;for(;a[i]<2;){for(k=0,n=2;a[++k]>0;);for(s=a[j++]|2*k;k<=i;k+=s)a[k]=n++;}return a[i];}
```
Lambda expression.
Creates an integer array and continually populates it until the nth value gets populated.
Pre-declaring variables at the top to cut down on as many declarations as possible as each `int` costs 4 bytes of space as opposed to adding `,n` which is 2.
On the `j`'th iteration of calculation, the number of 'blanks' one has to skip is equal to `a[j]` (or 2, if blank). It works out that if the first blank space we have to fill in is at position `k`, `k * a[j]` gives us the 'step' (`s`).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 104 bytes
```
j;k;f(n){int*p=calloc(n,4)-4,i=1,y;for(;j=k=p[n],!j;++i)for(y=p[i]?:2;j++<n;)p[j]||k++%y||(p[j]=k/y+2);}
```
[Try it online!](https://tio.run/##RYxBDoIwEEX3nmIkIenYEgFZOTQeBFmQGkxbLIS4IcDZa8vG2fzMe/lfZW@lvDdkqWcOV@2@l0mqbhhGxZyoMKuEloVYqB9nRkZaOTWuFWdDnGuMcAlEt497SYbz2hFOjWm3zXKeLtvG4iftdeEl0u7DPnw67RjCeoJwYQFYpBokFBSihlueE8R5mOagepakL5EI6JlGpKP2F093mNCJbvc/ "C (gcc) – Try It Online")
Trying to golf [the last C solution](https://codegolf.stackexchange.com/a/127407/) but it's just too hard to understand
```
f(n){
int*p=calloc(n,4)-4,i=0,j,k,y; // p as Array[1..n]
for(;j=k=p[n],!j;++i) // Once p[n] is filled we're over
// and that's what we want
// Otherwise j and k are inited to 0
for(;j++<n;) p[j]|| // For zeros
k++%(y=p[i]?:2)||(p[j]=k/y+2); // On correct time fill them
}
```
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 23 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
ü→è«wε⌠╒└I◄►¼═Öà=╬à╞⌐-Ω
```
[Run and debug it](https://staxlang.xyz/#p=811a8aae77eef4d5c0491110accd99853dce85c6a92dea&i=1%0A2%0A3%0A4%0A5%0A6%0A7%0A8%0A9%0A10%0A11%0A12%0A13%0A14%0A15%0A16%0A17%0A18%0A19%0A20%0A21%0A22%0A23%0A24%0A&m=2)
A direct implementation of the procedure.
Uses zeroes as placeholders till the array is fully filed, and take the last element.
## Explanation
```
z({c:0ni@i1>s2?::{i^^&F}x*H Input: x
z empty list
( pad with x zeroes (call this S)
{ }x* perform the following x times:
c:0 get the falsy indices
i1> ? if iteration index >1 :
ni@ get nth element of S
2 else push 2
:: get every nth element of the falsy indices
{ F for each index:
i^^& replace with iteration index + 2
```
] |
[Question]
[
Here in California, we're in a drought so we need to know how much water we have left so we can conserve as much water as possible.
Because water is limited supply, your code will need to be as short as possible.
## Examples
```
| |
| |
|~~~|
|___|
Output: 0.5
```
```
|~~~~~|
| |
| |
|_____|
Output: 1
```
```
| |
|__|
Output: 0 (or bonus)
```
## Specification
The input will consist solely of all of: `|_ ~` and newlines. All above the `~`'s are considered air; `_`, spaces below `~`, and `~` itself are considered water. The percent of water left is computer by `water / (air + water)`. Your output needs to be accurate to 4 decimal places (unless you go for the percent bonus). The input will always be rectangular. The `~` will only be on one line, if on any. The input may optionally also have a trailing line feed if you'd like.
## Bonus
If you go for both bonuses the -15% bonus is applied before the -35 bonus
**-35 byte Bonus:** If your code prints "This drought *goat* out of hand", instead of 0 when the Output is 0
**-15% Bonus:** If you output a percent.
To do this, you would shift the decimal place two places to the left, trim leading zeros, and add a `%` to the end. Trailing zeros (max 2) are allows as long as they don't affect the value. `0.5` -> any of: `50.00% 50% 50.0%`
[Answer]
# Pyth - ~~17~~ ~~46~~ ~~45~~ 52 \* .85 - 35 = 9.2 bytes
Filters the input (With the new `#` filter meta-op!) for a line with `~` in it, then indexes that to the input, and then divides that by the length of the input. If there are none with `~`, it errors, and triggers the except clause of `.x` and prints the string.
```
.x+*100-1cxK.zh@#\~KlK\%." u(C$éáPãbÉãç*îÂe[W
```
[Try it online here](http://pyth.herokuapp.com/?code=.x%2B%2a100-1cxK.zh%40%23%5C%7EKlK%5C%25.%22+u%03%28%C2%89C%C2%94%04%24%C2%89%C3%A9%C3%A1P%C3%A3b%C3%89%C3%A3%C3%A7%2a%C3%AE%C3%82e%5B%1EW%1C&input=%7C+++%7C%0A%7C+++%7C%0A%7C%7E%7E%7E%7C%0A%7C___%7C&debug=0).
[Answer]
## Python 3, 37 bytes
```
lambda x:1-(x+'|~').find('|~')/len(x)
```
No bonuses. Takes an input string with newlines, including a trailing newline.
Let's look at why the formula works. The fraction of water is the complement of the fraction of air, which we'll derive.
```
frac_water = 1 - frac_air
```
Numbering the rows `0, 1, 2, ...`, we have
```
frac_air = water_row_index / num_rows
```
The same is true if both are multiplied by the width of each row, counting newlines, which simplify to expressions in the number of characters.
```
frac_air = (width * water_row_index) / (width * num_rows)
= water_row_start_char_index / num_chars
```
The water row start is found by searching the input string `x` for `|~`, and the number of chars is just the length.
```
frac_air = x.find('|~') / len(x)
```
Finally, in order to make no-water inputs work, we append a fictional water row start `|~` to the end before searching, which makes it look like the water level is 0.
The bonuses seemed not worth it. The best I got on the string one is 73-35=38:
```
lambda x:['This drought goat out of hand',1-x.find('|~')/len(x)]['~'in x]
```
[Answer]
# CJam, ~~19~~ ~~17~~ ~~16~~ 58 \* 0.85 - 35 = 14.3 bytes
```
q'|-_'~#_)\@,d/1\m100*s'%+"This drought goat out of hand"?
```
[Try it online](http://cjam.aditsu.net/#code=q'%7C-_'~%23_)%5C%40%2Cd%2F1%5Cm100*s'%25%2B%22This%20drought%20goat%20out%20of%20hand%22%3F&input=%7C%20%20%20%7C%0A%7C%20%20%20%7C%0A%7C~~~%7C%0A%7C___%7C%0A)
This version gets both bonuses. The input *must* have a trailing newline for this solution to work.
Thanks to @Martin Büttner for saving 2 bytes.
Explanation:
```
q Get input.
'|- Remove left/right wall, so that position of first ~ in remaining string
corresponds to the water level.
_ Make a copy.
'~# Find ~ character.
_) Make copy of find result, and increment it. This is 0 if the ~
was not found, and will be used for the bonus condition.
\ Swap original find result to top.
@, Rotate copy of remaining input to top, and get its length.
d Convert to double to get float division.
/ Divide the two values. Since the position of the ~ was indexed from
the top, this is 1 minus the desired result.
1\m Subtract value from 1, to get the actual result.
100* Multiply by 100 to get percent.
s Convert to string.
'%+ Append % sign.
"This drought goat out of hand"
Push bonus zero string.
? Ternary operator to pick calculated result or zero string.
```
[Answer]
# JavaScript (ES6), 45 (94 -15% -35)
As an anonymous function. Using template strings, there is a newline that is significant and included in the byte count
**Edit** 1 byte saved thx @user81655
```
p=>p.split`
`.map((r,i)=>r>'|~'?p=i:q=~i)&&q-p?(1+p/q)*100+'%':'This drought goat out of hand'
```
**Less golfed**
```
p=>(
p.split('\n') // split in rows
.map((r,i)=> // execute for each row
r>'|~' // look for the water top
? p=i // position of water top in p
: q=~i // if not water top, set current position (-i-1) in q
),
// at the end,if water top not found, p still contains the input string
q-p // subtracting the input string I get NaN (that is a falsy value)
? (1+p/q)*100+'%' // calc % taking into account the negative sign of q
: 'This drought goat out of hand'
)
```
**Test snippet**
```
F=p=>p.split`\n`.map((r,i)=>r>'|~'?p=i:q=~i)&&q-p?(1+p/q)*100+'%':'This drought goat out of hand'
function Update() {
var w=+W.value, h=+H.value, t=+T.value,
b=Array(h).fill().map((r,i)=>'|'+(i==h-1?'_':i==t?'~':' ').repeat(w)+'|').join`\n`
O.textContent = b+'\n\n'+F(b)
}
Update()
```
```
<table>
<tr><td>Width</td><td><input id=W type=number value=4 oninput='Update()'></td></tr>
<tr><td>Height</td><td><input id=H type=number value=4 oninput='Update()'></td></tr>
<tr><td>~~~ at row</td><td><input id=T type=number value=2 oninput='Update()'></td></tr>
</table>
<pre id=O></pre>
```
[Answer]
# [Par](http://ypnypn.github.io/Par/), 57 \* 85% - 35 = 13.45 bytes
```
`This drought goat out of hand`r√″T┐↑⌐'~˦↑↔~÷Zx²*'%↔╡\z_g
```
## Explanation
```
`This dr...d` ## 'This drought goat out of hand'
r ## Read entire input
√ ## Split by newlines
″ ## Duplicate
T ## Transpose
┐↑ ## Second element of each line
⌐ ## Reverse
'~˦ ## First index of '~'
↑ ## Plus one
↔ ## Swap
~÷ ## Divide by size
Z ## Assign to z
x²* ## Multiply by 100
'%↔╡ ## Append '%'
\ ## Array of string and number
z_g ## If z=0, then string; else, number
```
[Answer]
## Perl, *70 - 15% - 35* = 24.5 bytes
*includes +1 for `-p`*
```
$S[$w|=/~/]++}{$_=$w?100*$S[1]/$..'%':'This drought goat out of hand'
```
With comments:
```
$S[ $w |= /~/ ]++ # $w=0 for air, 1 for having seen water; count element
}{ # -n/-p: end the `while(<>){` and begin END block
$_ = $w # assign output for -p
? 100 * $S[1] / $. . '%' # $. is $INPUT_LINE_NUMBER
:'This drought goat out of hand' # costs 35 aswell, but is effectively more after -15%
```
---
* 26+1 byte version, no bonus: **27**
```
$S[$w|=/~/]++}{$_=$S[1]/$.
```
* 34+1 byte version, with 15% bonus: **29.75**
```
$S[$w|=/~/]++}{$_=100*$S[1]/$..'%'
```
* 61+1 byte version, with -35 bonus: **27**
```
$S[$w|=/~/]++}{$_=$w?$S[1]/$.:'This drought goat out of hand'
```
* 69+1 byte version, both bonuses: **24.50**
```
$S[$w|=/~/]++}{$_=$w?100*$S[1]/$..'%':'This drought goat out of hand'
```
[Answer]
# Javascript, 59.3
I hope extra decimal places are OK. Assumes no trailing newline.
```
drought=
// code
a=>(b=-1,e=a.split`
`.map((c,d)=>b=c[1]=='~'?d:b).length,++b?(e-b+1)*100/e+"%":"This drought goat out of hand")
// I/O
var i = document.getElementById("i");
var o = document.getElementById("o");
i.onchange = i.onkeyup = function(){
o.textContent = drought(i.value);
};
// explanation
inputStr=>(
tildePosition = -1, // default: not found
containerDepth = // if the current line has a tilde, set tildePosition, otherwise
// keep current tildePosition
inputStr.split`\n`.map((line, pos)=> tildePosition = line[1]=='~' ? pos : tildePosition)
.length, // assign number of lines (container depth) to containerDepth
++tildePosition // if it's still -1, print the message, otherwise print percent
?(containerDepth-tildePosition+1)*100/containerDepth+"%"
:"This drought goat out of hand")
```
```
<textarea id="i"></textarea>
<p id="o"></p>
```
[Answer]
## Haskell, 56 bytes
```
l=sum.(>>[1])
f i|s<-lines i=l(snd$break(elem '~')s)/l s
```
Usage example: `f "| |\n|~~|\n| |\n|__|"` -> `0.75`.
`l` is a custom length function, which is necessary, because the build in `length` returns integer values, but we need floating point values for the division (there's `genericLength` which also provides this feature, but it's longer, let alone the required `import Data.List`). `f` splits the input `i` into lines (-> `s`) and then into a pair where the first element is a list with all the lines up to (and excluding) the first one with a `~` in it. The second element is a list with the rest of the lines. The result is the length of the second element divided by the length of `s`.
The bonuses don't pay off.
[Answer]
Python is verbose!
# Python: 98.45 bytes
*(157 \* 0.85) - 35 = 98.45 bytes*
This version reads from stdin, and collects both bonuses:
```
import sys
r=[x[1]for x in sys.stdin.read().split('\n|')]
o="This drought goat out of hand"if'~'not in r else"%g%%"%(100-100.0*r.index('~')/len(r))
print(o)
```
[Answer]
# Awk, 72 characters - 15% - 35 = 26.2
```
/~/{w=NR}END{print w?(NR-w+1)/NR*100"%":"This drought goat out of hand"}
```
Sample run:
(Initial `1;` only used in these sample runs to display the “human readable” tank.)
```
bash-4.3$ awk '1;/~/{w=NR}END{print w?(NR-w+1)/NR*100"%":"This drought goat out of hand"}' <<< $'| |\n| |\n| |\n|_|'
| |
| |
| |
|_|
This drought goat out of hand
bash-4.3$ awk '1;/~/{w=NR}END{print w?(NR-w+1)/NR*100"%":"This drought goat out of hand"}' <<< $'| |\n| |\n|~|\n|_|'
| |
| |
|~|
|_|
50%
```
[Answer]
# PHP, 92 characters - 15% - 35 = 43.2
(88 characters in two blocks of code + 4 characters command line options.)
```
$argn[1]>z&&$w=+$argi;
```
```
echo$w?100*($argi-$w+1)/$argi."%":"This drought goat out of hand";
```
Assumes `error_reporting` is set to default.
(Not a big deal, just wished to use the `-R` and `-E` once. Now only `-B` left.)
Sample run:
(Initial `echo"$argn\n";` only used in these sample runs to display the “human readable” tank.)
```
bash-4.3$ php -R 'echo"$argn\n";$argn[1]>z&&$w=+$argi;' -E 'echo$w?100*($argi-$w+1)/$argi."%":"This drought goat out of hand";' <<< $'| |\n| |\n| |\n|_|'
| |
| |
| |
|_|
This drought goat out of hand
bash-4.3$ php -R 'echo"$argn\n";$argn[1]>z&&$w=+$argi;' -E 'echo$w?100*($argi-$w+1)/$argi."%":"This drought goat out of hand";' <<< $'| |\n| |\n|~|\n|_|'
| |
| |
|~|
|_|
50%
```
[Answer]
**[QBIC](http://gamegiver.blogspot.nl/2015/12/introducing-qbic-qbasics-belated-entry.html) - 116 - 15% = 98.6 bytes**
```
{input S$:S$=MID$(S$,2,1):I=I+1:IF y<1 then x=I
y=y+instr(S$,"~"):IF instr(S$,"_")>0 THEN ?(1-(x-y)/I)*100;"%":END}
```
I've created QBIC to make QBasic more competitive, but it still needs several improvements. As of now, there are no shortcuts for error trapping, `THEN` (which is a pretty big oversight on my part) and `input$`. They will be added shortly.
I couldn't hit the 0 bonus, too costly... I did manage to print percentages.
Sample in/output:
```
? | |
? | |
? |~~|
? |__|
50 %
```
The program reads the input interactively. When it detects the bottom of the lake (`_`) it prints the percentage and quits. Tested for full containers and empty ones as well.
Edit: To show how QBIC has been expanded during the last year, here's the same program written for the current interpreter:
```
{_?A=$MID$|(A,2,1)#~|#_| i=i+1~j<1|k=i]j=j+instr(A,B)~instr(A,C)|?(1-(k-j)/i)*100,@%|_X
```
87 bytes, printing percentages, is a score of 74.
] |
[Question]
[
Given a rectangular text as a word search puzzle and a search string, determine if the text contains the search string. The search string may appear:
* horizontally, vertically or diagonally
* forwards or backwards
You may write a function or a program and take two strings as input via function argument, ARGV or STDIN. The output should be a [truthy or falsy](http://meta.codegolf.stackexchange.com/a/2194/8478) result which can either be returned from the function or written to STDOUT.
Assume that the text will contain arbitrary printable ASCII characters (hex codes 20 to 7E) and line break characters. Letters are case sensitive. You may assume that the input text is rectangular, i.e. all lines have the same length. You may whether the input ends with a trailing newline or not (if it matters for your submission).
This is code golf, the shortest answer (in bytes) wins.
## Examples
Using this grid from Wikipedia's article on word searches as the first input:
```
WVERTICALL
ROOAFFLSAB
ACRILIATOA
NDODKONWDC
DRKESOODDK
OEEPZEGLIW
MSIIHOAERA
ALRKRRIRER
KODIDEDRCD
HELWSLEUTH
```
the following search strings should yield truthy or falsy results respectively:
```
Truthy: RANDOM, VERTICAL, HORIZONTAL, WORDSEARCH, WIKIPEDIA, TAIL
Falsy: WordSearch, CODEGOLF, UNICORN
```
Alternatively, using this input text
```
Lorem ipsum dolor sit amet consectetu
r adipisicing elit sed do eiusmod tem
por incididunt ut labore et dolore ma
gna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco lab
oris nisi ut aliquip ex ea commodo co
nsequat. Duis aute irure dolor in rep
rehenderit in voluptate velit esse ci
llum dolore eu fugiat nulla pariatur.
```
We get the following search results (using quotes now, because there are spaces in some search strings):
```
Truthy: "Lorem", "mine", "uma bop", "tuetdod", "snol,a", "texas", "pii.d v", "vexta"
Falsy: "lorem", "wordsearch", "pii.d v", "mute"
```
[Answer]
# CJam, ~~46~~ 37 bytes
```
qN%{_zW%__,N**2$2$+,)/z\}4*]:+N*eas#)
```
Reads the grid from STDIN and the word as a command-line argument. Prints positive integers for matches and 0 for non-matches.
At the cost of two extra bytes, both strings (word, linefeed, grid) can be read from STDIN:
```
qN%(\{_zW%__,N**2$2$+,)/z\}4*](\:+N*\#)
```
You can try this version online with the [CJam interpreter](http://cjam.aditsu.net/).
### Example run
```
$ for W in Lorem mine uma\ bop tuetdod snol,a texas pii.d\ \ v vexta WordSearch CODEGOLF UNICORN; do echo -e "$(cjam wordsearch.cjam "$W" < grid)\t$W"; done
1 Lorem
3085 mine
2055 uma bop
5142 tuetdod
3878 snol,a
1426 texas
5371 pii.d v
2536 vexta
0 WordSearch
0 CODEGOLF
0 UNICORN
```
### Background
Assume the input was the following grid:
```
ABCD
EFGH
IJKL
```
Splitting at linefeeds, we obtain the following array:
```
A := [
"ABCD"
"EFGH"
"IJKL"
]
```
That covers East words (words going from left to right).
Now, we join the elements of `A` using a string of `len(A)` linefeeds as separator:
```
"ABCD⏎⏎⏎EFGH⏎⏎⏎IJKL"
```
Then, we chop the resulting string in chunks of length `len(A) + len(A[0]) + 1`:
```
[
"ABCD⏎⏎⏎E"
"FGH⏎⏎⏎IJ"
"KL"
]
```
If we "zip" the array (transpose rows and columns), we obtain:
```
[
"AFK"
"BGL"
"CH"
"D⏎"
"⏎⏎"
"⏎⏎"
"I⏎"
"EJ"
]
```
That covers South East words.
If we zip A and reverse the order of the result's rows, we obtain:
```
[
"DHL"
"CGK"
"BFJ"
"AEI"
]
```
That covers South and – after repeating the process for diagonals – South West words.
Zipping and reversing again, we obtain:
```
[
"LKJI"
"HGFE"
"DCBA"
]
```
That covers West and – after repeating the process for diagonals – North West words.
Zipping and reversing once more, we obtain:
```
[
"IEA"
"JFB"
"KGC"
"LHD"
]
```
That covers North and – after repeating the process for diagonals – North East words.
### How it works
The code does as explained in the previous section, with two minor differences:
* It zips and reverses once at the very beginning.
* It computes `len(A) + len(A[0])` as `len(A + zip(A))`.
Finally, it joins all rows of all generated arrays using linefeeds as separators and searches for the word in the resulting string.
```
qN% " A := split(input(),'\n') ";
{ }4* " Do 4 times: ";
_zW% " B := reverse(zip(A)) ";
__,N** " C := B.join(len(B) * '\n') ";
2$2$+,)/z " D := zip(C.chunks(len(A + B) + 1)) ";
\ " A := B ";
] " Collect all values of A and D in an array R. ";
:+ " R := flatten(R) ";
N* " R := R.join('\n') ";
eas " I := flatten(ARGV) ";
#) " print R.index(I) + 1 ";
```
[Answer]
# Java : 183 ~~211~~ ~~321~~
```
boolean s(char[]w,char[]s){int j,z,a=s.length,i=a*9,f=1,q=0;for(;s[q++]>10;);for(;i-->0;)for(j=w.length,z=i/9;i%9!=4&j-->0&z>=0&z<a&&s[z]==w[j];z+=q*(i/3%3)+i%3-q-1)f*=j;return f==0;}
```
A basic brute force. There's not much else to say, I guess. Input is needle first and haystack second. Assumes grid is [newline-terminated](https://codegolf.stackexchange.com/questions/37940/word-search-puzzle?noredirect=1#comment87224_37940).
A slightly more readable version with test case shown:
```
public class WordSearch {
static String grid = "WVERTICALL\nROOAFFLSAB\nACRILIATOA\nNDODKONWDC\nDRKESOODDK\nOEEPZEGLIW\nMSIIHOAERA\nALRKRRIRER\nKODIDEDRCD\nHELWSLEUTH";
static String search = "RANDOM";
public static void main(String[] args) {
System.out.println(new WordSearch().s(search.toCharArray(),grid.toCharArray()));
}
boolean s(char[]w,char[]s){
int j,z,a=s.length,i=a*9,f=1,q=0;
for(;s[q++]>10;);
for(;i-->0;)
for(j=w.length,z=i/9;
i%9!=4&j-->0&z>=0&z<a&&s[z]==w[j];
z+=q*(i/3%3)+i%3-q-1)
f*=j;
return f==0;
}
}
```
[Answer]
# JavaScript (E6) 111 ~~116~~
Brute force search for every character in every direction - as golfed as I can
```
F=(b,w)=>
[1,-1,r=b.search('\n'),-r,++r,-r,++r,-r].some(d=>
[...b].some((_,p)=>
[...w].every(c=>c==b[p+=d],p-=d)
)
)
```
**Test** In FireFox/Firebug console
```
;["RANDOM", "VERTICAL", "HORIZONTAL", "WORDSEARCH", "WIKIPEDIA", "TAIL",
"WordSearch", "CODEGOLF", "UNICORN"]
.forEach(w=>console.log('\n'+ w +' -> '+
F("WVERTICALL\nROOAFFLSAB\nACRILIATOA\nNDODKONWDC\nDRKESOODDK\nOEEPZEGLIW\nMSIIHOAERA\nALRKRRIRER\nKODIDEDRCD\nHELWSLEUTH",w)))
```
*Output*
```
RANDOM -> true
VERTICAL -> true
HORIZONTAL -> true
WORDSEARCH -> true
WIKIPEDIA -> true
TAIL -> true
WordSearch -> false
CODEGOLF -> false
UNICORN -> false
```
[Answer]
## Python, 175
Not very inspired, but here goes:
```
def s(h,n):
l=h.find('\n')+2;h+='\n'*l;L=i=len(h)
while i>0:
i-=1
for d in[-l,1-l,2-l,-1,1,l-2,l-1,l]:
j=i;m=len(n)
for c in n:m-=c==h[j%L];j+=d
if m<1:i=-1
return-i
```
First argument is haystack, second is needle.
[Answer]
# Bash+coreutils, 214 169 bytes
```
r()(tee >(rev) $@)
t()(eval paste -d'"\0"' `sed 's/.*/<(fold -1<<<"&")/'`)
d()(while IFS= read l;do echo "$a$l";a+=_;done|t)
r<<<"$2"|r >(d) >(r|t) >(r|d)|r|grep -q "$1"
```
Uses 3 transform functions `r`, `t` and `d` to reverse, transpose and diagonal shift, in all the necessary combinations.
*Update - the `r` function now produces reversed and non-reversed output for extra golfiness*
Input via commandline arguments - search string, followed by (newline separated) rectangular wordsearch block.
Output is an idiomatically correct shell exit status code - 0 meaning TRUE and 1 meaning FALSE.
### Output:
```
$ for w in "Lorem" "mine" "uma bop" "tuetdod" "snol,a" "texas" "pii.d v" "vexta" ; do ./ws.sh "$w" "Lorem ipsum dolor sit amet consectetu
r adipisicing elit sed do eiusmod tem
por incididunt ut labore et dolore ma
gna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco lab
oris nisi ut aliquip ex ea commodo co
nsequat. Duis aute irure dolor in rep
rehenderit in voluptate velit esse ci
llum dolore eu fugiat nulla pariatur."; echo $?; done
0
0
0
0
0
0
0
0
$ for w in WordSearch CODEGOLF UNICORN ; do ./ws.sh "$w" "Lorem ipsum dolor sit amet consectetu
r adipisicing elit sed do eiusmod tem
por incididunt ut labore et dolore ma
gna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco lab
oris nisi ut aliquip ex ea commodo co
nsequat. Duis aute irure dolor in rep
rehenderit in voluptate velit esse ci
llum dolore eu fugiat nulla pariatur."; echo $?; done
1
1
1
$
```
[Answer]
# C,163
```
f(char*h,char*n){int i,j,d,p,y=0,l=strlen(h),w=strchr(h,10)-h+1;for(i=l*9;i--;y+=d&&!n[j]){p=i/9;d=i%9/3*w-w+i%3-1;for(j=0;p>=0&p<l&h[p]==n[j];j++)p+=d;}return y;}
```
No rearrangement of the grid, I simply try every starting letter in every direction, and walk along until I run off the grid or find a mismatch.
I take advantage of the fact that a C string terminates in a zero byte. As there are no zero bytes in the grid, there will ALWAYS be a mismatch. But if the mismatch occurs at the zero byte we know we have found the end of the string to be searched for, and record it as a match.
**Ungolfed in a test program**
```
char h[]="WVERTICALL\nROOAFFLSAB\nACRILIATOA\nNDODKONWDC\nDRKESOODDK\nOEEPZEGLIW\nMSIIHOAERA\nALRKRRIRER\nKODIDEDRCD\nHELWSLEUTH\n";
f(char*h,char*n){ //haystack,needle
int i,j,d,p,y=0,l=strlen(h),w=strchr(h,10)-h+1; //l=length of whole grid. w=width of row, including terminal newline ASCII 10
for(i=l*9;i--;){ //for each start letter and direction
p=i/9; //pointer to start letter
d=i%9/3*w-w+i%3-1; //9 possible values of direction vector {-w,0,w}+{-1,0,1}
for(j=0;p>=0&p<l&h[p]==n[j];j++)p+=d; //walk p in the direction defined by d until we walk off the top or bottom of the grid or a mismatch is fount
y+=d&&!n[j]; //if we got all the way to the terminal 0, record it as a hit. If d=0, don't record as this is an invalid direction.
}
return y;
}
main(int c, char**v){
printf("%d",f(h,v[1]));
}
```
**Output**
Note that the function will return the total number of incidences of the string searched for in the grid. Thus for `OD` it returns 6. If no incidences are found it returns 0 which is the only falsy value in C. Changing to `y|=d*!n[j]` would save one character but lose this functionality.
```
$ ./a UNICORN
0
$ ./a CODEGOLF
0
$ ./a WordSearch
0
$ ./a RANDOM
1
$ ./a WORDSEARCH
1
$ ./a VERTICAL
1
$ ./a HORIZONTAL
1
$ ./a WIKIPEDIA
1
$ ./a TAIL
1
$ ./a OD
6
```
[Answer]
# C# - ~~218~~ ~~197~~ 186 bytes
C# function that takes 2 strings, the first the word to search for, the later the grid with line feeds (`\n`) between lines. Things are getting desperate now... *so desperate* in-fact that my previous edit *didn't work!*
Golfed code:
```
bool F(string D,string S){int l=S.Length,i=l*13,r,p;for(S+="\n";i-->l*5;i=r<0?r:i)for(r=D.Length,p=i%l;p>-1&p<l&r-->0&&D[r]==S[p];p+=(S.IndexOf('\n')+1)*(i/l%9/3-1)+i/l%3-1);return i<0;}
```
Less golfed with test code:
```
class P
{
static void Main()
{
System.Console.WriteLine(new P().F(System.Console.ReadLine(),System.Console.In.ReadToEnd())?"Truthy":"Falsy"); // because why not
}
bool F(string D,string S)
{
int l=S.Length,i=l*13,r,p;
for(S+="\n";i-->l*5;i=r<0?r:i) // for each cell/direction
for(r=D.Length,p=i%l;p>-1&p<l&r-->0&&D[r]==S[p];p+=(S.IndexOf('\n')+1)*(i/l%9/3-1)+i/l%3-1); // test against string (backwards)
return i<0;
}
}
```
[Answer]
## Haskell - 173
Instead of searching directly on the grid, I transform the grid in different ways and match the word with each row of the new grid.
For example,
```
G1 G2 G3 G4 G5
abcd aA1 abcd a.. ..1
ABCD bB2 .ABCD bA. .A2
1234 cC3 ..1234 cB1 aB3
dD4 dC2 bC4
D3 cD
4 d
```
Search the word in each row of G1, G2, G4 and G5, then we're done. Note that G3 is not used, I post it here just for illustration.
A similar idea is applied to search forward and backward: just search the original word and reversed word.
So now we have searched 8 directions. Here's the code, whose correctness was verified by [another script](http://pastebin.com/KsG1QTnn).
```
import Data.List
v=reverse
t=transpose
y=any
d r=zipWith(++)(scanr(\_->('\n':))[]r)r
g r w=y(y$y((==w).take(length w)).tails)[r,t r,t.d$r,t.d.v$r]
f r w=y(g(lines r))[w,v w]
```
The function `f` is what we want and its argument `r` is the rectangle string, `w` is the word to search.
[Answer]
## Python 2 - 246 ~~259~~ ~~275~~ ~~308~~ ~~298~~ ~~297~~ ~~294~~ ~~313~~ ~~322~~
```
w,s=input()
r=range
d='\n'
I=''.join
w=w.split(d)
t,u=len(w),len(w[0])
v=d.join([I(x)for x in zip(*w)]+[d]+[I([w[i+j][i]for i in r(min(u,t-j))])+d+I([w[i][i+j]for i in r(min(t,u-j))])for j in r(max(t,u))]+[d]+w)
print s in v or s[::-1]in v
```
Thanks to Will for some help with dealing with the print and defining join.
Thanks to underground railroad for reminding me to golf spaces properly ;p
Fixed for bad matches thanks to using ',' as delimiter.
Apparently the best way to golf is to add tons of horizontal scrolling.
Input as ~~whitespace~~ ~~bang~~ newline delimited lines in quotes:
"WVERTICALL\nROOAFFLSAB\nACRILIATOA\nNDODKONWDC\nDRKESOODDK\nOEEPZEGLIW\nMSIIHOAERA\nALRKRRIRER\nKODIDEDRCD\nHELWSLEUTH","RANDOM"
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 44 bytes
```
1∊⍞⍷↑{⍉0,⍵,↑(0,⊢)\↓0,⍵}¨{⍉⌽⍵}\4⍴⊂↑a⊆⍨a≠⊃⌽a←⎕
```
[Try it online!](https://tio.run/##TVLBbtNAEL3nK@ZWkNKolfgBYzuNFddbbVIiVb1s7W26ku11vbuhCHEBKbQRQSDEFSFO/QAQJy58yv5IGGdTtifPe/N25s14WFPuF69YKef7ecmUEvnGfvwqpF1@OujZ2/eXm0N7u7Lrb3b92y4/v7bru4O@Xf/qI3iC0erH03O7/LLl3vy97/L2w58OnD@z65929RaFzK6Wdn3P7N13u3qHeYblsc0GG2wyF5tcweFBjwHCvdmLmE6TMEjTvX7WY/2Oo4QEw2E6CZ57LghpkibBlASeyyISjUk2i0LPRXQcTwiJorHnSByfnMVHaTLz3PEkSUYkiOmjekFKx5QmNKaeG5MoieKIhpHnRnE6m6Tx6XTUcb3LHuvRAM0cu/hhIodGhCZnJJs@4Bmh0SQOaDja4WScnMRREjg4DZK0t@8ysi0mnLX5lUuFJIqPSDp06DRLQkIz1O42mcqWVyAaZSooZClbUEIDq7iGXNaK55pr44dogRWiEXgGop4DL1GreIEvgQujKlmA5pWXN1hP1LkoRGFqDUZDyS6wI2D5bTcOFfPyec2AleLasAGcauC1qLAfVKILFghZ1QcvvzZCQS2Vbk0B/Ia3udBMC1mDKUtW5bLr5uWy7eTovfOxbSMafAac4agVepf49XIcHo3oAURdG2Y0B9EadOzWJGpoefNoM/yK1wVvcSOYWsjSNGiGo@1uSVwpDrnw8rJ8WDguw8ClmQumoe6MQ8NaBKYd/D@U7V9yIS6Du8hUDC5k44A2XBeycEDVsuyzXYLfMOXCRohBAbBwaMFvNNsdTenrv8T7UY/uxz3avalwC/8A "APL (Dyalog Classic) – Try It Online")
[Answer]
# [J](http://jsoftware.com/), ~~60~~ 53 bytes
```
<@[e.[:,[:(;|.)@>[:<\\.@>[:(<"1,</.)@>@(;|.@|:)[;.2@]
```
[Try it online!](https://tio.run/##y/qvpKegnlhQkJpYlJmnYGulrqCjUGulYKAAxP9tHKJT9aKtdKKtNKxr9DQd7KKtbGJi9EC0ho2SoY6NPkjQASTpUGOlGW2tZ@QQ@1@TKyk/sSgFaJhCcUlKZp66Oldqcka@grqjk7O6AtwusCKojLOLKw4ZR1c3XDIu7ugy/4E2cAHN4nJ1c@cCAA "J – Try It Online")
Requires the first input to contain no newlines.
Explanation:
```
linkrotate=: ;|.@|: NB. link with itself rotated 90° ccw
infixes =: <\\. NB. list of boxes containing the infixes
lines =: <"1 , </. NB. horizontal and diagonal lines, boxed
linkrev =: ;|. NB. link with itself reversed
appearin =: <@[ e. [: , [: linkrev@> [: infixes@> [: lines@>@linkrotate [;.2@]
```
[Try it online!](https://tio.run/##dZBLbsIwGIT3PsWom2yQ@9g1UGQegV0vAF2Y2CF/G9kosaCqOFTP0IulfkR9IJFFpF8z883Ir33fkHlrrZNOP@UYn7k45wjf85wjaDiRq0Gu002FZFR4vPv6RFmeGJmK3nXn/T492W458CfdOdgKOxscpTVOkiGzh6s1hiDzFTGeADf3GGFyyxOgti19hFgDaRQUyb01/oiZUeQqFvfrYwL4/fi34HK/Puq28yl5OGjZkkm1YgPNscl9uf8NRDENx7AzHbFYTMXvm2Ez5g/ipd9Z2arA6pwik2VMl7VFNpsvMvx0RdOgLJbFFWVWrK4py/Wl0vsG5lmsWK3ZNw "J – Try It Online")
Hooks are useful.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
Solved a [related (possibly a duplicate) challenge](https://codegolf.stackexchange.com/q/164219/53748) with 15 of these 16 bytes as the core of the code...
```
ỴZU$3С;ŒD$€Ẏw€Ẹ
```
A dyadic link accepting a list of characters on the left and a list of characters on the right which returns 1 if found and 0 if not.
**[Try it online!](https://tio.run/##NY2xSgNBEIb7fY7ANuksrSY7c7lhNzdh9s6FEwuJAZGAkCak9QEk@AZWNpYWop2HDxJfZN0LWs338Q//f7febPY5Hz/f@m5yNhy@ns@/n3Dy8/B6/Hjcnc57Hl6GQ8GcrbXpgrRlByEYFYGqChFmBpxyYGgFTIOCXpqEzqB6iiKI3gjRsqd54GQWkbkWIAUDQb0qK6nxgoyE6tDUFFIM1LV12cuXVqF0LuzU/k8XrEW5l6Y9SRLFSKCuHoU9LwkZCrfAY/5XNrUzcD6B4vh2v72J6@vt6raIE6S5hKpg17ATbezVLw "Jelly – Try It Online")**
### How?
```
ZU$3С;ŒD$€Ẏw€Ẹ - Link: words, grid
3С - repeat three times and collect the results (inc input):
$ - last two links as a monad:
Z - transpose
U - upend (together these rotate by a quarter)
€ - for €ach:
$ - last two links as a monad:
ŒD - get forward-diagonals
; - concatenate
Ẏ - tighten (to get all the runs across the grid)
€ - for €ach run:
w - sublist-index (0 if not found)
Ẹ - any truthy? (i.e. was the word found?)
```
] |
[Question]
[
Given the 2-dimensional positions and velocities of a pair of billiard balls right before impact, calculate their velocities after a perfectly [elastic collision](https://en.wikipedia.org/wiki/Elastic_collision). The balls are assumed to be ideal spheres (or equivalently: circles) with the same radius, same mass, uniform density, and no friction.
Input consists of 8 numbers: `p0x,p0y,v0x,v0y,p1x,p1y,v1x,v1y` where `p0x,p0y` is the centre of the first ball, `v0x,v0y` its velocity, and similarly `p1x,p1y,v1x,v1y` for the second ball. You can accept input in any order and structured in any convenient way, e.g. as a 2x2x2 array, or maybe a 2x2 array for `p` and two length-2 arrays for `v0` and `v1`. It's also fine to take complex numbers (if your language supports them) instead of xy pairs. However, you should not take input in a coordinate system other than Cartesian, i.e. polar is not allowed.
Note that the radius of a billiard ball is half the distance between `p0x,p0y` and `p1x,p1y`, so it's not given as an explicit part of the input.
Write a program or function that outputs or returns 4 numbers in any convenient Cartesian representation: the post-collision values of `v0x,v0y,v1x,v1y`.
[](https://i.stack.imgur.com/lNIgt.png)
A possible algorithm is:
* find the *normal* line that passes through both centres
* find the *tangent* line that passes through the midpoint between the two centres and is perpendicular to the normal line
* change coordinate system and break down `v0x,v0y` and `v1x,v1y` into their tangential and normal components `v0t,v0n` and `v1t,v1n`
* swap the normal components of `v0` and `v1`, preserving their tangential components
* change back to the original coordinate system
Tests (results rounded to 5 decimal places):
```
p0x p0y v0x v0y p1x p1y v1x v1y -> v0x' v0y' v1x' v1y'
[-34.5,-81.8, 34.7,-76.1, 96.2,-25.2, 59.2,-93.3] [ 49.05873, -69.88191, 44.84127, -99.51809]
[ 36.9, 77.7,-13.6,-80.8, -7.4, 34.4, 15.1,-71.8] [ 5.57641, -62.05647, -4.07641, -90.54353]
[-51.0, 17.6, 46.1,-80.1, 68.6, 54.0,-35.1,-73.9] [ -26.48927,-102.19239, 37.48927, -51.80761]
[-21.1,-52.6,-77.7, 91.5, 46.0, 94.1, 83.8, 93.7] [ -48.92598, 154.40834, 55.02598, 30.79166]
[ 91.3, -5.3, 72.6, 89.0, 97.8, 50.5, 36.2, 85.7] [ 71.73343, 81.56080, 37.06657, 93.13920]
[-79.9, 54.9, 92.5,-40.7,-20.8,-46.9,-16.4, -0.9] [ 47.76727, 36.35232, 28.33273, -77.95232]
[ 29.1, 80.7, 76.9,-85.1,-29.3,-49.5,-29.0,-13.0] [ 86.08581, -64.62067, -38.18581, -33.47933]
[ 97.7,-89.0, 72.5, 12.4, 77.8,-88.2, 31.5,-34.0] [ 33.42847, 13.97071, 70.57153, -35.57071]
[-22.2, 22.6,-61.3, 87.1, 67.0, 57.6,-15.3,-23.1] [ -58.90816, 88.03850, -17.69184, -24.03850]
[-95.4, 15.0, 5.3, 39.5,-54.7,-28.5, -0.7, 0.8] [ 21.80656, 21.85786, -17.20656, 18.44214]
[ 84.0,-26.8,-98.6,-85.6,-90.1, 30.9,-48.1, 37.2] [ -89.76828, -88.52700, -56.93172, 40.12700]
[ 57.8, 90.4, 53.2,-74.1, 76.4,-94.4,-68.1,-69.3] [ 51.50525, -57.26181, -66.40525, -86.13819]
[ 92.9, 69.8,-31.3, 72.6,-49.1,-78.8,-62.3,-81.6] [-123.11680, -23.48435, 29.51680, 14.48435]
[-10.3,-84.5,-93.5,-95.6, 35.0, 22.6, 44.8, 75.5] [ -11.12485, 99.15449, -37.57515,-119.25449]
[ -3.9, 55.8,-83.3, 9.1, -2.7,-95.6, 37.7,-47.8] [ -82.84144, -48.75541, 37.24144, 10.05541]
[-76.5,-88.4,-76.7,-49.9, 84.5, 38.0, 4.2, 18.4] [ 6.52461, 15.43907, -79.02461, -46.93907]
[ 64.2,-19.3, 67.2, 45.4,-27.1,-28.7, 64.7, -4.3] [ 59.66292, 44.62400, 72.23708, -3.52400]
[ 9.8, 70.7,-66.2, 63.0,-58.7, 59.5, 83.7,-10.6] [ 68.07646, 84.95469, -50.57646, -32.55469]
[ 62.9, 46.4, 85.0, 87.4, 36.3,-29.0,-63.0,-56.3] [ 23.53487, -86.82822, -1.53487, 117.92822]
[ -5.5, 35.6, 17.6,-54.3, -2.2, 66.8,-15.2, 11.8] [ 24.15112, 7.63786, -21.75112, -50.13786]
```
Shortest wins. No loopholes.
---
thanks @Anush for [helping](https://chat.stackexchange.com/transcript/message/52466876#52466876) fix the diagram's background colour
[Answer]
# [Python 3](https://docs.python.org/3/), ~~67~~ ~~66~~ bytes, 53 bytes
```
def f(p,v,q,w):p-=q;d=((v-w)/p).real*p;return v-d,w+d
```
[Try it online!](https://tio.run/##XVbbUmM5DHxevsKPyeyx17IsX5jiSyiKooYwSxUDmSQEZn@eVcs@7NS@HBKB1VZ3qw/7X6e/X5754@N@9@AeNvvlvPxc3raXe3/18@v91WZz9m/bv/bbcNjdPX3Zfz3sTq@HZ3f298vbn/cfp93xdPvt7rg7uit3fbG59pyDLL5RaIvTz3XxtQRaXC8hLT6JPp10fO4c@GZx187lHqK0yovzpYfWqOsBl3NomVLVau9BqMV@s10Uw3EJfXG1ojtxKIoXgedryIaqTxJF9VXvMTCcBKklEzCSwpWsjZ3PIc5qj0EyCw8MLxSidqna3WVMAAz9u9JQET23eB4YHLph@FRCbj3hVjEF6on1mo7rrDo0bYpHEyMRzkvCBDaN66TsAU@xewZeY0ymXNWBkVvoSXrDhDpobKzDOpEQR9VxDLVTKZMr7QheBc8KJNe6da/oKxF4DG1ck4nhlLXKnPWEUyGlxBbHHLEUAW16HeKe4pyjduih19FnT9A/R2iToIrPUMtTgSo@Tq5c1nlLBSuAZ0msV3CpBeZkTlBCOqpzjtSNDfR11To2Y1/rrBgdqAmTwRFxYDTlsUkzzXMoKRaIwC3QrDKHXDvzypU5avBTMYejhFtXcOVbA0sMheDyiYEWqZmZFLjXWOHdqrxWEszBMJ5WV80TuiTTvJg2rZqvKlAFfvMEtXxSkofmoprHRgV6tBC5if6phzc7NbCa8qhOjC5zAyCbKc/Gj9g@KsdiSuDOcd2PBGsWAQY@Sm1lYKRZpRZyTpQnV802QB2vzPRmOyh4dtsSNaEqpF7FZ@0x5lBma2kJm6pzSKoRc4iqyVQhv9qGUJ0YYh7VjjqNMDKj2k5UeMl37LkvwEBszCzRFZMoCRPq8VRoyK8nZlVNQawRs2qe4FrEjqpKn1sCR2G3G@oaGGyZVoDhCcpQwVJApNw0NkAbQsqqjvKoTj0o2nlLRl0dPMGVY1PIvGBpp9hqlsEVaTak3NBY0093PXeYqaqZhLQDkYYoqnMOz7aDYk5lzOFsY3yC5hPP/K2b16YeCQmb4SCVqoogCE2vUXV68YjquufFsr2Bd/1cjSVFtcmc7hVmz/A3zDJzV8@kXNBYDZm5R@ygJkYcVYsHVOccBec9YauxE9orw80@Vdv2BtcW@BjZvWreQympp/HSKCnDV9AxcY3IRCVHUJ0YrhvXllHFsq8w3CzWXbAryF3L8aG5Q@7jTWE7qEEnuUAP5OeoetbAQHWdw3yVLfWa6dzG26nYbltSTdSyzqFmEs6tDpfqoiSM5Gmtkq5jR3XVXIx309beVNhwNs0xk@0m2RuXPt@DGhUkRGjs9AiPPdeVr6OKkQhVYNxcXDy8HNz@fPv4vH89Le58u3vf776ddvfu8dn99/a/vPjjHG9f7E8IP/XfgYfNl823lx/7p9375n35tXVopR9w8p/H/Wbten15iXz4/Er4vt1uteXstBm97X8QBRhfHn/cfV/R1t/Q52/0NLBvD7vj6xN63D09bQ4vr8/3G7ulbN3VldNh7FZWwpd5tfMc5XNa3ObueNwdTu63tovb/E7N/898/As "Python 3 – Try It Online")
*-1 byte thanks to @ngn*
*-13 bytes thanks to @Neil*
This function `f` takes four complex numbers as input and returns two complex numbers. The ungolfed version is shown in the following.
## Ungolfed
```
def elastic_collision_complex(p1, v1, p2, v2):
p12 = p1 - p2
d = ((v1 - v2) / p12).real * p12
return v1 - d, v2 + d
```
[Try it online!](https://tio.run/##dVbtTiM5EPzPU/hnsjf2@av9gbRPghBCkL2NlA1REhB7L89VtT0cOumQmDidcZe7qrpnTr@vP1@O6ePjeffD7A6Pl@v@6eHp5XDYX/YvR6x@nQ67980pLOYN/6eIz7i9vTH4O4VovuNqLOIaecb3zeaNEdxl/uQtW3fePR7MN671pvPu@no@Gr3rmenMH@b547q7XB@eHi@7C3Lc3WzubMpOFtuCa4vBui62Focz9OLiYqPgaqRz3ZNL94u5MyZ356XVtBhbumstdGwwObuWQ6yI9u4kNN/vtwswTCquL6ZWZg/JFeB54tnqsqLiGgSotuIcA8OIk1pyIEYEXMlIbGx2fka7d5KTpIFhJTiPLBXZTWYFxMB9pTEi2LfYNDCS64phY3G59chT@ehCjwnHNKnOqGHSBrwwMWLgfomsQKsxPYA94gG7Z@K1xMrAVR0YubkepTdWiEJ9SyjWiDg/oiZ5V3soZXKFjORVeK1EMq1r9sq84omXqI1pMjEMWKspZewwEFKKb37U4UsR0objhNSjn3XUTj1wHFx7pP7ZU5tIVWymWjYUqmL95Mpk1FsqWSF8kphwBBObSymqE0BIZ3TWEbuywbymasam7COegNGJGlkZHeEHRgOPTZpqnl2JvlCE1FyY0ZRcrj2llSt11OCnsg4TIk9dyZVtjSwlKkSXTwymiE3NBOBefaV3K3itQVhHovEQXTWPzBJV86LatKq@qkQV@s0GqmUjSB6aCzT3LRTq0ZxPTXCrpTd7aGQ15hGdGF1mB1A2VT4pP6L9CI5FleCZ/dofkdYsQgwupbYyMOKMhuZyjiFPrpp2ABwPZnrTHhReu3YJTAiF4FWukWPUAWZraZGdijokVs86BGqmUCk/bBMYnRiiHkVGVCOJM6NqT1R6yXb2uS3E4NiYswQtJl4iK8T2WMKQHztmFKYICSNm1TzStRw7UDV8dgkdxd5ujGNgJJ1phRg2UJlQ2BQUKTeMDdLGIaVRE/KITj2C1/06GdE6vJIrk1Qh9YJOO2DDLIOrgNkQc2NiTD/0eu40U4WZJCBDCBiijM46bNIeFHVqYh1GO8ZGaj7x1N/ovDb1iJywmQ6CVFWEg1D1GlGDg3tG1z4vOtsbece6KktA1coM@oq1Z/qbZplzF3tiLkwMQ@bUPXsQE8OPqI4HRmcdhfttYFezJ5Ar0802Vu32RtcW@pize9W8u1Jij@OhUWKmr6hjTNVzJoIcYXRimK5c64wqOvtKoptFswt7hXNX5/jQ3HDu80mhPYhBJ7lQD87PEbUJA4PRtQ71Vdap11TnNp5ORXtbJ9VELWsdMJOk3OpwKRolsiQb1mhAO3ZGV81FeVdt9UnFDk@qOWvS3gz6xA2fz0GMiiAhMLHBljT6HC1fR5QlBUaJcX9z8@PlbE5vD/vj6fWKx/7D7v20e7runs3@aP59@o9Xizf/8KJ3BX7ijeD/X02@bdbV@/J7a4iCBZP@vT9tVsC721uOjs@vgd@32@1AmyCbAasvLMs8g9v/evxrPcj6S/j8ZSTgCR7Ou8vrgWkeD4fN@eX1@LzRGmRrvqOA95OeTUP8Mg/4Ngv9pGOe6fFy2Z2vXzMvZvOVvv9uG69k5/3xuvmyafvxDw "Python 3 – Try It Online")
The computation formula is derived based on the 2D-vector formula on [wiki](https://en.wikipedia.org/wiki/Elastic_collision#Two-dimensional_collision_with_two_moving_objects).
Since \$m\_1=m\_2\$, the formula can be simplified to
$$\left\{\begin{array}{l} v\_1'=v\_1-dv \\ v\_2'=v\_2+dv\end{array}\right.$$
Let \$x\_{12}=x\_1-x\_2\$ and \$v\_{12}=v\_1-v\_2\$, we have
$$dv=\frac{\langle v\_{12}, x\_{12}\rangle}{\|x\_{12}\|^2}x\_{12} = \frac{Re(v\_{12}\cdot\overline{x\_{12}})}{x\_{12}\cdot \overline{x\_{12}}}x\_{12}=Re\left(\frac{v\_{12}\cdot\overline{x\_{12}}}{x\_{12}\cdot \overline{x\_{12}}}\right)x\_{12}=Re\left(\frac{v\_{12}}{x\_{12}}\right)x\_{12}$$
In the ungolfed program, `p12`, `v1 - v2`, `d` correspond to \$x\_{12}\$, \$y\_{12}\$, and \$dv\$, respectively.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~90~~ 88 bytes
```
(m,n,o,p,q,r,s,t,u=(q-=m)*q+(r-=n)*r,v=o*q+p*r-s*q-t*r)=>[o-(q*=v/u),p-(v*=r/u),s+q,t+v]
```
[Try it online!](https://tio.run/##lVXLbls3EN3nKwivJJlk@Ro@ECjL/kCXgoAIsV0oSCRbVowCRb/dPWcuFbToqpuLq4E4hzPncb8e3g6vXy7H56s7nR8e35@276vv9mTP9tm@2It9tVf7Y7t6cdvv683L/eritqf15mLftmf8fN5c3OvmxV03l/X20@7sVi@b7dsvP9b22a3eNtsLX1/vX@z1/m3//vHpfDGr3dGax705P5ndh93O5eLFuh59twbvzbpWfbRmVJ@sS4KnkcH3kX3eW7MzpgwfpLdsjavD9x4HDphSfC8xNVTH8BJ7GPu9BYbJ1Q9rWmP3mH0FXiCea74oKp5RgOoa7rFgGPHSaonESICrBY2NKz7M6gheSpa8YDiJPqBLQ3dTOAEx8L/aWRGcsy4vGNkPxXCp@tJH4q1C8nGkjGua3GbVsGkHXpwYKfK8JE6g05gRsT3iAXsU4vXMybCrtmCU7keS0TkhBg09Y1gj4sNSNTn4NmKtc1foyL0Kn41Ipg/t3thXAvEyuTFdJobB1lrOBScMiJQaeljmCLUK14brxDxSmHO0QT5wHTxHIv8lkJtEVlwhWy5WsuLC3JUpmLc2boXwWVLGFUzqPuekSsBCBqtzjjR0G@xrmnbsun3UMzAGURMnoyLCgtGxxy5dOS@@plBJQu4@zmrOvrSR821XqqhlP41zmJh468Zdud65pUyGqPKJwRapq5gAPFpo1G7DXlsUzpEpPFRvnCd2Scp5VW56U101ogr15iLZcglLXjgXcB56rOSj@5C74K@O2hyxc6upLNWJMWQ6gLQp81n3I@pH7FiUCd453PyRKM0qxOCrtF4XjDSrsftSUixzV10dAMVjM6OrB4XPoS6BCMEQtMp39FjmwGZb7YlOxRySWuAcAjZzbKQfsomsTgxRjaIjppHMzGjqiUYtuUGfu0oMxsbMElhMgiROiOOpxoV@nJhViCJmRMyN80TVMnbAavzpEiqK3u6sIzCyZlolhotkJlaagiSVjtjg2hhSWjWxLNXJRwx6XpMR1uGTuzJZGVItaNoBG2JZdhWRDal0Nkb6wetlUEwNYpKIDjEiRFmdc7isHhRVauYcRh3jEjmfeKpvOK9PPhITtlBBoKqJMAiVr6VqcPHA6s3nVbO9c@94b7oloOpkBr7i7IX6plhm7uJMKpWNIciSR6AHkRhhqWo8sDrnqDzvIl1NT6BXoZpdaur2TtVW6pjZfeN8@FrTSMtHo6ZCXZHHlFtgJmI5wurEMEN3rRlVNftqpppFuwu9wtzVHF84N8x9finUgwg6KZV8MD@XqssIDFZvc6iuiqZeV5778nWq6m1Nqolab3NATJJLb4tKYZTEkVy8VSPsOFi9cS66d@VWv1R0eFbOOZN6M@oXN/78DiIqosTIxgZH8uJzWL4tVY4UWSXGfm3@/GDMwWzN08p7f1x/xM8jfh7998Pz6rT9dPLX86/HPx4fVnHtnw8Pv10Pl@tK1mv/9Xw8fbafeeIRJx7/e0L@cSKGfx8h5uH/HflyPr2evz36b@ffV3e7O3OPm96bu73R94O@31l2xm0wyV/vfwM "JavaScript (Node.js) – Try It Online") Link includes test suite. Explanation: `q,r` are repurposed as the difference vector between the centres, and `u` is the square of its length. `v` is the difference in the dot products of `o,p` and `s,t` with `q,r`, so `v/u` is the scaling factor for `q,r` that gives the amount of velocity transferred from `o,p` to `s,t`. Edit: Saved 2 bytes thanks to @Arnauld.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~75~~ ~~64~~ ~~63~~ 61 bytes
*11 bytes saved by switching from `map` to `for`, dispensing with the need to put things into intermediate variables for the `map` to see.*
*1 byte saved by changing `($^a-$^c)².&{$_/abs}` to `($^a-$^c).&{$_/.conj}`.*
*2 bytes saved thanks to @nwellnhof.*
```
{(.($^b+$^d,{$_/.conj}($^a-$^c)*($b-$d).conj)/2 for *-*,*+*)}
```
[Try it online!](https://tio.run/##PVbbTlxHEHy2v6LlrKzd5cx4bj2XWIn4hDzkmWiBJSEyBrE4kUX4dlLVc/DL4bjNdE1XVdfh4fj4pb7efZePN/KLvD5v/XZzcXm2ubhenjd/fPJX91//fkHp4DYXV7v9dnPpNtc7K@8@Jbm5f5S92y/7s/3u5fXz@@27n@T34@lJrg6n4@lnuf368O3phB9PwDke/jley7@3T3/J4/H07cvT6f27rcvF6@J69H0RvLfFterjIqP6tLikeIoOvo/s826RrUgZPmhveRFXh@89DhyQUnwvMTVUx/Aaexi7BRCSqx@LtMbmMfsKuEA413wxUDyjAtQ1XGNCiHpttURCJKDVgr7iig9rdQSvJWs2CKfRBzRpaC6F9ycEfq12VhTHFpcnRPbDIFyqvvSReKmQfBwp45aS21oVNu2AixMiRR7XxPvbLDIiqCMcoEchXM@cC0S1CVG6H0lH53wYM/SMUUXVh1mVHHwbsdZJFBqSU@WzEUj6sOaNbTUQLlMX6bpCCChrORecEIioNfQwpwi1KjnDbWIeKcwp2qAWuAyeI1H6EqhLoiKuUCkXKxVxYSVKCqatjZQQPWvKuIGk7nNOZgLQMVidU6RhVLCtNGvYjXnUMyAGQRPnohnChOggsWs3uYuvKVQKkLuPazVnX9rIeSXKvDTJaZxCYuKdG4lyvZOiTHVo7xWCHVI3GwF3tNBo2gZSW1ROkWk5VFe5E5skk7uaLr2ZoxpBlU5zkUq5BIKn3Aq5Q4@VWnQfclf8qqMrR@ykNJVZnRBDV@dTMRM9Gzlqawh@1VTgjcPbXiR6sioh@Kqt1wmR1mrsvpQUyySqm/PhdNAyuq2e8jlsO@A@qAOT8h0t5hSgtdWeuKCYQlMLnEKhZI6NysMxkdUJoWZONMQsmhkUzXah0UVucLtdJQSzYg0QbJYGTZwPx1ONU3mcWKvwQ8zIlVXuRLsyaiBo/LEd9BI3urOOlMiWY5UQLlKVWLkMFKh0ZAU5YzBZVWKZ1alFDHbcwhAbwyeJkmzqmA0s4AANm0yiIhIhlc6@CDxseBm0UYONNKJDjMhNVucULtvqqVk0cwqxTXGJcq9wZmwsXF@1SMzUQu9ApqbK7DOtZlVw78Dqut3VwryTc7w3owigNpdgnTh4obFpkzVpcSaVyr6wYskjcPWQE2FWLRRYnVNUHneRu8xdQKtCG7vUbMc77VppYIb1m9zD15pGmh@JmgodRQ1TboExCGqU1Qkhw3i2XKoWdzXTxmrNlTvCpLXgnnILg55fBls9hJuWSi0YmbPqMmKC1XUKc1SxoOsmcZ8fo2obbem0gta3KWAjzaW3aU8sSOJALr5VI7ZwsLrKrca5yWofJu51Nrk5ka1ktM9r/PHVQz5EjZF9BUfy3G4septVDhRZBcTO3x0ets9iP/ZyJvvbnbzMqvtVzg@LnF/Ks5wO3@XDb4/3fz4e7viPkzx/vNn@d37YvSzy9PbHwvo/55cv/gO6fH79Hw "Perl 6 – Try It Online")
---
# Explanation
When the original post said that the input could be complex numbers, it was too hard to resist... So this takes 4 complex numbers (position 1, velocity 1, position 2, velocity 2) and returns the velocities as complex numbers.
The program uses just the same algorithm as described in the OP. However, with complex numbers, that is quite simple. First, let's notice that the complex number \$d = p\_1 - p\_0\$ points from the first ball to the second. So if we divide all the velocities by it, the normal direction suddenly coincides with the real axis and the tangent direction with the imaginary axis. (This messes up the magnitudes but we don't care.)
Now, we need to switch the normal (i. e. real) parts of the velocities \$v\_0/d\$ and \$v\_1/d\$, and after that, multiply it by \$d\$ again to make the normal (and the velocities) point in the correct direction (and to unmess the magnitudes). So we need to calculate
$$ \begin{align\*} v\_0' &= d \left( \Re \frac{v\_1}{d} + \mathrm{i} \Im \frac{v\_0}{d} \right), \\ v\_1' &= d \left( \Re \frac{v\_0}{d} + \mathrm{i} \Im \frac{v\_1}{d} \right) \end{align\*} $$
(where \$\Re\$ = real part, \$\Im\$ = imaginary part). Let's shuffle the first one a bit (using \$\star\$ for complex conjugation):
$$ v\_0' = d \left( \Re \frac{v\_1}{d} + \mathrm{i} \Im \frac{v\_0}{d} \right) = d \left[ \frac 1 2 \left( \frac{v\_1}{d} + \frac{v\_1^\star}{d^\star} \right) + \frac 1 2 \left( \frac{v\_0}{d} - \frac{v\_0^\star}{d^\star} \right) \right] =\ = \frac d 2 \left( \frac{v\_0 + v\_1}{d} - \frac{v\_0^\star - v\_1^\star}{d^\star} \right) = \frac 1 2 \left( v\_0 + v\_1 - \frac{d}{d^\star} (v\_0^\star - v\_1^\star) \right).$$
The result for \$v\_1'\$ can be obtained just by switching \$v\_0 \leftrightarrow v\_1\$. All that does is changing a sign:
$$ v\_1' = \frac 1 2 \left[ v\_0 + v\_1 + \frac{d}{d^\star} \left(v\_0^\star - v\_1^\star\right) \right]. $$
And that's it. All the program does is just this calculation, golfed a bit.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~140~~ 132 bytes
```
f(m,n,o,p,q,r,s,t,a)float*a,m,n,o,p,q,r,s,t;{q-=m;r-=n;m=q*q+r*r,n=o*q+p*r-s*q-t*r;q*=n/m;*a++=o-q;n*=r/m;*a++=p-n;*a++=s+q;*a=t+n;}
```
[Try it online!](https://tio.run/##bVBBjqQwDLzzCmukXTUhzpKEkEQob@gH7PYBtcRopCVA4Daat/fYtPYyOxJ2TFyuKueOr/f74zFdZpnlIle5ySJ3ecixnv4u4yFG@aUzvG@Y5qFgysOcNrE1RRSZ00LVKgruYsNDlGETKf@aBzE2TVpwG7JI5d//ivlZ7M1GRTqaPHw85vEtX@r3aSmXUxu@err@7m7Dfh/zdHn5McF335/8IuHnTJEpFoqVYqMoFDvFUacUhrW85YNpdKscDX5zMJW4kqi@UTKc7K2u/3@qa03m0XbKAQatAgDVHtD3SgPEXhlA4yiDi1xHq2wFtlcRwHtGaqt6mm15Fr3qTgbK2hEDeuKs0GnV0o0nJHTMzHji7wPfuI66aJ94q2KFRnPtDDOfKhA1OeRZ4okdzwbLiuTHV9y1pO44e56CEE@kZ4xredbyLhAc4dFH9k@6lKPh3buWdzG8BXa8Heqet8CW/ICJpyJjwJ/dcLqle0v4yAyGFfk12op1ie3pwTM/aMNsnv1gCOzE8kb88u0n "C (gcc) – Try It Online")
Basically a port of @Neil's JavaScript answer, but then @ceilingcat shaved off 8 bytes by cleverly reusing `m` and `n` to store temporaries.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~97~~ 92 bytes
```
m,n,o,p,q,r,s,t=input()
q-=m
r-=n
a=o*q+p*r-s*q-t*r
a/=q*q+r*r
print o-a*q,p-a*r,s+a*q,t+a*r
```
[Try it online!](https://tio.run/##HYw5FsMgDER7TkFpY4k8Q7xQcBi6uDCLLBc5PZHTzPw/xdQvf0p2vZ@QoUCFBgQXcDxyvXkYVcN4KsKYVYrFtKkawss0ZEMqvWKTiQQrHZl1wWQaVEk5mR5mSep9QP@2C2jcZ7uDFtlEttXOoMNqnYhbnlrCX4K3fvwB "Python 2 – Try It Online")
Modified version of Neil's approach.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
_/×ḋ÷²S¥_/ʋ¥N,$+
```
[Try it online!](https://tio.run/##TVS7jhQxEMz3Kya4jLHXdtttt07iB5BIiNBodREJuh8gO11CcBkJBBCeSIhIgHRXJPzF7Y8s/bBnLrTdXVNVXT3v393efrhcbvanz0@/H06/jj/fHB9v9v8ejo@v56sXl7@fnv58Od//eHV9vvs6uZfT@e7b9en7Xu@vdqeP/Pb2cll2y7I4yL7Mk2vRt8M8LYQ@8TEVnw5yXvi98kVFH@VcSN8JPBy4QCAAPc1Trb5Kgas@zxN3Zet3ETzKB4J9IBYfBU@@1wFciT7MU6wepQKbNJTsgyFk1A4GUAYOOgJ4WhFS1LuSDIJbGJAydxgJYccX0Rc5N/CNT8CMOwC/gPSzKjGhynsJXK3tNQmjRsyIj6AWtbJ1u0piAVMmZZiC9DtmQQZASU3OoXsUUUxyYVOQSAS0UcBH4ZNppaAmO/5qHAWsUMwNqwbV6AbNqiJca2OSVUnExJMRFVEpQd4AXEqiLHUTsconikzFTEQ1qdVOgScpHBOIyx2BigjjF6XgioUntSFDW4BsDKyfX8MWhJZVVEKLiqMgpkAYNjpqlqViDF1uWlBFokEUVc2NKrKaz7SmsYDGt@auARXAIW1x5lmx03xjHDJZ2prQVBKgNtTuksOkNvAC4WpDDHaXTSgnNnRfuw5Q86nryFlI1yIudQTQQJVOIqmNWm4AnGD@AJkKsMHn@mylWHmx6asRTbcc2tgpea8WMI1sFluiFHcA1BsXyTbCpao28CSrIXA6uCAXw0cbdH5mo0oaeS5N3ssaZ4e6RAgWFJYj7Wzb6iHqGHiFct85zRoNAU0t5SxmGwJocgpuBHiZRfKIikYbcUxRfjbSkLs@jqw4YH@l3eE/ "Jelly – Try It Online")
A dyadic link taking as its left argument a list of the initial positions `[[p0x, p0y], [p1x, p1y]]` and its right argument the initial velocities `[[v0x, v0y], [v1x, v2y]]`. Returns a list of the final velocities `[[v0x', v0y'], [v1x', v2y']]`
Based on the algorithm used by [@Neil’s JavaScript answer](https://codegolf.stackexchange.com/a/190837/42248) so be sure to upvote that one too!
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~77~~ 72 bytes
```
f(p,v,q,w,a)_Complex*a,p,v,q,w;{p-=q;p*=creal((v-w)/p);*a=v-p;a[1]=w+p;}
```
[Try it online!](https://tio.run/##rY9RasMwDIbfdwpRGNiurc1xEjeYPO0YXRkiNCXQpG4ZyaD07JlrJzvBQA/Sh/j1qVGnppnnlnk5yqucJPGvj0vvz8cfQXKB7u5VfXVe1M3tSGfGRjXxN8@doHpU3tFeH@pp691j7qkbGL@/AKwxQPvs4AJomTI5FrDVnVA7jTsJEIBNwJaoA6hKzBLICswCKKoVVAaNBAL@DPO3bvhuGWxeW1jrc9hISIaCeGi7nk5LG@nT84/HIYWFHFNiFc@AtWglKG2wXFTfo6qymKeNIJ0HoAvUi3t85v/NHvMv "C (gcc) – Try It Online")
Based on the python implementation of @Joel
[Answer]
# [APL (Dyalog Classic)](https://www.dyalog.com/), 21 bytes
```
⊢/-{,∘-⍨×/(9○÷⍨)\-⌿⍵}
```
[Try it online!](https://tio.run/##PVXBih1HDLzPV/TNCWTbrVarW51vycU42NlkYYN3L8H4lGDstZ9JDsY5GwK@7SUmYAiG9Z/Mj2yq1G9zefNGM62SVKWaBz@fnXz/y4Oz88cnD88eXFycPrzd37w9Pd@f/15u96v390@efrO/@PNkP3z48u7@V3N/9@rLP7j5@ruT/fXn/fDx2e1jvLsf3uxXv95c6/78D5y/ePIQv5c/nF7cPsLTp3hcku2Ht/uLq5lEkBGJbj48TjXV/fB3@VH2q7/2w8v99b8tIsy8Xa6zH/eX75/g76P98Olb5A28T4g/2V/9du/8p3vPNiC3bOnm2iV7SrgZuBk9S0qz54qbargkm3EzNWu6TKnNXMyHJsT6zO4ycSK1lr1JHQzPmU28zC1pzzOlMSK3aO7EK8QDVG4Bi18xoCLCSgCRLNvoTQKiAq435MVNy@UuPku2pqbowyQX5BjInlqPTMDAW90ZMpxCSI8Yioou2VzPzWeNwkrNMqui1KTjGE6R2AEowKgSp61GC9FQmoL5ERHosxHQla1hUiMgmudZbTobRJ/FtbE5y2VFk5Y8pvS@MVdM1HgZREk@I/FgSiuEUtKS3CJ9wrSGasP7CRRaL15W/aV347xQh@isBeWPSR5QBH5nDdpbCVIq2cAdicIkOum4uS4xpNTQZx8cBrHVqgI/Vc@qdSkAk5gMb6nOmACzprGy@Ro5nighZuDWGXRADIUQjvG5@eK65V5Lj9mrZ7mLq@Y2purGabDoNZrBRpJUljxGtOHOCakEkrYFwePVQ0JAnaMMCnZgpEMsulAKDmESXZmhLp57sOIjxDSIaSMeiEVLFRMOpg1MF5dOLjwXdSvMS01O8RhpbSsOjGlH0ZfQOiB0zcbWEmLAtlhgzWUtRaUYuxGCf214P0LUY1g8t1albcmX5CFxDmX62juLy4zV0BIMQaESmqnRBuY6utdYT/RhdZTow8CnyiD5kI0wvHEUFHthL6bhESO2YFBEAGpx6R4i6HPZB3bKitXoDxlqlyP3OHQXhyZE4SsbtQrF0mbIkvy/HKGmWGePR3AJXVbW0yWGQmKkexSP/81hFRwcjSnCSdqKblz/dXjZIbYmLpxW0uAo1BAOB3hIJWYlcITanGnhd1jwNkNKA1IysXgDzsn4xngsoC2V0kpxLEfnNTg/4i19txGc481KV20hIHA1zOh@QdgKJxRfGN3Cu20R15aTjzUnAEdvCTvF1hsVTrGE1@JQbZ1ZIcims8T6wTDKCi9vYHxLvQXNQi65EMjTLNDqWKvulGynjMOuF@Uz915nXV@JXhtFRR6rjuJh7MoiKKo0Y8jLm3r4XdcQs0Vq46LQZ5dvk@7weX4XYvtgcdZ6UEHTXGEAwCsYRw8hqRZG50Gvry9RXyu97OkOtK8WoCHT5uOoTqxIrVG43MUFizgZ3sLFLbTTj5@l2GxdZLOjtZcSn1c5fvTgD2IiTJtwRo/7jV0fKxwNCeP/AQ "APL (Dyalog Classic) – Try It Online")
based on [@Joel's answer](https://codegolf.stackexchange.com/a/190860/24908)
in: 2x2 complex matrix, out: complex pair
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 7 years ago.
[Improve this question](/posts/18761/edit)
You need to make three things:
1. Statement of a task, **T**.
2. Solution of the task in language not typically used for golfing, **A**.
3. Solution of the task in language typically used for golfing, **B**. Don't try to just bloat up **B** to pump up the score, instead think as if **B** was written by your competitor.
Use common sense in defining `typically used for golfing`, try to maximize fun for other users.
Other users may propose better `B`s (maybe including in other "golfy" languages).
Scoring is `(length_in_bytes(B)+5)/(length_in_bytes(A)+5)`, more is better. (Maybe the scoring formula should be changed?..)
The main idea is to invent a task where languages that typically perform well in codegolf meet a problem. It can be sudden strength of a usual language in the given task or sudden weakness of some golflang.
Avoid tasks that mention specific programming languages, like `Input a string and execute it as a Scheme code`.
[Answer]
My previous question, Print a sinusoidal wave (vertically), qualifies at this moment. I'm posting it here as a solution, also hoping that you guys can come up with some shorter solutions to my original question.
As required by Vi., I will post a summary of the question.
Print a continuous sinusoidal wave scrolling vertically on a terminal. The program should not terminate and should continuously scroll down the wave (except until SIGINT). You may assume overflow is not a problem (i.e. you may use infinite loops with incrementing counters, or infinite recursion).
The wave should satisfy the following properties:
* Amplitude = 20 chars (peak amplitude)
* Period = 60 to 65 lines (inclusive)
* The output should only consist of spaces, newline and `|`
* After each line of output, pause for 50ms
There is a sample output on my original question, but I'm not posting it here, because this will make my answer ridiculously long. My original question can be seen here: [Print a sinusoidal wave (vertically)](https://codegolf.stackexchange.com/questions/18633/print-a-sinusoidal-wave-vertically)
Shortest `A` currently: a Perl solution with 48 chars:
<https://codegolf.stackexchange.com/a/18655/12205>
```
print$"x(25+20*sin).'|
';$_+=.1;`sleep .05`;do$0
```
Shortest `B` currently: a J solution with 54 chars: <https://codegolf.stackexchange.com/a/18649/12205>
```
($:+&0.1[6!:3@]&0.05[2:1!:2~' |'#~1,~[:<.20*1+1&o.)0
```
Currently, the score of this answer is 1.113 (an awfully low score)
[Answer]
# Add two numbers
Get two numbers from STDIN, and add them together. You have to support floating point numbers, so 0.5 + 1.5 has to equal 2.
## Perl 5 (with `-E`)
```
say<>+<>
```
## GolfScript
```
n%'+'*'"#{
}"'n/\*~
```
[Answer]
# Print 'Hello, World!' to the stdout.
PHP, 13 bytes
```
Hello, World!
```
Golfscript, 15 bytes
```
'Hello, World!'
```
Pyth, 14 bytes
```
"Hello, World!
```
[Answer]
## Score 48/37 or 1.(297)
T: write a code snippet that ends the program after exactly one hour (as close as possible, like within a second) of running. Don't worry about exceptions, they can be unhandled.
A: Java (32)
```
Thread.sleep(3600000);int a=1/0;
```
B: is for Befunge 98, requires the [TIME fingerprint](http://www.rcfunge98.com/rcsfingers.html#TIME) (43)
```
"EMIT"4(HMS00p01p02p#;gS-!01gM-!H-!++3-!j;@
```
This takes the Hour, Minute, and Second at the time of running, and puts the at cells 02, 01, and 00. Then, it skips over the `;` to the second part. The second part works as follows:
```
g get the value at 00
"EMIT"4(S) get the current time in seconds
-! subtracts the values and changes a 0 to 1, anything else to 0
```
similarly for the Minute and Hour.
```
++ sums up the values
3-! i the sum is 3, we get a 1, otherwise, we get a 0.
j jump over the next that many cells
; skip code execution until the next ;
@ end program
```
Note that Befunge will automatically go back to the beginning of the line when the end of a line is reached.
---
As we can see, Befunge is not good when it comes to waiting for specific times. However, Java is not bad.
[Answer]
# Output a certain text file (498.388888 points)
The goal output is [here](https://bpaste.net/show/a1ba772bec0a).
The Python 3.4.3 script to print it is 49 bytes:
```
for b in dir(__builtins__):print(eval(b).__doc__)
```
The naive CJam program equal to the goal output, by wrapping the output string in `"..."` and escaping each `"` that occurs in it, would be 26908 bytes.
[Answer]
# Say "Hello world!" (50 / 26 ≈ 1.92)
Show a message box to say "Hello world!"
## JavaScript
```
alert('Hello world!')
```
In a browser with support for DOM Level 0+.
## Perl
```
use Win32;Win32::MsgBox('Hello world!','',48)
```
Running on ActivePerl with Win32::GUI.
[Answer]
# Output "Hello world!" until user presses "q", ~~1.842~~ 105/44 = 2.386
1. Print "Hello world!" (including newline).
2. The user presses a key, which is not echoed to the screen.
3. Repeat until the key pressed was "q".
## QBasic (~~52~~ 39 characters)
```
1?"Hello world!":IF"q"<>INPUT$(1)THEN 1
```
Since posting my original answer, I discovered that I could turn off autoformatting in QB64. :^D With the line number and `?` shortcut for `PRINT`, this looks rather like a ternary expression in C-like languages.
First version:
```
PRINT "Hello world!"
IF INPUT$(1) <> "q" THEN RUN
```
## Perl 5 (100 characters)
```
while("q"ne$e){print"Hello world!\n";system"stty cbreak -echo";$e=getc;system"stty -cbreak echo";}
```
The above will only work on (certain?) UNIX systems (tested on Ubuntu 12.04). It's possible that one could go cross-platform and get it down to 91 characters using the [Term::ReadKey](http://search.cpan.org/dist/TermReadKey/ReadKey.pm) module, but I haven't tested it:
```
use Term::ReadKey;while("q"ne$e){print"Hello world!\n";ReadMode 3;$e=ReadKey 0;ReadMode 0;}
```
[Answer]
# Hello, world (3 1/3 points)
Write program that outputs `Hello World.`.
## HQ9+ (1 character)
This is not language "typically used for golfing", so I believe it fits here. Works in [this interpreter, by the way](http://www.almnet.de/esolang/hq9plus.php).
```
H
```
## GolfScript (15 characters)
I doubt it can get any shorter, even if it's GolfScript.
```
"Hello World."
```
[Answer]
## Output "Hello world!", 33/97 = 2.94
Write a program that outputs `Hello world!`
## Arduino or GML
```
Serial.print("Hello world!")
```
or
```
show_message("Hello world!")
```
Both are 28 characters.
## [GTB](http://timtechsoftware.com/gtb "GTB")
I use GTB for golfing a lot (especially since I created it myself, and it is Turing complete). Unfortunately, there is only limited support for lowercase characters (because TI-84 calculator can't deal with it). This is probably the shortest GTB program that can output Hello world!
```
S;"lower",1,1)→_~"H"+S;"expr(",1,1)+_+_+S;"cos(",2,1)+" W"+S;" or ",2,2)+_+S;" and ",4,1)+"!
```
92 characters.
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/6666/edit)
We all know how the discussion about which is the best operating system caused a lot of flame-wars. Your goal is now, to provide decisive "proof" that your favorite operating system is better... ah, no, much better, to provide decisive "proof" that another operating system is bad.
**The task:
Write a program, that does some calculations, and it works correctly on at least one OS and incorrectly on at least another one.**
* the program should do at least some calculations, so it has to read some simple input (preferably on the standard input, or if from files if you want, but misusing little endian/big endian would not only be cheap, but also obvious), and provide some output depending on the input. The calculations should be meaningful and justified, for example solving a real life or a mathematical problem.
* you should specify both operating systems, stating on which one it will work correctly, and on which one it won't. Both operating systems should be well known, and from roughly the same time (so no DOS 1.0 versus a modern OS). **It is advised to provide a short description about the cause of the difference (especially if you suspect many people would not realize it) in spoiler tags.**
>
> like this
>
>
>
* the cause of the difference has to be subtle, so no `#ifdef _WIN32` or similar, please! Remember, your goal is to "prove" that this specific system is bad, so people should not be able to (immediately) spot your trick!
* if there is a very strange or very unusual part in your code, you have to justify it in comments why it is there. Of course, this "justification" can/will be a big lie.
**Scoring:**
This is not a golf! The code should be well organized, and kept simple. Remember, your goal is to hide a bug into it so that people won't suspect it. The simpler the code, the less suspicious it is.
The winner will be decided by votes. The most votes after approximately 10 days after the first valid submission wins. Generally, answers where the code is easy to read and understand, yet the bug is well hidden, and even if discovered, can be attributed to a mistake rather than malice, should be voted up. Similarly, it should be worth much more if the bug just causes an incorrect result, rather than just causing the program to crash or to not do anything.
As usual, I withhold the right to choose an answer as a winner if it is not more than either 10% or 1 point below the one with the most votes, on any subjective criteria.
[Answer]
# Python
This program opens the image specified on the command line and displays it.
```
import Image
import sys
with open(sys.argv[1]) as f:
im = Image.open(f)
im.show()
```
Works on linux, does not work on windows.
This is due to the way windows opens files. Binary mode must be specified for this to work properly on all operating systems.
[Answer]
# Unix shell + standard utilities
Let's write a shell script that finds the process (owned by any user) that has used the most CPU time, and kills all processes with the same name. I suppose that counts as reading in data (from the system) and performing a calculation. (That behavior could be useful for processes that fork off many processes, such as fork bombs and Google Chromium.)
The following should be a portable way to get the name of the process with the greatest CPU time (I tried to avoid obvious Linuxisms but haven't tested it on Solaris):
```
ps -A -o time= -o comm= | sort | tail -n 1 | cut -d ' ' -f 2
```
So our script is simply
```
killall `ps -A -o time= -o comm= | sort | tail -n 1 | cut -d ' ' -f 2`
```
Run as root for best results, so that it can kill processes from other users.
## Linux and BSD
This works on Linux and should work on the BSDs, because `killall arg` kills processes named `arg`.
## Solaris
However, on Solaris, if a user happens to be running a program named `9` in an infinite loop, the script will *bring down the system*. This is because:
>
> On Solaris, [`killall arg`](https://en.wikipedia.org/wiki/Killall) means to *kill all processes* with the signal `arg`. So the command line becomes `killall 9`. As [`9` is the number for SIGKILL on Solaris](http://developers.sun.com/solaris/articles/signalprimer.html), this will kill all processes and thereby bring down the system.
>
>
>
N.B.
>
> This shell injection issue doesn't apply on Linux, because even though the malicious user could supply some special argument like `-KILL` as a process name, `killall -KILL` will harmlessly print a usage message.
>
>
>
[Answer]
# Little Endian (Intel x86) vs. Big Endian (IBM Power7)
Any file format where there are multi-byte binary quantities in non-host order runs the risk of being misinterpreted. Here's a function which takes raw audio, say extracted from a WAV file (which is a Microsoft little endian file format), halves the amplitude and outputs the attenuated audio.
```
#include <stdio.h>
int main()
{
short audio;
while (fread(&audio, sizeof(short), 1, stdin))
{
audio >>= 1;
fwrite(&audio, sizeof(short), 1, stdout);
}
return 0;
}
```
In little endian machines, this works great, but in big endian machines, it's a disaster. E.g.
```
01001101 11001110 -> CE4D (little endian format)
```
Shift right on little endian:
```
00100110 01100111 -> 8726 (correct)
```
Shift right on big endian:
```
00100110 11100111 -> E726 (not correct)
```
Note that some of the nybbles are correct! In fact, it's a 50:50 chance that the output will be correct, depending on whether the least significant bit of the sound sample is 0 or 1!
So when you listen to this audio, it's like half amplitude but with some jarring loud high pitched noise overlaid. Quite startling if you're not prepared for it!
[Answer]
## [GTB](http://timtechsoftware.com/gtb "GTB")
```
:"-→_[_+_→_]
```
On the computer it works, but on my TI-84 calculator it doesn't. Why?
>
> On the calculator RAM overflows and is potentially cleared, while on the emulator for Windows, RAM cannot be overflown by the emulator because of limited allocation.
>
>
>
[Answer]
## C
This solution to problem 100 (about Collatz sequence) is accepted by UVa Online Judge.
However, this code only works correctly on **\*nix** platform since `long` type is implemented as 64-bit signed integer. On **Windows**, the code invokes undefined behavior, since `long` type is implemented as 32-bit signed integer, while one of the intermediate value in `cyc()` function needs at least 32-bit to represent.
```
#include <stdio.h>
#define swap(a, b, t) t __tmp__ = a; a = b; b = __tmp__;
#define M 1000000
short l[M] = {0, 1};
int cyc(long n) { // HERE
if (n < M && l[n]) return l[n];
n = n & 0x1 ? 3 * n + 1 : n >> 1;
return n < M ? (l[n] = cyc(n)) + 1 : cyc(n) + 1;
}
int max(int a, int b) { return a > b ? a : b; }
int main() {
#ifndef ONLINE_JUDGE
// freopen("input.txt", "r", stdin);
#endif
int i, j, m;
while (scanf("%d %d", &i, &j) == 2) {
printf("%d %d ", i, j);
if (i > j) { swap(i, j, int); }
for (m = 0; i <= j; i++)
m = max(m, cyc(i));
printf("%d\n", m);
}
return 0;
}
```
Another way to make this further incompatible is to put the array `l` inside `main()` and make corresponding changes to `cyc()` function. Since the executable is set to request for 2 MB stack by default on Windows, the program crashes right away.
[Answer]
## Python
I came across this on [StackOverflow](https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python) when looking for input timeouts.
```
import signal
TIMEOUT = 5
def interrupted(signum, frame):
print 'interrupted!'
signal.signal(signal.SIGALRM, interrupted)
def input():
try:
print 'You have 5 seconds to type in your stuff...'
foo = raw_input()
return foo
except:
return
signal.alarm(TIMEOUT)
s = input()
signal.alarm(0)
print 'You typed', s
```
This does not work for Windows.
[Answer]
## Linux + bash + GNU coreutils
```
rm --no-preserve-root -R -dir /
```
This will erase the root folder and everything in it which doesn't exist in Windows, even if you install bash for Windows :)
] |
[Question]
[
## Background
Boolean Algebra concerns representing values with letters and simplifying expressions. The following is a chart for the standard notation used:
[](https://i.stack.imgur.com/kWE7v.png)
Above is what actual boolean algebra looks like. For the purposes of this code golf, this is not the syntax that will be used.
## Your Task
Given a string with three characters, return the solution to the expression.
* Input: The string will be a valid expression in boolean algebra. The second character will either be ".", which represents AND, or "+", which represents OR. The first and third characters will be any of 0, 1, or a capital letter. If a capital letter is given, only one letter is ever given. ie. An input will never have two variables, such as A+B.
* Output: Return the evaluation of the expression as a single character.
**Explained Examples**
```
Input => Output
A+1 => 1
```
A + 1 evaluates to 1 because the OR statement is overridden by 1. That is, no matter what value A takes, the presence of 1 means that the statement will always evaluate to 1.
```
Input => Output
B+B => B
```
B + B evaluates to B because the OR statement is dependent on either Bs being true. If both Bs are false, then the output would also be false. So, the statement returns B since whatever value B takes, the output would return that.
```
Input => Output
0.H => 0
```
0 . H evaluates to 0 because the AND statement is overridden by 0. That is, no matter what value H takes, the presence of 0 means that the statement will always evaluate to 0.
```
Input => Output
1.1 => 1
```
1 . 1 evaluates 1 because the AND statement requires both inputs to be 1, and since they are both 1, 1 is returned.
**Examples**
```
Input => Output
A+1 => 1
B+B => B
R+0 => R
1+1 => 1
0+0 => 0
0.0 => 0
Q.Q => Q
0.A => 0
1.C => C
1.1 => 1
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer wins.
Too easy? Try [Intermediate Boolean Algebra Calculator](https://codegolf.stackexchange.com/questions/254719/intermediate-boolean-algebra-calculator).
[Answer]
# JavaScript (ES6), 26 bytes
-4 bytes by using the simplified logic suggested by [@loopywalt](https://codegolf.stackexchange.com/users/107561/loopy-walt).
```
([x,o,y])=>~x&y!=0^o+1?x:y
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@18jukInX6cyVtPWrq5CrVLR1iAuX9vQvsKq8r91tJ6enpKBoaNSrF5afpFrYnKGRoWCrZ0CFvFKuLieNpJwPki4mktBoVjBVqFCQVshH4grrYECyfl5xfk5qXo5@ekaxUBBdaACdSCdplGsqWnNVaupqfkfAA "JavaScript (Node.js) – Try It Online")
---
# JavaScript (ES6), 30 bytes
Expects a string of 3 characters.
```
([x,o,y])=>x<1^y<1^o+1^x<y?y:x
```
[Try it online!](https://tio.run/##bcqxCsIwFIXhvU9x6dKE1GBW01QcfIrSQoiNWkqvNCK5iM8e4yIODj8HPs5kHza49Xq7bxY8jcmbxLpYY009N21s1EA5FGqIDe1pF5PupJTlVh3KXnpcj9ZdWATTwh@nr0vxw/jhZwEQwEAEAZgjncHhEnAe5YxnFjJW@VDl9SxwrosX5zy9AQ "JavaScript (Node.js) – Try It Online")
### 28 bytes
If we can take three separate characters as input:
```
(x,o,y)=>x<1^y<1^o+1^x<y?y:x
```
[Try it online!](https://tio.run/##bc7BCsIwEATQe79i6aUNqYu52qbiwa8QCyG2aildaUSyiN8e14t48DAMPOYwo3u44Jfr7b6a6dSnwaYyVlSxsm1sTMcS0qaLDW95E1N9QMR8bXb5EQda9s5fygi2hT/OX0f9w/ThZwYQwEIEDSThWsDTHGjqcaJzGQQLGRTSg1wCqoCVqrOXUiq9AQ "JavaScript (Node.js) – Try It Online")
### Truth table
The table below shows the intermediate results coerced to \$0\$ or \$1\$, which is implicitly done by the bitwise operators.
Note that `o+1` evaluates to either `0.1` for `.` (coerced to \$0\$) or `1` for `+` (coerced to \$1\$).
```
x | y | o | x<1 | y<1 | o+1 | x<y | XOR | use | result
---+---+---+-----+-----+-----+-----+-----+-----+--------
0 | 0 | . | 1 | 1 | 0 | 0 | 0 | x | 0
0 | 0 | + | 1 | 1 | 1 | 0 | 1 | y | 0
0 | 1 | . | 1 | 0 | 0 | 1 | 0 | x | 0
0 | 1 | + | 1 | 0 | 1 | 1 | 1 | y | 1
0 | A | . | 1 | 0 | 0 | 1 | 0 | x | 0
0 | A | + | 1 | 0 | 1 | 1 | 1 | y | A
1 | 0 | . | 0 | 1 | 0 | 0 | 1 | y | 0
1 | 0 | + | 0 | 1 | 1 | 0 | 0 | x | 1
1 | 1 | . | 0 | 0 | 0 | 0 | 0 | x | 1
1 | 1 | + | 0 | 0 | 1 | 0 | 1 | y | 1
1 | A | . | 0 | 0 | 0 | 1 | 1 | y | A
1 | A | + | 0 | 0 | 1 | 1 | 0 | x | 1
A | 0 | . | 0 | 1 | 0 | 0 | 1 | y | 0
A | 0 | + | 0 | 1 | 1 | 0 | 0 | x | A
A | 1 | . | 0 | 0 | 0 | 0 | 0 | x | A
A | 1 | + | 0 | 0 | 1 | 0 | 1 | y | 1
A | A | . | 0 | 0 | 0 | 0 | 0 | x | A
A | A | + | 0 | 0 | 1 | 0 | 1 | y | A
\_________XOR_________/
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Ṣ⁼ÞOṂḂṾƲṪ
```
A monadic Link that accepts a list of three characters as specified and yields the resulting character.
**[Try it online!](https://tio.run/##y0rNyan8///hzkWPGvccnuf/cGfTwx1ND3fuO7bp4c5V/x/u3qJzuD3rUcMcBVs7hUcNc49tetS0JvL/f0dtQy4nbSeuIG0DLkMg2wBIG@gZcAXqBQJpRy5DPWcgNgQA "Jelly – Try It Online")**
### How?
Note that `+` and `.` are less than all other possible characters and that their ordinals are odd (\$43\$) and even (\$46\$), respectively. Also, variables always have ordinals greater than either `0` or `1`.
```
Ṣ⁼ÞOṂḂṾƲṪ - Link: list of characters, S = [a, o, b]
Ṣ - sort (S) -> [o, min(a,b), max(a,b)]
... this places a variable, if present, on the right
Ʋ - last four links as a monad - f(S):
O - ordinals
Ṃ - minimum -> 43 (o='+') or 46 (o='.')
Ḃ - mod two -> 1 or 0
Ṿ - uneval -> '1' or '0'
Þ - sort (the sorted S) by:
⁼ - equals ('1' or '0')
... i.e. for o='+' (OR) place any '0's at the right
or for o='.' (AND) place any '1's at the right
Ṫ - tail ...get the right-most
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 27 bytes
```
0\+|\+0|1\.|\.1
(\d?)..
$1
```
[Try it online!](https://tio.run/##DcYxCoBADETRfs5hoQSG5ASy6wnWOo2ghY2FWObuMcXn/ff67ufIVJdw0TBnOA2Y/VwXEpNlNjF06dhFYfVaKhWDo2wwbpX9 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
0\+|\+0|1\.|\.1
```
Rule 1: OR with 0 or AND with 1 returns the other parameter.
```
(\d?)..
$1
```
Rule 2: Return the first parameter if it's a digit. Rule 3: Otherwise, return the second parameter. Examples:
```
0+0 => 0 (by rule 1) 0.0 => 0 (by rule 2)
0+A => A (by rule 1) 0.A => 0 (by rule 2)
0+1 => 1 (by rule 1) 0.1 => 0 (by rule 1)
A+0 => A (by rule 1) A.0 => 0 (by rule 3)
A+A => A (by rule 3) A.A => A (by rule 3)
A+1 => 1 (by rule 3) A.1 => 1 (by rule 1)
1+0 => 1 (by rule 1) 1.0 => 0 (by rule 1)
1+A => 1 (by rule 2) 1.A => A (by rule 1)
1+1 => 1 (by rule 2) 1.1 => 1 (by rule 1)
```
[Answer]
# [Python](https://www.python.org), 36 bytes
```
lambda s:s[-("+."[s>"1"!=s[2]]in s)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3VXISc5NSEhWKrYqjdTWUtPWUoovtlAyVFG2Lo41iYzPzFIo1Y6FqQ9PyixQSFYBiSgaGjkpWXAoggSRkAbBIMlgEaBRIQKHINlkvKz8zT0MjUSdJUxMkVFCUmVeiUaSTplGkqQkxfMECCA0A)
#### How?
`s>"1"` due to lexicographic ordering this is the same as `s[0]>"0"` which is the same in both our "dream ordering" and actual string ordering.
`"1"!=s[2]` in standard ordering is `1>s[2]` in dream ordering.
Taken together this comprises the three cases where s[0]>s[2] and one equal case which we don't care about.
It remains to xor that with which operator is given.
# [Python](https://www.python.org), 40 bytes (@Jonathan Allan)
```
lambda s:sorted(s)[~("+."["0"in s]in s)]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3NXISc5NSEhWKrYrzi0pSUzSKNaPrNJS09ZSilQyUMvMUimNBhGYsVH1oWn6RQqICUEzJwNBRyYpLASSQhCwAFkkGiwCNAQkoFNkm62XlZ-ZpaCTqJGlqgoQKijLzSjSKdNI0ijQ1IYYvWAChAQ)
# [Python](https://www.python.org), 41 bytes
```
lambda s:sorted(s)[s.find("+."["0"in s])]
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3NXMSc5NSEhWKrYrzi0pSUzSKNaOL9dIy81I0lLT1lKKVDJQy8xSKYzVjoRpC0_KLFBIVgIJKBoaOSlZcCiCBJGQBsEgyWARoBEhAocg2WS8rPzNPQyNRJ0lTEyRUUJSZV6JRpJOmUaSpCTF8wQIIDQA)
### How?
Ideally, we would like to have an ordering 0 < variables < 1. Then we could use `min` and `max` or similar. But in fact "0" < "1" < variables.
But, as we are are ranking only 2 values we can instead
* check if "0" is one of them
+ if yes: use normal string ordering
+ if no: use it up-side-down
Actual algorithm step-by-step:
sort input (standard string ordering). This puts the operator in front of the operands, so we need to select index 1 or -1. It so happens that these are the values find will return if we search the original string for either operator (-1 means not found, 1 is the original position of the operator). We choose which operator to test for depending on the above: whether "0" is in the input.
[Answer]
# [Python 3.8+](https://docs.python.org/3.8/), ~~46~~ 45 bytes
```
lambda s:(c:='01'['+'in s])*(c in s)or max(s)
```
An unnamed function that accepts the string and returns a character.
**[Try it online!](https://tio.run/##ZdBNCoJAFMDxfad4tHkzKeLQJoQJ1BPY1lxMpiT4hU5QiMt2HaEu50XMyUKpWT1@/IdhXnmVpyJfb8qqj/m@T0V2OAqoLRJaHE2GPmqY5FAHdEVCUBMtKsjEhdS0j4dRRrXUIbqUUSijoyrIAoZD0NYY6oAMqf4RR3OUOJPsNFPJbhL2d8scG3Mmxq94hqfEmzf2T8MMV4k7l@ktar1RhPIsUuAQE/Uz@saySnJJ4mWjqAW@hWbsWoAGu@e9e9zQH4nz7y6Cdkn7Fw "Python 3.8 (pre-release) – Try It Online")**
### How?
When the operator is `'+'` (OR) we should return `'1'` if a `'1'` is present or a variable if present, otherwise we have `'0+0'` and should return `'0'`.
When the operator is `'.'` (AND) we should return `'0'` if a `'0'` is present or a variable if present, otherwise we have `'1.1'` and should return `'1'`.
The code implements this logic by constructing a character, `c`, which is `'0'` if the operator is `'+'` or `'0'` if the operator is `'.'` - this is `(c:='01'['+'in s])` - then repeating that character once if it is present in the input string or zero times (giving `''`) if not - this is `*(c in s)` - we return this if it is non-empty otherwise we return the variable if present or the repeated, non-matching digit character - this is `or max(s)`.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 9 bytes
```
sµ?Cg∷=;t
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwic8K1P0Nn4oi3PTt0IiwiIiwiQSsxXG5CK0JcblIrMFxuMSsxXG4wKzBcblwiMC4wXCJcblEuUVxuMC5BXG4xLkNcblwiMS4xXCIiXQ==)
Port of Jonathan Allan's Jelly answer, so upvote that!
```
sµ?Cg∷=;t
s # Sort
µ ; # Sort by:
?Cg # Minimum charcode of input
∷ # Modulo two
= # Equals the current item
t # Last item
```
[Answer]
# x86-64 machine code, 17 bytes
```
66 AD 8A 16 A8 40 74 02 86 C2 9E 10 C4 0F 4A C2 C3
```
[Try it online!](https://tio.run/##bZJdb5swFIav7V9xxpRiFxKRFE1TaDJNu97NriolmeQaA54MVJiusDR/fezYaZtNmkD@eM97HtvHlvNSymkStgYG3wJGF6Vp74WBghZrYtrcPlFStz8hNzHsOqsPlPTK9iBwngxpQsmPX2CxG2RVepcw1CZrYkVVUCJyCaLyIpHIeVCgxBCDygdKOtVTHgDP6GNjddmoHGQlOiiYbnpAlGwbXMpr1xZt9L1upHnMFdzaPtftotpS6ry10A3j9IiLOLPdpQfYwDGJ/XfKKCnaDjzWjjWGkswP3m1g5UdRxCnBdGJ3S5fqgp8gXISwhjAKEXAh6HO@dtkfsfe5PpnoAi1wC6lTzhISV44YJiE8g75aZi9qclGZ3m6X/CV0co0yVv2N0FdnyOdwnkY6u6jf/wP3hIcO91qwYGb3/UzumyAGG2Npb2LLubOhC/9X2775KmSlG4VFz9U6cBZ32MEdNoYRp3kLx1c7zJLVHSLHDWP/XN41L/huiKIDz07wVGmjgI2uUsnw5cZB3whspuF@xMfE/eYGDJ6m6bcsjCjtNK8/pNjgw9ygX5k/)
Following the standard calling convention for Unix-like systems (from the System V AMD64 ABI), this takes the length of the string (which is always 3 and is ignored) in RDI and its address (as an array of single-byte ASCII characters) in RSI, and returns a value in AL.
In assembly:
```
f: lodsw # Load two bytes from the string into AL and AH, advancing the pointer.
mov dl, [rsi] # Load the next byte from the string into DL.
test al, 0x40 # Check bit 6 of AL, which is 1 for letters and 0 for digits.
jz s0 # Jump if the bit is zero.
xchg dl, al # (Otherwise: letters) Exchange DL and AL.
s0: # At this point, AL must be a digit (as they can't be both letters).
sahf # Set flags based on AH (which holds the operation character).
# In particular, its low bit goes into CF.
adc ah, al # Add AL+CF to AH.
# AH can be '+', 00101011 in binary, becoming 00101100 after adding CF=1,
# or '.', 00101110 in binary, staying 00101110 after adding CF=0.
# AL can be '0' (00110000) or '1' (00110001).
# Adding that in produces 010111xy, where x is 0 for '+' and 1 for '.',
# and y is 0 for '0' and 1 for '1'.
cmovpe eax, edx # If the sum of the bits in the result is even,
# which is true for (+,0) and (.,1), set EAX to EDX's value,
# so that the other operand becomes the return value.
# Otherwise -- for (+,1) and (.,0) -- AL is kept unchanged.
ret # Return.
```
[Answer]
# Javascript, ~~130~~ 90 chars
```
s=>([x,y]=s[1]=="+"?'01':'10',t=[s[0],s[2]].sort(),s[0]==x&s[2]==x?x:t.includes(y)?y:t[1])
```
130 -> 90 Thanks to @Steffan
[Answer]
# [Java (JDK)](http://jdk.java.net/), 43 bytes
```
(x,o,y)->x==(o+=~o&4|2)|y==o?o:x==(o^1)?y:x
```
[Try it online!](https://tio.run/##ZY89b4MwEIZ3fsUpUiq7IRaOOoFo5KVbp4xVK7kEp04JRviIQAn96/SAdmg6nO557@vVHfVZr4/7z8GeKlcjHEmLBm0h7pPgX800ZYbWlWMzK7T38KxtCZcAwJaY10ZnOTzBBbIPXYOuqqJjE7bhXHI/ueMJ9LRVNe@FzcCjRkpnZ/dwootsh7UtDy@voOuD55MB0GED6cDa0IUdXz@2acrcKv1ydw/XDb92aeq2Lp6qb5Jvu7gdkmnPuBrYmVwx9wjxn5sAu85jfhKuQVGRKRq2WPoYltmyXITTSghGzL@MSowPKGQRn7u/Wt7oDed89h8f7YN@GKJVRKEo5KCIFbEilsSSWBJHgmYEzQiaIVbEilgSS2Ip5Dc "Java (JDK) – Try It Online")
Taken as three characters, returning one character.
[Answer]
# Python3, ~~116~~ ~~103~~ 74 chars
```
lambda s:[[max(s),y:='01'[b:=s[1]<'.']][y in s],x:='10'[b]][s[0]==s[2]==x]
```
116 => 103 Thanks to @Unrelated String
103 => 74 Thanks to @Steffan, with a radically different answer
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
FI№θ+¿№θιι⌈θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBwzmxuETDOb80r0SjUEdBSVtJU1NTITNNASGWCRQIKMoEcjI1rRVSc4pToVzfxIrM3NJcjUJNTev//x21Df7rluUAAA "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Port of @JonathanAllan's Python answer.
```
FI№θ+
```
Count the number of `+`s in the input string, then cast that to string and loop over the character (golfy way of reusing the result as a variable).
```
¿№θι
```
If the input contains that digit, then...
```
ι
```
... output the digit, otherwise...
```
⌈θ
```
... output the letter if there is one, otherwise the other digit.
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), 9 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
s‼╞├$¥░=§
```
[Try it online.](https://tio.run/##y00syUjPz0n7/7/4UcOeR1PnPZoyR@XQ0kfTJtoeWv7/v5KjtqESl5KTthOQDNI2AJKGYBEDMNtAD0QG6gWC2Y4gWT1nMGmoBAA)
**Explanation:**
```
# (e.g. input1="R+0"; input2="A.0")
s # Sort the (implicit) input-string
# STACK1: "+0R"; STACK2: ".0A"
‼ # Apply the following two commands separately on the same stack:
╞ # Discard the left character
├ # Extract the left character
# STACK1: "0R","0R","+"; STACK2: "0A","0A","."
$ # Convert the top character to its codepoint integer
# STACK1: "0R","0R",43; STACK2: "0A","0A",46
¥ # Modulo-2
# STACK1: "0R","0R",1; STACK2: "0A","0A",0
░ # Convert it to a string
# STACK1: "0R","0R","1"; STACK2: "0A","0A","0"
= # Get the index of this character in the string (-1 if not found)
# STACK1: "0R",-1; STACK2: "0A",0
§ # Modular 0-based index it into the string
# STACK1: "R"; STACK2: "0"
# (after which the entire stack joined together is output implicitly as result)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 32 bytes
```
->s{s[s=~/0\+|\+1|1\.|\.0/?2:0]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1664uji62LZO3yBGuyZG27DGMEavJkbPQN/eyMogtvZ/gUK0kqO2oZKOkqF2FJB00nYCkkHaBkDSQDsELG4IZkNEwGw9EDtQLxDMdgSp0XMGkxBZQ6VYvdzEAg21NM3/AA "Ruby – Try It Online")
If the expression contains one of `0+`, `+1`, `1.` or `.0`, then the result is the RHS, otherwise it's the LHS.
### Why?
First, let's discard the case where the first and third character is the same, in that case both are good. We are left with 8 cases to handle:
```
RHS cases:
0+X => X
X+1 => 1
X.0 => 0
1.X => X
LHS casaes:
X+0 => X
1+X => 1
0.X => 0
X.1 => X
```
[Answer]
# [Haskell](https://www.haskell.org/), 99 bytes
```
c i=fromEnum i+91*fromEnum(i=='1')
f x=toEnum$(if x!!1>'+'then min else max)(c$x!!0)(c$x!!2)`mod`91
```
[Try it online!](https://tio.run/##ZdBPS8MwGAbwez/Fs1FoamppvA2MsA5vXjqPIix0KQ0mjTQZ7uB3r4lurmy5vLy/PPnbC/chtZ6mFop3ozXPw8FA0RW7O3dEcZ6xLE86HLm3kVKiQrNYsKeMZr6XA4waILWTMOKYkzYNk9WpPuQ7Y/e7FZu8dL4VTjpwvCUIgyzXlC0LxP2Lk9S0jlJfZEurKNuLsJtV1V@mmkl5LU3ZRGnmmfVVhpWbKJu5nM/6hfckGeP9OyhwDotvEFXYHI/3@H9gCBkRvoTj8@Bf/fgyIIXr7VcoQmuoPcZk@gE "Haskell – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~72~~ 65 bytes
*-7 bytes thanks to [@ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)*
```
#define f(x)x[2*((*x-x[2]+((*x==49)-(x[2]==49))*91)*(x[1]-44)>0)]
```
[Try it online!](https://tio.run/##TY/dasMwDIWv46cQLQU7f9hbNihbCk2fIL1tzSiO0xg6NzQOC4w@eyYnZRSE@HQ4R0IqOSs1jstK18ZqqOnAhsNLSGk4JAgy8pTn2Zol1M8TsnAtWIizkEmWsQ1nclwaqy59peGzc5W5ps2GEGMdfJ@MpeyXBKo53cDYtneHd/lBgp/GXDTQs3YdnWTGAG2zTw/t17V3qEL@CGU@FMz8Kp/kf3zzyL2rveHpmi5WHayUr6NdxLMrftod47@P05i6E3Ift5EAQYqogILsIw57IiaFI3PCU9/LtIQSeYss0h3ssKPnDw "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
{ΣIÇßÉQ}θ
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/254517/52210), so make sure to upvote him as well!
[Try it online](https://tio.run/##yy9OTMpM/f@/@txiz8Pth@cf7gysPbfj//8gbQMA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeWhlf@rzy0@tO5w@@H5hzsDa8/t@K/zP1rJUdtQSUfJSdsJSAZpGwBJQ7CIAZhtoAciA/UCwWxHkKyeM5g0VIoFAA).
**Explanation:**
```
{ # Sort the characters of the (implicit) input (based on codepoints)
Σ # Then (stable-)sort it further by:
IÇ # Push the input as a list of codepoints
ß # Pop and push the minimum
É # Check if this is odd
Q # Check if it's equal to the current character
# (a '0' for '+'; and a '1' for '.')
}θ # After the sort-by, leave the last character
# (which is output implicitly as result)
```
[Answer]
# [Haskell](https://www.haskell.org/), 60 bytes
```
f(a:o:b)|a<'1'||b=="1",o<'.'=b|a=='1'||b<"1",o>'+'=b|1>0=[a]
```
[Try it online!](https://tio.run/##bc/RCoIwFMbxe5/iMIIVy7FzKzuC@gTzNrqYlCSaRnW5d180DZp4@@PP@Tg3@@qvw@B9u7fZlDUHZzVH7lxDxJAdJ80lp8ZZopl10JyLr2Ku6GTP/m67EQguUwKPZze@YQctsEIggzQFjLQUZdAy0lqooHWkKKqNC2ppVRKz/PG/GmmCmlVbbLQo57lqpcsb/gM "Haskell – Try It Online")
Inspired by @G B [answer](https://codegolf.stackexchange.com/a/254549/84844)
[Answer]
# GNU [sed](https://www.gnu.org/software/sed/) -r, 33
```
s/0\+|\+0|1\.|\.1//
s/(\d)?../\1/
```
I golfed this myself, *honest*. Though in reality it turns out to be a simple port of @Neil's [answer](https://codegolf.stackexchange.com/a/254521/11259).
[Try it online!](https://tio.run/##Dca7DYAwDADR3pOArPgzAQpMALXLIEQDiECX2TEuTu/qWtJ2vO6VxbAZSlOjZqTMULmz0g9EbMruGRVGHGFBAY2XUEhgpjnMoDRFCt95Pft5VE/3Dw "sed – Try It Online")
[Answer]
# T-SQL, 59 bytes
input is a table
```
SELECT iif(a+b+c in(a+'+0',a+'.1','1+'+c,'0.'+c),a,c)FROM @
```
**[Try it online](https://dbfiddle.uk/N04FyPFN)**
# T-SQL, 77 bytes
input is char(3) - which is kind of a string in sql
```
PRINT stuff(@,iif(right(@,2)in('+1','.0')or
left(@,2)in('1.','0+'),1,2),2,'')
```
**[Try it online](https://dbfiddle.uk/1uKB8BaG)**
[Answer]
# [Scala](http://www.scala-lang.org/), 108 bytes
Port of [@AZTECCO's Haskell answer](https://codegolf.stackexchange.com/a/254556/110802) in Scala.
Golfed version. [Try it online!](https://tio.run/##dY89D4IwEIb3/ooLg7RpUltHYknA2QGNk3GoCgaDaKAxEfW3Yyv4EQhd7vI8fS935U5lqj5vj/FOw1ylOdwRuqoMEg8vdZHmB@k3lci6kn6a4ApzMnWF@3hUeEKkNC15Y2Ewe2Pe4NHIQt@l7V@bIrZh@twMhTgrY0c4toDNfU0N@ziBk9kIq@JQehAUhbqtG7khHqzyVIM064J5F0N1luMEOwEVDiEwHoPoqpCGrQq7akF5qxZdJehsaCD/pjjqOfZzHRWxqFVRPxUMpQT77DHrq/@bn@iJ6hc)
```
z=>if(z(0)<'1'||z(2)=='1')if(z(1)<'.'||z(0)=='1'&&z(1)>'+'||z(2)<'1')z(2).toString else"1"else z(0).toString
```
Golfed version. [Try it online!](https://tio.run/##dZA9b4MwGIR3fsWJBVtIDu4YJZUgcwdSdUnVwaQQUVGowKpUJfx26i9ahJXtvffxne0bzqIRU1d8lGeJJ1G3uE7vZYWKnLZ4ln3dXug8YI9rAHyLBkLNJ5JQJzsj@SwLIx9ooHRdgQjsEPEIt5tGez1TE2VxpzFTq4LJzl5lWNkMpfNbkw3YLf1zwiOi2E9wGSEPjRytFMtD/m4MJugKPlUbRPSXYYu078XPq@Vvqo@XtpauDeBLbWXTkoqEacxDSrHZgK9RFmcOZWt0jBOHjmvE48O9wOTPlQQeY/9shXKWO5T7rvSei7P5HQcfLf886vp@AQ)
```
def f(Z: String): String = {
val a = Z(0)
val o = Z(1)
val b = Z(2)
if (a < '1' || b == '1') {
if (o < '.') b.toString
else if (a == '1' || b < '1') {
if (o > '+') b.toString
else "1"
} else a.toString
} else a.toString
}
```
] |
[Question]
[
Write a short program which takes in a positive number of seconds representing an age, and outputs an estimate of that time in English.
Your program must output the *least precise* amount of time which has passed, among the following metrics and their lengths in seconds:
```
second = 1
minute = 60
hour = 60 * 60
day = 60 * 60 * 24
week = 60 * 60 * 24 * 7
month = 60 * 60 * 24 * 31
year = 60 * 60 * 24 * 365
```
**Examples**
```
input : output
1 : 1 second
59 : 59 seconds
60 : 1 minute
119 : 1 minute
120 : 2 minutes
43200 : 12 hours
86401 : 1 day
1815603 : 3 weeks
1426636800 : 45 years
```
As you can see above, after the time of say, 1 day (60 \* 60 \* 24 = 86400 seconds), **we no longer output minute(s) or hour(s)**, but only days until we surpass the time of one week, and so on.
Consider the given length of time to be an age. For example, after 119 seconds, 1 minute has *passed*, not 2.
**Rules**
* No specification for 0 or negative inputs.
* Follow proper pluralization. Every measure greater than 1 must include an `s` following the word.
* You may not use a pre-existing library which serves the function of the entire program.
* This is a code golf, shortest program wins the internet points.
* Have fun!
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 62 [bytes](https://github.com/DennisMitchell/jelly/wiki/Cde-page)
```
TṀị
“¢<<ð¢‘×\×€0¦7,31,365F⁸:µç“ɲþḣ⁹ḢṡṾDU¤µQƝṁ⁼ẹ»Ḳ¤ṭÇK;⁸Ç>1¤¡”s
```
A full program printing the result.
(As a monadic link it returns a list of an integer followed by characters)
**[Try it online!](https://tio.run/##AYYAef9qZWxsef//VOG5gOG7iwrigJzCojw8w7DCouKAmMOXXMOX4oKsMMKmNywzMSwzNjVG4oG4OsK1w6figJzJssO@4bij4oG54bii4bmh4bm@RFXCpMK1Ucad4bmB4oG84bq5wrvhuLLCpOG5rcOHSzvigbjDhz4xwqTCoeKAnXP///84NjQwMQ "Jelly – Try It Online")**
### How?
```
TṀị - Link 1: list of integers, K; list, V e.g. [86401,1440,24,1,0,0,0], ["second","minute","hour","day","week","month","year"]
T - truthy indexes of K [1,2,3,4]
Ṁ - maximum 4
ị - index into V "day"
“¢<<ð¢‘×\×€0¦7,31,365F⁸:µç“...»Ḳ¤ṭÇK;⁸Ç>1¤¡”s - Main link: integer, N e.g. 3599
“¢<<𢑠- list of code-page indices = [1,60,60,24,1]
\ - cumulative reduce with:
× - multiplication = [1,60,3600,86400,86400]
7,31,365 - list of integers = [7,31,365]
¦ - sparse application...
0 - ...to index: 0 (rightmost)
×€ - ...of: multiplication for €ach = [1,60,3600,86400,[604800,2678400,31536000]]
F - flatten = [1,60,3600,86400,604800,2678400,31536000]
⁸ - chain's left argument, N 3599
: - integer divide [3599,59,0,0,0,0,0]
µ - start a new monadic chain, call that X
¤ - nilad followed by links as a nilad:
“...» - compression of "second minute hour day week month year"
Ḳ - split at spaces = ["second","minute","hour","day","week","month","year"]
ç - call the last link (1) as a dyad - i.e. f(X,["second","minute","hour","day","week","month","year"])
- "minute"
Ç - call the last link (1) as a monad - i.e. f(X,X)
- 59
ṭ - tack [59,['m','i','n','u','t','e']]
K - join with spaces [59,' ','m','i','n','u','t','e']
”s - literal character '
¡ - repeat...
¤ - ...number of times: nilad followed by link(s) as a nilad:
⁸ - chain's left argument, X [3599,59,0,0,0,0,0]
Ç - call the last link (1) as a monad - i.e. f(X,X)
- 59
>1 - greater than 1? 1
; - concatenate [59,' ','m','i','n','u','t','e','s']
- implicit print - smashes to print "59 minutes"
```
[Answer]
# C, 194 180 144 128 characters
Thanks to @gastropher for the code reductions. I forgot that C allows for implicit parameters using K&R-style functions! Also thanks to @gmatht for the idea of putting literals inside instead of arrays. I extended that to the characters by abusing taking advantage of wide character/`char16_t` strings! The compiler doesn't seem to like `\1` in its ☺ form though.
```
f(t,c,d){for(c=7;!(d=t/L"\1<ฐ\1•▼ŭ"[--c]/(c>2?86400:1)););printf("%d %.6s%s\n",d,c*6+(char*)u"敳潣摮業畮整潨牵 慤y†敷步 潭瑮h敹牡",(d<2)+"s");}
```
[Try it online!](https://tio.run/##VY6xToNAAIZ3nuI8Q3JHjxYag1UovoBvUDrgnZRLKhigTUzThMWhmx1w1moTF1jUqImMvodhOB4DYXT7v@8f/p@qM0qbQx7Q@YJdAitO2Jxf9H1b@ud42KrGQwmhhOGVF0aIjo/NA8TGyeAcOrr1@3nn6FW6q@6/f3I4UVU6HSBqD89GxpGmneoYm9i8jniQeAjKDMh9I5ZjJ4CEEaoYPUR9N1LwAorsVZRPYluIfV5nhcjeRPlSb96rNBW3zzdV@iCyD5HvOy7zelv4IvuqN4@QIGYNcQ/GEJvrph0CVy4PUBfcaEYJ6BaAorSwxGAlAQC4h7rK1jFoUxLyDpcTfdq@ldZNMzJONO0P "C (gcc) – Try It Online")
# Original solution
I split up the arrays into separate lines to make it easier to see the rest of the solution.
```
char *n[]={"second","minute","hour","day","week","month","year"};
int o[]={1,60,3600,86400,604800,2678400,31536000};
f(int t){int c=7,d;while(!(d=t/o[--c]));printf("%d %s%s\n",d,n[c],d>1?"s":"");}
```
[Try it online!](https://tio.run/##VU9BbsMgELz7FZTKkolwC01KrFK7D3F9IIBjVAcqjBNFlt/uQnvqZWdnZ2dWK8uzlNujsXKclQbvU1CjOT0NTfZvZlwcbXIQHuxs29ULnLR0VkEML8bOQcdmcLOPoMQ91pvWX0l0NgwR71p4uHJjA3DJTjEjeM8IwRU7xMrIoYrwwo5Vonv6mkSy8r5InoCWBLI@YsVvgxl18VCoOjy7tixlhxD/9nGhL2CuQD7l06eFWGHbyg6rhn7ACb5BiPi6pZiLMPY3VvizxODvq10kVwSWDABg@iJJDUUgdsGZRK8tTYeyddvoDw "C (gcc) – Try It Online")
Running the divisors in order from largest to smallest, we get the coarsest unit of time. The program misbehaves if you give it 0 seconds, but as the specification explicitly excludes this value, I deem that to be acceptable.
[Answer]
# [Perl 5](https://www.perl.org/), 110 bytes
```
year31536000month2678400week604800day86400hour3600minute60second1=~s:\D+:say"$% $&",$_=$%>1&&"s"if$%=$_/$':reg
```
[Try it online!](https://tio.run/##NcpBDoIwEEDRq5hmwIWCU6GVkODKrTcwIUQGaZSWtBDDxqM76sK/fPkj@YdiXqjxmVSZRsTB2anf60ORIz6J7hrzArFtlkJ/pXez/22DsfNEGgNdnW1l9Qrl5bQpQ7MIiFYQiy3UFURHGcciCNNBVEG9g3Xp6cYs8d/bjZNxNnBiOTmrVGKKHw "Perl 5 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 54 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
▀♂♂┼╕Qá◙à*ä∙Φò►⌠╨Ns↔║►πîÇ∙cI≡ªb?δ♪9gΓ╕┬≥‼⌡Öå01:♪EoE╘≡ë
```
[Run and debug it](https://staxlang.xyz/#p=df0b0bc5b851a00a852a84f9e89510f4d04e731dba10e38c80f96349f0a6623feb0d3967e2b8c2f213f5998630313a0d456f45d4f089&i=1%0A59%0A60%0A43200%0A86401%0A1815603%0A1426636800&a=1&m=2)
Here's the unpacked, ungolfed, ascii representation of the same program.
```
stack starts with total seconds
c60/ push total minutes to stack
c60/ ... hours
c24/ ... days
Yc7/ ... weeks
y31/ ... months
y365/ ... years
L make a list out of all the calculated time units
`)sQP(dr'pk,oV4?_HIFD?x`j compressed literal for singular forms of unit names
\ zip totals with names
rF foreach pair of total and name (in reverse orer)
h!C skip if the current total is falsey (0)
_J join the total and unit name with a space
's_1=T+ concat 's' unless the total is one
```
Following execution, since there's no other output, the top of the stack is printed implicitly.
[Run this one](https://staxlang.xyz/#c=+++++++++++++++++++++++++%09stack+starts+with+total+seconds%0Ac60%2F+++++++++++++++++++++%09push+total+minutes+to+stack%0Ac60%2F+++++++++++++++++++++%09...+hours+%0Ac24%2F+++++++++++++++++++++%09...+days%0AYc7%2F+++++++++++++++++++++%09...+weeks%0Ay31%2F+++++++++++++++++++++%09...+months%0Ay365%2F++++++++++++++++++++%09...+years%0AL++++++++++++++++++++++++%09make+a+list+out+of+all+the+calculated+time+units%0A%60%29sQP%28dr%27pk,oV4%3F_HIFD%3Fx%60j%09compressed+literal+for+singular+forms+of+unit+names%0A%5C++++++++++++++++++++++++%09zip+totals+with+names%0ArF+++++++++++++++++++++++%09foreach+pair+of+total+and+name+%28in+reverse+orer%29%0A++h%21C++++++++++++++++++++%09skip+if+the+current+total+is+falsey+%280%29%0A++_J+++++++++++++++++++++%09join+the+total+and+unit+name+with+a+space%0A++%27s_1%3DT%2B++++++++++++++++%09concat+%27s%27+unless+the+total+is+one&i=1%0A59%0A60%0A43200%0A86401%0A1815603%0A1426636800&a=1&m=2)
[Answer]
# JavaScript (ES6), 131 bytes
```
n=>[60,60,24,7,31/7,365/31,0].map((v,i)=>s=n<1?s:(k=n|0)+' '+'second,minute,hour,day,week,month,year'.split`,`[n/=v,i])|k>1?s+'s':s
```
[Try it online!](https://tio.run/##XZBta4MwEIC/71fkW5TeNDExtWVxP6QUGmraOjURYzsK/e8uIhszx3Fw8PDcy5d6KHce6n58N7bS00VORpYHQcBnxmELjKa@iDxlFMgx6VQfRQ@oY1k6aT7op9tHjTQvEm8wwhvs9NmaCrra3EcNN3sfoFJP@Na6gc6a8QZPrQacuL6txxOcDiaVXneMX03pZV6A927yDmdbnbT2Gl0iin4jjlGaIoqWKW9rLN@tMd8vnAtAQULfsm6AcZYR8h/L0HxPaCsEJ3Rl8wcHDC1oLgj7YxiaHxKaKM@EYKIgZKF4juZnuekH "JavaScript (Node.js) – Try It Online")
[Answer]
# Java 8, ~~197~~ ~~195~~ 157 bytes
```
n->(n<60?n+" second":(n/=60)<60?n+" minute":(n/=60)<24?n+" hour":(n/=24)<7?n+" day":n<31?(n/=7)+" week":n<365?(n/=31)+" month":(n/=365)+" year")+(n>1?"s":"")
```
-38 bytes thanks to *@OlivierGrégoire*.
**Explanation:**
[Try it online.](https://tio.run/##hY/LboMwEEX3@YqRV7aipJiHQwgJX9Bsuqy6cMFtSGCMwKRCVb6dGkjUVYtky/KZa/mes7zKla4UnrNLnxayaeBZ5vi9AMjRqPpDpgqOwxXgxdQ5fkJKC20PZDtLb3bb1Rhp8hSOgLCHHlcHirFwElwSaFSqMSMRxae9cNgDlzm2Rv1i1x/xSbf1BF2fxZuRZbIjEcYeTwa@YRZ9KXUZmQhG6PGBlhrNaXptBwPplKwJW1I88IQ0JCKE9bupctW@F7byvflV5xmU1pxOlq9vkt2tu8aocq1bs67sxBRIcZ1Szkb/P@fBdiZgpf8PbOcC3J1L@J7rzGVC4TtzMjzkgXC8uZTvCuGJ8PHlbXHrfwA)
```
n-> // Method with long parameter and String return-type
(n<60? // If `n` is below 60:
n // Output `n`
+" second" // + " second"
:(n/=60)<60? // Else-if `n` is below 60*60
n // Integer-divide `n` by 60, and output it
+" minute" // + " minute"
:(n/=60)<24? // Else-if `n` is below 60*60*24:
n // Integer-divide `n` by 60*60, and output it
+" hour" // + " hour"
:(n/=24)<7? // Else-if `n` is below 60*60*24*7:
n // Integer-divide `n` by 60*60*24, and output it
+" day" // + " day"
:n<31? // Else-if `n` is below 60*60*24*31:
(n/=7) // Integer-divide `n` by 60*60*24*7, and output it
+" week" // + " week"
:n<365? // Else-if `n` is below 60*60*24*365:
(n/=31) // Integer-divide `n` by 60*60*24*31, and output it
+" month" // + " month"
: // Else:
(n/=365) // Integer-divide `n` by 60*60*24*365, and output it
+" year") // + " year"
+(n>1?"s":"") // And add a trailing (plural) "s" if (the new) `n` is larger than 1
```
[Answer]
# [Kotlin](https://kotlinlang.org), ~~205~~ ~~203~~ 196 bytes
```
x->val d=86400
with(listOf(1 to "second",60 to "minute",3600 to "hour",d to "day",d*7 to "week",d*31 to "month",d*365 to "year").last{x>=it.first}){val c=x/first
"$c ${second+if(c>1)"s" else ""}"}
```
[Try it online!](https://tio.run/##ZZBBboMwEEX3nMKysrAbkpoALo0E@6666AksMMGKMZU9JESIs1MwuzLSSPPfSF9/5t6BVmaue4NaoQx5CCvsDS3trugHrDI3isYALfUQGtVXMly/DNBTsS3zcR5Oxbqq8ownjAVPBQ3RysF3TSIEHcJOlp2pcMiZl60yPUgcxpxtoOl6i8PKz5V4LePbhxdPKe@rijeftjPQeM1TD15SWEzPWjgYhyJXcK6VdTDRcQ1U5sO71wE@lOgwbjGOqiZlEVHsMJLaSYTxhKd5CvyNv8tNoA1ZolP6j6SfO8TZDiXxhe3p@pq9Y5RFKWfxnicXzmOeeaNp/gM "Kotlin – Try It Online")
[Answer]
# [T-SQL](https://www.microsoft.com/sql-server), 306 bytes (281 bytes without I/O)
```
DECLARE @n INT=1
DECLARE @r VARCHAR(30)=TRIM(COALESCE(STR(NULLIF(@n/31536000,0))+' year',STR(NULLIF(@n/2678400,0))+' month',STR(NULLIF(@n/604800,0))+' week',STR(NULLIF(@n/86400,0))+' day',STR(NULLIF(@n/3600,0))+' hour',STR(NULLIF(@n/60,0))+' minute',STR(@n)+' second'))IF LEFT(@r,2)>1 SET @r+='s'
PRINT @r
```
[Answer]
# [R](https://www.r-project.org/), 157 bytes
```
function(n,x=cumprod(c(1,60,60,24,7,31/7,365/31)),i=cut(n,x),o=n%/%x[i])cat(o," ",c("second","minute","hour","day","week","year")[i],"if"(o>1,"s",""),sep="")
```
[Try it online!](https://tio.run/##FYtRCoMwEESvIguFDWzRVGv7UXuR0g@JCQ3FrMSE6unTFYZ5wzATi6se5@JyMMlzwEDbYPK8RJ7QoKa@OXTp6EatrsX6a91qpcjLLB1zRTyEU33aXv6tzJiQCSogg7Baw2ECgtmHnKyED@comMZd/GftV7DbMYKSM4F3gPzUBKv0oGi1yyAsDu9912hV/g "R – Try It Online")
`cut` is handy, since it splits ranges into `factor`s, which are stored internally as `integer`s, meaning we can use them as array indices as well. We can probably do something a bit more clever with the time period names, but I can't figure it out just yet.
[Answer]
# APL+WIN, ~~88~~ 119 bytes
Original version missed out weeks and months as pointed out by Phil H;(
Prompts screen input of number of seconds
```
a←⌽<\⌽1≤b←⎕÷×\1 60 60 24 7,(31÷7),365÷31⋄b,(-(b←⌊a/b)=1)↓∊a/'seconds' 'minutes' 'hours' 'days' 'weeks' 'months' 'years'
```
Explanation
```
b←⎕÷×\1 60 60 24 7,(31÷7),365÷31 prompts for input and converts to years, days, hours, minutes, seconds
a←⌽<\⌽1≤b identify largest unit of time and assign it to a
a/'years' 'days' 'hours' 'minutes' 'seconds' select time unit
(-(b←⌊a/b)=1)↓∊ determine if singular if so drop final s in time unit
b, concatenate number of units to time unit from previous steps
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 177 bytes
```
x=>{return d=86400,v=[[d*365,'year'],[d*31,'month'],[d*7,'week'],[d,'day'],[3600,'hour'],[60,'minute'],[1,'second']].find(i=>x>=i[0]),c=parseInt(x/v[0]),c+' '+v[1]+(c>1?'s':'')}
```
[Try it online!](https://tio.run/##bZDBUoMwFEX3fkV3DyStSQOR6gTXfgOTRYYEG22TThKQjuO3I9CVU3b3nDf3Lt6n7GVovLnErXVKjy0fB179eB07bzeKlyzHGPW8rtUjZQWCq5YeBJqRIDg7G483fEbwrfXXAgiUvM6JsqkNR9ctHTbls7Fd1DNN9aAbZxUIsWuNVYnh1VBxU2ORooZfpA/63cZkeOpvKoMNZH1NRJY0FXmDAC8A6e84jQR30ruT@0jahKTp68N/VRzuHcP3Lqd7vKLnJ6yskpIUDNOVQ75njLJy2Rr/AA "JavaScript (Node.js) – Try It Online")
[Answer]
## Batch, 185 bytes
```
@for %%t in (1.second 60.minute 3600.hour 43200.day 302400.week, 1339200.month, 15768000.year)do @if %1 geq %%~nt set/an=%1/%%~nt&set u=%%~xt
@if %n% gtr 1 set u=%u%s
@echo %n%%u:.= %
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~146~~ 144 bytes
```
lambda n,d=86400:[`n/x`+' '+y+'s'*(n/x>1)for x,y in zip([365*d,31*d,7*d,d,3600,60,1],'year month week day hour minute second'.split())if n/x][0]
```
[Try it online!](https://tio.run/##FY/BboMwEETPzVfszRBW6RqDSyKRH6FIobURVpM1AkeN@/PUHHa0M4d5u3MMk@dyG9vP7T48vswAjKZtdEV06W78/roVAkQRC7GKY5b8VeajX@CFERzDn5uzTun6aFDJJB9p0qqJUBPKHkW0wwIPz2GCX2t/wAwRJv9MmeNnsLDab89GnNb57kKW526EROk76redwzulk1if90KoVJmqYb9PIshG1poUyqrUWumGqL8c3ubFcUhvgGivAmHMOD9s/w "Python 2 – Try It Online")
2 bytes saved thanks to Jonathan Allan
[Answer]
# [PHP](https://php.net/), 183 bytes
```
<?$a=[second=>$l=1,minute=>60,hour=>60,day=>24,week=>7,month=>31/7,year=>365/31];foreach($a as$p=>$n){$q=$n*$l;if($q<=$s=$argv[1])$r=($m=floor($s/$q))." $p".($m>1?s:"");$l=$q;}echo$r;
```
[Try it online!](https://tio.run/##HY7BisIwFEV/RcpbNBLtxEyVTnzxQ8RFqKkptnlpUmeQYX7dWGZ3ORwON7iQ8/EEBs/JtuSvqGFAwcfeP2aLev/BHT3i/7iaJ@rdJ/@x9o76wEfys0MtRXXgT2sWSe7rSoqL6iha07oSzMokCEvTs1@YEPwaBtV3JUxHhIRg4u37LC4MIpYwYjcQxRJSBRNj22IFodguXItT@ioKppZrMKk/2zqCqHLOUtSybprmRWHuyae88W8)
[Answer]
# [Julia 0.6](http://julialang.org/), 161 bytes
```
f(n,d=cumprod([1,60,60,24,7,31/7,365/31]),r=div.(n,d),i=findlast(r.>=1),l=Int(r[i]))="$l $(split("second minute hour day week month year",' ')[i])$("s"^(l>1*1))"
```
[Try it online!](https://tio.run/##VY3RisMgEEXf@xUigWqR1onJbPpg3/cbSguhGmrXmGBMl359NnlahGHg3DuHec3etbgsHQvC6Mfcj3Ew7AoC5TZlJb6EgtO6sD4puHERtXHv43bOhdOdC8a3U2LxeNHAhdffYYWru3GuaeFJwabRu8ToZB9DMKR3YU6WPIc5EtN@yK@1P6QfQnqSj20jFXuy55terAq9M3@BA3BOlzG6kHxgHVtx90/1OUOUGQLkNZR5X6lS5kmDlcw/QAM1SpVnVYmosNnk5Q8 "Julia 0.6 – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 129 bytes
```
->n{x=[365*d=24*k=3600,d*31,d*7,d,k,60,1].index{|j|0<d=n/k=j};"#{d} #{%w{year month week day hour minute second}[x]}#{d>1??s:p}"}
```
[Try it online!](https://tio.run/##VZDdboMwDIXv@xQW1VSpyrqEQMa60T4I4oKRdKRoCSqgUgHPzsLPgObCiv2dYzu5ld@P7uJ3rydVV35Ambvnvu3sU58yjBHfU2LCO@IoRQwjEh6k4qKqm2uDv7iv3lL/2n5a25q3sK1f7vVDRDf41apI4C5ECjx6QKJLU5OqLATkItaKt0EVtsZ0Iudzfsxaq@2CDUBAYD4ILDKpLYAQ9dj9WGOTjTy3Rszws3scObsdamO8YHvYK5@xxxxMVm6zuTVkIyYecRmmE6bD63rzP3ZsxijzzASDHRf6jxiab8KDiOIEuIZGIt0YdXaTqoCdVFlZHPuOu75YFjnIhf7oka3oJZDhIhBVJuJC8OMi0NNlIxTv/gA "Ruby – Try It Online")
[Answer]
# [Perl 6/Rakudo](https://perl6.org/) 138 bytes
I'm sure there's further to go, but for now
```
{my @d=(365/31,31/7,7,24,60,60);$_/[[email protected]](/cdn-cgi/l/email-protection) while @d&&$_>@d[*-1];$_.Int~" "~ <year month week day hour minute second>[+@d]~($_>1??"s"!!"")}
```
Explicate:
```
{ # bare code block, implicit $_ input
my @d=(365/31,31/7,7,24,60,60); # ratios between units
$_ /= @d.pop while @d && $_ > @d[*-1]; # pop ratios off @d until dwarfed
$_.Int~ # implicitly output: rounded count
" "~ # space
<year month week day hour minute second>[+@d]~ # unit given @d
($_>1??"s"!!"") # plural
}
```
[Answer]
# R, 336
Working in progress
```
function(x){
a=cumprod(c(1,60,60,24,7,31/7,365/31))
t=c("second","minute","hour","day","week","month")
e=as.data.frame(cbind(table(cut(x,a,t)),a,t))
y=x%/%as.integer(as.character(e$a[e$V1==1]))
ifelse(x>=a[7],paste(x%/%a[7],ifelse(x%/%a[7]==1,"year","years")),
ifelse(y>1,paste(y,paste0(e$t[e$V1==1],"s")),paste(y,e$t[e$V1==1])))}
```
[Answer]
# [R](https://www.r-project.org/), 246 bytes
```
f=function(x,r=as.integer(strsplit(strftime(as.POSIXlt(x,"","1970-01-01"),"%Y %m %V %d %H %M %S")," ")[[1]])-c(1970,1,1,1,1,0,0),i=which.max(r>0)){cat(r[i],paste0(c("year","month","week","day","hour","minute","second")[i],ifelse(r[i]>1,"s","")))}
```
[Try it online!](https://tio.run/##LU3BasMwDL3vK4zBYINb7CTN0kN63g5jg8LYCDkEx17MEqfYDm0Z@/ZMMUPi6UnvSfLramqzOBXt7OiN@7oLe@ui/tKehujDZbRxIybaSVMQ317Pzx9jBC/GHMvjo9gJCYkZx@QTkQmRd0R6RJ4QeUHkvM0RZk0j25btFN02uPwPwQXjtr4OVg37qbtRfxKM/aguUt/Yll@6ELWgiuK77jz8m2YXB6hXrb@h9N0dcJiXpFm3RA0kaDW7Hn7CBWv0GHS6dpIggYwZY7@roZI9GHo4bliKDaVMjcxSV@SZSKQqC5G8spKHUuSJFllZ5mUFjvUP "R – Try It Online")
This is using time formating instead of arithemtics, just for the hell of it. Maybe others could make this smaller?
] |
[Question]
[
The [Chaos Game](http://en.wikipedia.org/wiki/Chaos_game) is a simple method to generate fractals. Given a starting point, a length ratio *r* and a set of 2D points, repeatedly do the following:
* From your set of points, pick one at random (uniformly).
* Average that point and the last drawn point (or the starting point) using *r* and *1 - r* as the weights (i.e. *r = 0* means you get the starting point, *r = 1* means you get the random point and *r = 0.5* means you get the point halfway in between.)
* Draw the resultant point.
For instance, if you picked the vertices of an equilateral triangle and *r = 0.5*, the plotted points would map out a Sierpinski triangle:

[Image found on Wikipedia](http://en.wikipedia.org/wiki/Chaos_game#mediaviewer/File:Sierpinski_chaos_animated.gif)
You're to write a program or function which "plays" the chaos game to create a fractal.
## Input
You may write either a program or a function, and take following inputs via ARGV, STDIN or function argument:
* The number of points to plot.
* The starting coordinate (which has to be plotted, too!).
* The averaging weight *r* in the interval *[0,1]*.
* A list of points to choose from.
## Output
You may render on screen or write an image file. If the result is rasterised, it needs to be at least 600 pixels on each side, all points must be on the canvas, and at least 75% of the horizontal and vertical extent of the image must be used for points (this is to avoid answers with a single black pixels saying "it's really far zoomed out"). The *x* and *y* axis must be on the same scale (that is the line from (0,0) to (1,1) must be at a 45 degree angle) and each point plotted in the chaos game must be represented as a single pixel (if your plotting method anti-aliases the point, it may be spread over 2x2 pixels).
Colours are your choice, but you need at least two distinguishable colours: one for the background and one for the dots plotted during the chaos game. You may but don't have to plot the input points.
Please include *three* interesting example outputs in your answer.
## Scoring
This is code golf, so the shortest answer (in bytes) wins.
**Edit:** You no longer need to plot the input points, as they aren't really visible as single pixels anyway.
[Answer]
# Java : 246 ~~253~~ ~~447~~
As a function `m()`:
```
void m(float[]a){new java.awt.Frame(){public void paint(java.awt.Graphics g){int i=0,x=i,y=i,v;for(setSize(832,864),x+=a[1],y+=a[2];i++<=a[0];v=a.length/2-2,v*=Math.random(),x+=(a[v+=v+4]-x)*a[3],y+=(a[v+1]-y)*a[3])g.drawLine(x,y,x,y);}}.show();}
```
Line breaks (within a program to show usage):
```
class P{
public static void main(String[]a){
new P().m(new float[]{1000000, // iterations
416,432, // start
0.6f, // r
416,32,16,432, // point list...
416,832,816,432,
366,382,366,482,
466,382,466,482});
}
void m(float[]a){
new java.awt.Frame(){
public void paint(java.awt.Graphics g){
int i=0,x=i,y=i,v;
for(setSize(832,864),x+=a[1],y+=a[2];
i++<=a[0];
v=a.length/2-2,v*=Math.random(),
x+=(a[v+=v+4]-x)*a[3],
y+=(a[v+1]-y)*a[3])
g.drawLine(x,y,x,y);
}
}.show();
}
}
```
Drawing input points was removed from the requirements (yay 80 bytes!). They're still shown in the old screenshots below, but won't show up if you run it. See revision history if interested.
The inputs are given as an array of floats. The first is iterations, the next two are starting `x y`. Fourth is `r`, and last comes the list of coordinates, in `x1 y1 x2 y2 ...` fashion.
**Ninja Star**
```
1000000 400 400 0.6 400 0 0 400 400 800 800 400 350 350 350 450 450 350 450 450
```

**Cross**
```
1000000 400 400 0.8 300 0 500 0 500 300 800 300 800 500 500 500 500 800 300 800 300 500 0 500 0 300 300 300
```

**Octochains**
```
1000000 400 400 0.75 200 0 600 0 800 200 800 600 600 800 200 800 0 600 0 200
```

[Answer]
# Mathematica, 89
```
f[n_,s_,r_,p_]:=Graphics@{AbsolutePointSize@1,Point@NestList[#-r#+r RandomChoice@p&,s,n]}
f[10000, {0, 0}, .5, {{-(1/2), Sqrt[3]/2}, {-(1/2), -(Sqrt[3]/2)}, {1, 0}}]
```

## How it works
In Mathematica the `Graphics[]` function produces scalable graphics, you render it to whatever size you want by simply dragging the picture corners. In fact, the initial size of all displayed graphics is a ".ini" setting that you may set at 600 or at any other value you wish. So there is no need to do anything special for the 600x600 requirement.
The `AbsolutePointSize[]` thing specifies that the point size will not be modified by enlarging the image size.
The core construct is
```
NestList[#-r#+r RandomChoice@p&,s,n]
```
or in non-golfed pseudo-code:
```
NestList[(previous point)*(1-r) + (random vertex point)*(r), (start point), (iterations)]
```
It is recursively building a list starting from `(start point)` and applying the (vectorial) function in the first argument to each successive point, finally returning the list of all calculated points to be plotted by `Point[]`
## Some self-replication examples:
```
Grid@Partition[Table[
pts = N@{Re@#, Im@#} & /@ Table[E^(2 I Pi r/n), {r, 0, n - 1}];
Framed@f[10000, {0, 0}, 1/n^(1/n), pts], {n, 3, 11}], 3]
```

[Answer]
# JavaScript (E6) + Html 173 ~~176 193~~
Edit: big cut, thanks to William Barbosa
Edit: 3 bytes less, thanks to DocMax
173 bytes counting the function and the canvas element needed to show the output.
**Test** save as html file and open in FireFox.
[JSFiddle](http://jsfiddle.net/8nkqxsyd/27/)

---

---

---

---
```
<canvas id=C>
<script>
F=(n,x,y,r,p)=>{
for(t=C.getContext("2d"),C.width=C.height=600;n--;x-=(x-p[i])*r,y-=(y-p[i+1])*r)
i=Math.random(t.fillRect(x,y,1,1))*p.length&~1
}
F(100000, 300, 300, 0.66, [100,500, 500,100, 500,500, 100,100, 300,150, 150,300, 300,450, 450,300]) // Function call, not counted
</script>
```
[Answer]
# Python - ~~200~~ 189
```
import os,random as v
def a(n,s,r,z):
p=[255]*360000
for i in[1]*(n+1):
p[600*s[0]+s[1]]=0;k=v.choice(z);s=[int(k[i]*r+s[i]*(1-r))for i in(0,1)]
os.write(1,b'P5 600 600 255 '+bytes(p))
```
Takes input as function arguments to a, writes result to stdout as pgm file.
`n` is iterations, `s` is starting point, `r` is r, and `z` is list of input points.
Edit: No longer draws input points in gray.
## Interesting outputs:

```
Iterations: 100000
Starting Point: (200, 200)
r: 0.8
Points: [(0, 0), (0, 599), (599, 0), (599, 599), (300, 300)]
```
---

```
Iterations: 100000
Starting Point: (100, 300)
r: 0.6
Points: [(0, 0), (0, 599), (599, 0), (300, 0), (300, 300), (0, 300)]
```
---

```
Iterations: 100000
Starting Point: (450, 599)
r: 0.75
Points: [(0, 0), (0, 300), (0, 599), (300, 0), (599, 300), (150, 450)]
```
[Answer]
## SuperCollider - 106
[SuperCollider](http://supercollider.sourceforge.net/) is a language for generating music, but it can do graphics at a pinch.
```
f={|n,p,r,l|Window().front.drawHook_({{Pen.addRect(Rect(x(p=l.choose*(1-r)+(p*r)),p.y,1,1))}!n;Pen.fill})}
```
I've used some obscure syntax shortcuts to save a few bytes - a more readable and more memory-efficient version is
```
f={|n,p,r,l|Window().front.drawHook_({n.do{Pen.addRect(Rect(p.x,p.y,1,1));p=l.choose*(1-r)+(p*r)};Pen.fill})}
```
at 109 chars.
As with the Mathematica example, you have to manually resize the window to get 600x600 pixels. You have to wait for it to re-draw when you do this.
This generates a basic Sierpinsky triangle (not shown because you've seen it before)
```
f.(20000,100@100,0.5,[0@600,600@600,300@0])
```
This makes a kind of Sierpinsky pentagon type thing:
```
f.(100000,100@100,1-(2/(1+sqrt(5))),{|i| (sin(i*2pi/5)+1*300)@(1-cos(i*2pi/5)*300)}!5)
```

The same thing with 6 points leaves an inverted Koch snowflake in the middle:
```
f.(100000,100@100,1/3,{|i| (sin(i*2pi/6)+1*300)@(1-cos(i*2pi/6)*300)}!6)
```

Finally, here's a riff on the 3D pyramids from ace's answer. (Note that I've used one of the points twice, to get the shading effect.)
```
f.(150000,100@100,0.49,[300@180, 0@500,0@500,350@400,600@500,250@600])
```

[Answer]
# Python, ~~189~~ ~~183~~ 175
**Edit:** fixed the inversed *r* ratio, and switched to B&W image in order to save a few bytes.
Takes the number of points as `n`, first point as `p`, ratio as `r` and list of points as `l`.
Needs the module Pillow.
```
import random,PIL.Image as I
s=850
def c(n,p,r,l):
i=I.new('L',(s,s));x,y=p;
for j in range(n):w,z=random.choice(l);w*=r;z*=r;x,y=x-x*r+w,y-y*r+z;i.load()[x,s-y]=s
i.show()
```
Examples:
I am generating points in circle around the image's center
```
points = [(425+s*cos(a)/2, 425+s*sin(a)/2) for a in frange(.0, 2*pi, pi/2)]
c(1000000, (425, 425), 0.4, points)
```

XOXO repetitions, just changing ratio from 0.4 to 0.6

Some sort of snow flake
```
stars = [(425+s*cos(a)/2,425+s*sin(a)/2) for a in frange(.0,2*pi, pi/4)]
c(1000000, (425, 425), 0.6, stars)
```

[Answer]
# JavaScript (407) (190)
I'm happy to get any feedback on my script and on golfing since I am not comfortable with JS=) (Feel free to use this/change it for your own submission!)
**Reading Input** (To be comparable to [edc65](https://codegolf.stackexchange.com/a/38201/24877)'s entry I do not count the the input.):
```
p=prompt;n=p();[x,y]=p().split(',');r=p();l=p().split(';').map(e=>e.split(','));
```
**Canvas Setup & Calculation**
```
d=document;d.body.appendChild(c=d.createElement('canvas'));c.width=c.height=1000;c=c.getContext('2d');
for(;n--;c.fillRect(x,y,2,2),[e,f]= l[Math.random()*l.length|0],x-=x*r-e*r,y-=y*r-f*r);
```
Somewhat more ungolfed (including an example input where the real input promts are just commented out, so ready to use):
```
p=prompt;
n=p('n','4000');
[x,y]=p('start','1,1').split(',');
r=p('r','0.5');
l=p('list','1,300;300,1;300,600;600,300').split(';').map(e=>e.split(','));d=document;
d.body.appendChild(c=d.createElement('canvas'));
c.width=c.height=1000;c=c.getContext('2d');
for(;n--;c.fillRect(x,y,2,2),[e,f]= l[Math.random()*l.length|0],x-=x*r-e*r,y-=y*r-f*r);
```
## Examples
```
for(k = 0; k<50; k++){
rad = 10;
l.push([350+rad*k*Math.cos(6.28*k/10),350+rad*k*Math.sin(6.28*k/10)]);
}
r = 1.13;
```

```
r = 0.5;list = [[1,1],[300,522],[600,1],[300,177]];
```

```
r = 0.5
list = [[350+350*Math.sin(6.28*1/5),350+350*Math.cos(6.28*1/5)],
[350+350*Math.sin(6.28*2/5),350+350*Math.cos(6.28*2/5)],
[350+350*Math.sin(6.28*3/5),350+350*Math.cos(6.28*3/5)],
[350+350*Math.sin(6.28*4/5),350+350*Math.cos(6.28*4/5)],
[350+350*Math.sin(6.28*5/5),350+350*Math.cos(6.28*5/5)],
[350+90*Math.sin(6.28*1.5/5),350+90*Math.cos(6.28*1.5/5)],
[350+90*Math.sin(6.28*2.5/5),350+90*Math.cos(6.28*2.5/5)],
[350+90*Math.sin(6.28*3.5/5),350+90*Math.cos(6.28*3.5/5)],
[350+90*Math.sin(6.28*4.5/5),350+90*Math.cos(6.28*4.5/5)],
[350+90*Math.sin(6.28*5.5/5),350+90*Math.cos(6.28*5.5/5)]];
```

[Answer]
## Processing, 153
Ported @Geobits' Java answer to Processing and did some more golfing, resulting in a reduction of 100 chars. I originally intended to animate the process, but the input constraints are too harsh on this (Processing does not have stdin or argv, which means that I must write my own function instead of using Processing's native `draw()` loop).
```
void d(float[]a){int v;size(600,600);for(float i=0,x=a[1],y=a[2];i++<a[0];v=(int)random(a.length/2-2),point(x+=(a[v*2+4]-x)*a[3],y+=(a[v*2+5]-y)*a[3]));}
```
Complete program with line breaks:
```
void setup() {
d(new float[]{100000,300,300,.7,0,600,600,0,600,600,0,0,400,400,200,200,400,200,200,400});
}
void d(float[]a){
int v;
size(600,600);
for(float i=0,x=a[1],y=a[2];
i++<a[0];
v=(int)random(a.length/2-2),point(x+=(a[v*2+4]-x)*a[3],y+=(a[v*2+5]-y)*a[3]));
}
```
Above program gives Crosses:

```
d(new float[]{100000,300,300,.65,142,257,112,358,256,512,216,36,547,234,180,360});
```
This gives Pyramids:

```
d(new float[]{100000,100,500,.5,100,300,500,100,500,500});
```
This gives Sierpinski triangle:

[Answer]
## Ungolfed "reference implementation", Python
**Update**: much, much faster (by orders of magnitude)
**Check out the interactive shell!**
Edit the file and set `interactive` to `True`, then do one of these:
`polygon numberOfPoints numeratorOfWeight denominatorOfWeight startX startY numberOfSides` generates, saves and displays a polygon.
`points numberOfPoints numeratorOfWeight denominatorOfWeight startX startY point1X point1Y point2X point2Y ...` does what the spec asks for.

```
import matplotlib.pyplot as plt
import numpy as np
from fractions import Fraction as F
import random
from matplotlib.colors import ColorConverter
from time import sleep
import math
import sys
import cmd
import time
def plot_saved(n, r, start, points, filetype='png', barsize=30, dpi=100, poly=True, show=False):
printed_len = 0
plt.figure(figsize=(6,6))
plt.axis('off')
start_time = time.clock()
f = F.from_float(r).limit_denominator()
spts = []
for i in range(len(points)):
spts.append(tuple([round(points[i].real,1), round(points[i].imag,1)]))
if poly:
s = "{}-gon ({}, r = {}|{})".format(len(points), n, f.numerator, f.denominator)
else:
s = "{} ({}, r = {}|{})".format(spts, n, f.numerator, f.denominator)
step = math.floor(n / 50)
for i in range(len(points)):
plt.scatter(points[i].real, points[i].imag, color='#ff2222', s=50, alpha=0.7)
point = start
t = time.clock()
xs = []
ys = []
for i in range(n+1):
elapsed = time.clock() - t
#Extrapolation
eta = (n+1-i)*(elapsed/(i+1))
printed_len = rewrite("{:>29}: {} of {} ({:.3f}%) ETA: {:.3f}s".format(
s, i, n, i*100/n, eta), printed_len)
xs.append(point.real)
ys.append(point.imag)
point = point * r + random.choice(points) * (1 - r)
printed_len = rewrite("{:>29}: plotting...".format(s), printed_len)
plt.scatter(xs, ys, s=0.5, marker=',', alpha=0.3)
presave = time.clock()
printed_len = rewrite("{:>29}: saving...".format(s), printed_len)
plt.savefig(s + "." + filetype, bbox_inches='tight', dpi=dpi)
postsave = time.clock()
printed_len = rewrite("{:>29}: done in {:.3f}s (save took {:.3f}s)".format(
s, postsave - start_time, postsave - presave),
printed_len)
if show:
plt.show()
print()
plt.clf()
def rewrite(s, prev):
spaces = prev - len(s)
sys.stdout.write('\r')
sys.stdout.write(s + ' '*(0 if spaces < 0 else spaces))
sys.stdout.flush()
return len(s)
class InteractiveChaosGame(cmd.Cmd):
def do_polygon(self, args):
(n, num, den, sx, sy, deg) = map(int, args.split())
plot_saved(n, (num + 0.0)/den, np.complex(sx, sy), list(np.roots([1] + [0]*(deg - 1) + [-1])), show=True)
def do_points(self, args):
l = list(map(int, args.split()))
(n, num, den, sx, sy) = tuple(l[:5])
l = l[5:]
points = []
for i in range(len(l)//2):
points.append(complex(*tuple([l[2*i], l[2*i + 1]])))
plot_saved(n, (num + 0.0)/den, np.complex(sx, sy), points, poly=False, show=True)
def do_pointsdpi(self, args):
l = list(map(int, args.split()))
(dpi, n, num, den, sx, sy) = tuple(l[:6])
l = l[6:]
points = []
for i in range(len(l)//2):
points.append(complex(*tuple([l[2*i], l[2*i + 1]])))
plot_saved(n, (num + 0.0)/den, np.complex(sx, sy), points, poly=False, show=True, dpi=dpi)
def do_default(self, args):
do_generate(self, args)
def do_EOF(self):
return True
if __name__ == '__main__':
interactive = False
if interactive:
i = InteractiveChaosGame()
i.prompt = ": "
i.completekey='tab'
i.cmdloop()
else:
rs = [1/2, 1/3, 2/3, 3/8, 5/8, 5/6, 9/10]
for i in range(3, 15):
for r in rs:
plot_saved(20000, r, np.complex(0,0),
list(np.roots([1] + [0] * (i - 1) + [-1])),
filetype='png', dpi=300)
```
[Answer]
## Python (202 chars)
Takes the number of points as `n`, the averaging weight as `r`, the starting point as a `tuple` `s` and the list of points as a list of XY `tuple`s called `l`.
```
import random as v,matplotlib.pyplot as p
def t(n,r,s,l):
q=complex;s=q(*s);l=[q(*i)for i in l];p.figure(figsize=(6,6))
for i in range(n):p.scatter(s.real,s.imag,s=1,marker=',');s=s*r+v.choice(l)*(1-r)
p.show()
```
] |
[Question]
[
## Terms
A **worm** is any list of nonnegative integers, and its *rightmost* (i.e., *last*) element is called the **head**. If the head is not 0, the worm has an **active segment** consisting of *the longest contiguous block of elements that includes the head and has all of its elements at least as large as the head*. The **reduced active segment** is the active segment with the head decremented by 1. For example, the worm `3 1 2 3 2` has active segment `2 3 2`, and the reduced active segment is `2 3 1`.
## Rules of evolution
A worm evolves step-by-step as follows:
>
> In step t (= 1, 2, 3, ...),
> if
> the head is 0: delete the head
>
> else: replace the active segment by t+1
> concatenated copies of the reduced active segment.
>
>
>
**Fact**: *Any worm eventually evolves into the empty list*, and the number of steps to do so is the worm's **lifetime**.
(Details can be found in [*The Worm Principle*](http://dspace.library.uu.nl/handle/1874/27024), a paper by L. D. Beklemishev. The usage of "list" to mean a finite sequence, and "head" to mean its *last* element, is taken from this paper -- it should not be confused with the common usage for [lists as an abstract data type](https://en.wikipedia.org/wiki/List_(abstract_data_type)), where *head* usually means the *first* element.)
## Examples (active segment in parentheses)
**Worm: 0,1**
```
step worm
0(1)
1 0 0 0
2 0 0
3 0
4 <- lifetime = 4
```
**Worm: 1,0**
```
step worm
1 0
1 (1)
2 0 0 0
3 0 0
4 0
5 <- lifetime = 5
```
**Worm: 1,1**
```
step worm
(1 1)
1 1 0 1 0
2 1 0(1)
3 1 0 0 0 0 0
4 1 0 0 0 0
5 1 0 0 0
...
8 (1)
9 0 0 0 0 0 0 0 0 0 0
10 0 0 0 0 0 0 0 0 0
...
18 0
19 <- lifetime = 19
```
**Worm: 2**
```
step worm
(2)
1 (1 1)
2 1 0 1 0 1 0
3 1 0 1 0(1)
4 1 0 1 0 0 0 0 0 0
5 1 0 1 0 0 0 0 0
6 1 0 1 0 0 0 0
...
10 1 0(1)
11 1 0 0 0 0 0 0 0 0 0 0 0 0 0
12 1 0 0 0 0 0 0 0 0 0 0 0 0
...
24 (1)
25 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
...
50 0
51 <- lifetime = 51
```
**Worm: 2,1**
```
(2 1)
1 2 0 2 0
2 2 0(2)
3 2 0(1 1 1 1)
4 2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0
5 2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0(1 1 1)
6 2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0
7 2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0(1 1)
8 2 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0 1 1 0{1 0}^9
...
?? <- lifetime = ??
```
**Worm: 3**
```
step worm
(3)
1 (2 2)
2 (2 1 2 1 2 1)
3 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0
4 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1(2)
5 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0(2 1 2 1 1 1 1 1 1 1)
6 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0{2 1 2 1 1 1 1 1 1 0}^7
7 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0{2 1 2 1 1 1 1 1 1 0}^6 (2 1 2 1 1 1 1 1 1)
... ...
?? <- lifetime = ??
```
## Aside
Worm lifetimes are typically enormous, as shown by the following lower bounds in terms of the standard [fast-growing hierarchy](https://en.wikipedia.org/wiki/Fast-growing_hierarchy#Functions_in_fast-growing_hierarchies) of functions fα:
```
worm lower bound on lifetime
---------------- ------------------------------------------
11..10 (k 1s) f_k(2)
2 f_ω(2)
211..1 (k 1s) f_(ω+k)(2)
2121..212 (k 2s) f_(ωk)(2)
22..2 (k 2s) f_(ω^k)(2)
3 f_(ω^ω)(2)
...
n f_(ω^ω^..^ω)(2) (n-1 ωs) > f_(ε_0) (n-1)
```
Remarkably, worm [3] already has a lifetime that far surpasses [Graham's number](https://en.wikipedia.org/wiki/Graham%27s_number#Definition), G:
fωω(2) = fω2(2) = fω2(2) = fω+2(2) = fω+1(fω+1(2)) >> fω+1(64) > G.
## Code Golf Challenge
>
> Write the shortest possible function subprogram with the following
> behavior:
>
>
> **Input**: Any worm.
>
> **Output**: The lifetime of the worm.
>
>
> Code size is measured in bytes.
>
>
>
Here's an example (Python, golfs to about 167 bytes):
```
from itertools import *
def T(w):
w=w[::-1]
t=0
while w:
t+=1
if w[0]:a=list(takewhile(lambda e:e>=w[0],w));a[0]-=1;w=a*(t+1)+w[len(a):]
else:w=w[1:]
return t
```
**NB**:
If t(n) is the lifetime of the worm [n], then the rate of growth of t(n) is roughly that of [the Goodstein function](https://en.wikipedia.org/wiki/Goodstein%27s_theorem#Sequence_length_as_a_function_of_the_starting_value). So *if this can be golfed to below 100 bytes, it could well give a winning answer to the [Largest Number Printable](https://codegolf.stackexchange.com/questions/18028/largest-number-printable) question*. (For that answer, the growth-rate could be vastly accelerated by always starting the step-counter at n -- the same value as the worm [n] -- instead of starting it at 0.)
[Answer]
## GolfScript (56 54 chars)
```
{-1%0\{\)\.0={.0+.({<}+??\((\+.@<2$*\+}{(;}if.}do;}:L;
```
[Online demo](http://golfscript.apphb.com/?c=ey0xJTBce1wpXC4wPXsuMCsuKHs8fSs%2FP1woKFwrLkA8MiQqXCt9eyg7fWlmLn1kbzt9Okw7CgpbMSAxXUwgcApbMl1MIHA%3D)
I think that the key trick here is probably keeping the worm in reverse order. That means that it's pretty compact to find the length of the active segment: `.0+.({<}+??` (where the `0` is added as a guard to ensure that we find an element smaller than the head).
---
As an aside, some analysis of the worm lifespan. I'll denote the worm as `age, head tail` (i.e. in reverse order from the question's notation) using exponents to indicate repetition in the head and tail: e.g. `2^3` is `2 2 2`.
**Lemma**: for any active segment `xs`, there is a function `f_xs` such that `age, xs 0 tail` transforms into `f_xs(age), tail`.
Proof: no active segment can ever contain a `0`, so the age by the time we delete everything before the tail is independent of the tail and is hence a function only of `xs`.
**Lemma**: for any active segment `xs`, the worm `age, xs` dies at age `f_xs(age) - 1`.
Proof: by the previous lemma, `age, xs 0` transforms into `f_xs(age), []`. The final step is deletion of that `0`, which is not touched previously because it can never form part of an active segment.
With those two lemmata, we can study some simple active segments.
For `n > 0`,
```
age, 1^n 0 xs -> age+1, (0 1^{n-1})^{age+1} 0 xs
== age+1, 0 (1^{n-1} 0)^{age+1} xs
-> age+2, (1^{n-1} 0)^{age+1} xs
-> f_{1^{n-1}}^{age+1}(age+2), xs
```
so `f_{1^n} = x -> f_{1^{n-1}}^{x+1}(x+2)` (with base case `f_{[]} = x -> x+1`, or if you prefer `f_{1} = x -> 2x+3`). We see that `f_{1^n}(x) ~ A(n+1, x)` where `A` is the Ackermann–Péter function.
```
age, 2 0 xs -> age+1, 1^{age+1} 0 xs
-> f_{1^{age+1}}(age+1)
```
That's enough to get a handle on `1 2` (`2 1` in the notation of the question):
```
1, 1 2 -> 2, 0 2 0 2
-> 3, 2 0 2
-> f_{1^4}(4), 2
-> f_{1^{f_{1^4}(4)+1}}(f_{1^4}(4)+1) - 1, []
```
So given input `2 1` we expect output ~ `A(A(5,4), A(5,4))`.
```
1, 3 -> 2, 2 2
-> 3, 1 2 1 2 1 2
-> 4, 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2
-> 5, 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2 0 2 1 2 1 2
-> f_{21212}^4(5) - 1
age, 2 1 2 1 2 -> age+1, (1 1 2 1 2)^{age+1}
-> age+2, 0 1 2 1 2 (1 1 2 1 2)^age
-> age+3, 1 2 1 2 (1 1 2 1 2)^age
```
and I can really start to comprehend why this function grows so insanely.
[Answer]
### GolfScript, 69 62 characters
```
{0:?~%{(.{[(]{:^0=2$0+0=<}{\(@\+}/}{,:^}if;^?):?)*\+.}do;?}:C;
```
The function `C` expects the worm on the stack and replaces it by the result.
Examples:
```
> [1 1]
19
> [2]
51
> [1 1 0]
51
```
[Answer]
### Ruby — 131 characters
I know this can't compete with the GolfScript solutions above and I'm fairly sure that this can be reduced a score or more characters, but honestly I'm happy to have been able to solve the problem ungolfed. Great puzzle!
```
f=->w{t=0;w.reverse!;until w==[];t+=1;if w[0]<1;w.shift;else;h=w.take_while{|x|x>=w[0]};h[0]-=1;w.shift h.size;w=h*t+h+w;end;end;t}
```
My pre-golfed solution from which the above is derived:
```
def life_time(worm)
step = 0
worm.reverse!
until worm.empty?
step += 1
if worm.first == 0
worm.shift
else
head = worm.take_while{ |x| x >= worm.first }
head[0] -= 1
worm.shift(head.size)
worm = head * (step + 1) + worm
end
end
step
end
```
[Answer]
# [Sclipting](http://esolangs.org/wiki/Sclipting) (43 characters)
```
글坼가⑴감套擘終長①加⒈丟倘⓶增⓶가采⓶擘❷小終⓷丟❶長貶❷가掊貶插①增復合감不가終終
```
This expects the input as a space-separated list. This outputs the correct answer for `1 1` and `2`, but for `2 1` or `3` it takes too long so I gave up waiting for it to finish.
With commentary:
```
글坼 | split at spaces
가⑴ | iteration count = 0
감套 | while:
擘終長①加⒈丟 | remove zeros from end and add to iteration count
倘 | if the list is not empty:
⓶增⓶ | increment iteration count
가采⓶擘❷小終⓷丟 | separate out active segment
❶長貶❷가掊貶插 | compute reduced active segment
①增復合 | repeat reduced active segment and concat
감 | continue while loop
不 | else
가 | stop while loop
終 | end if
終 | end while
```
[Answer]
# k (83)
`worm:{-1+*({x,,(,/((x+:i)#,@[y@&w;(i:~~#y)#0;-1+]),y@&~w:&\~y<*y;1_y)@~*y}.)/(1;|,/x)}`
this can probably be golfed further, as it just implements the recurrence fairly straightforwardly.
the basic evolution function, `{x,,(,/((x+:i)#,@[y@&w;(i:~~#y)#0;-1+]),y@&~w:&\~y<*y;1_y)@~*y}`, is 65 chars, and uses some tricks to stop incrementing the age when the worm dies. the wrapper coerces an input of a single integer to a list, reverses the input (it's shorter to write the recurrence in terms of a worm reversed from your notation), asks for the fixpoint, selects the age as the output, and adjusts the result to account for the overshoot in the last generation.
if i do the coercion and reversal manually, it drops to 80 (`{-1+*({x,,(,/((x+:i)#,@[y@&w;(i:~~#y)#0;-1+]),y@&~w:&\~y<*y;1_y)@~*y}.)/(1;x)}`).
some examples:
```
worm 1 1 0
51
worm 2
51
worm 1 1
19
```
unfortunately, it's probably not much use for [Largest Number Printable](https://codegolf.stackexchange.com/questions/18028/largest-number-printable), except in a very theoretical sense, as it's quite slow, limited to 64-bit integers, and probably not particularly memory-efficient.
in particular, `worm 2 1` and `worm 3` just churn (and would probably throw `'wsfull` (out of memory) if i let them keep going).
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 52 [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")
Saved 7 bytes thanks to @ngn and @Adám.
```
0{⍬≡⍵:⍺⋄n←⍺+1⋄0=⊃⍵:n∇1↓⍵⋄n∇∊(⊂1n/-∘1@1¨)@1⊆∘⍵⍳⍨⌊\⍵}⌽
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///36D6Ue@aR50LH/VutXrUu@tRd0veo7YJQJa2IZBtYPuoqxkklfeoo93wUdtkIBuspKP9UUeXxqOuJsM8fd1HHTMMHQwPrdB0MHzU1QbkgVT1bn7Uu@JRT1cMkFP7qGfv/zSwuX2P@qZ6@gNNPbTe@FHbRCAvOMgZSIZ4eAb/T1MwVDDkApMKBkBaxwgA "APL (Dyalog Unicode) – Try It Online")
Explanation:
```
0{...}⌽ ⍝ A monadic function train. We define a recursive function with two
⍝ arguments: zero (our counter), and the reverse of our input
⍬≡⍵:⍺ ⍝ Our base case - if our input is an empty list, return our counter
n←⍺+1 ⍝ Define 'n' as our counter plus 1
0=⊃⍵:n∇1↓⍵ ⍝ If the first element of the input is zero, recurse with the tail
⍝ of our input and n
⌊\⍵ ⍝ Minimum-expand: creates a new list from our input where each element
⍝ is the incremental minimum
⍳⍨ ⍝ Applies above to both sides of the index-of function. Index-of returns
⍝ the index of the first occurence of each element in the left-side list.
⍝ At this point, a (reversed) input list of [3 4 5 2 3 4] would result
⍝ in [1 1 1 4 4 4]
⊆∘⍵ ⍝ Partition, composed with our input. Partition creates sublists of the
⍝ right input whenever the integer list in the left input increases.
⍝ This means we now have a list of sub-lists, with the first element
⍝ being the worm's active segment.
(...)@1 ⍝ Take the active segment and apply the following function train...
-∘1@1¨ ⍝ Subtract 1 from the first element of the active segment
1n/ ⍝ Replicate the resultant list above n+1 times
⊂ ⍝ Enclose the above, so as to keep the original shape of our sub-array
∊ ⍝ Enlist everything above together - this recursively concatenates our
⍝ new active segment with the remainder of the list
n∇ ⍝ Recurse with the above and n
```
[Answer]
# Scala, 198
```
type A=List[Int]
def T(w:A)={def s(i:Int,l:A):Stream[A]=l match{case f::r=>l#::s(i+1,if(f<1)r
else{val(h,t)=l.span(_>=l(0));List.fill(i)(h(0)-1::h.tail).flatten++t})
case _=>Stream()};s(2,w).length}
```
Usage:
```
scala> T(List(2))
res0: Int = 51
```
[Answer]
# K, 95
```
{i::0;#{~x~,0}{((x@!b),,[;r]/[i+:1;r:{@[x;-1+#x;-1+]}@_(b:0^1+*|&h>x)_x];-1_x)@0=h:*|x:(),x}\x}
```
.
```
k)worm:{i::0;#{~x~,0}{((x@!b),,[;r]/[i+:1;r:{@[x;-1+#x;-1+]}@_(b:0^1+*|&h>x)_x];-1_x)@0=h:*|x:(),x}\x}
k)worm 2
51
k)worm 1 1
19
q)worm 1 1 0 0 0 0
635
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 396 bytes
```
#define K malloc(8)
typedef*n;E(n e,n o){n s=K,t=s;for(*s=*o;o=o[1];*t=*o)t=t[1]=K;t[1]=e;e=s;}main(c,f,l,j,a)n*f;{n w=K,x=w;for(;l=--c;x=x[1]=K)*x=atoi(f[c]);for(;w&&++l;)if(*w){n v=K,z=v,u=w,t=K;for(a=*v=*w;(u=u[1])&&*u>=*w;*z=*u)z=z[1]=K;for(x=v[1],v=K,*v=a-1,1[u=v]=x;u;u=u[1])w=w[1];for(j=~l;j++;)u=t=E(t,v);for(;(u=u[1])&&(x=u[1])&&x[1];);u[1]=0;w=w?E(w,t):t;}else w=w[1];printf("%d",--l);}
```
[Try it online!](https://tio.run/##RY/BbsMgEETv/QorVS3AWKrbS9XVtqec/AlRDhaByBGBKAbjuko/vRQcSz3BrGbezor6KESMjwepeiOLtjh3WltB3uiD@7rINGYGtsQUkpvC0m9TDNhyhwMoeyVsQGbBot01e2AuCerQJYEtLI8Emay3c9cbIrjimp94Rw1TkEghkSYMCwk01rWACaclTdmEnbM9UTuxp3dHKMuq0kB7RVjITcaUn3HkHkNq1C6uDtmILADx6BOJliXzH3nAZmSezjjf22XvhGMSPGNSqKsb3uw8jnucwMOaDxjybdl@wh8Np6oC6tHhljg@rs3@lyXm@st3AIWs8BkS5nNLUk367uAm9SCLlXy59sYpsnk6bHhdawq3GGMTm1@hdHccYn1@ffkD "C (gcc) – Try It Online")
I know I'm EXTREMELY late to the party, but I thought I'd try my hand at this in C, which required a linked-list implementation. It's not really golfed at all besides changing all the identifiers to single characters, but it functions!
All in all, I'm pretty happy considering this is the 3rd C/C++ program I've ever wrote.
[Answer]
# [Haskell](https://www.haskell.org/), 84 bytes
```
(0!).reverse
n!(x:y)|x<1=(n+1)!y|(a,b)<-span(>=x)y=(n+1)!(([-1..n]*>x-1:a)++b)
n!_=n
```
[Try it online!](https://tio.run/##LYxBC4IwGEDv/YqJHr4vN3EdxXnpHHhfIz5hmKRDtGKS/fZl0eXx4MG70nyzfR9eImY9ufZBrWXHumaxeO8G6pxiA40nNk6du7OEQZlUWudcGq4lz3/8@sEY3PI5QB5hNtmnnWa7cxH4YsHVl1KBSyVGywrEGyzFPJKDSnlc/gVAC5llzuwrL2RBmKYNboeLciF8AA)
Thanks to @xnor for two bytes.
I feel like there should be a good way to factor out the common increment, but I haven't found a short one yet.
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 206 bytes
```
ĐƩ?ŕ:ŕ0;áƑ0`⇹ĐŁ⁻?ŕ:ŕÁ⇹⁺Đ↔⁻⇹⁺⑴*;⇹⁺⁺⇹Đ1~⦋¬?ŕ⁺ĐŁĐř≠*ž⁻:ŕĐ1~⦋⇹Đ⁺ĐŁĐř≠*ž⁻Đ04Ș06Ș+<ĐŁř*↑Ь?ŕŕŕĐŁĐř=-0↔Đ3Ș+↔+⇹⑴⇹ɐ*Ƒ:ŕ⑴*ĐŁ3Ș⁺⇹ĐŁ⇹04ȘĐŁř⇹04Ș>*ž⁻ĐŁĐř=-+0↔+⇹ŕ+Đ4Ș⇹04Ș⑴⇹ɐ*Ƒ0↔++↔+áƑĐ0⦋⇹⁺ĐŁř1≠*ž⁻;ĐƩ¬?ŕŁ+0:ŕ⇹⁻;łŕ⁻⁻⁻?⁺⁺:⁺;
```
[Try it online!](https://tio.run/##bZC/CsIwEMbfp1FIURwa/zyICD6Cg4uLEAdFXBKw0G66CIJjFy04aK7oa@RF6l2SioM0Kcnld999d7PFvK6Nqs4jSBNIuXgeK82ndnM1CqSVpY8/JUasvBll13uM@pvVRSTCERflxEt72j0umOVokLhzuz1EcMc0VAqIg/8hRvHuK@O9V8b69Ah5ZNfaKKdJX5MxaHP0YlQHSTww8qEL/L9VVGmsRO4IRqBxB9QG6XvlcBk2lRthxoMgpMwoJAL4o@8IV5cGhqZ9T6EjyONvQ4Km691LxskXYaWAFc2o9GvkR5jgFnU9jlvx5AM "Pyt – Try It Online")
Takes input as an array.
| Code | Pseudocode |
| --- | --- |
| ĐƩ?ŕ:ŕ0;áƑ | If sum of w (worm parts) is 0, add another zero to avoid breaking the function (kludge) |
| ĐƩ?ŕ:ŕ1~; | if all zeroes, ctr=-1, otherwise ctr=0 (kludge) |
| ` | do... |
| ⇹ĐŁ⁻?ŕ | if len(w)!=1, do nothing |
| :ŕÁ⇹⁺Đ↔⁻⇹⁺⑴\* | otherwise, decrement w[0] and push 2 copies |
| ;⇹⁺⁺⇹ | ctr+=2 |
| Đ1~⦋¬? | if w[-1]=0: |
| ŕ⁺ĐŁĐř≠\*ž⁻ | remove the head |
| :ŕ | otherwise: |
| Đ1~⦋⇹ | q=w[-1]-1 |
| Đ⁺ĐŁĐř≠\*ž⁻ | x=w[:-1] |
| Đ04Ș06Ș+<ĐŁř\* | h=[x\_i\*(x\_i>q) for i in range(len(x))] |
| ↑ | k=max(h) |
| Ь?ŕŕŕ | if k=0 |
| ĐŁĐř=- | decrement the head |
| 0↔Đ3Ș+↔+⇹⑴⇹ɐ\*Ƒ | concatenate the head ctr times |
| :ŕ | otherwise |
| ⑴\*ĐŁ3Ș⁺⇹ĐŁ⇹04ȘĐŁř⇹04Ș>\*ž⁻ĐŁĐř=-+ | g=w[:k]; b=[w\_i-(i=len(w)-1) for i in [k...len(w)-1]] |
| 0↔+⇹ŕ+Đ4Ș⇹04Ș⑴⇹ɐ\*Ƒ | concatenate the reduced head (b) ctr times |
| 0↔++↔+ | clean up the stack |
| áƑĐ0⦋⇹⁺ĐŁř1≠\*ž⁻ | assemble the new worm |
| ;ĐƩ¬?ŕŁ+0:ŕ⇹⁻; | if worm is not dead, decrement the counter |
| ł | ... while the worm is not dead |
| ŕ⁻ | decrement ctr and implicitly print |
[Answer]
# [Perl 5](https://www.perl.org/) `-pa`, 92 bytes
```
while(@F){++$\;my@a;if($b=pop@F){unshift@a,pop@F while$F[-1]>=$b;push@F,(@a,--$b)x($\+1)}}}{
```
[Try it online!](https://tio.run/##K0gtyjH9/788IzMnVcPBTbNaW1slxjq30iHROjNNQyXJtiC/ACRcmleckZlW4pCoAxZQAGtQcYvWNYy1s1VJsi4oLc5wcNPRACrQ1VVJ0qzQUInRNtSsra2t/v/f8F9@QUlmfl7xf11fUz0DQ4P/uokFAA "Perl 5 – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 31 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
àîz7αan♣óàNµK2☻₧⌡▐`Γl½f{♂♂_KZÖÄ
```
[Run and debug it](https://staxlang.xyz/#p=858c7a37e0616e05a2854ee64b32029ef5de60e26cab667b0b0b5f4b5a998e&i=[0+1]%0A[1+0]%0A[1+1]%0A[2]%0A[1+1+0+0+0+0]&a=1&m=2)
] |
[Question]
[
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
---
This question does not appear to be about code golf or coding challenges within the scope defined in the [help center](https://codegolf.stackexchange.com/help/on-topic).
Closed 7 years ago.
[Improve this question](/posts/19569/edit)
# The Task
Write a program, in the language of your choice, that reads lines of input from standard input until EOF, and then writes them to standard output in ASCIIbetical order, similar to the `sort` command-line program. A short, non-underhanded example in Python is:
```
import sys
for line in sorted(sys.stdin):
print(line.rstrip('\n'))
```
# The underhanded part
Similar to [The OS War](https://codegolf.stackexchange.com/questions/6666/underhanded-contest-the-os-war), your goal is to prove that your favored platform is “better”, by having your program deliberately run much more slowly on a competing platform. For the sake of this contest, a “platform” consists of any combination of:
* Processor
+ Architecture (x86, Alpha, ARM, MIPS, PowerPC, etc.)
+ Bitness (64-bit vs. 32-bit vs. 16-bit)
+ Big- versus little-endian
* Operating System
+ Windows vs. Linux vs. Mac OS, etc.
+ Different versions of the same operating system
* Language implementation
+ Different compiler/interpreter vendors (e.g., MSVC++ vs. GCC)
+ Different versions of the same compiler/interpreter
Although you could meet the requirements by writing code like:
```
#ifndef _WIN32
Sleep(1000);
#endif
```
Such an answer should not be upvoted. The goal is to be subtle. Ideally, your code should *look* like it's not platform-dependent at all. If you *do* have any `#ifdef` statements (or conditions based on `os.name` or `System.Environment.OSVersion` or whatever), they should have a plausible justification (based on a lie, of course).
# Include in your answer
* The code
* Your “favorite” and “unfavorite” platforms.
* An input with which to test your program.
* The running time on each platform, for the same input.
* A description of *why* the program runs so slowly on the unfavorite platform.
[Answer]
# C
### CleverSort
CleverSort is a state-of-the-art (i. e. over-engineered and sub-optimal) two-step string sorting algorithm.
In step 1, it starts by pre-sorting the input lines using [radix sort](http://en.wikipedia.org/wiki/Radix_sort) and the first two bytes of each line. Radix sort is non-comparative and works very well for strings.
In step 2, it uses [insertion sort](http://en.wikipedia.org/wiki/Insertion_sort) on the pre-sorted list of strings. Since the list is almost sorted after step 1, insertion sort is quite efficient for this task.
### Code
```
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Convert first two bytes of Nth line into integer
#define FIRSTSHORT(N) *((uint16_t *) input[N])
int main()
{
char **input = 0, **output, *ptemp;
int first_index[65536], i, j, lines = 0, occurrences[65536];
size_t temp;
// Read lines from STDIN
while(1)
{
if(lines % 1000 == 0)
input = realloc(input, 1000 * (lines / 1000 + 1) * sizeof(char*));
if(getline(&input[lines], &temp, stdin) != -1)
lines++;
else
break;
}
output = malloc(lines * sizeof(char*));
// Radix sort
memset(occurrences, 0, 65536 * sizeof(int));
for(i = 0; i < lines; i++) occurrences[FIRSTSHORT(i)]++;
first_index[0] = 0;
for(i = 0; i < 65536 - 1; i++)
first_index[i + 1] = first_index[i] + occurrences[i];
memset(occurrences, 0, 65536 * sizeof(int));
for(i = 0; i < lines; i++)
{
temp = FIRSTSHORT(i), output[first_index[temp] + occurrences[temp]++] = input[i];
}
// Insertion sort
for(i = 1; i < lines; i++)
{
j = i;
while(j > 0 && strcmp(output[j - 1], output[j]) > 0)
ptemp = output[j - 1], output[j - 1] = output[j], output[j] = ptemp, j--;
}
// Write sorted lines to STDOUT
for(i = 0; i < lines; i++)
printf("%s", output[i]);
}
```
### Platforms
We all know that big-endian machines are much more efficient than their little-endian counterparts. For benchmarking, we'll compile CleverSort with optimizations turned on and create randomly a huge list (just over 100,000 strings) of 4-byte lines:
```
$ gcc -o cleversort -Ofast cleversort.c
$ head -c 300000 /dev/zero | openssl enc -aes-256-cbc -k '' | base64 -w 4 > input
$ wc -l input
100011 input
```
### Big-endian benchmark
```
$ time ./cleversort < input > /dev/null
real 0m0.185s
user 0m0.181s
sys 0m0.003s
```
Not too shabby.
### Little-endian bechmark
```
$ time ./cleversort < input > /dev/null
real 0m27.598s
user 0m27.559s
sys 0m0.003s
```
Boo, little Endian! Boo!
### Description
Insertion sort is really rather efficient for almost-sorted lists, but it is horribly inefficient for randomly sorted ones.
CleverSort's underhanded part is the *FIRSTSHORT* macro:
```
#define FIRSTSHORT(N) *((uint16_t *) input[N])
```
On big-endian machines, ordering a string of two 8-bit integers lexicographically or converting them to 16-bit integers and ordering them afterwards yields the same results.
Naturally, this is possible on little-endian machines as well, but the macro should have been
```
#define FIRSTSHORT(N) (input[N][0] | (input[N][1] >> 8))
```
which works as expected on all platforms.
The "big-endian benchmark" above is actually the result of using the proper macro.
With the wrong macro and a little-endian machine, the list is pre-sorted by the **second** character of every line, resulting in a random ordering from the lexicographical point of view. Insertion sort behaves very poorly in this case.
[Answer]
# Python 2 vs. Python 3
Obviously, Python 3 is several orders of magnitude faster than Python 2. Let's take this implementation of the [Shellsort](https://en.wikipedia.org/wiki/Shellsort) algorithm as an example:
## Code
```
import sys
from math import log
def shellsort(lst):
ciura_sequence = [1, 4, 10, 23, 57, 132, 301, 701] # best known gap sequence (Ciura, 2001)
# check if we have to extend the sequence using the formula h_k = int(2.25h_k-1)
max_sequence_element = 1/2*len(lst)
if ciura_sequence[-1] <= max_sequence_element:
n_additional_elements = int((log(max_sequence_element)-log(701)) / log(2.25))
ciura_sequence += [int(701*2.25**k) for k in range(1,n_additional_elements+1)]
else:
# shorten the sequence if necessary
while ciura_sequence[-1] >= max_sequence_element and len(ciura_sequence)>1:
ciura_sequence.pop()
# reverse the sequence so we start sorting using the largest gap
ciura_sequence.reverse()
# shellsort from http://sortvis.org/algorithms/shellsort.html
for h in ciura_sequence:
for j in range(h, len(lst)):
i = j - h
r = lst[j]
flag = 0
while i > -1:
if r < lst[i]:
flag = 1
lst[i+h], lst[i] = lst[i], lst[i+h]
i -= h
else:
break
lst[i+h] = r
return lst
# read from stdin, sort and print
input_list = [line.strip() for line in sys.stdin]
for line in shellsort(input_list):
print(line)
assert(input_list==sorted(input_list))
```
## Benchmark
Prepare a test input. This is taken from Dennis answer but with fewer words - Python 2 is sooo slow...
```
$ head -c 100000 /dev/zero | openssl enc -aes-256-cbc -k '' | base64 -w 4 > input
```
### Python 2
```
$ time python2 underhanded2.py < input > /dev/null
real 1m55.267s
user 1m55.020s
sys 0m0.284s
```
### Python 3
```
$ time python3 underhanded2.py < input > /dev/null
real 0m0.426s
user 0m0.420s
sys 0m0.006s
```
# Where is the underhanded code?
I assume some readers may want to hunt down the trickster themselves, so I hide the answer with a spoiler tag.
>
> The trick is the integer division in the calculation of the `max_sequence_element`. In Python 2 `1/2` evaluates to zero and hence the expression is always zero. However, the behavior of the operator changed to floating point division in Python 3. As this variable controls the length of the gap sequence, which is a critical parameter of Shellsort, Python 2 ends up using a sequence which contains only the number one while Python 3 uses the correct sequence. This results in a quadratic run time for Python 2.
>
>
>
Bonus 1:
>
> You can fix the code by simply adding a dot after the `1` or the `2` in the calculation.
>
>
>
Bonus 2:
>
> At least on my machine Python 2 is a bit faster than Python 3 when running the fixed code...
>
>
>
] |
[Question]
[
The [Factorial Number System](http://en.wikipedia.org/wiki/Factorial_number_system), also called factoradic, is a mixed radix numeral system. The factorials determine the place value of a number.
In this system, the right most digit can be either 0 or 1, the second rightmost digit can be 0, 1 or 2, and so on. This means that an `n` digit factoradic number can have a maximum value of `(n + 1)!`.
For example, to convert the factoradic number `24201` to decimal you would do this:
```
2 * 5! = 240
4 * 4! = 96
2 * 3! = 12
0 * 2! = 0
1 * 1! = 1
240 + 96 + 12 + 0 + 1 = 349
```
Hence the factoradic number `24201` is `349` base `10`.
To convert a decimal number (with `349` as an example) into a factoradic number, you would do this:
Take the largest factorial less than the number. In this case it is `120`, or `5!`.
```
349 / 5! = 2 r 109
109 / 4! = 4 r 13
13 / 3! = 2 r 1
1 / 2! = 0 r 1
1 / 1! = 1 r 0
```
Hence `349` base `10` is the factoradic number `24201`.
Your challenge is to create the shortest program or function that converts an input number to the other base.
The input will be a string representation of a non-negative integer. A factoradic number will be preceded by a `!` (eg. `!24201`), while a decimal number will not be preceded by anything. You may assume that the maximum input will be `10! - 1` - `3628799` in decimal and `987654321` in factoradic. This means that letters will not appear in a factoradic input/output.
The program doesn't need to prepend a `!` to a factoradic output, and may output a string or an integer. The input may be in any reasonable format.
---
Test cases:
```
Input: 1234
Output: 141120
Input: 746
Output: 101010
Input: !54321
Output: 719
Input: !30311
Output: 381
```
[Answer]
### APL, 39 37 characters
```
{A B←(9⍴10)(⌽1+⍳9)⌽⍨'!'∊⍵⋄A⊥B⊤⍎⍵~'!'}
```
Examples:
```
{A B←(9⍴10)(⌽1+⍳9)⌽⍨'!'∊⍵⋄A⊥B⊤⍎⍵~'!'}'1234'
141120
{A B←(9⍴10)(⌽1+⍳9)⌽⍨'!'∊⍵⋄A⊥B⊤⍎⍵~'!'}'!54321'
719
```
[Answer]
## Python 2.7 (~~163~~ ~~157~~ 152)
```
i=raw_input()
exec("b='';a=362880;j=int(i);x=9;"+'b+=`j//a`;j%=a;a/=x;x-=1;'*9,"a=x=1;b=0;"+'b+=a*int(i[-x]);x+=1;a*=x;'*~-len(i))['!'in i]
print int(b)
```
More readable version:
```
i=raw_input()
if'!'in i:a=x=1;b=0;c='b+=a*int(i[-x]);x+=1;a*=x;'*~-len(i)
else:b='';a=362880;j=int(i);x=9;c='b+=`j//a`;j%=a;a/=x;x-=1;'*9
exec c;print int(b)
```
Breakdown:
```
Factoradic -> Decimal, when i is in the form !(number)
a=1 #Factorial value (multiplied every iteration)
x=1 #Index value
b=0 #Output
iterate ~-len(i) times: #PSEUDOCODE! bitwisenot(a) = ~a = -a-1
b+=a*int(i[-x]) #add the value of the xth last character in the factoradic #
x+=1 #Increment x
a*=x #Set a to x!, (x-1)! * x = x!
Decimal -> Factoradic
b='' #Output
a=362880 #Factorial value, set to 9! here
j=int(i) #Integer value of the input
x=9 #Index value
iterate 9 times: #PSEUDOCODE! This block is in an exec() loop
b+=`j/a` #Add floor(j/a) to b
j%=a #Take out all multiples of a in j
a/=x #Set a to (x-1)!, x! / x = (x-1)!
x-=1 #Decrement x
```
[Answer]
## GolfScript (48 44 43 chars)
```
.~\{1{):?\.?%\?/@}9*{*+}+9*}:^{:N,{^N=}?}if
```
This is a self-contained program. The factoriadic => decimal conversion is quite slow, because it does a search using the decimal => factoriadic conversion rather than a direct base conversion.
The input format allows for a very short mode switch: `.~` copies the input string and evaluates it, so if the input is just a number we end up with e.g. `"1234" 1234` on the stack, and if it starts with `!` (logical not, with any non-empty string being truthy) we end up with e.g. `0 30311` on the stack. Then the value at the bottom of the stack is truthy for decimal => factoriadic and falsy for factoriadic => decimal.
[Answer]
# PHP <7.1 ~~178 171 170 168 164 155 147 144 138 126~~ 123 bytes
```
for($b=$j=1,$i=strlen($x=$argn);+$x?$b<=$x:--$i;$b*=++$j)$r+=$x[$i]*$b;if(+$x)for(;$j>1;$x%=$b)$r.=$x/($b/=$j--)|0;echo+$r;
```
Run as pipe with `-r` or [test it online](http://sandbox.onlinephpfunctions.com/code/e4764cc460fd438404d1959e1d3a674597941463).
* no extension required
* no ~~sub~~ function needed: the factorial base is being reused (incresed/decreased in the loops)
* pure integer and string arithmetics, should even work in php 3 (and still works in php 7):
* ~~decimal 0 returns empty string instead of `0`.~~ (both other PHP answers do too.) ~~If that is unacceptable, add +5 for the extra case.~~
**ungolfed:**
```
// two loops in one: compute the decimal number from a factorial
// or find the first factorial larger than a decimal $x
// the latter inits $r with '0': $i=strlen -> $x[$i]=='' -> (int)$x[$i]==$x[$i]*$b==0
// $b is the current digit´s base; $j is the bases´ latest factor
for($b=$j=1,$i=strlen($x=$argn);+$x?$b<=$x:--$i;$b*=++$j)
$r+=$x[$i]*$b;
// and now for dec->fact ...
if(+$x)
for(;$j>1;$x%=$b)
// both $b and $j are one step too far in the first iteration;
// -> decrement must precede the actual loop body
// -> can be merged into the digit calculation -> all braces golfed
$r.=$x/($b/=$j--)|0;
// now: go on with the remainder (see loop head)
echo+$r; // final type cast removes leading zeros (from the first loop)
// and fixes the '0' result (no operations at all on that input!)
```
**abandoned golfing ideas:**
* `$b<=$x` --> `$b<$x` (-1)
would break pure decimal factorials (i.e. those that result in a factorial number with only one non-zero digit).
JMPC´s solution suffers from that; HamZa´s does not.
* ~~`floor($x/$b)` -> `(int)($x/$b)`
could be a bit faster, but type casting precedes division, so I need the parentheses and don´t gain a byte.~~ `$x/$b|0` does the trick
* ~~The loop in fact->dec is similar to the factorial-find in dec->fact. Same increment, body does not matter, but unfortunately different preset and different post condition. Dang; could have golfed -21 there.~~
YAY I found a solution. Took quite a bit of golfing, but chopped off another -4 (no: -9) *and* closed all bugs/loopholes.
Any more potential ... or am I done golfing?
[Answer]
# JavaScript (ES 6) ~~139 137 122 113~~ 111
tried a different approach using some array magic; but I ended up at ~~174~~ 172 bytes with that:
```
f=x=>{if('!'==x[0]){a=x.split``.reverse();i=b=1;r=0;a.pop();a.map(d=>{r+=d*b;b*=++i})}else{t=[];for(i=b=1;b<=x;b*=++i){t.unshift(b)}r='';t.map(b=>{r+=x/b|0;x%=b})}return r}
```
So I just took my PHP code and translated it. Could remove all the `$`s and a few `;`, but the necessity to initialize vars ate up some of that benefit. Managed to golf both answers down a bit further, though.
**golfed**
```
f=x=>{for(r=0,b=j=1,i=x.length;x|0?b<=x:--i;b*=++j)r+=x[i]*b;if(x|0)for(r='';j>1;x%=b)r+=x/(b/=j--)|0;return r}
```
* first version returns '' for decimal 0; add +2 to fix
* second version requires string input
* both tested in Firefox, Edge and Opera
**ungolfed**
```
f=x=>
{
for(r=0,b=j=1,i=x.length;x|0?b<=x:--i;b*=++j)
r+=x[i]*b;
if(x|0)
for(r='';j>1;x%=b)
r+=x/(b/=j--)|0;
return r
}
```
**test suite**
```
<table id=out border=1><tr><th>dec</th><th>result<th>expected</th><th>ok?</th></tr></table>
<script>
addR=(r,s)=>{var d=document.createElement('td');d.appendChild(document.createTextNode(s));r.appendChild(d)}
test=(x,e)=>{var y=f(x),r=document.createElement('tr');addR(r,x);addR(r,y);addR(r,e);addR(r,e==y?'Y':'N');document.getElementById('out').appendChild(r)}
samples={'349':'24201','1234':'141120','746':'101010','719':'54321','381':'30311','24':'1000','0':'0'};
for(d in samples){test(d,samples[d]);test('!'+samples[d],d)}
</script>
```
[Answer]
## Python, 128 chars
This takes about half an hour to run, but it's small:
```
A=[`x`for x in xrange(10**9)if all(x/10**d%10<d+2 for d in range(9))]
i=raw_input()
print A.index(i[1:])if'!'in i else A[int(i)]
```
It builds a list of all <= 9 digit factoradic numbers in numeric order, then does a lookup or index to convert.
If you want to test, just replace `10**9` with `10**6` and restrict yourself to 6-digit variadic numbers.
I could technically save a character by using `range(10**9)` instead of `xrange(10**9)`. Don't try this at home.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 15 bytes
```
ḊV€;0Æ¡µÆ!ṖḌƊ¬?
```
[Try it online!](https://tio.run/##AS0A0v9qZWxsef//4biKVuKCrDsww4bCocK1w4Yh4bmW4biMxorCrD////8hNTQzMjE "Jelly – Try It Online")
### How it works
```
ḊV€;0Æ¡µÆ!ṖḌƊ¬? Main link (monad). Input: integer or string
¬? *) If the given input is a string, run 1); otherwise run 2)
ḊV€;0Æ¡ 1) Factorial base -> integer
ḊV€ Remove "!" and map each char to number
;0 Append zero (this is needed to run the built-in correctly)
Æ¡ Built-in conversion
Æ!ṖḌ 2) Integer -> factorial base
Æ! Built-in conversion
ṖḌ Remove a zero at the end, and convert to decimal
```
### Why `*)` works
`¬` is element-wise logical NOT. When given a single integer, it becomes a single zero, which is false. However, when given a string, each element (character) is turned to a zero, and the whole result is an array of zeroes which is true.
Zero as an integer is a special case. It goes through the "factorial -> integer" route, but it still gives zero which is correct.
# Without factorial base built-in, 25 bytes
```
⁵R!µ³%Ḋ:ṖUḌ
⁵R!ḋḊUV€ƊµÇ¬?
```
[Try it online!](https://tio.run/##y0rNyan8//9R49YgxUNbD21Wfbijy@rhzmmhD3f0cIFFH@7oBoqFhj1qWnOs69DWw@2H1tj///9f0dLC3MzUxNjIEAA "Jelly – Try It Online")
### How it works
```
⁵R!µ³%Ḋ:ṖUḌ Aux. link (monad). Integer -> factorial base
⁵R!µ Set (1..10)! as left argument
³%Ḋ:Ṗ Compute each digit: (input % (2..10)!) // (1..9)!
UḌ Reverse and convert the digit array to decimal
⁵R!ḋḊUV€ƊµÇ¬? Main link (monad).
怪? If the input is a string, apply the left chain;
otherwise, apply the aux. link above
⁵R! (1..10)!
ḋ Dot product with...
ḊUV€Ɗ Remove "!", reverse, map each character to digit
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~66~~ ~~65~~ 60 bytes
*-1 byte thanks to Jo King*
```
{/\!/??:1[.flip.chop.comb Z*[\*] 1..*]!![R~] .polymod(2..*)}
```
[Try it online!](https://tio.run/##DcjNCgIhFAbQV/kuRMy4cLpqE0Q179AyR6I/KVCUaSVRr26zOYuTH1PoayxYeuzrpxupG4YtW@nDK8vbM82keMVJ2FE4sJTCEdnjz0HmFEpM90bN2X7r@1Lgm8W5hU8Tdqy0wcb0oLXRikF6pZkP9Q8 "Perl 6 – Try It Online")
[Answer]
### GolfScript, 69 characters
```
10,1>{1$*}*](.0=33={1>01/-1%0\{~@(@*@+}/\}{~\-1%{1$<},{1$1$/@@%}/}if;
```
Takes input from STDIN as usual and prints the result. [Online test](http://golfscript.apphb.com/?c=OyIhNTQzMjEiCgoxMCwxPnsxJCp9Kl0oLjA9MzM9ezE%2BMDEvLTElMFx7fkAoQCpAK30vXH17flwtMSV7MSQ8fSx7MSQxJC9AQCV9L31pZjs%3D&run=true).
[Answer]
## Haskell, 221 chars
### Code Golf
```
m v@(a:b)|a=='!'=(sum.zipWith(*)g.map(read.(:[])).reverse) b|True=(fst.until((<0).fst.snd)(\(s,(i,b))->(s*10+b`quot`f i,(i-1,b`rem`f i))).(\n->(0,((1+).last.takeWhile((n>=).f)$[1..], n))).read) v;g=scanl1(*)[1..];f=(g!!)
```
### Usage
```
$ ghci factorial.hs
ghci> m "1234"
141120
ghci> m "!54321"
719
```
### Ungolfed code
```
parse v@(a:b) | a == '!' = to b
| otherwise = from v
to = sum . zipWith (*) factorials . map (read . (:[])) . reverse
from = fst . until finished next . boostrap . read
where finished = ((<0) . fst . snd)
next (s,(i,r)) = (s * 10 + r `quot` factorial i, (i-1 ,r `rem` factorial i))
bootstrap n = (0, (lastFact n, n))
lastFact n = (1+) . last . takeWhile ((n>=) . factorial) $ [1..]
factorials = scanl1 (*) [1..]
factorial = (factorials!!)
```
[Answer]
# Mathematica 213 177 175
A factorial number is wrapped in `f[]`, whether it is input or output.
```
g@{n_,j_,r_}:=If[j==0,FromDigits@r,g@{q=QuotientRemainder[n,j!];q[[2]],j-1,Append[r,q[[1]]]}]
z@n_:=If[!IntegerQ@n, g[{n[[1]],9,{}}], f@Tr@(p=1;# (p++)!&/@Reverse@IntegerDigits@n)]
```
**Usage**
```
z[24201]
```
>
> f[349]
>
>
>
```
z[f[349]]
```
>
> 24201
>
>
>
*Conversion of factorial to decimal number*.
`QuotientRemainder[n,j!]` recursively acts on the digits of the factorial number from left to right, decrementing `j` at each step. `QuotientRemainder[349, 5!]`, for instance, returns `{2, 109}` and so on.
*Conversion of decimal to factorial number*.
Moving right to left, the pure function, `# (p++)! &`, multiplies each digit,`#`, by the appropriate factorial.
[Answer]
# PHP ~~231~~ ~~214~~ 204
Newest Answer
```
function g($x){return $x?$x*g($x-1):1;}function f($x,$e){if($x[0]=="!"){for($t=1;$t<$c=strlen($x);$t++){$e+=$x[$t]*g($c-$t);}}else{while(g(++$p)<=$x);while(--$p){$e.=floor($x/g($p));$x%=g($p);}}return$e;}
```
Old Answer
```
function f($n){if($n[0]=="!"){$n=str_split($n);$c=count($n);$f=$y=1;while($c-->1){$e+=($f*$n[$c]);$f*=++$y;}return$e;}else{for($i=$c=1;$i<$n;$i*=$c){$r[$c++]=$i;}foreach(array_reverse($r)as$t){$e.=floor($n/$t);$n=$n%$t;}return$e;}}
```
### Example
```
echo f('349')."\n"
.f('!24201')."\n"
.f('1234')."\n"
.f('746')."\n"
.f('!54321')."\n"
.f('!30311');
```
### Output
```
24201
349
141120
101010
719
381
```
[Answer]
# K, 102
```
"I"$,/$*:'|:'{{(x-y*g),g:_(x:*x)%y:*/1+!y}\[x,0n;|1+!{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]]}
```
Could definitely be improved.
```
k)"I"$,/$*:'|:'{{,[;g]x-y*g:_(x:*x)%y:*/1+!y}\[(x;0n);|1+!{{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]}x]} 349
24201
k)"I"$,/$*:'|:'{{,[;g]x-y*g:_(x:*x)%y:*/1+!y}\[(x;0n);|1+!{{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]}x]} 746
101010
k)"I"$,/$*:'|:'{{,[;g]x-y*g:_(x:*x)%y:*/1+!y}\[(x;0n);|1+!{{$[(x>(*/1+!y))&x<*/1+!y+1;y;.z.s[x;1+y]]}[x;0]}x]} 1234
141120
```
[Answer]
# D (159 chars)
```
int x(string n){import std.conv;int r,i=9,f=9*'鶀',d;if(n[0]<48){while(r.text.x<n[1..$].to!int)r++;}else{d=n.to!int;while(i){r=r*10+d/f;d%=f;f/=i--;}}return r;}
```
## Ungolfed and with program entry point
All command line arguments are printed as `<original> -> <converted>`. Only decimal to factoradic is actually implemented in `x`. The other way round just calls `x` with all decimal numbers (0..\*) until the result equals the input. This takes ~3 seconds for the largest input (!987654321).
Executable online version: <http://dpaste.dzfl.pl/46e425f9>
```
void main(string[] args) {
import std.stdio;
foreach (arg; args[1 .. $]) {
writefln("%s -> %s", arg, x(arg));
}
}
int x(string n) {
import std.conv;
int r, i=9, f=9*'鶀', d; // 鶀's Unicode index equals 8*7*6*5*4*3*2*1
// If the first character value is less than 48 ('0') it should be a '!'.
if (n[0] < 48) {
// Call x with different input (0..*) until it matches our n.
// r.text.x is rewritten as x(text(r)).
while (r.text.x < n[1..$].to!int) r++;
} else {
d = n.to!int;
// Try d / 9!, d / 8!, etc. just as in the problem description.
while (i) {
r = r*10 + d/f;
d %= f;
f /= i--;
}
}
return r;
}
```
[Answer]
## VBA 225
Thanks to Titus for the help! Still looking to golf some more.
```
Sub a(b)
Set w=WorksheetFunction
e=Len(b)
If IsNumeric(b) Then
i=0
For d=0To 8
h=w.Fact(9-d)
g=b Mod h
If g<b+i Then
i=1
f=f &Int(b/h)
b=g
End If
Next
Else
For d=2To e
f=f+w.Fact(e-d-1)*Mid(b,d,1)
Next
End If
MsgBox f
End Sub
```
[Answer]
# [PHP](https://php.net/), 124 bytes
```
for($f=1;("$">$a=$argn)&&~$c=strrev($a)[$n];)$r+=$c*$f*=++$n;for(;$a>=$f*=++$i;);for(;~-$i;$a%=$f)$r.=0|$a/$f/=$i--;echo+$r;
```
[Try it online!](https://tio.run/##LYtBDoIwFET33sJmJJSmAuvvx4MYFz8NtWxKU40rw61dV1RmNXkzL4VUTucU0g6Sb5HVvt/SKSp@zjU891QrqAHCv5OuqgWO74@cx2cN0RfEK2lkw3ANfMPGINJXJsjAG5lI/9li1w45rMMqHbl7QVr4ljFZS6MLs0GmUt5xtk5cGD8 "PHP – Try It Online")
Extended
```
for($f=1;("$">$a=$argn)&&~$c=strrev($a)[$n];) # runs in case of "!" at the beginning
$r+=$c*$f*=++$n; #reverse string multiply with the next factorial "!"*$f=0
for(;$a>=$f*=++$i;); # runs not in case of "!" at the beginning string comparing. search the factorial that is higher as input value
for(;~-$i;$a%=$f) # runs only when the second loop had runs
$r.=0|$a/$f/=$i--; # concat the value of the division with the highest factorial used
echo+$r; # Output result
```
[Answer]
# [Perl 6](http://perl6.org/), 150 bytes
```
{/^\!/??([+] [Z*] .comb.skip.reverse,[\*] 1..*)!!(reduce
->\a,\b{a[0]~a[1] div b,a[1]%b},("",+$_),|(first
*[*-1]>$_,[\,] [\*] 1..*).reverse[1..*])[0]}
```
[Answer]
# APL(NARS), 36 chars, 72 bytes
```
{⍵⊆⎕D:10⊥(9..2)⊤⍎⍵⋄t+.×⌽!⍳≢t←⍎¨,1↓⍵}
```
it seems that 10⊥(9..2)⊤ is better than the recursive function, thanks to Howard for the other APL solution that show that... (even if i not understand 100%). Input for numbers without '!' <10!. Test:
```
u←{⍵⊆⎕D:10⊥(9..2)⊤⍎⍵⋄t+.×⌽!⍳≢t←⍎¨,1↓⍵}
u¨'1234' '746' '!54321' '!30311' '!24201'
141120 101010 719 381 349
u '0'
0
u '!0'
0
u '9'
111
u '!111'
9
u '!9'
9
```
] |
[Question]
[
## The task
This is a simple challenge.
Your input is a single non-empty string, containing only digits `0123456789` and hashes `#`.
It will contain exactly one run of digits, which encodes a nonnegative integer and may wrap around the end of the string, and at least one `#`.
The integer may have leading zeroes.
For example, `##44##`, `013####` and `23###1` are valid inputs, while `###`, `0099` and `#4#4` are not.
Your task is to extract the integer `n` from the string, and output the string rotated `n` steps to the right.
## Examples
* The input `#1##` should be rotated 1 step to the right, so the correct output is `##1#`.
* The input `#026###` should be rotated 26 steps to the right, since the leading 0 is ignored. The correct output is `26####0`.
* The input `1####2` contains the integer 21 wrapped over the end, so it should be rotated 21 steps to the right. The correct output is `##21##`.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins, and standard loopholes are disallowed.
You can assume that the number `n` fits into the standard `int` type of your language.
Conversely, if that standard `int` type implements arbitrary-precision integers, you must support (in theory) an arbitrarily large `n`.
## Test cases
```
#1## -> ##1#
##4## -> #4###
1####1 -> ####11
1####2 -> ##21##
#026### -> 26####0
#000### -> #000###
###82399 -> ##82399#
51379#97 -> #9751379
#98##### -> ###98###
#######4## -> #4########
60752#1183 -> 8360752#11
####99366800## -> 366800######99
########9##### -> ###9##########
91#####515694837 -> 1#####5156948379
###6114558###### -> #6114558########
######219088736090042#### -> 9088736090042##########21
#46055080150577874656291186550000138168########### -> 0138168############4605508015057787465629118655000
568375993099127531613012513406622393034741346840434468680494753262730615610086255892915828812820699971764142551702608639695081452206500085233149468399533981039485419872101852######################3680 -> 99533981039485419872101852######################36805683759930991275316130125134066223930347413468404344686804947532627306156100862558929158288128206999717641425517026086396950814522065000852331494683
```
[Answer]
# CJam, 11 bytes
```
q_'#%W%sim>
```
[Try it online!](http://cjam.tryitonline.net/#code=cV8nIyVXJXNpbT4&input=IyMjIyMjMjE5MDg4NzM2MDkwMDQyIyMjIw) or [verify all test cases](http://cjam.tryitonline.net/#code=cU4vewpRXycjJVclc2ltPgpOfWZRCg&input=IzEjIwojIzQjIwoxIyMjIzEKMSMjIyMyCiMwMjYjIyMKIzAwMCMjIwojIyM4MjM5OQo1MTM3OSM5NwojOTgjIyMjIwojIyMjIyMjNCMjCjYwNzUyIzExODMKIyMjIzk5MzY2ODAwIyMKIyMjIyMjIyM5IyMjIyMKOTEjIyMjIzUxNTY5NDgzNwojIyM2MTE0NTU4IyMjIyMjCiMjIyMjIzIxOTA4ODczNjA5MDA0MiMjIyM).
Note that this won't work for the last two test cases, since the involved numbers don't fit into 64 bits.
### How it works
```
q_ e# Read all input and push it twice.
'#% e# Split at runs of '#'.
W% e# Reverse the resulting array.
si e# Cast to string, then to int.
m> e# Rotate the original input that many places to the right.
```
[Answer]
# Julia, ~~71~~ 65 bytes
```
s->join(circshift([s...],maximum(parse,split(s*s,"#",keep=1<0))))
```
This is an anonymous function that accepts a string and returns a string. To call it, assign it to a variable.
We append the input to itself, split it into an array with `#` as the separator, parse each integer, and take the maximum. This defines the number of times we shift the string to the right. We splat the string into a `Char` array, shift, and `join` it back together.
[Answer]
# Python, 66 bytes
```
lambda l:(2*l)[-int(''.join(l.split('#')[::-1]))%len(l):][:len(l)]
```
[Answer]
# Retina, ~~65~~ ~~57~~ 49
```
(\d*)#*(\d+)
$2$1 $0
^\d+
$*
+`1 (.*)(.)
$2$1
<space>
```
Saved 8 bytes thanks to Martin!
[Try it Online!](http://retina.tryitonline.net/#code=KFxkKikjKihcZCspCiQyJDEgJDAKXlxkKwokKgorYDEgKC4qKSguKQogJDIkMQogCg&input=MSMjIyMy)
Note that this will time out / run out of memory for the very large test cases online, and on most sane machines, for some of the larger ones.
This takes the last number in the string and the first or no number in the string and puts them in front of the string. Then it converts that combined number to unary and repeatedly rotates while dropping a unary digit.
[Answer]
# Jelly, ~~12~~ 10 bytes
```
ẋ2~ṣ0‘ḌṂṙ@
```
[Try it online!](http://jelly.tryitonline.net/#code=4bqLMn7huaMw4oCY4biM4bmC4bmZQA&input=&args=IiMjIyMjIzIxOTA4ODczNjA5MDA0MiMjIyMi) or [verify all test cases](http://jelly.tryitonline.net/#code=4bqLMn7huaMw4oCY4biM4bmC4bmZQArDh-KCrGrigbc&input=&args=IiMxIyMiLCIjIzQjIyIsIjEjIyMjMSIsIjEjIyMjMiIsIiMwMjYjIyMiLCIjMDAwIyMjIiwiIyMjODIzOTkiLCI1MTM3OSM5NyIsIiM5OCMjIyMjIiwiIyMjIyMjIzQjIyIsIjYwNzUyIzExODMiLCIjIyMjOTkzNjY4MDAjIyIsIiMjIyMjIyMjOSMjIyMjIiwiOTEjIyMjIzUxNTY5NDgzNyIsIiMjIzYxMTQ1NTgjIyMjIyMiLCIjIyMjIyMyMTkwODg3MzYwOTAwNDIjIyMjIiwiIzQ2MDU1MDgwMTUwNTc3ODc0NjU2MjkxMTg2NTUwMDAwMTM4MTY4IyMjIyMjIyMjIyMiLCI1NjgzNzU5OTMwOTkxMjc1MzE2MTMwMTI1MTM0MDY2MjIzOTMwMzQ3NDEzNDY4NDA0MzQ0Njg2ODA0OTQ3NTMyNjI3MzA2MTU2MTAwODYyNTU4OTI5MTU4Mjg4MTI4MjA2OTk5NzE3NjQxNDI1NTE3MDI2MDg2Mzk2OTUwODE0NTIyMDY1MDAwODUyMzMxNDk0NjgzOTk1MzM5ODEwMzk0ODU0MTk4NzIxMDE4NTIjIyMjIyMjIyMjIyMjIyMjIyMjIyMjMzY4MCI).
### Background
Say the input is `51379#97`.
By repeating the string twice (`51379#9751379#97`), we can make sure that it will contain a contiguous representation of the number.
Next, we apply bitwise NOT to all characters. This attempts to cast to int, so **'1'** gets evaluated to **1**, then mapped to **~1 = -2**. On failure (`#`), it returns **0**.
For our example, this gives
```
[-6, -2, -4, -8, -10, 0, -10, -8, -6, -2, -4, -8, -10, 0, -10, -8]
```
Next, we split at zeroes to separate the part that encodes the number from the rest.
```
[[-6, -2, -4, -8, -10], [-10, -8, -6, -2, -4, -8, -10], [-10, -8]]
```
Bitwise NOT maps **n** to **-n - 1**, so we increment each to obtain **-n**.
```
[[-5, -1, -3, -7, -9], [-9, -7, -5, -1, -3, -7, -9], [-9, -7]]
```
Next, we convert each list from base 10 to integer.
```
[-51379, -9751379, -97]
```
The lowest number is the negative of the one we're searching for. Since Jelly list rotation atom `ṙ` rotates to the *left*, this avoid multiplying by **-1** to rotate to the right.
### How it works
```
ẋ2~ṣ0‘ḌṂṙ@ Main link. Input: S (string)
ẋ2 Repeat the string twice.
~ Apply bitwise NOT to all characters.
This maps 'n' to ~n = -(n+1) and '# to 0.
ṣ0 Split at occurrences of zeroes.
‘ Increment all single-digit numbers.
Ḍ Convert each list from base 10 to integer.
Ṃ Take the minimum.
ṙ@ Rotate S that many places to the left.
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), ~~28~~ ~~25~~ ~~17~~ 16 bytes
```
!G1Y4XXPZcXvUYS!
```
*8 bytes less borrowing Dennis' idea of splitting the array and reversing the order of the pieces*
The two last test cases don't work because the number is too large.
*EDIT (May 20, 2016) The code in the link uses `Xz` instead of `Xv`, owing to recent changes in the language.*
[**Try it online!**](http://matl.tryitonline.net/#code=IUcxWTRYWFBaY1h6VVlTIQ&input=JyMjIyMjIzIxOTA4ODczNjA5MDA0MiMjIyMn)
```
! % take implicit input: string. Transpose into column char array
G % push input string again
1Y4 % predefined literal '\d' (for regexp)
XX % match regexp. Gives cell array with 1 or 2 strings
P % flip that array
ZcXv % join the strings in that array, without spaces
U % convert to number
YS % rotate the transposed input that many times
! % put back into row form (string). Implicitly display
```
[Answer]
## PowerShell, 153 bytes
(But see the Extra Credit section, below)
```
param($a)$d=[System.collections.arraylist][char[]]$a;for($b=+("$a$a"-split"#"-ne'')[1];$b;$b--){$r=$d[-1];$d.removeAt($d.Count-1);$d.insert(0,$r)}-join$d
```
PowerShell doesn't have the concept of "shifting" an array, so I had to roll my own solution. Will take a *long* time for larger numbers, but it should eventually complete anything that fits in a 32-bit int.
Takes input `$a`, and sets a new variable `$d` as a [[System.Collections.ArrayList]](https://msdn.microsoft.com/en-us/library/system.collections.arraylist(v=vs.110).aspx) object. This is done because, technically, arrays in PowerShell are immutable (further explained below in Extra Credit), and thus don't support arbitrary insertions or removals, which is needed for shifting. Then, we enter a `for` loop.
The initial condition is a trick I found -- if we concatenate the input together, split on `#`, and ignore empties, the second element of the resulting array will be equal to our number, regardless of wrapping. We set that to `$b`, and decrement `$b` each time until it's zero.
Each iteration, we set helper `$r` as the last element in the arraylist, remove that last element, and then insert the element onto the front ... effectively "shifting" the array to the right by one element.
Finally, we simply output with `-join$d` so that it's concatenated into one string.
---
### Extra Credit
If the problem was shifting the array *left* instead of *right*, we can do it significantly shorter using [*multiple assignment*](https://technet.microsoft.com/en-us/library/hh847875(v=wps.620).aspx). Basically, "If the assignment value contains more elements than variables, all the remaining values are assigned to the last variable."
In essence, this means something like `$c=@(1,2,3)` and `$a,$b=$c`
will have `$a=1` an int and `$b=@(2,3)` an array.
### PowerShell, 90 bytes, does a left shift instead of a right shift
```
param($a)$b=+("$a$a"-split"#"-ne'')[1];$a=[char[]]$a;for(;$b;$b--){$r,$a=$a;$a+=$r}-join$a
```
Here we once again take input, and set `$b` as above. We re-cast `$a` as a char-array, and then enter the same `for` loop as above. This time, though, we've not needed to support arbitrary removal/insertion, so we don't need to use the costly `[System.Collections.ArrayList]` object, nor the expensive method calls. Instead we simply set `$r` to be the first element of `$a`, and the remaining elements are re-saved in `$a`. Then we `+=` to tack it back on to the end.
*(As I said, PowerShell arrays are technically immutable, but the `+=` operator here is overloaded - it takes an array and another object, mushes them together (technical term) into a new array, returns that and saves it as the variable name, and destroys the original array. Functionally, we've just added an element to the end of the array, but technically (and from a memory/garbage-cleanup perspective, etc.) it's a brand-new array. This can obviously become a costly operation if the array is large or complex. The flipside is that, since arrays are immutable, indexing into them or iterating over them is very cheap.)*
Output remains the same action, with a `-join` statement to turn it into a single string.
[Answer]
## Seriously, 21 bytes
```
,;;+'#@s`≈`MM@#@`/`nΣ
```
[Try it online!](http://seriously.tryitonline.net/#code=LDs7KycjQHNg4omIYE1NQCNAYC9gbs6j&input=JzEjIyMjMic)
Warning: this solution is very inefficient, so the larger test cases will time out on TIO. Use the local interpreter.
Explanation:
```
,;;+'#@s`≈`MM@#@`/`nΣ
,;;+ make 3 copies of input, and concatenate two of them
'#@s split on #s
`≈`MM convert strings to ints, take maximum
@#@ explode final copy of input
`/`n rotate to the right n times
Σ join
```
[Answer]
# Mathematica, 69 Bytes
```
#~StringRotateRight~ToExpression[""<>Reverse@TextCases[#,"Number"]]&
```
Find sequences of numbers in the, if there are 2 then their order needs to be reversed. Concatenate the strings (if it's only one it just returns the number string). Convert string to numeric and rotate the string that number of times.
[Answer]
# Pyth, ~~22~~ 14 bytes
```
.>zs-.<zxz\#\#
```
[Try it here!](http://pyth.herokuapp.com/?code=.%3Ezs-.%3Czxz%5C%23%5C%23&input=%23026%23%23%23&test_suite=1&test_suite_input=%231%23%23%0A%23%234%23%23%0A1%23%23%23%231%0A1%23%23%23%232%0A%23026%23%23%23%0A%23000%23%23%23%0A%23%23%2382399%0A51379%2397%0A%2398%23%23%23%23%23%0A%23%23%23%23%23%23%234%23%23%0A60752%231183%0A%23%23%23%2399366800%23%23%0A%23%23%23%23%23%23%23%239%23%23%23%23%23%0A91%23%23%23%23%23515694837%0A%23%23%236114558%23%23%23%23%23%23%0A%23%23%23%23%23%23219088736090042%23%23%23%23%0A568375993099127531613012513406622393034741346840434468680494753262730615610086255892915828812820699971764142551702608639695081452206500085233149468399533981039485419872101852%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%233680&debug=1)
### Explanation
```
.>zs-.<zxz\#\# # z=input
.<z # rotate z left by
xz\# # index of the first occurence of a hash
# this ensures that the integer is not wrapped around the end
- \# # filter all hashes out
s # cast to an integer, also removes leading zeroes
.>z # do the final roation of the input string and print it
```
This works for all testcases and also almosts finishes instantly for the very big numbers.
[Answer]
# JavaScript (ES6) 66
For once, the stupid negative `%` of javascript for negative numbers come useful
```
z=>(z+z).substr(-(l=z.length,[a,b]=z.match(/\d+/g),b?b+a:a)%l-l,l)
```
[Answer]
# Pyth, 10 bytes
```
.>zss_cz\#
```
[Try it online.](https://pyth.herokuapp.com/?code=.%3Ezss_cz%5C%23&input=%23%23%23%23%23%23219088736090042%23%23%23%23&debug=0) [Test suite.](https://pyth.herokuapp.com/?code=.%3Ezss_cz%5C%23&test_suite=1&test_suite_input=%231%23%23%0A%23%234%23%23%0A1%23%23%23%231%0A1%23%23%23%232%0A%23026%23%23%23%0A%23000%23%23%23%0A%23%23%2382399%0A51379%2397%0A%2398%23%23%23%23%23%0A%23%23%23%23%23%23%234%23%23%0A60752%231183%0A%23%23%23%2399366800%23%23%0A%23%23%23%23%23%23%23%239%23%23%23%23%23%0A91%23%23%23%23%23515694837%0A%23%23%236114558%23%23%23%23%23%23%0A%23%23%23%23%23%23219088736090042%23%23%23%23%0A%2346055080150577874656291186550000138168%23%23%23%23%23%23%23%23%23%23%23%0A568375993099127531613012513406622393034741346840434468680494753262730615610086255892915828812820699971764142551702608639695081452206500085233149468399533981039485419872101852%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%23%233680&debug=0)
This is a translation of [Dennis' CJam answer](https://codegolf.stackexchange.com/a/74106/30164). I'm making it a community wiki, since I didn't come up with it.
### Explanation
```
cz\# split input at #
_ reverse
s join
s cast to integer
.>z rotate input right
```
[Answer]
## JavaScript (ES6), ~~67~~ 64 bytes
```
s=>(l=s.length,s+s).substr(l-s.split(/#+/).reverse().join``%l,l)
```
Another port of Dennis's CJam answer.
Edit: Saved 3 bytes by appropriating the part of edc65's answer that he didn't draw attention to.
[Answer]
# Perl 5, 41 bytes
39 bytes plus two for the `-lF` flags (`-M5.01` is free): `perl -lF -M5.01 script.pl`
```
/#+/;map{unshift@F,pop@F}1..$'.$`;say@F
```
Explanation:
* `-lF` reads the input, removes the trailing newline, puts the remainder into the string `$_`, splits it up into characters, and puts that split into the array `@F`.
* `/#+/` finds the first string of `#`s in `$_` and sets `$`` equal to the stuff before it and `$'` equal to the stuff after it. If `$`` is empty then `$'` may contain more `#`s. However, `$'.$`` is a string whose initial substring is the number of times to rotate the array.
* Now we build the list `1..$'.$``, which treats `$'.$`` as an integer and thus numifies it, which strips any final `#`s, so the list is from `1` to the number of times to rotate the array.
* For each element in that list, we rotate the array (`pop` the last element and `unshift` it onto the beginning).
* Then `say` all the elements of the rotated array.
[Answer]
# Ruby - ~~68~~ ~~72~~ 70 bytes
```
s=ARGV[0]
p s.split(//).rotate(-(s+s).scan(/\d+/).map(&:to_i).max)*""
```
* `split` converts string into an array
* `(s+s).scan(/\d+/)` concatenate string to itself and get an array of numbers (as strings)
* `map(&:to_i)` convert strings to ints
* `max` pick the largest int
* `rotate` `max` times
* `*""` convert the array back into a string (shorthand for `join`)
Usage : `ruby scriptname.rb "[string]"`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~14~~ 13 bytes
Well, the code is very unlikely to terminate for the numbers bigger than 100000, but if you're patient enough, there will be an output :). Code:
```
'#¡rJ¹sF¤rS\J
```
Explanation:
```
'#¡ # Split the input on '#'
r # Reverse the stack
J # Join the stack
¹ # Take the first input
s # Swap with the number
F # For N in range(0, number), do...
¤ # Obtain the last character
r # Reverse the stack
S # Split everything to individual characters
\ # Delete the last character
J # Join the stack
```
[Try it online!](http://05ab1e.tryitonline.net/#code=JyPCoXJKwrlzRsKkclNcSg&input=Izk4IyMjIyM)
Uses **CP-1252** encoding
[Answer]
**VBSCRIPT, 82 99 BYTES**
previous code didn't handle cases with number wrapped over the end
```
b=len(a):f=replace(a,"#","/",1,1):c=replace(split(f&f,"/")(1),"#",d) mod b:d=right(a,c)&left(a,b-c)
```
UNGOLFED
```
b=len(a) -a->implicit input, get its length
f=replace(a,"#","/",1,1) -replace first instance of # so we can split later
c=replace(split(f&f,"/")(1),"#",d) mod b -get the number and calc the mod
d=right(a,c)&left(a,b-c) -d->implicit output
```
this kinda sucks ... there's probably a better way to do it, even in VBscript
[Answer]
# Mathematica, ~~73~~ 58 bytes
```
#~StringRotateRight~Max[FromDigits/@StringSplit[#<>#,"#"]]&
```
Much byte.
*15* *bytes* *saved* *thanks* *to* *IPoiler*
[Answer]
## Matlab(73)
```
@(a)regexprep(a,'(\d*)#*(\d*)#*','${circshift($0,[0 str2num([$2 $1])])}')
```
* This is using another approach that i wonder if @luis used it, because refering to his description there is some points in common while (un)?fortunately i dont understand the cropped Matl language.
[Answer]
## matlab~~(86)~~72
```
@(n)circshift(n,[0 str2num(circshift(n(n~='#'),[0,-find(n=='#',1)+1]))])
```
* The function totates the string two times, once for integer extraction, second for the desired task, it doesnt take too much time because matlab proceeds to rotate by `(Dim)modulus(Length)` to the exception that it falls in segmentation failure for bigger ranges.
* Will struggle how to golf it more ....
---
## (86)
```
@(n)circshift(n,[0 str2num([strtok(n(find(n=='#',1,'last'):end),'#') strtok(n,'#')])])
```
* The difference between this function and the previous, this one does concatenate two distant occurences of integers way backwards, while the first one just rotates it.
] |
[Question]
[
A little known fact about vampires is that they must drink the blood of victim that has a compatible donor blood type. The compatibility matrix for vampires is the same as the regular [red blood cell donor/recipient matrix](http://en.wikipedia.org/wiki/Blood_type#Red_blood_cell_compatibility). This can be summarized by the following [American Red Cross table](http://chapters.redcross.org/br/northernohio/INFO/bloodtype.html)
```
Type You Can Give Blood To You Can Receive Blood From
A+ A+, AB+ A+, A-, O+, O-
O+ O+, A+, B+,AB+ O+, O-
B+ B+, AB+ B+, B-, O+, O-
AB+ AB+ everyone
A- A+, A-, AB+, AB- A-, O-
O- everyone O-
B- B+, B-, AB+, AB- B- O-
AB- AB+, AB- AB-, A-, B-, O-
```
### Challenge
Write a function or program that takes a blood type as input and outputs two lists:
1. the unordered list of types that may receive donation of the input type
2. the unordered list of types that may give donation to the input type
If you write a function, then please also provide a test program to call that function with a few examples, so I can easily test it. In this case, the test program would not count towards your score.
### Input
Input must be a string representing exactly one of the 8 possible red blood cell types `O−` `O+` `A−` `A+` `B−` `B+` `AB−` `AB+`. Input may be given via the normal methods (STDIN, command-line args, function args, etc).
If any other input is given then the program/function must return empty output or throw an error. Normally strict input-checking is not great in [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") questions, but I felt given the life-death implications of getting blood types wrong that I should add this rule.
### Output
Output will be two human-readable lists of blood types in whatever format is suitable for your language. In the special cases where one of the output list contains all 8 types, this list may optionally be replaced with a single item list containing `everyone`.
Normal output will go to one of the normal places (STDOUT, function return, etc).
### Other rules
* [Standard loopholes](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) are banned
* You may use whatever pre-existing 3rd party libraries you need, so long as they are not designed explicitly for this purpose.
### Examples
* For input `AB-`, the two output lists would be: `{AB+, AB-}, {AB-, A-, B-, O-}`
* For input `AB+`, the two output lists would be: `{AB+}, {O−, O+, A−, A+, B−, B+, AB−, AB+}` or `{AB+}, {everyone}`
---
Personal note: Please consider donating blood if you are able to. Without the transfusion I received a few years ago, I might not be here today, so I feel very grateful towards those who are able to donate!
[Answer]
# [Clip](http://esolangs.org/wiki/Clip), 69
```
*cTx\{fFx`Tf[tFtx}T`[Fx[y!VVx"O-"Vy"O-"}[TC"A+ B+ AB+ O+ A- B- AB- O-
```
Input: `AB-`
Output: `{{"AB+", "AB-"}, {"A-", "B-", "AB-", "O-"}}`
## Explanation
A blood type `x` can give to `y` if all of `x`'s antigens are included in `y`. The program defines the function `F` as whether `x` can give to `y`, and `T` as the list of types.
```
*cTx .- If T contains x (the input) -.
\ .- Print -.
{ ` .- a list of -.
fFx`T .- filter each t in T with F(x,t) -.
f[tFtx}T .- filter each t in T with F(t,x) -.
[Fx[y } .- F is a function of x and y -.
!V .- all letters of ... are included in ... -.
Vx"O-" .- x, with O and - removed -.
Vy"O-" .- y, with O and - removed -.
[TC"A+ B+ AB+ O+ A- B- AB- O- .- T is the list of types -.
```
[Answer]
# Java 8, 373
```
import java.util.*;void f(String s){List<String>l=new ArrayList(Arrays.asList("A+,B+,AB+,O+,A-,B-,AB-,O-".split(","))),m=new ArrayList(l);int i=l.contains(s)?1:0/0;l.removeIf(x->g(s,x)<1);m.removeIf(x->g(x,s)<1);System.out.print(l+","+m);}int g(String s,String t){for(char c:s.replaceAll("O|-","").toCharArray())if(!t.replaceAll("O|-","").contains(""+c))return 0;return 1;}
```
## Explanation
```
void f(String s) {
List<String> l = new ArrayList(Arrays.asList("A+,B+,AB+,O+,A-,B-,AB-,O-".split(","))),
m = new ArrayList(l);
int i = l.contains(s) ? 1 : 0 / 0;
l.removeIf(x -> g(s, x) < 1);
m.removeIf(x -> g(x, s) < 1);
System.out.print(l + "," + m);
}
int g(String s, String t) {
for (char c : s.replaceAll("O|-", "").toCharArray()) {
if (!t.replaceAll("O|-", "").contains("" + c)) {
return 0;
}
}
return 1;
}
```
Run it here: <http://repl.it/e98/1>
Note that `static` had to be added to each method to call them from the main method.
[Answer]
# Pyth, 61 59 50
```
L-{b"O-"M!-yGyHJmsd*c"A O B AB"d"+-"I}zJfgzTJfgYzJ
```
[Run it here.](https://pyth.herokuapp.com/?code=L-%7Bb%22O-%22M!-yGyHJmsd*c%22A+O+B+AB%22d%22%2B-%22I%7DzJfgzTJfgYzJ&input=B%2B&debug=0)
Explanation:
```
L-{b"O-" Create function y(b) that makes a set from b's
characters minus O and -.
M!-yGyH Create function g(G,H) that checks if y(G) is
a subset of y(H).
J Assign to J...
msd The concatenation of every element in...
*c"A O B AB"d"+-" The Cartesian product of A O B AB and + -.
I}zJ If input in J then...
fgzTJ Print all elements e in J if g(input, e).
fgYzJ Print all elements e in J if g(e, input).
```
[Answer]
# CJam, 64 bytes
```
"AB"_a+'O+"+-"m*:s:TT{}+Tqa#=a+T4=f&_)f{\-!}\)f-:!]{T]z::*La-p}/
```
The `m*:s` part comes from [Martin's CJam answer](https://codegolf.stackexchange.com/a/47994/25180). (I didn't read the other parts yet.)
There will be still some serious problems because they'll be never sure about the order of the two lists. And `Block ArrayList &` might be implemented in later versions of CJam.
### Explanation
```
"AB"_a+'O+ " Generate ['A 'B \"AB\" 'O]. ";
"+-"m*:s:T " Generate the list of blood types and store in T. ";
T{}+
Tqa# " Find the input in T. ";
= " Find the blood type by the index.
If not found, return a block to cause an error. ";
a+ " Append the verified input to T. ";
T4= " AB+. ";
f& " Intersect each blood type with AB+. ";
_)f{\-!} " Check emptiness of input - each item. ";
\)f-:! " Check emptiness of each item - input. ";
]{ " For both lists: ";
T]z::* " Replace items in T where there is a 0 with empty strings. ";
La- " Remove empty strings. ";
p " Print. ";
}/
```
[Answer]
# Prolog, ~~119~~ 110 bytes
```
u(A,B):-member(A:B,[a:ab,b:ab,o:a,o:b,o:ab]);A=B,member(A,[a,ab,b,o]).
g(X,Y):-(X= -A;X=A),(Y= -B;Y=B),u(A,B).
```
*Remarks*:
1. Blood types have the following properties: everytime you have a `-` (e.g. `a-`), you can give to the same people as the one who have positive equivalent of your group (e.g. `a`), as well as their negative counterpart (e.g. `a` gives to `ab`, so `a-` gives to `ab` and `ab-`). Based on this property, and *abusing the notations a little bit* to make use of the minus and plus operators, we can factor a lot of cases. *Please tell me if you find it acceptable*. If you prefer having the original (postfix) syntax, here is a non-golfed version:
```
blood(X):-member(R,['a+','o+','b+','ab+','a-','b-','ab-']).
give('o-',R):-blood(R).
give(X,X):-blood(X).
give('a+','ab+').
give('b+','ab+').
give('o+','a+').
give('o+','b+').
give('o+','ab+').
give('a-','a+').
give('a-','ab+').
give('a-','ab-').
give('b-','b+').
give('b-','ab+').
give('b-','ab-').
give('ab-','ab+').
```
2. This is Prolog, so the interactive environment allows to query everything as requested (see example below). Granted, we don't have lists strictly as an output, but this is equivalent.
We also naturally handle error cases as a consequence.
## Example
```
donors(X,L) :- findall(Y,g(Y,X),L).
receivers(X,L) :- findall(Y,g(X,Y),L).
test :-
member(X,[a,o,b,ab,-a,-o,-b,-ab]),
donors(X,D),
receivers(X,R),
writeln(X:give_to(R):receive_from(D)),
fail.
test.
```
Then, we execute `test`:
```
a : give_to([ab, a]) : receive_from([o, a])
o : give_to([a, b, ab, o]) : receive_from([o])
b : give_to([ab, b]) : receive_from([o, b])
ab : give_to([ab]) : receive_from([a, b, o, ab])
-(a) : give_to([+(ab), +(a), -(ab), -(a)]) : receive_from([-(o), -(a)])
-(o) : give_to([+(a), +(b), +(ab), +(o), -(a), -(b), -(ab), -(o)]) : receive_from([-(o)])
-(b) : give_to([+(ab), +(b), -(ab), -(b)]) : receive_from([-(o), -(b)])
-(ab) : give_to([+(ab), -(ab)]) : receive_from([-(a), -(b), -(o), -(ab)])
```
... which, without proper formatting, is the same matrix as the one given in the question.
## Details
The predicate `g/2` is the *give* relationship: `g(X,Y)` means *people of blood type X may give blood to people of blood type Y*.
Find receivers for group `a`:
```
[eclipse]: g(a,R).
R = ab
Yes (0.00s cpu, solution 1, maybe more) ? ;
R = a
Yes (0.00s cpu, solution 2)
```
Find receivers for `orange_juice` (should fail):
```
[eclipse] g(orange_juice,L).
No (0.00s cpu)
```
Find donors for `O-`:
```
[eclipse] g(X,-o).
X = -(o)
Yes (0.00s cpu)
```
Who can give what? :
```
[eclipse] g(X,Y).
.... 27 answers ....
```
We do not go into an infinite recursion loop (it was the case in preliminary tests).
[Answer]
# Javascript, 167
```
p=function(t){o="";if((x=(l="O- O+ B- B+ A- A+ AB- AB+".split(" ")).indexOf(t))<0)return;n=2;while(n--){y=8;while(y--)if([y,x][n]-(y&x)==0)o+=" "+l[y];o+=";"}return o}
```
ungolfed:
```
function p(btype){
output = "";
btypeList = "O- O+ B- B+ A- A+ AB- AB+".split(" ");
btypeInt = btypeList.indexOf(btype);
// thus we have the scheme
// btypeInt = 0b(has A antigen)(has B antigen)(has rhesus antigen)
if(btypeInt < 0) // i.e. broken blood type string
return;
for(receiving = 7; receiving >= 0; receiving--)
if(giving - (receiving & btypeInt) == 0)
// i.e. the receiving person has at least all the antigens of our donor
output += " " + btypeList[receiving];
output += ";";
for(giving = 7; giving >= 0; giving--)
if(btypeInt - (receiving & btypeInt) == 0)
// i.e. the giving person has no antigens that our patient doesn't have
output += " " + btypeList[receiving];
return output;
}
```
testing function:
```
function tester(){
btypeList = "O- O+ B- B+ A- A+ AB- AB+".split(" ");
for(i=0; i<8; i++){
console.log("Patient is " + btypeList[i])
console.log(p(btypeList[i]))
}
console.log("Erroneous blood type => returns void:")
console.log(p("asdf"))
}
```
Encoding the blood type in binary has the advantage that another antigen (e.g. the [Kell antigen](http://en.wikipedia.org/wiki/Kell_antigen_system)) is easily incorporated into the code by just adding another bit.
---
Donate blood in Zurich, CH: [Blutspende Zürich](http://www.blutspendezuerich.ch/)
[Answer]
# CJam, 94 bytes
Wow, this is long... while I think I could probably golf this approach below 80, I think I might have done better by first computing the matrix and then simply picking out the correct row and column. Anyway, here it is:
```
'O'A'B"AB"]:A"+-"m*:sq_a@&!!*_)'++_&\"AB"&A{1$\-!},\;\m*::+p)'-+_&\"AB"&A1>{1$-!},'O+\;\m*::+p
```
[Test it here.](http://cjam.aditsu.net/#code='O'A'B%22AB%22%5D%3AA%22%2B-%22m*%3Asq_a%40%26!!*_)'%2B%2B_%26%5C%22AB%22%26A%7B1%24%5C-!%7D%2C%5C%3B%5Cm*%3A%3A%2Bp)'-%2B_%26%5C%22AB%22%26A1%3E%7B1%24-!%7D%2C'O%2B%5C%3B%5Cm*%3A%3A%2Bp&input=AB-)
I'll add an explanation when I'm done golfing.
[Answer]
# Groovy, 115
```
x={i=(l=('O-O+B-B+A-A+AB-AB+'=~/\w+./)[0..7]).indexOf(it);f=(0..7).&findAll;i<0?[]:[l[f{!(~it&i)}],l[f{!(it&~i)}]]}
```
The idea is to encode A, B and rhesus factor as one bit each. We can then inverse the bits to get all the antigens on the receiving side and use it to check that there is no corresponding antibodies on the giving side. This is more or less the same as the existing JavaScript solution.
Sample execution
```
groovy> println x("AB+")
groovy> println x("AB-")
groovy> println x("A+")
groovy> println x("A-")
groovy> println x("B+")
groovy> println x("B-")
groovy> println x("O+")
groovy> println x("O-")
groovy> println x("X")
[[AB+], [O-, O+, B-, B+, A-, A+, AB-, AB+]]
[[AB-, AB+], [O-, B-, A-, AB-]]
[[A+, AB+], [O-, O+, A-, A+]]
[[A-, A+, AB-, AB+], [O-, A-]]
[[B+, AB+], [O-, O+, B-, B+]]
[[B-, B+, AB-, AB+], [O-, B-]]
[[O+, B+, A+, AB+], [O-, O+]]
[[O-, O+, B-, B+, A-, A+, AB-, AB+], [O-]]
[]
```
[Answer]
# Python, 187 bytes
Different approach:
```
def D(a,b):X=lambda c:c in a and 1-(c in b);return(X('A')+X('B')+X('+'))<1
T="O- O+ A- A+ B- B+ AB- AB+".split()
X=lambda t:(0,([u for u in T if D(t,u)],[u for u in T if D(u,t)]))[t in T]
```
Can probably be golfed a bit more.
**Test:**
```
for t in T + ["zz"]:
print t, X(t)
```
**Output:**
```
O- (['O-', 'O+', 'A-', 'A+', 'B-', 'B+', 'AB-', 'AB+'], ['O-'])
O+ (['O+', 'A+', 'B+', 'AB+'], ['O-', 'O+'])
A- (['A-', 'A+', 'AB-', 'AB+'], ['O-', 'A-'])
A+ (['A+', 'AB+'], ['O-', 'O+', 'A-', 'A+'])
B- (['B-', 'B+', 'AB-', 'AB+'], ['O-', 'B-'])
B+ (['B+', 'AB+'], ['O-', 'O+', 'B-', 'B+'])
AB- (['AB-', 'AB+'], ['O-', 'A-', 'B-', 'AB-'])
AB+ (['AB+'], ['O-', 'O+', 'A-', 'A+', 'B-', 'B+', 'AB-', 'AB+'])
zz 0
```
[Answer]
# Ruby, 237 232 223 221 210 207 bytes
Fixed some extraneous backslashes in the regular expressions and made it so it just prints out the lists as opposed to storing them to variables and then printing them. Sometimes you miss the obvious things when trying to golf!
```
o=->b{Regexp.new b.gsub(?O,?.).gsub(?+,'.?\\\+').gsub'-','.?(\W)'};b=gets.chop;t=["A+","B+","AB+","O+","A-","B-","AB-","O-"];exit if !t.include? b;p t.reject{|x|!x.match o.(b)};p t.reject{|x|!b.match o.(x)}
```
Ungolfed:
```
#!/usr/bin/ruby
b=gets.chomp;
types = ["A+","A-","B+","B-","AB+","AB-","O+","O-"];
exit if !types.include?(b);
regex1 = Regexp.new b.gsub("O",".").gsub('+','.?\\\+').gsub('-','.?(\\\+|\\\-)')
donate = types.reject {|x|!x.match(regex1)};
p donate;
receive = types.reject {|x| regex2 = Regexp.new x.gsub("O",".").gsub('+','.?\\\+').gsub('-','.?(\\\+|\\\-)'); !b.match(regex2)};
p receive;
```
Basically, I construct a custom regular expression for the blood type entered to check if you can donate to another blood type. I then iterate through the blood types and apply that same regex to them and check if they can donate to the one specified.
This can probably be golfed down even more. This is my first time attempting code golf, heh.
[Answer]
# Python 2, 168 bytes
This is the same method as Blackhole's answer. Exits with an error if the parameter is not found in the list of types.
```
def f(t):l='A+ O+ B+ AB+ A- O- B- AB-'.split();c=[9,15,12,8,153,255,204,136];i=l.index(t);print[s for s in l if c[i]&1<<l.index(s)],[s for s in l if c[l.index(s)]&1<<i]
```
**Less golfed:**
```
def f(t):
l = 'A+ O+ B+ AB+ A- O- B- AB-'.split()
c = [9, 15, 12, 8, 153, 255, 204, 136]
i = l.index(t)
x = [s for s in l if c[i] & 1 << l.index(s)]
y = [s for s in l if c[l.index(s)] & 1 << i]
print x, y
```
Run it here: <http://repl.it/eaB>
I also tried a couple other slight changes, but couldn't get it any shorter...
```
#172 bytes
def f(t):l='A+ O+ B+ AB+ A- O- B- AB-'.split();c=[9,15,12,8,153,255,204,136];a=lambda x:l.index(x);i=a(t);print[s for s in l if c[i]&1<<a(s)],[s for s in l if c[a(s)]&1<<i]
#171 bytes
def f(t):l='A+ O+ B+ AB+ A- O- B- AB-'.split();c=[9,15,12,8,153,255,204,136];a=lambda x:l.index(x);print[s for s in l if c[a(t)]&1<<a(s)],[s for s in l if c[a(s)]&1<<a(t)]
```
[Answer]
# PHP (287 bytes):
Yeah, this is pretty long, but it works as expected.
It may be possible to shorten a lot:
```
!preg_match('@^(AB?|B|O)[+-]$@',$t=$_GET[T])&&die("$t invalid");$S=array_flip($D=split(0,'O+0A+0B+0AB+0O-0A-0B-0AB-'));$L=[[1230,40],[13,1504],[23,2604],[3,$r=12345670],[$r,4],[1537,54],[2637,64],[37,7564]];for($j=0;$j<2;){foreach(str_split($L[$S[$t]][$j++])as$v)echo$D[$v].' ';echo'
';}
```
This is not easy to read and was't easy to write.
It works as intended, outputting the ones you can give to and the ones you can receive from on another line.
This requires a URL parameter `T=` with the type.
[Answer]
# CJam, 80 bytes
This is still too long. Probably I can shave off 4 to 5 bytes more.
```
U1023_XKC30D]2/La+"AB"a"OAB"1/+:Mr):P;a#=_P"+-":G&+!!{AfbMff=G1/Pf|]z{~m*:s}%}*`
```
For any invalid input, either prints an empty array, or throws an error.
[Try it online here](http://cjam.aditsu.net/#code=U1023_XKC30D%5D2%2FLa%2B%22AB%22a%22OAB%221%2F%2B%3AMr)%3AP%3Ba%23%3D_P%22%2B-%22%3AG%26%2B!!%7BAfbMff%3DG1%2FPf%7C%5Dz%7B~m*%3As%7D%25%7D*%60&input=A-%2B) or [run the whole test suite](http://cjam.aditsu.net/#code=8%7BU1023_XKC30D%5D2%2FLa%2B%22AB%22a%22OAB%221%2F%2B%3AMl)%3AP%3Ba%23%3D_P%22%2B-%22%3AG%26%2B!!%7BAfbMff%3DG1%2FPf%7C%5Dz%7B~m*%3As%7D%25%7D*p%7D*&input=A%2B%0AO%2B%0AB%2B%0AAB%2B%0AA-%0AO-%0AB-%0AAB-)
[Answer]
# APL, 66
```
(↓⊃∧/(↓t∘.∊v)(≥,[.5]≤)¨t∊⊃v⌷⍨v⍳⊂⍞)/¨⊂v←,'+-'∘.,⍨('O'∘,,⊂)2↑t←'AB+'
```
[Try it here.](http://tryapl.org/?a=%7B%28%u2193%u2283%u2227/%28%u2193t%u2218.%u220Av%29%28%u2265%2C%5B.5%5D%u2264%29%A8t%u220A%u2283v%u2337%u2368v%u2373%u2282%u2375%29/%A8%u2282v%u2190%2C%27+-%27%u2218.%2C%u2368%28%27O%27%u2218%2C%2C%u2282%292%u2191t%u2190%27AB+%27%7D%27A+%27&run)
[Answer]
# C, 224
```
#define d(x)for(i=0;i<8;i++)if((i x j)==j)printf("%s%s%s%c ",i&2?"A":"",i&4?"B":"",i&6?"":"0","-+"[i&1]);puts("");
main(i,j){char d[4],*c=&d;scanf("%s",c);j=(c[2]?c++,2:0)+(c[1]-'+'?0:1)+(*c>='A'?2:0)+(*c>'A'?2:0);d(&)d(|)}
```
De-golfed it shows:
```
/* j = 1*(has+) + 2*(hasA) + 4*(hasB) */
#define d(x) for(i=0;i<8;i++) \
if((i x j)==j) \
printf("%s%s%s%c ",i&2?"A":"",i&4?"B":"",i&6?"":"0","-+"[i&1]); \
puts("");
main(i,j)
{
char d[4], *c=&d;
scanf("%s",c);
j= (c[2]? (c++,2):0) /* ABx */
+ (c[1]-'+'?0:1)
+ (c[0]>='A'?2:0)
+ (c[0]>'A'?2:0);
// print possible receipients, and then donators
d(&)
d(|)
}
```
[Answer]
## PHP - ~~215~~ ~~212~~ 206 bytes
```
function($t){$c=[9,15,12,8,153,255,204,136];if(($a=array_search($t,$l=split(1,'A+1O+1B+1AB+1A-1O-1B-1AB-')))===!1)die;foreach($l as$k=>$v){if($c[$a]&1<<$k)$x[]=$v;if($c[$k]&1<<$a)$y[]=$v;}var_dump($x,$y);}
```
Here is the ungolfed version:
```
function ($type)
{
$typesList = ['A+', 'O+', 'B+', 'AB+', 'A-', 'O-', 'B-', 'AB-'];
$donationCompatibilityList = [
0b00001001,
0b00001111,
0b00001100,
0b00001000,
0b10011001,
0b11111111,
0b11001100,
0b10001000,
];
$idType = array_search($type, $typesList);
if ($idType === false) {
die;
}
$canGiveToList = [];
$canReceiveFromList = [];
foreach ($typesList as $currentIdType => $currentType)
{
if ($donationCompatibilityList[$idType] & 1 << $currentIdType ) {
$canGiveToList[] = $currentType;
}
if ($donationCompatibilityList[$currentIdType ] & 1 << $idType) {
$canReceiveFromList[] = $currentType;
}
}
var_dump($canGiveToList, $canReceiveFromList);
}
```
Thanks to [manatwork](https://codegolf.stackexchange.com/users/4198/manatwork) for saving 4 bytes.
[Answer]
# Perl, 107 ~~112~~
Finally encoding the type names in numbers gave the shorter code.
```
#!perl -p
$x=y/AB+/421/r%9;@a=grep{~$x&$_%9||push@b,$_;!($x&~($_%9))}map{("$_-",$_.1)}0,2,4,42;$_="@a
@b";y/421/AB+/
```
Older version
```
#!perl -p
$x=y/AB+/421/r%9;@a=grep!($x&~$_),0..7;@b=grep!(~$x&$_),0..7;$_="@a
@b";s/\d/(map{("$_+","$_-")}0,A,B,AB)[$&]/eg
```
[Answer]
# Pyth, 58
Partly the same as orlp's [solution](https://codegolf.stackexchange.com/a/48026/30164), but somewhat different and completely self-designed.
```
M&n+eGeH"+-"!f!}T+H\OPGJsm,+d\++d\-c"O A B AB"dfgzYJfgZzJJ
```
## Explanation
```
M create a function g(G,H) that returns
n+eGeH"+-" G[-1] + H[-1] is not "+-"
& and
!f!}T+H\OPG chars of G[:-1] not in H + "O" is falsy (empty)
J J =
s merge
m map
,+d\++d\- lambda d: (d + "+", d + "-")
c"O A B AB"d over ["O", "A", "B", "AB"]
fgzYJ print all J's items x where g(input, x)
fgZzJ print all J's items x where g(x, input)
```
[Answer]
# J, 120 bytes
```
f=.3 :';"1(2 8$,(s-:"*<y,'' '')#8 2 8$#:213472854600871062656691437010712264449x)#s=.<;.2''A+ B+ AB+ O+ A- B- AB- O- '''
f 'A+'
A+ AB+
A+ O+ A- O-
f 'AB-'
AB+ AB-
A- B- AB- O-
```
The function fails on invalid inputs. The big decimal number is the encoding of the full compatibility matrix.
(Very long solution for multiple reasons.)
[Try it online here.](http://tryj.tk/)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 29 bytes
```
„ABD`'O)„+-âJÐIkVāY&èê,āY~èê,
```
[Try it online!](https://tio.run/##yy9OTMpM/f//UcM8RyeXBHV/TSBLW/fwIq/DEzyzw440RqodXnF4lQ6QUQdm/P/vpA0A "05AB1E – Try It Online")
] |
[Question]
[
[Deadfish](http://esolangs.org/wiki/Deadfish) is one of the best known non Turing-complete programming languages. It has only one accumulator (which starts at 0) to store data, and only four commands:
```
i - Increment the accumulator
s - Square the accumulator
d - Decrement the accumulator
o - Output the accumulator
```
A Deadfish program may look like:
```
iiisdo
```
And that would print:
```
8
```
---
# The challenge
Create a program that will input a number and output Deadfish code to display the number.(Or make a function that takes the number as a parameter and returns the code.) It must work for any integer from `0` to `255`
## Goal
Try to make your code make the shortest code possible to generate the given number. For example:
```
iiiiiiiiio
```
and
```
iiiso
```
each print `9`, but the second is shorter.
# Scoring
Your score is:
```
The number of characters in your source code +
The sum of the lengths of your output for all numbers from 1-255
-100 if the language you chose is Deadfish :)
```
Lowest score wins!
---
In the original challenge I only had the sum of 6 numbers(9,17,99,100 and 123).
This was from me wanting to not make everyone test for every number, and I wanted the shortest code to be relevant. Then I realized that programmers are good at making scripts to test things like that, and I would rather have this be a contest for best algorithm with golfing as a tiebreaker.
Therefor I changed this, as suggested by Martin Büttner.
[Answer]
# ES6 JavaScript 2126 + 311 = 2437 score
```
m=Math;s=n=>[b=m.min(m.sqrt(n)+.5|0,15),n-b*b];f=n=>(n<0?'d':'i').repeat(m.abs(n));g=(n,t)=>n<4?f(n):g((t=s(n))[0])+'s'+f(t[1]);q=n=>((x=g(n)).length>(z=[...n+''].map((k,i,a)=>i?(a[i-1]==a[i]?'':(y=f((l=s(k))[0]-a[i-1])+(l[0]?'s':'')+f(l[1])).length>m.abs(Q=a[i]-a[i-1])?f(Q):y):g(k)).join('o')).length?z:x)+'o'
```
Semi-commented:
```
m = Math; // Keep a reference to math
// This function returns the closest perfect square and the distance from that square to the number
// E.g. s(10) --> [3, 1] because 3^2 + 1 = 10
s = n => [b = m.min(m.sqrt(n) + .5 | 0, 15), n - b * b];
// This creates a bunch of "d"s or "i"s
// E.g. f(3) --> "iii" or f(-2) --> "dd"
f = n => Array(m.abs(n) + 1).join(n < 0 ? 'd' : 'i');
// This constructs the number as a number rather than by digit
g = (n, t) => n < 4 ?
// If n is less than 4, then we can just increment in normally (base case)
f(n) :
// Otherwise, build the square root recursively and shift
g((t = s(n))[0]) + 's' + f(t[1]);
// This maps based on digits (constructs the number by digit)
// This has now been removed and replaced inline because it is only used once
d = n => (a = [...(n + '')]).map((k, i) => i ? (a[i - 1] == a[i] ? '' : f((l = s(k))[0] - a[i - 1]) + (l[0] ? 's' : '') + f(l[1])) : g(k)).join('o');
// For the official function, compare the digit-method and nondigit-method and return the best one
q = n => ((x = g(n)).length > (z = d(n)).length ? z : x) + 'o'
```
This takes advantage of the fact that in deadfish, you can print more than one character.
Example: `10` compiles to `iodo` which is "print one, decrement, print zero."
Usage:
```
q(10) // --> iodo
q(16) // --> iisso
```
Here's json data of output:
```
{
"0": "o",
"1": "io",
"2": "iio",
"3": "iiio",
"4": "iiso",
"5": "iisio",
"6": "iisiio",
"7": "iiisddo",
"8": "iiisdo",
"9": "iiiso",
"10": "iodo",
"11": "ioo",
"12": "ioio",
"13": "ioiio",
"14": "ioiso",
"15": "iissdo",
"16": "iisso",
"17": "iissio",
"18": "iissiio",
"19": "ioiiso",
"20": "iioddo",
"21": "iiodo",
"22": "iioo",
"23": "iioio",
"24": "iioso",
"25": "iisiso",
"26": "iisisio",
"27": "iisisiio",
"28": "iioisdo",
"29": "iioiso",
"30": "iiiodddo",
"31": "iiioddo",
"32": "iiiodo",
"33": "iiioo",
"34": "iiioio",
"35": "iiioiio",
"36": "iisiiso",
"37": "iisiisio",
"38": "iiiosdo",
"39": "iiioso",
"40": "iisoddddo",
"41": "iisodddo",
"42": "iisoddo",
"43": "iisodo",
"44": "iisoo",
"45": "iisoio",
"46": "iisoiio",
"47": "iisoiiio",
"48": "iisodsdo",
"49": "iisodso",
"50": "iiisddsio",
"51": "iiisddsiio",
"52": "iisiodddo",
"53": "iisioddo",
"54": "iisiodo",
"55": "iisioo",
"56": "iisioio",
"57": "iisioiio",
"58": "iisioiiio",
"59": "iisioddso",
"60": "iiisdsddddo",
"61": "iiisdsdddo",
"62": "iiisdsddo",
"63": "iiisdsdo",
"64": "iiisdso",
"65": "iiisdsio",
"66": "iisiioo",
"67": "iisiioio",
"68": "iisiioiio",
"69": "iisiioiiio",
"70": "iiisdsiiiiiio",
"71": "iiisdsiiiiiiio",
"72": "iiisddodddddo",
"73": "iiisddoddddo",
"74": "iiisddodddo",
"75": "iiisddoddo",
"76": "iiisddodo",
"77": "iiisddoo",
"78": "iiissdddo",
"79": "iiissddo",
"80": "iiissdo",
"81": "iiisso",
"82": "iiissio",
"83": "iiissiio",
"84": "iiissiiio",
"85": "iiissiiiio",
"86": "iiisdoddo",
"87": "iiisdodo",
"88": "iiisdoo",
"89": "iiisdoio",
"90": "iiissiiiiiiiiio",
"91": "iiisoddddddddo",
"92": "iiisodddddddo",
"93": "iiisoddddddo",
"94": "iiisodddddo",
"95": "iiisoddddo",
"96": "iiisodddo",
"97": "iiisoddo",
"98": "iiisodo",
"99": "iiisoo",
"100": "iodoo",
"101": "iodoio",
"102": "iodoiio",
"103": "iodoiiio",
"104": "iodoiiso",
"105": "iodoiisio",
"106": "iodoiisiio",
"107": "iodoiiisddo",
"108": "iodoiiisdo",
"109": "iodoiiiso",
"110": "ioodo",
"111": "iooo",
"112": "iooio",
"113": "iooiio",
"114": "iooiso",
"115": "iooisio",
"116": "iooisiio",
"117": "iooiisddo",
"118": "iooiisdo",
"119": "iooiiso",
"120": "ioioddo",
"121": "ioiodo",
"122": "ioioo",
"123": "ioioio",
"124": "ioioso",
"125": "ioiosio",
"126": "ioiosiio",
"127": "ioioisddo",
"128": "ioioisdo",
"129": "ioioiso",
"130": "ioiiodddo",
"131": "ioiioddo",
"132": "ioiiodo",
"133": "ioiioo",
"134": "ioiioio",
"135": "ioiioiio",
"136": "ioiioiiio",
"137": "ioiiosddo",
"138": "ioiiosdo",
"139": "ioiioso",
"140": "ioisoddddo",
"141": "ioisodddo",
"142": "ioisoddo",
"143": "ioisodo",
"144": "ioisoo",
"145": "ioisoio",
"146": "ioisoiio",
"147": "ioisoiiio",
"148": "ioisodsdo",
"149": "ioisodso",
"150": "ioisiodddddo",
"151": "ioisioddddo",
"152": "ioisiodddo",
"153": "ioisioddo",
"154": "ioisiodo",
"155": "ioisioo",
"156": "ioisioio",
"157": "ioisioiio",
"158": "ioisioiiio",
"159": "ioisioddso",
"160": "ioisiioddddddo",
"161": "ioisiiodddddo",
"162": "ioisiioddddo",
"163": "ioisiiodddo",
"164": "ioisiioddo",
"165": "ioisiiodo",
"166": "ioisiioo",
"167": "ioisiioio",
"168": "iissdddsdo",
"169": "iissdddso",
"170": "iissdddsio",
"171": "iissdddsiio",
"172": "iissdddsiiio",
"173": "iissdddsiiiio",
"174": "ioiisddodddo",
"175": "ioiisddoddo",
"176": "ioiisddodo",
"177": "ioiisddoo",
"178": "ioiisddoio",
"179": "ioiisddoiio",
"180": "ioiisdoddddddddo",
"181": "ioiisdodddddddo",
"182": "ioiisdoddddddo",
"183": "ioiisdodddddo",
"184": "ioiisdoddddo",
"185": "ioiisdodddo",
"186": "ioiisdoddo",
"187": "ioiisdodo",
"188": "ioiisdoo",
"189": "ioiisdoio",
"190": "iissddsddddddo",
"191": "iissddsdddddo",
"192": "iissddsddddo",
"193": "iissddsdddo",
"194": "iissddsddo",
"195": "iissddsdo",
"196": "iissddso",
"197": "iissddsio",
"198": "ioiisodo",
"199": "ioiisoo",
"200": "iioddoo",
"201": "iioddoio",
"202": "iioddoiio",
"203": "iioddoiiio",
"204": "iioddoiiso",
"205": "iioddoiisio",
"206": "iioddoiisiio",
"207": "iioddoiiisddo",
"208": "iioddoiiisdo",
"209": "iioddoiiiso",
"210": "iiododo",
"211": "iiodoo",
"212": "iiodoio",
"213": "iiodoiio",
"214": "iiodoiso",
"215": "iiodoisio",
"216": "iiodoisiio",
"217": "iiodoiisddo",
"218": "iiodoiisdo",
"219": "iiodoiiso",
"220": "iiooddo",
"221": "iioodo",
"222": "iiooo",
"223": "iiooio",
"224": "iiooso",
"225": "iissdso",
"226": "iissdsio",
"227": "iissdsiio",
"228": "iiooisdo",
"229": "iiooiso",
"230": "iioiodddo",
"231": "iioioddo",
"232": "iioiodo",
"233": "iioioo",
"234": "iioioio",
"235": "iioioiio",
"236": "iioioiiio",
"237": "iioiosddo",
"238": "iioiosdo",
"239": "iioioso",
"240": "iiosoddddo",
"241": "iiosodddo",
"242": "iiosoddo",
"243": "iiosodo",
"244": "iiosoo",
"245": "iiosoio",
"246": "iiosoiio",
"247": "iiosoiiio",
"248": "iiosodsdo",
"249": "iiosodso",
"250": "iiosiodddddo",
"251": "iiosioddddo",
"252": "iiosiodddo",
"253": "iiosioddo",
"254": "iiosiodo",
"255": "iiosioo"
}
```
That was generated by this code:
```
var c = {}, result = 0;
for (var i = 0; i <= 255; ++i) result += (c[i] = q(i)).length;
```
which prints `result = (the result)` and `c =` the thing above.
This gets a remarkably high score despite being pretty simple. It searches for the nearest perfect square, calculates the square root of that perfect square, adds 's', and increments/decrements appropriately.
Old version which didn't use the fact that "10" = "print one, print zero"
```
m=Math;s=n=>[b=m.sqrt(n)+.5|0,n-b*b];f=(n)=>Array(m.abs(n)+1).join('id'[+(n<0)]);g=(n,t)=>n<4?f(n):g((t=s(n))[0])+'s'+f(t[1]);q=n=>g(n)+'o'
```
[Answer]
# Haskell, ~~2200~~ ~~2177~~ 2171 = 2036 + 135
```
f n=[s|s<-l,s%0==show n]!!0
l="":[c:x|x<-l,c<-"iosd"]
(h:s)%n|h<'e'=s%(n-1)|h<'j'=s%(n+1)|h<'p'=show n++s%n|n==16=s%0|0<1=s%(n^2)
x%_=x
```
this works by having an infinite list of all deadfish programs, sorted by their length, accompanied by the internal state and the output. the function `f` searches the list and returns the first entry that matches.
this approach allows for for multiple `o` in each resulting code, but does not restrict it to either printing all the digits separately, or printing the whole number at once. for example, here 216 has the code of `iiosso`.
**Edit:**
according to the spec, when the state is 256 (but not 257) it is made into a 0. now my code takes this into account. for example, 160 is `iissoso`.
this has a few efficiency problems; because `l` is a top-level list, all the elements of `l` which have been evaluated stay in memory, and so runtime will probably be out of memory at some point.
to calculate the score, I made an equivalent-but-less-memory-heavy version.
my more-efficient code works by recomputing the list on every application of `f`, so that the garbage collector can throw the already searched part of the list away. in a sense, this is breadth-first search using laziness.
the more-efficient code also adds some more constraints to the elements of the list - it filters out all codes that contain `id` or `di`, or contains an `s` when the state is smaller than 2.
**Edit:**
I moved the `g` function from the top level to being a helper function to
`f'`, so now `g` filters codes that printed something which isn't a prefix of our wanted number. now the code is much faster.
the more-efficient code:
```
f' n=[reverse s|(s,_,r)<-l,r==show n]!!0 where
l=("",0,""):l>>= \(i,s,r)->filter g[('i':i,s+1,r),('o':i,s,r++show s),('s':i,if s==16 then 0 else s*s,r),('d':i,s-1,r)]
g('i':'d':_,_,_)=False
g('d':'i':_,_,_)=False
g('i':'i':_,4,_)=False
g('s':_,1,_)=False
g("s",_,_)=False
g("si",_,_)=False
g(i,s,r)=s<256&&s>=0&&isPrefixOf r (show n)
```
note the more-efficient code will not have the same results because the programs traverse all the possible codes in different order. however, they will output codes of the same length. also, switching `c:x` with `x++[c]` makes the programs equivalent.
with this code i was able to compute all the programs in ~~52~~ 0.81 seconds.
**Edit:**
apparently this is the best answer! i noticed it just now, so far from when this was asked...
the results:
```
1 io
2 iio
3 iiio
4 iiso
5 iisio
6 iisiio
7 iiisddo
8 iiisdo
9 iiiso
10 iodo
11 ioo
12 ioio
13 ioiio
14 ioiso
15 iissdo
16 iisso
17 iissio
18 iissiio
19 ioiiso
20 iioddo
21 iiodo
22 iioo
23 iioio
24 iioso
25 iiosio
26 iiosiio
27 iioisddo
28 iioisdo
29 iioiso
30 iiioisso
31 iiioddo
32 iiiodo
33 iiioo
34 iiioio
35 iiioiio
36 iisiiso
37 iiiosddo
38 iiiosdo
39 iiioso
40 iisosso
41 iisossio
42 iisoddo
43 iisodo
44 iisoo
45 iisoio
46 iisoiio
47 iisoiiio
48 iisodsdo
49 iisodso
50 iiisddsio
51 iiisddsiio
52 iisiodddo
53 iisioddo
54 iisiodo
55 iisioo
56 iisioio
57 iisioiio
58 iisioiiio
59 iisioddso
60 iiisdsddddo
61 iiisdsdddo
62 iiisdsddo
63 iiisdsdo
64 iiisdso
65 iiisdsio
66 iisiioo
67 iisiioio
68 iisiioiio
69 iisiioiiio
70 iiisdsiiiiiio
71 iiisdsiiiiiiio
72 iiisddodddddo
73 iiisddoddddo
74 iiisddodddo
75 iiisddoddo
76 iiisddodo
77 iiisddoo
78 iiissdddo
79 iiissddo
80 iiissdo
81 iiisso
82 iiissio
83 iiissiio
84 iiissiiio
85 iiissiiiio
86 iiisdoddo
87 iiisdodo
88 iiisdoo
89 iiisdoio
90 iiisodddddsso
91 iiisodddddssio
92 iiisodddddddo
93 iiisoddddddo
94 iiisodddddo
95 iiisoddddo
96 iiisodddo
97 iiisoddo
98 iiisodo
99 iiisoo
100 iodoo
101 iodoio
102 iodoiio
103 iodoiiio
104 iodoiiso
105 iodoiisio
106 iodoiisiio
107 iiisiodddo
108 iiisioddo
109 iiisiodo
110 ioodo
111 iooo
112 iooio
113 iooiio
114 iooiso
115 ioissdo
116 ioisso
117 ioissio
118 ioissiio
119 iooiiso
120 ioioddo
121 ioiodo
122 ioioo
123 ioioio
124 ioioso
125 ioiosio
126 ioiosiio
127 ioioisddo
128 ioioisdo
129 ioioiso
130 ioiioisso
131 ioiioddo
132 ioiiodo
133 ioiioo
134 ioiioio
135 ioiioiio
136 ioisiiso
137 ioiiosddo
138 ioiiosdo
139 ioiioso
140 ioisosso
141 ioisossio
142 ioisoddo
143 ioisodo
144 ioisoo
145 ioisoio
146 ioisoiio
147 ioisoiiio
148 ioisodsdo
149 ioisodso
150 iissdoiso
151 iissdoisio
152 ioisiodddo
153 ioisioddo
154 ioisiodo
155 ioisioo
156 ioisioio
157 ioisioiio
158 ioisioiiio
159 ioisioddso
160 iissoso
161 iissosio
162 iissosiio
163 ioiisdsdo
164 ioiisdso
165 ioiisdsio
166 ioisiioo
167 ioisiioio
168 iissdddsdo
169 iissdddso
170 iissiodso
171 iissiodsio
172 iissiodsiio
173 iissiodsiiio
174 iissiodsiiso
175 ioiisddoddo
176 ioiisddodo
177 ioiisddoo
178 ioiissdddo
179 ioiissddo
180 ioiissdo
181 ioiisso
182 ioiissio
183 ioiissiio
184 ioiissiiio
185 ioiissiiiio
186 ioiisdoddo
187 ioiisdodo
188 ioiisdoo
189 ioiisdoio
190 iissiiiodddso
191 iissddsdddddo
192 iissddsddddo
193 iissddsdddo
194 iissddsddo
195 iissddsdo
196 iissddso
197 iissddsio
198 ioiisodo
199 ioiisoo
200 iioddoo
201 iioddoio
202 iioddoiio
203 iioddoiiio
204 iioddoiiso
205 iioddoiisio
206 iioddoiisiio
207 iioddoiiisddo
208 iioddoiiisdo
209 iioddoiiiso
210 iioisio
211 iiodoo
212 iiodoio
213 iiodoiio
214 iiossddo
215 iiossdo
216 iiosso
217 iiossio
218 iiossiio
219 iiossiiio
220 iiooddo
221 iioodo
222 iiooo
223 iiooio
224 iiooso
225 iioosio
226 iioosiio
227 iiooisddo
228 iiooisdo
229 iiooiso
230 iioioisso
231 iioioddo
232 iioiodo
233 iioioo
234 iioioio
235 iioioiio
236 iiosiiso
237 iioiosddo
238 iioiosdo
239 iioioso
240 iiososso
241 iiosossio
242 iiosoddo
243 iiosodo
244 iiosoo
245 iiosoio
246 iiosoiio
247 iiosoiiio
248 iiosodsdo
249 iiosodso
250 iioisddsio
251 iioisddsiio
252 iiosiodddo
253 iiosioddo
254 iiosiodo
255 iiosioo
```
[Answer]
## Mathematica, ~~254~~ 165 characters + 3455 = 3620
```
f@n_:=n;g@0="";l={f@0=0};h=If[f@#>f@i&&#<256&&#>0,f@#=f@i+1;g@#=g@i<>#2;l~AppendTo~#]&;While[l!={},i=#&@@l;l=Rest@l;h[i+1,"i"];h[i-1,"d"];h[i*i,"s"];];g@Input[]<>"o"
```
Less golf:
```
f@n_ := n;
g@0 = "";
l = {f@0 = 0};
h = If[f@# > f@i && # < 256 && # > 0,
f@# = f@i + 1;
g@# = g@i <> #2;
l~AppendTo~#] &;
While[l != {},
i = # & @@ l;
l = Rest@l;
h[i + 1, "i"];
h[i - 1, "d"];
h[i*i, "s"];
];
g@Input[] <> "o"
```
I believe the resulting numbers are optimal. This is doing a breadth-first search over all 256 numbers, keeping track of the shortest way it has found to represent each number. The search is building a sort of lookup table in the function `g` which is then applied to the input.
For reference, here are all 255 results:
```
io
iio
iiio
iiso
iisio
iisiio
iisiiio
iiisdo
iiiso
iiisio
iiisiio
iiisiiio
iissdddo
iissddo
iissdo
iisso
iissio
iissiio
iissiiio
iissiiiio
iissiiiiio
iisisdddo
iisisddo
iisisdo
iisiso
iisisio
iisisiio
iisisiiio
iisisiiiio
iisisiiiiio
iisisiiiiiio
iisiisddddo
iisiisdddo
iisiisddo
iisiisdo
iisiiso
iisiisio
iisiisiio
iisiisiiio
iisiisiiiio
iisiisiiiiio
iisiisiiiiiio
iisiisiiiiiiio
iisiiisdddddo
iisiiisddddo
iisiiisdddo
iisiiisddo
iisiiisdo
iisiiiso
iisiiisio
iisiiisiio
iisiiisiiio
iisiiisiiiio
iisiiisiiiiio
iisiiisiiiiiio
iisiiisiiiiiiio
iiisdsdddddddo
iiisdsddddddo
iiisdsdddddo
iiisdsddddo
iiisdsdddo
iiisdsddo
iiisdsdo
iiisdso
iiisdsio
iiisdsiio
iiisdsiiio
iiisdsiiiio
iiisdsiiiiio
iiisdsiiiiiio
iiisdsiiiiiiio
iiissdddddddddo
iiissddddddddo
iiissdddddddo
iiissddddddo
iiissdddddo
iiissddddo
iiissdddo
iiissddo
iiissdo
iiisso
iiissio
iiissiio
iiissiiio
iiissiiiio
iiissiiiiio
iiissiiiiiio
iiissiiiiiiio
iiissiiiiiiiio
iiissiiiiiiiiio
iiissiiiiiiiiiio
iiisisddddddddo
iiisisdddddddo
iiisisddddddo
iiisisdddddo
iiisisddddo
iiisisdddo
iiisisddo
iiisisdo
iiisiso
iiisisio
iiisisiio
iiisisiiio
iiisisiiiio
iiisisiiiiio
iiisisiiiiiio
iiisisiiiiiiio
iiisisiiiiiiiio
iiisisiiiiiiiiio
iiisisiiiiiiiiiio
iiisisiiiiiiiiiiio
iiisiisdddddddddo
iiisiisddddddddo
iiisiisdddddddo
iiisiisddddddo
iiisiisdddddo
iiisiisddddo
iiisiisdddo
iiisiisddo
iiisiisdo
iiisiiso
iiisiisio
iiisiisiio
iiisiisiiio
iiisiisiiiio
iiisiisiiiiio
iiisiisiiiiiio
iiisiisiiiiiiio
iiisiisiiiiiiiio
iiisiisiiiiiiiiio
iiisiisiiiiiiiiiio
iiisiisiiiiiiiiiiio
iiisiisiiiiiiiiiiiio
iiisiiisddddddddddo
iiisiiisdddddddddo
iiisiiisddddddddo
iiisiiisdddddddo
iiisiiisddddddo
iiisiiisdddddo
iiisiiisddddo
iiisiiisdddo
iiisiiisddo
iiisiiisdo
iiisiiiso
iiisiiisio
iiisiiisiio
iiisiiisiiio
iiisiiisiiiio
iiisiiisiiiiio
iiisiiisiiiiiio
iiisiiisiiiiiiio
iiisiiisiiiiiiiio
iiisiiisiiiiiiiiio
iiisiiisiiiiiiiiiio
iiisiiisiiiiiiiiiiio
iiisiiisiiiiiiiiiiiio
iissdddsddddddddddddo
iissdddsdddddddddddo
iissdddsddddddddddo
iissdddsdddddddddo
iissdddsddddddddo
iissdddsdddddddo
iissdddsddddddo
iissdddsdddddo
iissdddsddddo
iissdddsdddo
iissdddsddo
iissdddsdo
iissdddso
iissdddsio
iissdddsiio
iissdddsiiio
iissdddsiiiio
iissdddsiiiiio
iissdddsiiiiiio
iissdddsiiiiiiio
iissdddsiiiiiiiio
iissdddsiiiiiiiiio
iissdddsiiiiiiiiiio
iissdddsiiiiiiiiiiio
iissdddsiiiiiiiiiiiio
iissddsddddddddddddddo
iissddsdddddddddddddo
iissddsddddddddddddo
iissddsdddddddddddo
iissddsddddddddddo
iissddsdddddddddo
iissddsddddddddo
iissddsdddddddo
iissddsddddddo
iissddsdddddo
iissddsddddo
iissddsdddo
iissddsddo
iissddsdo
iissddso
iissddsio
iissddsiio
iissddsiiio
iissddsiiiio
iissddsiiiiio
iissddsiiiiiio
iissddsiiiiiiio
iissddsiiiiiiiio
iissddsiiiiiiiiio
iissddsiiiiiiiiiio
iissddsiiiiiiiiiiio
iissddsiiiiiiiiiiiio
iissddsiiiiiiiiiiiiio
iissdsdddddddddddddddo
iissdsddddddddddddddo
iissdsdddddddddddddo
iissdsddddddddddddo
iissdsdddddddddddo
iissdsddddddddddo
iissdsdddddddddo
iissdsddddddddo
iissdsdddddddo
iissdsddddddo
iissdsdddddo
iissdsddddo
iissdsdddo
iissdsddo
iissdsdo
iissdso
iissdsio
iissdsiio
iissdsiiio
iissdsiiiio
iissdsiiiiio
iissdsiiiiiio
iissdsiiiiiiio
iissdsiiiiiiiio
iissdsiiiiiiiiio
iissdsiiiiiiiiiio
iissdsiiiiiiiiiiio
iissdsiiiiiiiiiiiio
iissdsiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiiiiiiiiiio
iissdsiiiiiiiiiiiiiiiiiiiiiiiiiiiiiio
```
[Answer]
## C, 433 code + 3455 output = 3888
## C++, 430 code + 3455 output = 3885
And now for something completely different.
I used the output from [Martin's Mathematica answer](https://codegolf.stackexchange.com/a/40126/32254) (updated on October 23rd as it was wrong for 240+ before). My output is the same 3455 characters. I analyzed patterns in the output and discovered that [0,255] can be represented by this sequence:
1. 0-3 `i`s
2. 0-2 `s`s
3. 0-3 `i`s or `d`s
4. 0-1 `s`s
5. 0-14 `i` or 0-16 `d`s
6. 1 `o`
The next step was to carefully construct these five columns (`c` through `g` in the code below). I used negative numbers to indicate `d` instead of `i` in columns `e` and `g`. Then, it turns out that the results work mostly like a counter in the `g` column, since each row `u` usually removes one `d` or adds one `i` relative to the previous row (`v`). There are 15 exceptions, which are stored in `x` (the indexes) and `b` (the five columns, packed into an integer which only requires 14 bits to store the maximum `10832`).
For example, the first "exception" is the very first row, where we want zero characters apart from the terminating `o`. So `x[0]` is `0`, and `b[0]` is `544`, which when unpacked is ("little endian" style, since `g` is the counting column) `{ 32, 0, 4, 0, 0 }`. We always subtract 32 from `g` and 4 from `e` to make the unsigned bit-fields work (i.e. those two columns represent negative numbers conceptually when `d` is required instead of `i`, but in the implementation the values are offset to avoid actual negative numbers).
Here's a table showing how the first ten numbers work (blanks are zeros):
```
n text c d e f g
0 o
1 io 1
2 iio 2
3 iiio 3
4 iiso 2 1
5 iisio 2 1 1
6 iisiio 2 1 2
7 iisiiio 2 1 3
8 iiisdo 3 1 -1
9 iiiso 3 1
```
You can see that `g` mostly just increments by one for each new row, but some rows (0, 4, 8, ..., which I briefly hoped to find in OEIS) "reset" the sequence, meaning `g` takes on some new value and at least one other column is modified as well.
The code character count excludes whitespace except the mandatory newline before each `#` and space after `unsigned` and `int`. You can save 3 characters by compiling as C++ instead of C, replacing `<stdio.h>` with `<cstdio>`, and `*(int*)&u` with `(int&)u`.
```
#include <stdio.h>
struct { unsigned g:6, f:1, e:3, d:2, c:2; } u;
int
x[] = { 0,4,8,13,22,32,44,57,72,92,112,134,157,182,210,256 },
b[] = { 544,9760,13855,9821,9949,10076,10203,13785,13911,14040,14167,14294,10452,10578,10705,10832 };
int main()
{
int n,i=0,q=0;
scanf("%d", &n);
while(i++ <= n) {
++u.g;
if (i > x[q])
*(int*)&u = b[q++];
}
#define m(p, q) while (p) putchar(#q[0]);
m(u.c--, i)
m(u.d--, s)
m(u.e++ < 4, d)
m(--u.e > 4, i)
m(u.f--, s)
m(u.g++ < 32, d)
m(--u.g > 32, i)
puts("o");
}
```
A fun fact about this code: an earlier version used an array of 256 unions instead of just `u` and `v`. That version caused GCC 4.7.2 to generate an internal compiler error! GCC 4.9 fixed it, however, and the above code works with either version.
[Answer]
# Picat 516 + 2060 = 2576
It is somewhat modified version of [Sergey Dymchenko](https://codegolf.stackexchange.com/users/32308/sergey-dymchenko) program. This version outputs more compact deadfish programs.
```
import planner.
final((N,N))=>true.
action((N,A),B,M,C)?=>B=(N,A+1),M=i,C=1.
action((N,A),B,M,C)?=>A!=16,A<N,B=(N,A*A),M=s,C=1.
action((N,A),B,M,C)?=>A>0,B=(N,A-1),M=d,C=1.
r([X,Y|Z],A)?=>(r([Y|Z],R),A=[X|R];X!=['0'],r([(X++Y)|Z],R),A=R).
r([],A)=>A=[]. r([N],A)=>A=[N]. lf(X)=[X].
table(+,-,min) fs(N,M,L)=>r(map(lf,N.to_string()),X),Np:=0,Pp:=[],
foreach(Y in X)N:=Y.to_integer(),best_plan((N,Np),P),Np:=N,Pp:=Pp++P++[o]
end,L=Pp.length(),M=Pp. main=>foreach(X in 1..255)fs(X,P,L),printf("%s",P) end.
```
As far as I understood "lengths of outputs" sentence, it means that I should sum output without new-line chars.
Use:
```
picat filename.pi
```
1-255 Codes:
```
picat filename.pi | wc -c
2060
```
## Performance:
```
cat /proc/cpuinfo # 4 cores with HT = virtual 8 cores
processor : 0
vendor_id : GenuineIntel
cpu family : 6
model : 42
model name : Intel(R) Core(TM) i7-2600K CPU @ 3.40GHz
stepping : 7
physical id : 0
siblings : 8
core id : 1
cpu cores : 4
apicid : 2
cpu MHz : 1600.000
cache size : 8192 KB
...
bogomips : 6819.33
...
```
Version of program to measure time:
```
import planner.
import sys.
final((N,N))=>true.
action((N,A),B,M,C)?=>B=(N,A+1), M=i, C=1.
action((N,A),B,M,C)?=>A!=16, A<N, B=(N,A*A), M=s, C=1.
action((N,A),B,M,C)?=>A>0, B=(N,A-1), M=d, C=1.
r([X,Y|Z],A)?=>(r([Y|Z],R),A=[X|R];r([(X++Y)|Z],R),A=R).
r([],A)=>A=[]. r([N],A)=>A=[N]. lf(X)=[X].
table(+,-,min) fs(N,M,L)=>r(map(lf,N.to_string()),X),Np:=0,Pp:=[],
foreach(Y in X)N:=Y.to_integer(),best_plan((N,Np),P),Np:=N,Pp:=Pp++P++[o]
end,L=Pp.length(),M=Pp. go=>foreach(X in 1..255)fs(X,P,L),printf("%d %s",X,P),nl end.
main=>time2(go).
```
Result:
```
picat filename.pi
...
251 iiosioddddo
252 iiosiodddo
253 iiosioddo
254 iiosiodo
255 iiosioo
CPU time 2.2 seconds. Backtracks: 0
```
Full output:
```
1 io
2 iio
3 iiio
4 iiso
5 iisio
6 iisiio
7 iiisddo
8 iiisdo
9 iiiso
10 iodo
11 ioo
12 ioio
13 ioiio
14 ioiso
15 ioisio
16 iisso
17 iissio
18 ioiisdo
19 ioiiso
20 iioddo
21 iiodo
22 iioo
23 iioio
24 iioso
25 iiosio
26 iiosiio
27 iioisddo
28 iioisdo
29 iioiso
30 iiiodddo
31 iiioddo
32 iiiodo
33 iiioo
34 iiioio
35 iiioiio
36 iisiiso
37 iiiosddo
38 iiiosdo
39 iiioso
40 iisoddddo
41 iisodddo
42 iisoddo
43 iisodo
44 iisoo
45 iisoio
46 iisoiio
47 iisoiiio
48 iisodsdo
49 iisodso
50 iiisddsio
51 iisioddddo
52 iisiodddo
53 iisioddo
54 iisiodo
55 iisioo
56 iisioio
57 iisioiio
58 iisioiiio
59 iisioddso
60 iiisdsddddo
61 iiisdsdddo
62 iiisdsddo
63 iiisdsdo
64 iiisdso
65 iisiiodo
66 iisiioo
67 iisiioio
68 iisiioiio
69 iisiioiiio
70 iiisdsiiiiiio
71 iiisddoddddddo
72 iiisddodddddo
73 iiisddoddddo
74 iiisddodddo
75 iiisddoddo
76 iiisddodo
77 iiisddoo
78 iiisddoio
79 iiissddo
80 iiissdo
81 iiisso
82 iiissio
83 iiissiio
84 iiissiiio
85 iiisdodddo
86 iiisdoddo
87 iiisdodo
88 iiisdoo
89 iiisdoio
90 iiisodddddddddo
91 iiisoddddddddo
92 iiisodddddddo
93 iiisoddddddo
94 iiisodddddo
95 iiisoddddo
96 iiisodddo
97 iiisoddo
98 iiisodo
99 iiisoo
100 iodoo
101 iodoio
102 iodoiio
103 iodoiiio
104 iodoiiso
105 iodoiisio
106 iodoiisiio
107 iiisiodddo
108 iiisioddo
109 iiisiodo
110 ioodo
111 iooo
112 iooio
113 iooiio
114 iooiso
115 iooisio
116 ioisso
117 ioissio
118 iooiisdo
119 iooiiso
120 ioioddo
121 ioiodo
122 ioioo
123 ioioio
124 ioioso
125 ioiosio
126 ioiosiio
127 ioioisddo
128 ioioisdo
129 ioioiso
130 ioiiodddo
131 ioiioddo
132 ioiiodo
133 ioiioo
134 ioiioio
135 ioiioiio
136 ioisiiso
137 ioiiosddo
138 ioiiosdo
139 ioiioso
140 ioisoddddo
141 ioisodddo
142 ioisoddo
143 ioisodo
144 ioisoo
145 ioisoio
146 ioisoiio
147 ioisoiiio
148 ioisodsdo
149 ioisodso
150 ioiisddsio
151 ioisioddddo
152 ioisiodddo
153 ioisioddo
154 ioisiodo
155 ioisioo
156 ioisioio
157 ioisioiio
158 ioisioiiio
159 ioisioddso
160 ioiisdsddddo
161 ioiisdsdddo
162 ioiisdsddo
163 ioiisdsdo
164 ioiisdso
165 ioisiiodo
166 ioisiioo
167 ioisiioio
168 ioisiioiio
169 iissdddso
170 iissdddsio
171 iissdddsiio
172 iissdddsiiio
173 ioiisddoddddo
174 ioiisddodddo
175 ioiisddoddo
176 ioiisddodo
177 ioiisddoo
178 ioiisddoio
179 ioiissddo
180 ioiissdo
181 ioiisso
182 ioiissio
183 ioiissiio
184 ioiissiiio
185 ioiisdodddo
186 ioiisdoddo
187 ioiisdodo
188 ioiisdoo
189 ioiisdoio
190 iissddsddddddo
191 iissddsdddddo
192 iissddsddddo
193 iissddsdddo
194 iissddsddo
195 iissddsdo
196 iissddso
197 ioiisoddo
198 ioiisodo
199 ioiisoo
200 iioddoo
201 iioddoio
202 iioddoiio
203 iioddoiiio
204 iioddoiiso
205 iioddoiisio
206 iioddoiisiio
207 iioddoiiisddo
208 iioddoiiisdo
209 iioddoiiiso
210 iiododo
211 iiodoo
212 iiodoio
213 iiodoiio
214 iiodoiso
215 iiossdo
216 iiosso
217 iiossio
218 iiossiio
219 iiodoiiso
220 iiooddo
221 iioodo
222 iiooo
223 iiooio
224 iiooso
225 iioosio
226 iioosiio
227 iiooisddo
228 iiooisdo
229 iiooiso
230 iioiodddo
231 iioioddo
232 iioiodo
233 iioioo
234 iioioio
235 iioioiio
236 iiosiiso
237 iioiosddo
238 iioiosdo
239 iioioso
240 iiosoddddo
241 iiosodddo
242 iiosoddo
243 iiosodo
244 iiosoo
245 iiosoio
246 iiosoiio
247 iiosoiiio
248 iiosodsdo
249 iiosodso
250 iioisddsio
251 iiosioddddo
252 iiosiodddo
253 iiosioddo
254 iiosiodo
255 iiosioo
```
[Answer]
# Perl, ~~132~~ 131 bytes + 2036 bytes = 2167
Includes +2 for `-lp`
Run with the target number on STDIN, e.g.
```
perl -lp deadfish.pl <<< 160
```
deadfish.pl:
```
@;=map{s%(o)|(s)|(i|d)|%$_-=e cmp$3.e;$_*=$_-16&&$_ if$2;$1&&$_%eg;@$_=$`;grep/id|di/^y/o//<4,<{o,s,d,i}$`>}~~o,@;until$\="@$_"}{
```
The grep is a filter to constrain the exponential explosion a bit (though this program still needs 2 GB for the hard cases). It also works without but I can't run it on my hardware like that except for the easy cases. But in principle this `110=108+2` byte program works too:
```
@;=map{s%(o)|(s)|(i|d)|%$_-=e cmp$3.e;$_*=$_-16&&$_ if$2;$1&&$_%eg;@$_=$`;<{o,s,d,i}$`>}$a,@;until$\="@$_"}{
```
Output list:
```
1 io
2 iio
3 iiio
4 iiso
5 iisio
6 iisiio
7 iisiiio
8 iiisdo
9 iiiso
10 iodo
11 ioo
12 ioio
13 ioiio
14 ioiso
15 ioisio
16 iisso
17 iissio
18 iissiio
19 ioiiso
20 iioddo
21 iiodo
22 iioo
23 iioio
24 iioso
25 iiosio
26 iiosiio
27 iiosiiio
28 iioisdo
29 iioiso
30 iiiodddo
31 iiioddo
32 iiiodo
33 iiioo
34 iiioio
35 iiioiio
36 iisiiso
37 iisiisio
38 iiiosdo
39 iiioso
40 iisosso
41 iisossio
42 iisoddo
43 iisodo
44 iisoo
45 iisoio
46 iisoiio
47 iisoiiio
48 iisodsdo
49 iisodso
50 iisiiisio
51 iisiiisiio
52 iisiodddo
53 iisioddo
54 iisiodo
55 iisioo
56 iisioio
57 iisioiio
58 iisioiiio
59 iisioddso
60 iiisdsddddo
61 iiisdsdddo
62 iiisdsddo
63 iiisdsdo
64 iiisdso
65 iiisdsio
66 iisiioo
67 iisiioio
68 iisiioiio
69 iisiioiiio
70 iiisdsiiiiiio
71 iiisdsiiiiiiio
72 iisiiiodddddo
73 iisiiioddddo
74 iisiiiodddo
75 iisiiioddo
76 iisiiiodo
77 iisiiioo
78 iisiiioio
79 iiissddo
80 iiissdo
81 iiisso
82 iiissio
83 iiissiio
84 iiissiiio
85 iiissiiiio
86 iiisdoddo
87 iiisdodo
88 iiisdoo
89 iiisdoio
90 iiisodddddsso
91 iiisodddddssio
92 iiisodddddddo
93 iiisoddddddo
94 iiisodddddo
95 iiisoddddo
96 iiisodddo
97 iiisoddo
98 iiisodo
99 iiisoo
100 iodoo
101 iodoio
102 iodoiio
103 iodoiiio
104 iodoiiso
105 iodoiisio
106 iodoiisiio
107 iiisiodddo
108 iiisioddo
109 iiisiodo
110 ioodo
111 iooo
112 iooio
113 iooiio
114 iooiso
115 iooisio
116 ioisso
117 ioissio
118 ioissiio
119 iooiiso
120 ioioddo
121 ioiodo
122 ioioo
123 ioioio
124 ioioso
125 ioiosio
126 ioiosiio
127 ioiosiiio
128 ioioisdo
129 ioioiso
130 ioiiodddo
131 ioiioddo
132 ioiiodo
133 ioiioo
134 ioiioio
135 ioiioiio
136 ioisiiso
137 ioisiisio
138 ioiiosdo
139 ioiioso
140 ioisosso
141 ioisossio
142 ioisoddo
143 ioisodo
144 ioisoo
145 ioisoio
146 ioisoiio
147 ioisoiiio
148 ioisodsdo
149 ioisodso
150 iissdoiso
151 iissdoisio
152 ioisiodddo
153 ioisioddo
154 ioisiodo
155 ioisioo
156 ioisioio
157 ioisioiio
158 ioisioiiio
159 ioisioddso
160 iissoso
161 iissosio
162 iissosiio
163 ioiisdsdo
164 ioiisdso
165 ioiisdsio
166 ioisiioo
167 ioisiioio
168 ioisiioiio
169 iissdddso
170 iissiodso
171 iissiodsio
172 iissiodsiio
173 iissiodsiiio
174 ioisiiiodddo
175 ioisiiioddo
176 ioisiiiodo
177 ioisiiioo
178 ioisiiioio
179 ioiissddo
180 ioiissdo
181 ioiisso
182 ioiissio
183 ioiissiio
184 ioiissiiio
185 ioiissiiiio
186 ioiisdoddo
187 ioiisdodo
188 ioiisdoo
189 ioiisdoio
190 iissiiiodddso
191 iissddsdddddo
192 iissddsddddo
193 iissddsdddo
194 iissddsddo
195 iissddsdo
196 iissddso
197 iissddsio
198 ioiisodo
199 ioiisoo
200 iioddoo
201 iioddoio
202 iioddoiio
203 iioddoiiio
204 iioddoiiso
205 iioddoiisio
206 iioddoiisiio
207 iioddoiisiiio
208 iioddoiiisdo
209 iioddoiiiso
210 iioisio
211 iiodoo
212 iiodoio
213 iiodoiio
214 iiossddo
215 iiossdo
216 iiosso
217 iiossio
218 iiossiio
219 iiossiiio
220 iiooddo
221 iioodo
222 iiooo
223 iiooio
224 iiooso
225 iioosio
226 iioosiio
227 iioosiiio
228 iiooisdo
229 iiooiso
230 iioiodddo
231 iioioddo
232 iioiodo
233 iioioo
234 iioioio
235 iioioiio
236 iiosiiso
237 iiosiisio
238 iioiosdo
239 iioioso
240 iiososso
241 iiosossio
242 iiosoddo
243 iiosodo
244 iiosoo
245 iiosoio
246 iiosoiio
247 iiosoiiio
248 iiosodsdo
249 iiosodso
250 iiosiiisio
251 iiosiiisiio
252 iiosiodddo
253 iiosioddo
254 iiosiodo
255 iiosioo
```
[Answer]
# Prolog, 621 + 2036 - 100 = 2557
Here is a backward search, memoization solution in Prolog:
```
x(N,R):-between(1,inf,D),y(N,O,M),z(M,O,D,L),!,reverse([o|L],R).
:-dynamic t/4.
z(N,O,D,L):-t(N,O,D,L),!,L\==s.
z(N,O,D,L):-u(N,O,D,L),!,assertz(t(N,O,D,L)).
z(N,O,D,_):-assertz(t(N,O,D,s)),fail.
u(N,O,0,[]):-!,N=0,O=0.
u(N,O,D,[C|L]):-E is D-1,member(C,[s,o,i,d]),v(C,N,O,M,P),z(M,P,E,L),!.
v(s,N,O,M,O):-(N=0->M=16;H is sqrt(N),M is truncate(H),H is float(M)).
v(o,N,O,N,P):-y(O,P,R),R=N,!.
v(i,N,O,M,O):-(N=0->M=255;M is N-1).
v(d,N,O,M,O):-M is N+1.
y(N,0,N):-N<10,!.
y(N,P,R):-divmod(N,10,D,M),(P=D,R=M;y(D,P,Q),Q\==0,R is Q*10+M).
w:-between(1,255,N),x(N,L),atom_chars(A,L),write(A),nl,fail.
w.
:-initialization(w).
```
Dry run takes only 0.055 seconds! Numbered output lines:
```
1 io
2 iio
3 iiio
4 iiso
5 iisio
6 iisiio
7 iisiiio
8 iiisdo
9 iiiso
10 iodo
11 ioo
12 ioio
13 ioiio
14 ioiso
15 ioisio
16 iisso
17 iissio
18 ioiisdo
19 ioiiso
20 iioddo
21 iiodo
22 iioo
23 iioio
24 iioso
25 iiosio
26 iiosiio
27 iiosiiio
28 iioisdo
29 iioiso
30 iiioisso
31 iiioddo
32 iiiodo
33 iiioo
34 iiioio
35 iiioiio
36 iisiiso
37 iiiosddo
38 iiiosdo
39 iiioso
40 iisosso
41 iisossio
42 iisoddo
43 iisodo
44 iisoo
45 iisoio
46 iisoiio
47 iisoiiio
48 iisodsdo
49 iisodso
50 iisiodsso
51 iisiodssio
52 iisiodddo
53 iisioddo
54 iisiodo
55 iisioo
56 iisioio
57 iisioiio
58 iisioiiio
59 iisioddso
60 iisiioddsso
61 iiisdsdddo
62 iiisdsddo
63 iiisdsdo
64 iiisdso
65 iisiiodo
66 iisiioo
67 iisiioio
68 iisiioiio
69 iisiioiiio
70 iisiiiodddsso
71 iisiiiodddssio
72 iisiiiodddddo
73 iisiiioddddo
74 iisiiiodddo
75 iisiiioddo
76 iisiiiodo
77 iisiiioo
78 iisiiioio
79 iiissddo
80 iiissdo
81 iiisso
82 iiissio
83 iiissiio
84 iiissiiio
85 iiisdodddo
86 iiisdoddo
87 iiisdodo
88 iiisdoo
89 iiisdoio
90 iiisodddddsso
91 iiisodddddssio
92 iiisodddddddo
93 iiisoddddddo
94 iiisodddddo
95 iiisoddddo
96 iiisodddo
97 iiisoddo
98 iiisodo
99 iiisoo
100 iodoo
101 iodoio
102 iodoiio
103 iodoiiio
104 iodoiiso
105 iodoiisio
106 iodoiisiio
107 iiisiodddo
108 iiisioddo
109 iiisiodo
110 ioodo
111 iooo
112 iooio
113 iooiio
114 iooiso
115 iooisio
116 ioisso
117 ioissio
118 iooiisdo
119 iooiiso
120 ioioddo
121 ioiodo
122 ioioo
123 ioioio
124 ioioso
125 ioiosio
126 ioiosiio
127 ioiosiiio
128 ioioisdo
129 ioioiso
130 ioiioisso
131 ioiioddo
132 ioiiodo
133 ioiioo
134 ioiioio
135 ioiioiio
136 ioisiiso
137 ioiiosddo
138 ioiiosdo
139 ioiioso
140 ioisosso
141 ioisossio
142 ioisoddo
143 ioisodo
144 ioisoo
145 ioisoio
146 ioisoiio
147 ioisoiiio
148 ioisodsdo
149 ioisodso
150 iissdoiso
151 iissdoisio
152 ioisiodddo
153 ioisioddo
154 ioisiodo
155 ioisioo
156 ioisioio
157 ioisioiio
158 ioisioiiio
159 ioisioddso
160 iissoso
161 iissosio
162 iissosiio
163 ioiisdsdo
164 ioiisdso
165 ioisiiodo
166 ioisiioo
167 ioisiioio
168 ioisiioiio
169 iissdddso
170 iissiodso
171 iissiodsio
172 iissiodsiio
173 iissiodsiiio
174 iissiodsiiso
175 ioisiiioddo
176 ioisiiiodo
177 ioisiiioo
178 ioisiiioio
179 ioiissddo
180 ioiissdo
181 ioiisso
182 ioiissio
183 ioiissiio
184 ioiissiiio
185 ioiisdodddo
186 ioiisdoddo
187 ioiisdodo
188 ioiisdoo
189 ioiisdoio
190 iissiiiodddso
191 iissddsdddddo
192 iissddsddddo
193 iissddsdddo
194 iissddsddo
195 iissddsdo
196 iissddso
197 ioiisoddo
198 ioiisodo
199 ioiisoo
200 iioddoo
201 iioddoio
202 iioddoiio
203 iioddoiiio
204 iioddoiiso
205 iioddoiisio
206 iioddoiisiio
207 iioddoiisiiio
208 iioddoiiisdo
209 iioddoiiiso
210 iiododo
211 iiodoo
212 iiodoio
213 iiodoiio
214 iiodoiso
215 iiossdo
216 iiosso
217 iiossio
218 iiossiio
219 iiodoiiso
220 iiooddo
221 iioodo
222 iiooo
223 iiooio
224 iiooso
225 iioosio
226 iioosiio
227 iioosiiio
228 iiooisdo
229 iiooiso
230 iioioisso
231 iioioddo
232 iioiodo
233 iioioo
234 iioioio
235 iioioiio
236 iiosiiso
237 iioiosddo
238 iioiosdo
239 iioioso
240 iiososso
241 iiosossio
242 iiosoddo
243 iiosodo
244 iiosoo
245 iiosoio
246 iiosoiio
247 iiosoiiio
248 iiosodsdo
249 iiosodso
250 iiosiodsso
251 iiosiodssio
252 iiosiodddo
253 iiosioddo
254 iiosiodo
255 iiosioo
```
[Answer]
# JavaScript (E6) 141+3455=3596
Recursive function looking for the closest square root, but avoiding 16 as 16\*16=256 will be changed to 0. Many other answer don't get this point.
```
F=(t,s='o',o='i')=>
t>3?(
q=Math.sqrt(t)|0,
r=q+1,
q-16?r-16||++r:--q,
d=t-q*q,e=r*r-t,
e<=d&&(o='d',d=e,++q),
F(q,'s'+o.repeat(d)+s)
):o.repeat(t)+s
```
**Test** In FireFox/FireBug console
```
for(l=0,i=1;i<256;++i)o=F(i),l+=o.length,console.log(i,o),l
```
*Output*
```
1 io
2 iio
3 iiio
4 iiso
5 iisio
6 iisiio
7 iiisddo
8 iiisdo
9 iiiso
10 iiisio
11 iiisiio
12 iiisiiio
13 iissdddo
14 iissddo
15 iissdo
16 iisso
17 iissio
18 iissiio
19 iissiiio
20 iissiiiio
21 iisisddddo
22 iisisdddo
23 iisisddo
24 iisisdo
25 iisiso
26 iisisio
27 iisisiio
28 iisisiiio
29 iisisiiiio
30 iisisiiiiio
31 iisiisdddddo
32 iisiisddddo
33 iisiisdddo
34 iisiisddo
35 iisiisdo
36 iisiiso
37 iisiisio
38 iisiisiio
39 iisiisiiio
40 iisiisiiiio
41 iisiisiiiiio
42 iisiisiiiiiio
43 iiisddsddddddo
44 iiisddsdddddo
45 iiisddsddddo
46 iiisddsdddo
47 iiisddsddo
48 iiisddsdo
49 iiisddso
50 iiisddsio
51 iiisddsiio
52 iiisddsiiio
53 iiisddsiiiio
54 iiisddsiiiiio
55 iiisddsiiiiiio
56 iiisddsiiiiiiio
57 iiisdsdddddddo
58 iiisdsddddddo
59 iiisdsdddddo
60 iiisdsddddo
61 iiisdsdddo
62 iiisdsddo
63 iiisdsdo
64 iiisdso
65 iiisdsio
66 iiisdsiio
67 iiisdsiiio
68 iiisdsiiiio
69 iiisdsiiiiio
70 iiisdsiiiiiio
71 iiisdsiiiiiiio
72 iiisdsiiiiiiiio
73 iiissddddddddo
74 iiissdddddddo
75 iiissddddddo
76 iiissdddddo
77 iiissddddo
78 iiissdddo
79 iiissddo
80 iiissdo
81 iiisso
82 iiissio
83 iiissiio
84 iiissiiio
85 iiissiiiio
86 iiissiiiiio
87 iiissiiiiiio
88 iiissiiiiiiio
89 iiissiiiiiiiio
90 iiissiiiiiiiiio
91 iiisisdddddddddo
92 iiisisddddddddo
93 iiisisdddddddo
94 iiisisddddddo
95 iiisisdddddo
96 iiisisddddo
97 iiisisdddo
98 iiisisddo
99 iiisisdo
100 iiisiso
101 iiisisio
102 iiisisiio
103 iiisisiiio
104 iiisisiiiio
105 iiisisiiiiio
106 iiisisiiiiiio
107 iiisisiiiiiiio
108 iiisisiiiiiiiio
109 iiisisiiiiiiiiio
110 iiisisiiiiiiiiiio
111 iiisiisddddddddddo
112 iiisiisdddddddddo
113 iiisiisddddddddo
114 iiisiisdddddddo
115 iiisiisddddddo
116 iiisiisdddddo
117 iiisiisddddo
118 iiisiisdddo
119 iiisiisddo
120 iiisiisdo
121 iiisiiso
122 iiisiisio
123 iiisiisiio
124 iiisiisiiio
125 iiisiisiiiio
126 iiisiisiiiiio
127 iiisiisiiiiiio
128 iiisiisiiiiiiio
129 iiisiisiiiiiiiio
130 iiisiisiiiiiiiiio
131 iiisiisiiiiiiiiiio
132 iiisiisiiiiiiiiiiio
133 iiisiiisdddddddddddo
134 iiisiiisddddddddddo
135 iiisiiisdddddddddo
136 iiisiiisddddddddo
137 iiisiiisdddddddo
138 iiisiiisddddddo
139 iiisiiisdddddo
140 iiisiiisddddo
141 iiisiiisdddo
142 iiisiiisddo
143 iiisiiisdo
144 iiisiiiso
145 iiisiiisio
146 iiisiiisiio
147 iiisiiisiiio
148 iiisiiisiiiio
149 iiisiiisiiiiio
150 iiisiiisiiiiiio
151 iiisiiisiiiiiiio
152 iiisiiisiiiiiiiio
153 iiisiiisiiiiiiiiio
154 iiisiiisiiiiiiiiiio
155 iiisiiisiiiiiiiiiiio
156 iiisiiisiiiiiiiiiiiio
157 iissdddsddddddddddddo
158 iissdddsdddddddddddo
159 iissdddsddddddddddo
160 iissdddsdddddddddo
161 iissdddsddddddddo
162 iissdddsdddddddo
163 iissdddsddddddo
164 iissdddsdddddo
165 iissdddsddddo
166 iissdddsdddo
167 iissdddsddo
168 iissdddsdo
169 iissdddso
170 iissdddsio
171 iissdddsiio
172 iissdddsiiio
173 iissdddsiiiio
174 iissdddsiiiiio
175 iissdddsiiiiiio
176 iissdddsiiiiiiio
177 iissdddsiiiiiiiio
178 iissdddsiiiiiiiiio
179 iissdddsiiiiiiiiiio
180 iissdddsiiiiiiiiiiio
181 iissdddsiiiiiiiiiiiio
182 iissdddsiiiiiiiiiiiiio
183 iissddsdddddddddddddo
184 iissddsddddddddddddo
185 iissddsdddddddddddo
186 iissddsddddddddddo
187 iissddsdddddddddo
188 iissddsddddddddo
189 iissddsdddddddo
190 iissddsddddddo
191 iissddsdddddo
192 iissddsddddo
193 iissddsdddo
194 iissddsddo
195 iissddsdo
196 iissddso
197 iissddsio
198 iissddsiio
199 iissddsiiio
200 iissddsiiiio
201 iissddsiiiiio
202 iissddsiiiiiio
203 iissddsiiiiiiio
204 iissddsiiiiiiiio
205 iissddsiiiiiiiiio
206 iissddsiiiiiiiiiio
207 iissddsiiiiiiiiiiio
208 iissddsiiiiiiiiiiiio
209 iissddsiiiiiiiiiiiiio
210 iissddsiiiiiiiiiiiiiio
211 iissdsddddddddddddddo
212 iissdsdddddddddddddo
213 iissdsddddddddddddo
214 iissdsdddddddddddo
215 iissdsddddddddddo
216 iissdsdddddddddo
217 iissdsddddddddo
218 iissdsdddddddo
219 iissdsddddddo
220 iissdsdddddo
221 iissdsddddo
222 iissdsdddo
223 iissdsddo
224 iissdsdo
225 iissdso
226 iissdsio
227 iissdsiio
228 iissdsiiio
229 iissdsiiiio
230 iissdsiiiiio
231 iissdsiiiiiio
232 iissdsiiiiiiio
233 iissdsiiiiiiiio
234 iissdsiiiiiiiiio
235 iissdsiiiiiiiiiio
236 iissdsiiiiiiiiiiio
237 iissdsiiiiiiiiiiiio
238 iissdsiiiiiiiiiiiiio
239 iissdsiiiiiiiiiiiiiio
240 iissdsiiiiiiiiiiiiiiio
241 iissdsiiiiiiiiiiiiiiiio
242 iissdsiiiiiiiiiiiiiiiiio
243 iissdsiiiiiiiiiiiiiiiiiio
244 iissdsiiiiiiiiiiiiiiiiiiio
245 iissdsiiiiiiiiiiiiiiiiiiiio
246 iissdsiiiiiiiiiiiiiiiiiiiiio
247 iissdsiiiiiiiiiiiiiiiiiiiiiio
248 iissdsiiiiiiiiiiiiiiiiiiiiiiio
249 iissdsiiiiiiiiiiiiiiiiiiiiiiiio
250 iissdsiiiiiiiiiiiiiiiiiiiiiiiiio
251 iissdsiiiiiiiiiiiiiiiiiiiiiiiiiio
252 iissdsiiiiiiiiiiiiiiiiiiiiiiiiiiio
253 iissdsiiiiiiiiiiiiiiiiiiiiiiiiiiiio
254 iissdsiiiiiiiiiiiiiiiiiiiiiiiiiiiiio
255 iissdsiiiiiiiiiiiiiiiiiiiiiiiiiiiiiio
3455
```
[Answer]
# Picat, 242 code + 3455 output = 3697
See <http://picat-lang.org/> for info about Picat.
```
import planner. final((N,N))=>true. action((N,A),B,M,C)?=>B=(N,A+1),M=i,C=1. action((N,A),B,M,C)?=>A!=16,A<N,B=(N,A*A),M=s,C=1. action((N,A),B,M,C)?=>A>0,B=(N,A-1),M=d,C=1. main([X])=>N=X.to_integer(),best_plan((N,0),P),printf("%w\n",P++[o]).
```
Less golf:
```
import planner.
final((N,N))=>true.
action((N,A),B,M,C)?=>B=(N,A+1),M=i,C=1.
action((N,A),B,M,C)?=>A!=16,A<N,B=(N,A*A),M=s,C=1.
action((N,A),B,M,C)?=>A>0,B=(N,A-1),M=d,C=1.
main([X])=>N=X.to_integer(),best_plan((N,0),P),printf("%w\n",P++[o]).
```
[Answer]
# [Python 3](https://docs.python.org/3/), 3455 + 182 bytes = 3637
```
from heapq import*
def f(x):
q=[(0,0,"")]
while 1:
l,s,c=heappop(q)
if s==x:return c+"o"
for n,i in[(s+1,"i"),(s-1,"d"),(s*s,"s")]:
if(n+1)*(n-256):heappush(q,(l+1,n,c+i))
```
[Try it online!](https://tio.run/##VY3LCoMwEEXX@hUhqxkdwQdtUfBLpIuiBgOaxESp/XobhYLd3XuGe8Z8lkGrYt@F1RMb@peZmZyMtksUdr1gAjaswmCuG0gpJc7xGQbvQY49yzwPRnLU1sfOaAMzeiQFc3W9VbZfVqtYG3PNPRbaMkWSSdWAizPikiOBS3zqzhQ54s77D62XgIozjEAl@e2O1flhdQPMBKNfK2pjibgbK9UCAkrE8Jezx6WUf5c0vba88IYv "Python 3 – Try It Online")
This finds the optimal way to generate the number itself. It is not optimal if you allow partial outputting.
[Answer]
# Python 3 – 4286 + 168 = 4454
Not a too serious one, but extremely simple. Just finds the best one of adding to 0, a square, a 4th power ~~and an 8th power~~.
**EDIT:** Golfed 75 bytes, the 8th power did nothing
**EDIT 2:** Removed some bytes in order to correctly implement `d`. Score increased, though.
```
i=int(input())
s=round(i**.5)
q=round(s**.5)
o=round(q**.5)
a,b,c,d=i-256if i>127else i,i-s*s,i-q**4,i-o**8
print(sorted([(a*'i'if a>0else'd'*-a)+'o',s*'i'+'s'+(b*'i'if b>0else'd'*-b)+'o',q*'i'+'ss'+(c*'i'if c>0else'd'*-c)+'o',o*'i'+'sss'+(d*'i'if d>0else'd'*-d)+'o'],key=len)[0])
```
# Python 3 – 2594 + 201 = 2795
This one uses a kind of depth-first search to find the shortest program. I added some (unnecessary?) optimizations to it, so I could get the result; this way it doesn't have to run that many paths. Might try to remove some of them. Doesn't beat the JS one as it uses smart tricks like multiple `o`'s.
**EDIT:** Golfed off 93 bytes, I apparently had a crapton of useless code left there by development. Also removed everything I found unnecessary so far. Here I come, JS.
**EDIT 2:** Golfed off another 8 bytes. That `return` was unnecessary.
**EDIT 3:** Golfed an additional 5 bytes. Now that we got rid of that one wo could just put an `elif` instead of the other `return`.
**EDIT 4:** Corrected the functionality of `d`. Size increased by 1 byte, score by some bytes.
```
def f(i,s,h):
global x,p
if h==a:p+=[i]
elif s<x[h]:x[h]=s;f(i+'s',s+1,h*h%256);f(i+'i',s+1,(h+1)%256);f(i+'d',s+1,max(h-1,0))
a,p=int(input()),[];x=[a]*256;f('',0,0);print(sorted(p,key=len)[0]+'o')
```
[Answer]
**APL: 80 + 3456 = 3536**
```
⌽'o',{⍵<4:⍵⍴'i'⋄(b/'ids'),∇(-⊃b)+b[2]+⍵*÷1+3⊃b←(⍵>240)⌽⊃(>,<,=)/|⍵-2*⍨(⌈,⌊)⍵*.5}
```
**Explanation:** (corrected after edc65's note, thanks)
⍵<4:⍵⍴'i' If argument is less than 3, replicate "i" that many times
(⌈,⌊)⍵\*.5 ⍵ is the argument, take square root and take the ceiling and the floor
|⍵-2\*⍨ elevate those ceiling and floor to power 2, remove argument, and make positive
b←⊃(>,<,=)/ get a boolean vector with a>b, a
(⍵>240)⌽ To avoid going to 256, do "i" for numbers over 240, instead of ^2
b/'ids' use that boolean to take either i, d or s and append it to the solution with ,
,∇(-⊃b)+b[2]+⍵\*÷1+3⊃b Recursively call the function with argument -b[1](http://TryApl.org) +b[2] elevated to the power (inverse of b[3]+1)
*Can count output with:*
```
+/⊃,/⍴¨(⌽'o',{⍵<4:⍵⍴'i'⋄(b/'ids'),∇(-⊃b)+b[2]+⍵*÷1+3⊃b←(⍵>240)⌽⊃(>,<,=)/|⍵-2*⍨(⌈,⌊)⍵*.5})¨¯1+⍳256
```
¨ applies the function to each number 0-255
+/⊃,/⍴¨ counts total number of elements
Again, you can try all of the above on [TryApl.org](http://TryApl.org)
**BTW:** It's 3456 and not 3455 because I'm considering 0 too, as I think the problem was asking. If It's 1-255 then the score is 80+3455 = 3535
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 86 bytes, optimal output by brute-forcing
```
f=(n,a='',b=a,c,...s)=>n^b?f(n,...s,a+'i',b,-~c,a+'d',b,~-c,a+'s',b,c*c,a+'o',b+c,c):a
```
[Try it online!](https://tio.run/##ZczBCoMwDMbx@16k7UwLbp6EujcZxGiHQ5phZUdfvWu8jd5@@X@QN34x0bZ8dht5mnMOXkdArxSMHoHAOZeMH@JzfISyyAnYqKXsYA8ST@LDnk5iup7m4oaATI@ZOCZeZ7fySwfdGnP5L7eq3KvSVaWVR/kH "JavaScript (Node.js) – Try It Online")
[Answer]
# Python 2712 = 2608 + 104
Code:
```
v=lambda i:reduce(lambda x,y:(int(y),x[1]+['d','i'][int(y)>x[0]]*abs(int(y)-x[0])+"o"),str(i),(0,""))[1]
```
Use:
```
v(20) -> 'iioddo'
v(250) -> 'iioiiiodddddo'
```
0-255 Code:
```
len(reduce(lambda x,y:x+v(y),range(256),"")) -> 2608
```
[Answer]
## CJam, ~~2436 2392 2296~~ 2173 ([74](https://mothereff.in/byte-counter#%22%E5%8F%B4%EE%90%93%E5%99%AF%E6%92%98%E6%A1%9C%E1%AA%8D%EB%BE%80%E6%88%A0%EB%83%9E%E9%9C%B3%E3%88%A8%E5%B5%83%E7%95%AF%E3%93%B1%EB%88%BF%EF%A4%92%E3%BA%AF%E8%9B%99%E3%A1%9F%E6%BF%80%EB%96%8D%E4%91%9C%E3%A6%98%E5%95%9F%E4%82%B3%E5%97%B3%E6%BA%98%E6%A1%A0%E3%BC%BC%E1%97%8E%EC%9C%86%EA%98%B6%EF%B8%8C%E8%8B%B1%E8%B4%88%E8%A2%84%E7%9E%A6%E3%BA%A3%E6%A8%85%ED%9C%8F%EE%A6%88%E2%95%B4%E0%B7%BC%E7%93%B5%EA%83%B4%EF%B8%A5%E3%B7%AE%EC%8B%8E%EA%97%9E%E5%86%BA%E6%86%B3%EB%94%95%E7%A4%95%EF%9B%A9%E4%80%98%E4%AC%B4%E5%8D%BA%E3%BD%85%E9%AC%9E%E5%BA%98%E4%B2%B5%222G%23b129b%3Ac~) characters + 2099)
```
"叴噯撘桜뾀戠냞霳㈨嵃畯㓱눿裸㺯蛙㡟激떍䑜㦘啟䂳嗳溘桠㼼ᗎ윆︌英贈袄瞦㺣樅휏╴瓵ꃴ︥㷮싎ꗞ冺憳딕礕䀘䬴卺㽅鬞庘䲵"2G#b129b:c~
```
Which translates to:
```
r_(sa\a+{},\1/{{i_L\[_Tm3>{{__mqi:NN*-N)_*@-_@e<_@=_N+:N;'d'i?*+'s+N_Z3e>>}g}*T-_0<'d'i?\z*\2$3<'s*-W%'o]s\:Z:T;}%s0:T;3:Z;}:A~\A]_:,_$0=#=
```
Tries to optimize the Deadfish code length by choosing the shortest path to reach each digit of the number.
Thanks Martin for the Unicode translation
Here is the complete list of code
```
1:io
2:iio
3:iiio
4:iiso
5:iisio
6:iisiio
7:iiisddo
8:iiisdo
9:iiiso
10:iodo
11:ioo
12:ioio
13:ioiio
14:ioiiio
15:ioisio
16:ioisiio
17:ioiisddo
18:ioiisdo
19:ioiiso
20:iioddo
21:iiodo
22:iioo
23:iioio
24:iioiio
25:iioiiio
26:iiosiio
27:iioisddo
28:iioisdo
29:iioiso
30:iiiodddo
31:iiioddo
32:iiiodo
33:iiioo
34:iiioio
35:iiioiio
36:iiioiiio
37:iiiosddo
38:iiiosdo
39:iiioso
40:iisoddddo
41:iisodddo
42:iisoddo
43:iisodo
44:iisoo
45:iisoio
46:iisoiio
47:iisoiiio
48:iisodsdo
49:iisodso
50:iisiodddddo
51:iisioddddo
52:iisiodddo
53:iisioddo
54:iisiodo
55:iisioo
56:iisioio
57:iisioiio
58:iisioiiio
59:iisioddso
60:iisiioddddddo
61:iisiiodddddo
62:iisiioddddo
63:iisiiodddo
64:iisiioddo
65:iisiiodo
66:iisiioo
67:iisiioio
68:iisiioiio
69:iisiioiiio
70:iiisddodddddddo
71:iiisddoddddddo
72:iiisddodddddo
73:iiisddoddddo
74:iiisddodddo
75:iiisddoddo
76:iiisddodo
77:iiisddoo
78:iiisddoio
79:iiisddoiio
80:iiisdoddddddddo
81:iiisdodddddddo
82:iiisdoddddddo
83:iiisdodddddo
84:iiisdoddddo
85:iiisdodddo
86:iiisdoddo
87:iiisdodo
88:iiisdoo
89:iiisdoio
90:iiisodddddddddo
91:iiisoddddddddo
92:iiisodddddddo
93:iiisoddddddo
94:iiisodddddo
95:iiisoddddo
96:iiisodddo
97:iiisoddo
98:iiisodo
99:iiisoo
100:iodo
101:ioo
102:ioio
103:ioiio
104:ioiiio
105:ioisio
106:ioisiio
107:ioiisddo
108:ioiisdo
109:ioiiso
110:ioodo
111:iooo
112:iooio
113:iooiio
114:iooiiio
115:iooisio
116:ioisso
117:ioissio
118:iooiisdo
119:iooiiso
120:ioioddo
121:ioiodo
122:ioioo
123:ioioio
124:ioioiio
125:ioisiso
126:ioiosiio
127:ioioisddo
128:ioioisdo
129:ioioiso
130:ioiiodddo
131:ioiioddo
132:ioiiodo
133:ioiioo
134:ioiioio
135:ioiioiio
136:ioisiiso
137:ioiiosddo
138:ioiiosdo
139:ioiioso
140:ioiiioddddo
141:ioiiiodddo
142:ioiiioddo
143:ioiiiodo
144:ioiiioo
145:ioiiioio
146:ioiiioiio
147:ioiiioiiio
148:ioiiiodsdo
149:ioiiiodso
150:ioiisddsio
151:ioisioddddo
152:ioisiodddo
153:ioisioddo
154:ioisiodo
155:ioisioo
156:ioisioio
157:ioisioiio
158:ioisioiiio
159:ioisioddso
160:ioiisdsddddo
161:ioiisdsdddo
162:ioiisdsddo
163:ioiisdsdo
164:ioiisdso
165:ioisiiodo
166:ioisiioo
167:ioisiioio
168:ioisiioiio
169:ioisiioiiio
170:ioiisdsiiiiiio
171:ioiisddoddddddo
172:ioiisddodddddo
173:ioiisddoddddo
174:ioiisddodddo
175:ioiisddoddo
176:ioiisddodo
177:ioiisddoo
178:ioiisddoio
179:ioiissddo
180:ioiissdo
181:ioiisso
182:ioiissio
183:ioiissiio
184:ioiissiiio
185:ioiisdodddo
186:ioiisdoddo
187:ioiisdodo
188:ioiisdoo
189:ioiisdoio
190:ioiisodddddddddo
191:ioiisoddddddddo
192:ioiisodddddddo
193:ioiisoddddddo
194:ioiisodddddo
195:ioiisoddddo
196:ioiisodddo
197:ioiisoddo
198:ioiisodo
199:ioiisoo
200:iioddo
201:iiodo
202:iioo
203:iioio
204:iioiio
205:iioiiio
206:iiosiio
207:iioisddo
208:iioisdo
209:iioiso
210:iiododo
211:iiodoo
212:iiodoio
213:iiodoiio
214:iiossddo
215:iiossdo
216:iiosso
217:iiossio
218:iiossiio
219:iiodoiiso
220:iiooddo
221:iioodo
222:iiooo
223:iiooio
224:iiooiio
225:iiosiso
226:iioosiio
227:iiooisddo
228:iiooisdo
229:iiooiso
230:iioiodddo
231:iioioddo
232:iioiodo
233:iioioo
234:iioioio
235:iioioiio
236:iiosiiso
237:iioiosddo
238:iioiosdo
239:iioioso
240:iioiioddddo
241:iioiiodddo
242:iioiioddo
243:iioiiodo
244:iioiioo
245:iioiioio
246:iioiioiio
247:iioiioiiio
248:iioiiodsdo
249:iioiiodso
250:iioisddsio
251:iioisddsiio
252:iioiiiodddo
253:iioiiioddo
254:iioiiiodo
255:iioiiioo
```
[Try it online here:](http://cjam.aditsu.net/)
] |
[Question]
[
Consider the following spiral of positive integers:
[](https://i.stack.imgur.com/FlVDV.png)
We now define [grambulation](https://www.reddit.com/r/mathmemes/comments/tvn2gj/the_solution_to_the_april_fools_math/) as a binary operation \$\lozenge : \mathbb N \times \mathbb N \to \mathbb N\$, using this grid. Some example inputs and outputs for grambulation are:
\begin{align\*}
1 & \lozenge 9 = 25 \\
1 & \lozenge 2 = 11 \\
11 & \lozenge 10 = 25 \\
9 & \lozenge 1 = 5 \\
19 & \lozenge 4 = 13 \\
76 & \lozenge 6 = 62 \\
17 & \lozenge 17 = 17 \\
62 & \lozenge 55 = 298
\end{align\*}
Feel free to try to figure out the pattern before continuing.
---
### How to grambulate \$x\$ and \$y\$
The two coordinates of the inputs, \$x \lozenge y\$, in the spiral grid above are found, where \$1\$ is located at \$(0, 0)\$, \$2\$ at \$(1, 0)\$ and so on. For \$x \lozenge y\$, call these coordinates \$x'\$ and \$y'\$. You then find the vector from \$x'\$ to \$y'\$, and calculate the coordinates found by applying this vector to \$y'\$.
A worked example: \$3 \lozenge 11 = 27\$. First, we calculate our coordinates: $$x' = (1, 1), y' = (2, 0).$$ Next, we see that the vector from \$x'\$ to \$y'\$ is \$\vec v = (+1, -1)\$. Finally, we add this to \$y'\$ to get the coordinate \$(3, -1)\$, which is the coordinates of \$27\$.
Alternatively, a visual demonstration:
[](https://i.stack.imgur.com/UzeJpm.png)
Note from the \$62 \lozenge 55 = 298\$ example above, our spiral is not limited to integers below \$121\$, and in fact, this binary operation is well defined for all pairs of positive integers.
Some properties of grambulation:
* \$x \lozenge x = x\$
* \$x \lozenge y = z \iff z \lozenge y = x\$
* It is non-associative and non-commutative
* It is non-injective but is surjective
* \$x^2 \lozenge y^2 = z^2\$ where \$x < y\$ and \$x, y, z\$ all have the same parity
Additionally, \$x^2 \lozenge y^2 = z^2 - 1\$ where \$x\$ and \$y\$ have different parities
Further, \$x^2 \lozenge (x + 2c)^2 = (x + 4c)^2\$ for \$x, c \in \mathbb N\$.
---
Given two positive integers \$x, y \in \mathbb N\$, output \$x \lozenge y\$. You may take input and output in any reasonable format or [method](https://codegolf.meta.stackexchange.com/questions/2447), and this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
Note that the order of inputs does matter (\$x \lozenge y \ne y \lozenge x\$ for most \$x, y \in \mathbb N\$), but you may take input in either consistent order.
### Test cases
```
x y x◊y
1 9 25
1 2 11
11 2 1
11 10 25
9 1 5
19 4 13
76 6 62
17 17 17
62 55 298
3 11 27
16 400 1296
182 240 306
249 1 281
281 1 249
32 98 196
88 16 202
60 41 210
59 85 227
```
And, a visual guide for the last few, on a larger grid:
[](https://i.stack.imgur.com/nqT1M.png)
[Answer]
# [MATL](https://github.com/lmendo/MATL), 22 bytes
```
sQ1YLXIG"I@=&fh]Ew-X{)
```
[**Try it online!**](https://tio.run/##y00syfn/vzjQMNInwtNdydPBVi0tI9a1XDeiWvP//2hTSwUL01gA "MATL – Try It Online")
As a **bonus**, see the beautiful pattern of the function for all pairs of inputs from 1 to *L*. [MATL Online](https://matl.io/?code=%3AtXg%2Cwle%5Dv%22%40sQ1YLXI%40%21%22I%40%3D%26fh%5DEw-X%7B%29%5D50Y02ZGv%5B%5De1YG&inputs=14&version=22.7.4) times out for *L* moderately large, but here's the result for *L*=100 (click [here](https://i.stack.imgur.com/YrysR.png) for a view with better resolution):
[](https://i.stack.imgur.com/YrysRm.png)
### How it works
```
% Implicit input: row vector of two numbers.
sQ % Sum, add 1. This is enough for the size of the spiral
1YL % Matrix with spiral of that size
XI % Copy into clipboard I
G" % For each number in the input
I % Push the spiral again
@= % True for the entri that equals the number
&fh % Row and column indices of that entry as a vector of two numbers
] % End
E % Multiply by two, element-wise
w- % Swap, subtract. Gives the coordinates of the result
X{ % Convert to cell array, for indexing
) % Index into the spiral
% Implcit display
```
The version with graphical input is as above but replaces the input by a loop over all pairs of values from 1 to *L*. The results are concatenated and reshaped as a square matrix, which is displayed with the [`autumn`](https://www.mathworks.com/help/matlab/ref/autumn.html) colormap.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~49~~ ~~32~~ 31 bytes
```
@Jsua_MCG+LheeGUGysQ]]1s-MPBxLJ
```
[Try it online!](https://tio.run/##K6gsyfj/38GruDQx3tfZXdsnIzXVPdS9sjgwNtawWNc3wKnCx@v/fxMdQ0sA "Pyth – Try It Online")
Takes input as `[y, x]`.
* `Jsua_MCG+LheeGUGysQ]]1`: Generate the spiral to a sufficient size, then collapse it to a flat list and save it in `J`.
* `xLJ`: Find the index in J of the two inputs.
* `s-MPB`: Convert to the target index.
* `@`: Index into `J` to get the target number.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 187 bytes
```
(t=(n=#;{1,-1}(Sum[#[.5π⌊(4k-3)^.5⌋],{k,n-1}]&/@{Sin,Cos}))&;(x=#1;y=#2;s=#1+#2;Which[x>y&&x>-y,(2x-1)^2+s,x<=y&&x>-y,4y^2-s+1,x<=y&&x<=-y,4x^2-s+1,True,(2y-1)^2+s])&@@(2t@#2-t@#1))&
```
[Try it online!](https://tio.run/##NY3hCoIwAIQfZjA23Kwtg2BOBr1AYNAPUZAQFdFAJ2yI0O/y3XqHXsQW1J@74@OOa3NdFW2u62u@lnJFWqJOAjExQtmM4rFNQOLvX/f38kBBQ3c48/fv5ZmSqSGdq6Rwo6a47sjxNswYQ4GMBExYCbgYXPKcX6r6WiUmshCaiFqCuKEMZ9wbiAnlnwY243Tw2J@F8gvND577sXBD@xumGCqFuFaAUyfMPa@nvu60KhN24IQH23T9AA "Wolfram Language (Mathematica) – Try It Online")
Ungolfed self-explained:
```
Clear[toXY, fromXY, main];
toXY[n_] := {
Sum[
Sin[.5 π ⌊Sqrt[4 k - 3]⌋], {k,
n - 1}],
-Sum[
Cos[-.5 π ⌊Sqrt[4 k - 3]⌋], {k,
n - 1}]};
fromXY[{x_, y_}] := Which[
x > y && x > -y, (x*2 - 1)^2 + (x + y),
x <= y && x > -y, (y*2)^2 - (x + y) + 1,
x <= y && x <= -y, (x*2)^2 - (x + y) + 1,
True, (y*2 - 1)^2 + (x + y)
];
main[n1_, n2_] := fromXY[2 toXY@n2 - toXY@n1];
```
[Answer]
# [Raku](https://raku.org/), 74 bytes
```
{.first(2*.[$^b]-.[$^a]):k given ½,0,|[\+] flat (1,*i...*)Zxx(1,1.5...*)}
```
[Try it online!](https://tio.run/##RY5NCoJAAEav8i0CfxoHR3JEMQ@SGihoDImFWoyYF@gCnaZNR@ki5sym1XvvW33Xqmv40t9KiLYWMoq/r2eyTLQWXT@Ynk3TzbHMHYUit6IzTuJetfi8iUseabbNUTfFAJMRW1BKbesg5RqM@rrmpb50iBnChCh4Gn8yV0kIpjvETjHg4LoDsEAJ9@D7CZwEaSYJsjHHhL4YsYaB9TEMglH5XpnU04h5@QE "Perl 6 – Try It Online")
* `{ expr1 given expr2 }` is the function body. It evaluates `expr1` after assigning the value of `expr2` to the `$_` topic variable. `expr2` here is an expression for the lazy infinite sequence of spiral coordinates, in the form of complex numbers.
* `(1, *i ... *)` is the sequence of `1`, `i`, `-1`, and `-i`, repeated infinitely.
* `(1, 1.5 ... *)` is the infinite arithmetic sequence 1, 1.5, 2, 2.5, 3, 3.5, ....
* `Zxx` `Z`ips the two preceding sequences together using the `xx` replication operator: `1 xx 1`, `i xx 1.5`, `-1 xx 2`, `-i xx 2.5`, .... The half-integer replication numbers are rounded down, producing `(1)`, `(i)`, `(-1, -1)`, `(-i, -i)`, `(1, 1, 1)`, `(i, i, i)`, ....
* `flat` flattens that list of lists.
* `[\+]` scans that list with the addition operator `+`, producing the infinite list of partial sums. This is the spiral, except that it lacks the first origin element `0`.
* `½, 0, |...` pastes the origin `0` onto the front of the spiral, as well as another leading element `½` to make the whole thing 1-indexed instead of 0-indexed.
* `.[$^a]` and `.[$^b]` are the coordinates in the spiral of the first and second arguments to the function, respectively.
* `2 * .[$^b] - .[$^a]` are the coordinates of the grambulated output.
* `.first(...):k` finds the first index (thanks to the `:k`ey adverb) within the spiral where the value is the coordinates found in the previous step.
[Answer]
# JavaScript (ES6), 132 bytes
Expects `(p)(q)` and returns \$p\lozenge q\$.
```
p=>q=>((g=(t,h=o=[1],v=n=x=y=0)=>n==t|x+[,y]==t?x:g(t,(i=o[o[[x-=h,y-=v]]=++n,[x-v,y+h]])?h:v,i?v:-h))(q),Y=2*y,g([2*x-g(p),Y-y]),n)
```
[Try it online!](https://tio.run/##dZBNboMwEIX3PQVLTzCNbf4M0sA5KuRFlCZAFWHSIARS704dIFJq0o1lzTfvzZv5OvSH2/G7bjuv0Z@n6YxTi9kVM0JKJB2tUGPBFe2xwQFHZIBZg9j9DG5BR2V@@ZCWppHUqAtdFIOHFR097JVC122oKfR0dCulIK/SntZ5n3oVALkC/UCxG2lJCrEbvJK0puKNCmgD01E3N305vV90Sc7EcTiYJwFw9ntHhG8vsVgw5zbmf/BLytm/3gnMA2a8oXymwWrt2ziO7jhacCQ26hjmZ1HHNo6EwWG4JkvkJpoPc/yFb@TcDA/YuhgXSWQ1cGn8RbA2@MzmInheXUj7cqbyzIPEDuDf8ydyDbCZ70gJc8pFzzbniZjhwcOfM5uH93zycR8RT78 "JavaScript (Node.js) – Try It Online")
### How?
The helper function \$g\$ expects a target \$t\$ which is either the index *or* the coordinates of an element in the spiral.
Whenever \$g\$ is called, it starts at the origin and walks through the spiral until the target is reached, keeping track of its index \$n\$ and its position \$(x,y)\$ (all these variables being available in the global scope).
We first invoke \$g(q)\$ to get the coordinates \$(X,Y)\$ of the 2nd element, then \$g(p)\$ to get the coordinates \$(x,y)\$ of the 1st element, and finally \$g([2X-x,2Y-y])\$ to get the index of \$p\lozenge q\$.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~65~~ ~~47~~ ~~45~~ ~~38~~ ~~34~~ ~~31~~ 30 bytes
*-18 bytes by changing the loop structure*
*-2 bytes by altering some assignment*
*-7 bytes by switching to integer coordinates*
*-1 byte from swapping input order, -3 bytes from better list construction*
*-3 bytes by switching to imaginary coordinates*
*-1 byte from better representation of i*
```
xJ+bm=+Z^.j).Ey@d2^sQ3_i@LJQ_2
```
[Try it online!](https://tio.run/##K6gsyfj/v8JLOynXVjsqTi9LU8@10iHFKK440Dg@08HHKzDe6P//aCMdw1gA "Pyth – Try It Online")
Takes input as a list of integers `[y,x]`. Generates a list `J` of spiral coordinates in the imaginary plane, then gets the index in `J` for `2*J[y] - J[x]`. To generate this list, we take advantage of the fact that `ceil(2*sqrt(x))` stays the same values for increasingly long intervals, in the exact same way that the direction of travel when traversing this kind of spiral does.
### Explanation
```
# implicitly assign Z = 0 and Q = eval(input())
J # assign J to
m ^sQ3 # map range(sum(Q)**3) over lambda d
=+Z # add and assign to Z
^.j) # i to the power of
.E # ceiling
y@d2 # 2 * sqrt(d)
+b # prepend a char (to offset list)
xJ # find the index in J of
@LJQ # map x and y to their coordinates in J
_i _2 # double the first and subtract the second
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), ~~60~~ ~~59~~ 58 bytes
```
1//.i_/;{1,-2,1}.Tr/@+I^⌈2√Range[{##,i}-1]⌉!=0:>i+1&
```
[Try it online!](https://tio.run/##TU3NasJAEL7PU0xjKS2uJrOJMakoHtqDt1K9hbQEiXZBY4hbsIbcLfgEPp4vks7GWnr4hvlmvp91oj/SdaLVPKkXw5psu6ve7UFJoiMFVd1ZYY/bk7fz8SDPh9Nrki3TqGy1hKo6FJ@P3zdD53Gk2nRXP20iKHfiS@wrHOJs87zLi3S7VZtsPNWFypbTfKX0eKWydAAvfNCRkVfYGeEi4i0WaOG9JXDPy4MVgyiNWPxzR7fTeaFyPcnyT325CwusuIprRELEkIGyBxcmDSMCxpXhLyPnT2k81PyYkWFeI3QB@z4vBuhL/vWxgZnAFzb0TEgYcIqLlxaU/CMfPYcbSIY@UCBReqbPdXyQ3rVPBgSMK/NCQJczw8Bc2IcBb2TapcPtPid4jZIcwB6nBE277P8A "Wolfram Language (Mathematica) – Try It Online")
Input `[x, y]`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 68 bytes
```
NθNη≔⁰ζ≔⁰εW¬ε«⊞υ⟦ⅈⅉ⟧≧⁺⊗¬ΣKD²✳⁺²ζζ✳ζ¹¿›Lυ⌈⟦θη⟧≔⊕⌕υE§υ⊖η⁻⊗κ§§υ⊖θλε»⎚Iε
```
[Try it online!](https://tio.run/##dVDLTsMwEDwnX@HjRgpSixCXnqpGoEikiuACqnpwkyW26jiNY0MVxLeHddIHHPDJszNjz2whuCkaroYh1Qdn167eoYE2WoS/sSC87DpZaZjFrP@DkNCnkAoZrBsLGEXsKwxy1wlwMdu8QhSzN4i2JAsyfpiMz7ISFnLlupgljdspLEf3i6shR9wn0mBhZaPhlgQX4A1@0kfjmaIEuZHawlXVEzH3hHxn8GiQW6rwhLqyFIm4jB9lTR9t2piJLb3DTm1SXRisUVtK8yB16QtQZFjaVJd49DDBq0T4BJnUlOncYU@Ts/ofV@td6pTfL@87XCnkBug6NVnxbtzjYhjuZ@xuPtx8qB8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `x` and `y`.
```
≔⁰ζ
```
Start in an arbitrary direction.
```
≔⁰ε
```
Start not knowing `x◊y`.
```
W¬ε«
```
Repeat until `x◊y` is known.
```
⊞υ⟦ⅈⅉ⟧
```
Save the current position.
```
≧⁺⊗¬ΣKD²✳⁺²ζζ
```
Turn if this is a corner.
```
✳ζ¹
```
Take one step.
```
¿›Lυ⌈⟦θη⟧
```
If we know `x'` and `y'`, then...
```
≔⊕⌕υE§υ⊖η⁻⊗κ§§υ⊖θλε
```
... see if we can find `x◊y`.
```
»⎚Iε
```
Output `x◊y`.
I tried using complex numbers but that also took 68 bytes:
```
NθNη≔⁰ζ≔⁰ε≔¹δW¬ζ«⊞υεF¬№υ⁺ε×δI1j≧×I1jδ≧⁺δε¿›Lυ⌈⟦θη⟧≔⊕⌕υ⁻⊗§υ⊖η§υ⊖θζ»Iζ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=dVFNS8NAEMVj8iuWnDawhQZEhJ5KixIwJYi30sMmmWRXkk2zH1oqnvwZXnqw6G_y17jJBloF9_bmvZ03b-b9K2dU5i2tD4ej0eXk-vviLRZbo1emyUDiLpz555hZPFeKVwJPCdr_QnBCEUGFRc-M14DwqtV4H4boxfdSoxg2TuuVrXTkojVC9-W0NgoDQQ-8AYULghZUaRxEj0E4PJTQrbO45xXTeNCdq5yv90fWt7XMaMtLhG8lUG3z3IGotJ3IfkzojjemweuOILbpzcYwscglNCA0FPiGi6IfNOHCTrpsTVbb6lzHooBdTyzhJGa2CUH_kN0QyO3w1U8ltxsYcthNzT5UlqvxIp_rYPJUB5vj1RRdRq72Aw "Charcoal – Attempt This Online") Link is to verbose version of code. Explanation:
```
NθNη
```
Input `x` and `y`.
```
≔⁰ζ
```
Start not knowing `x◊y`.
```
≔⁰ε≔¹δ
```
Start at the origin in an arbitrary direction.
```
W¬ζ«
```
Repeat until `x◊y` is known.
```
⊞υε
```
Save the current position.
```
F¬№υ⁺ε×δI1j
```
If this is a corner, then...
```
≧×I1jδ
```
... rotate the direction.
```
≧⁺δε
```
Take one step.
```
¿›Lυ⌈⟦θη⟧
```
If we know `x'` and `y'`, then...
```
≔⊕⌕υ⁻⊗§υ⊖η§υ⊖θζ
```
... see whether we know `x◊y`.
```
»Iζ
```
Output `x◊y`.
[Answer]
# [Uiua](https://www.uiua.org/), 47 chars
```
f←⁅≡/+○[¯+η.÷2×π⌊√-3×4↘1⇡]
+1⊗-∶×2⊃∩f(∵f↘1⇡ⁿ3+)
```
[Try It Online!](https://uiua.org/pad?src=ZiDihpAg4oGF4omhLyvil4tbwq8rzrcuw7cyw5fPgOKMiuKImi0zw5c04oaYMeKHoV0KZyDihpAgKzHiipct4oi2w5cy4oqD4oipZijiiLVm4oaYMeKHoeKBvzMrKQp-fn4K4o2kLj0yNSBnOSAxCuKNpC49MTEgZzIgMQrijaQuPTEgZzIgMTEK4o2kLj0yNSBnMTAgMTEK4o2kLj01IGcxIDkKIyBleGNlZWQgdGltZW91dAojIOKNpC49MTMgZzE5IDQKIyDijaQuPTYyIGc3NiA2Cn5-fg==)
takes input as y,x on the stack
[Answer]
# [Scala](http://www.scala-lang.org/), 395 bytes
395 bytes, it can be golfed much more. Golfed version. [Try it online!](https://tio.run/##fZFBS8NAEIXv@RVzKjPpJrixgqTdgpCLB0EQTyJlU5Mam@zG7FYTSn573ATBUtG5zc733jxmzVaWctDpW7a1cCcLBcehqGrdWDDjKKykfQ03nu3qDBKR6ENaZt5LloNFFSckkIPVoEKrb5UNODlBjXuxNoXC8Mq/L/y81LpB895YXPj74JJcheZQBWsI/lJvtcHgf/kUIsc6xoQlROL4IUtsWUei9ooc23U3m7VuRUe1/sTIbwPOIppjO@8oK00GI7QSZ1TnmGBi5hzOsJU4cfvFfetPtvRTxAoVjxOmovFaPyHd@SJajq1k6dRyWuY4BZVsNEqJ@gFg8nAfg7LZmRhumkZ2Tw@2KdTumWJ4VIUFAUcPXNXu1ZYKK@TXEYNocUHkBr3XD18)
```
import scala.math._
type D=Double
def t(n:D)=(1 to n.toInt-1).map(k=>sin(.5*Pi*floor(sqrt(4*k-3)))).sum-> -(1 to n.toInt-1).map(k=>cos(-.5*Pi*floor(sqrt(4*k-3)))).sum
def f(p:(D,D))={val(x,y)=p
if(x>y&&x> -y)pow(2*x-1,2)+(x+y)else if(x<=y&&x> -y)pow(2*y,2)-(x+y)+1 else if(x<=y&&x<= -y)pow(2*x,2)-(x+y)+1 else pow(2*y-1,2)+(x+y)}
def m(n1:D,n2:D)={val(x,y)=t(n2);val(a,b)=t(n1);f((2*x-a,2*y-b))}
```
Ungolfed version. [Try it online!](https://tio.run/##lVJNS8NAEL3nV7xT2a1JMLGCFFsQvHgQBBEUEUlqUtcmu3F3qwnS3x6n@Wgr1YJ7GObrvX0zjJlFWVTXIi@UtjDryM8j@@o/O46K35KZxXUkJL4c4CVJYdX9A5NjXKplnCV8DNZ6bp/BpOkFPqIMJUUswFJakUH6Vl1Jy4m/YAtMpjBCMv8UQ9wIMmmmlGbmXVs2onABDyecnm@W@YaxIkbvAOVMGeb9g5OVLipO7srpJky1ymnGQglp98fj/eg/5mxZKNWgmrRIWYkp6R0MsHY8qhfqk4XDkkQELkKOIwKSaf4HkswkLex88huuajBejyET/Ikjb@fDQ8CO@1dNm53kdAJMBv3sLmS4cwKHFtLeS8i3lchFvK0EbaVbercdamklxXxfRqTnZowLraPq8dZqIedPpOFOCrtRUFDWZpI1/cFZSHSj445qVdff)
```
import scala.math._
object Main {
def toXY(n: Double): (Double, Double) = {
val x = (1 until n.toInt).map(k => sin(.5 * Pi * floor(sqrt(4 * k - 3)))).sum
val y = -(1 until n.toInt).map(k => cos(-.5 * Pi * floor(sqrt(4 * k - 3)))).sum
(x, y)
}
def fromXY(point: (Double, Double)): Double = {
val (x, y) = point
if(x > y && x > -y) pow(2*x - 1, 2) + (x + y)
else if(x <= y && x > -y) pow(2*y, 2) - (x + y) + 1
else if(x <= y && x <= -y) pow(2*x, 2) - (x + y) + 1
else pow(2*y - 1, 2) + (x + y)
}
def main(n1: Double, n2: Double): Double = {
val (x, y) = toXY(n2)
val (a, b) = toXY(n1)
fromXY((2*x - a, 2*y - b))
}
def main(args: Array[String]): Unit = {
println(main(182, 240))
}
}
```
] |
[Question]
[
## Challenge
Write code which, given an image of a panel from a random xkcd comic, returns a truthy value if Blackhat is in the comic or falsey if not.
## Who is Blackhat?
[Blackhat](http://www.explainxkcd.com/wiki/index.php/Black_Hat) is the unofficial name given to the character in xkcd comics who wears a black hat:

Taken from the Explain xkcd page on Blackhat
Blackhat's hat is always straight sided, black and looks the same as in the above image.
Other characters may also have hats and hair but none will have hats which are black and straight sided.
## Input
The image may be input in anyway you wish whether it be a path to the image or bytes via STDIN. You should not need to take a URL as input.
## Rules
Hardcoding the answer is not banned, but it is not appreciated.
You are not allowed to access the internet to get the answer.
## Examples
All images cropped from images from <https://xkcd.com>
### Blackhat is in the panel (return `truthy`)

---

### Blackhat is not in the panel (return `falsey`)

---

## Test Battery
The 20 images which contain Blackhat can be found here: <https://beta-decay.github.io/blackhat.zip>
The 20 images which do not contain Blackhat can be found here: <https://beta-decay.github.io/no_blackhat.zip>
**If you want more images to test your programs with (to train for the mystery test cases), you can find a list of all appearances of Blackhat here: <http://www.explainxkcd.com/wiki/index.php/Category:Comics_featuring_Black_Hat>**
## Winning
The program which correctly identifies whether Blackhat is in the comic or not for the most images wins. Your header should include your score as a percentage.
In the event of a tiebreak, the tied programs will be given "mystery" images (i.e. ones that only I know about). The code which identifies the most correctly wins the tiebreak.
The mystery images will be revealed along with the scores.
***Note:*** it seems that Randall’s name for him may be Hat Guy. I prefer Blackhat though.
[Answer]
# [PHP](http://www.php.net/) (>=7), 100% (40/40)
```
<?php
set_time_limit(0);
class BlackHat
{
const ROTATION_RANGE = 45;
private $image;
private $currentImage;
private $currentImageWidth;
private $currentImageHeight;
public function __construct($path)
{
$this->image = imagecreatefrompng($path);
}
public function hasBlackHat()
{
$angles = [0];
for ($i = 1; $i <= self::ROTATION_RANGE; $i++) {
$angles[] = $i;
$angles[] = -$i;
}
foreach ($angles as $angle) {
if ($angle == 0) {
$this->currentImage = $this->image;
} else {
$this->currentImage = $this->rotate($angle);
}
$this->currentImageWidth = imagesx($this->currentImage);
$this->currentImageHeight = imagesy($this->currentImage);
if ($this->findBlackHat()) return true;
}
return false;
}
private function findBlackHat()
{
for ($y = 0; $y < $this->currentImageHeight; $y++) {
for ($x = 0; $x < $this->currentImageWidth; $x++) {
if ($this->isBlackish($x, $y) && $this->isHat($x, $y)) return true;
}
}
return false;
}
private function isHat($x, $y)
{
$hatWidth = $this->getBlackishSequenceSize($x, $y, 'right');
if ($hatWidth < 10) return false;
$hatHeight = $this->getBlackishSequenceSize($x, $y, 'bottom');
$hatLeftRim = $hatRightRim = 0;
for (; ; $hatHeight--) {
if ($hatHeight < 5) return false;
$hatLeftRim = $this->getBlackishSequenceSize($x, $y + $hatHeight, 'left');
if ($hatLeftRim < 3) continue;
$hatRightRim = $this->getBlackishSequenceSize($x + $hatWidth, $y + $hatHeight, 'right');
if ($hatRightRim < 2) $hatRightRim = $this->getBlackishSequenceSize($x + $hatWidth, $y + $hatHeight, 'right', 'isLessBlackish');
if ($hatRightRim < 2) continue;
break;
}
$ratio = $hatWidth / $hatHeight;
if ($ratio < 2 || $ratio > 4.2) return false;
$widthRatio = $hatWidth / ($hatLeftRim + $hatRightRim);
if ($widthRatio < 0.83) return false;
if ($hatHeight / $hatLeftRim < 1 || $hatHeight / $hatRightRim < 1) return false;
$pointsScore = 0;
if ($this->isSurroundedBy($x, $y, 3, true, true, false, false)) $pointsScore++;
if ($this->isSurroundedBy($x + $hatWidth, $y, 3, true, false, false, true)) $pointsScore++;
if ($this->isSurroundedBy($x, $y + $hatHeight, 3, false, false, true, false)) $pointsScore++;
if ($this->isSurroundedBy($x + $hatWidth, $y + $hatHeight, 3, false, false, true, false)) $pointsScore++;
if ($this->isSurroundedBy($x - $hatLeftRim, $y + $hatHeight, 3, true, true, true, false)) $pointsScore++;
if ($this->isSurroundedBy($x + $hatWidth + $hatRightRim, $y + $hatHeight, 3, true, false, true, true)) $pointsScore++;
if ($pointsScore < 3 || ($hatHeight >= 19 && $pointsScore < 4) || ($hatHeight >= 28 && $pointsScore < 5)) return false;
$middleCheckSize = ($hatHeight >= 15 ? 3 : 2);
if (!$this->isSurroundedBy($x + (int)($hatWidth / 2), $y, $middleCheckSize, true, null, null, null)) return false;
if (!$this->isSurroundedBy($x + (int)($hatWidth / 2), $y + $hatHeight, $middleCheckSize, null, null, true, null)) {
if (!$this->isSurroundedBy($x + (int)(($hatWidth / 4) * 3), $y + $hatHeight, $middleCheckSize, null, null, true, null)) return false;
}
if (!$this->isSurroundedBy($x, $y + (int)($hatHeight / 2), $middleCheckSize + 1, null, true, null, null)) return false;
if (!$this->isSurroundedBy($x + $hatWidth, $y + (int)($hatHeight / 2), $middleCheckSize, null, null, null, true)) return false;
$badBlacks = 0;
for ($i = 1; $i <= 3; $i++) {
if ($y - $i >= 0) {
if ($this->isBlackish($x, $y - $i)) $badBlacks++;
}
if ($x - $i >= 0 && $y - $i >= 0) {
if ($this->isBlackish($x - $i, $y - $i)) $badBlacks++;
}
}
if ($badBlacks > 2) return false;
$total = ($hatWidth + 1) * ($hatHeight + 1);
$blacks = 0;
for ($i = $x; $i <= $x + $hatWidth; $i++) {
for ($j = $y; $j <= $y + $hatHeight; $j++) {
$isBlack = $this->isBlackish($i, $j);
if ($isBlack) $blacks++;
}
}
if (($total / $blacks > 1.15)) return false;
return true;
}
private function getColor($x, $y)
{
return imagecolorsforindex($this->currentImage, imagecolorat($this->currentImage, $x, $y));
}
private function isBlackish($x, $y)
{
$color = $this->getColor($x, $y);
return ($color['red'] < 78 && $color['green'] < 78 && $color['blue'] < 78 && $color['alpha'] < 30);
}
private function isLessBlackish($x, $y)
{
$color = $this->getColor($x, $y);
return ($color['red'] < 96 && $color['green'] < 96 && $color['blue'] < 96 && $color['alpha'] < 40);
}
private function getBlackishSequenceSize($x, $y, $direction, $fn = 'isBlackish')
{
$size = 0;
if ($direction == 'right') {
for ($x++; ; $x++) {
if ($x >= $this->currentImageWidth) break;
if (!$this->$fn($x, $y)) break;
$size++;
}
} elseif ($direction == 'left') {
for ($x--; ; $x--) {
if ($x < 0) break;
if (!$this->$fn($x, $y)) break;
$size++;
}
} elseif ($direction == 'bottom') {
for ($y++; ; $y++) {
if ($y >= $this->currentImageHeight) break;
if (!$this->$fn($x, $y)) break;
$size++;
}
}
return $size;
}
private function isSurroundedBy($x, $y, $size, $top = null, $left = null, $bottom = null, $right = null)
{
if ($top !== null) {
$flag = false;
for ($i = 1; $i <= $size; $i++) {
if ($y - $i < 0) break;
$isBlackish = $this->isBlackish($x, $y - $i);
if (
($top && !$isBlackish) ||
(!$top && $isBlackish)
) {
$flag = true;
} elseif ($flag) {
return false;
}
}
if (!$flag) return false;
}
if ($left !== null) {
$flag = false;
for ($i = 1; $i <= $size; $i++) {
if ($x - $i < 0) break;
$isBlackish = $this->isBlackish($x - $i, $y);
if (
($left && !$isBlackish) ||
(!$left && $isBlackish)
) {
$flag = true;
} elseif ($flag) {
return false;
}
}
if (!$flag) return false;
}
if ($bottom !== null) {
$flag = false;
for ($i = 1; $i <= $size; $i++) {
if ($y + $i >= $this->currentImageHeight) break;
$isBlackish = $this->isBlackish($x, $y + $i);
if (
($bottom && !$isBlackish) ||
(!$bottom && $isBlackish)
) {
$flag = true;
} elseif ($flag) {
return false;
}
}
if (!$flag) return false;
}
if ($right !== null) {
$flag = false;
for ($i = 1; $i <= $size; $i++) {
if ($x + $i >= $this->currentImageWidth) break;
$isBlackish = $this->isBlackish($x + $i, $y);
if (
($right && !$isBlackish) ||
(!$right && $isBlackish)
) {
$flag = true;
} elseif ($flag) {
return false;
}
}
if (!$flag) return false;
}
return true;
}
private function rotate($angle)
{
return imagerotate($this->image, $angle, imagecolorallocate($this->image, 255, 255, 255));
}
}
$bh = new BlackHat($argv[1]);
echo $bh->hasBlackHat() ? 'true' : 'false';
```
To run it:
```
php <filename> <image_path>
```
Example:
```
php black_hat.php "/tmp/blackhat/1.PNG"
```
### Notes
* Prints "true" if finds black hat and "false" if doesn't find it.
* This should work on previous versions of PHP as well, but to be safe, use PHP>=7 with [GD](http://php.net/manual/en/book.image.php).
* This script actually tries to find the hat and by doing so, it might rotate the image many many times and each time checks for thousands and thousands of pixels and clues. So the larger the image is or the more dark pixels it has, the script will take more time to finish. It should take a few seconds to a minute for majority of images though.
* I would love to train this script more, but I don't have enough time to do so.
* This script is not golfed (again because I don't have enough time), but has lots of potential to golf in case of a tie.
### Some examples of detected black hats:
[](https://i.stack.imgur.com/mwx0q.png)
These examples are acquired by drawing red lines on special points found on the image that script decided has a black hat (images can have rotation compared to original ones).
---
# Extra
Before posting here, I did test this script against another set of 15 images, 10 with black hat and 5 without black hat and it went correct for all of them as well (100%).
Here is the ZIP file containing extra test images I used: [extra.zip](https://www.dropbox.com/s/1krz98hd8mbsetb/extra.zip?dl=1)
In the `extra/blackhat` directory, the detection results with red lines are also available. For example `extra/blackhat/1.png` is the test image and `extra/blackhat/1_r.png` is the detection result of it.
[Answer]
## Matlab, 87,5%
```
function hat=is_blackhat_here2(filepath)
img_hsv = rgb2hsv(imread(filepath));
img_v = img_hsv(:,:,3);
bw = imdilate(imerode( ~im2bw(img_v), strel('disk', 4, 8)), strel('disk', 4, 8));
bw = bwlabel(bw, 8);
bw = imdilate(imerode(bw, strel('disk', 1, 4)), strel('disk', 1, 4));
bw = bwlabel(bw, 4);
region_stats = regionprops(logical(bw), 'all');
hat = false;
for i = 1 : numel(region_stats)
if mean(img_v(region_stats(i).PixelIdxList)) < 0.15 ...
&& region_stats(i).Area > 30 ...
&& region_stats(i).Solidity > 0.88 ...
&& region_stats(i).Eccentricity > 0.6 ...
&& region_stats(i).Eccentricity < 1 ...
&& abs(region_stats(i).Orientation) < 75...
&& region_stats(i).MinorAxisLength / region_stats(i).MajorAxisLength < 0.5;
hat = true;
break;
end
end
```
Enhancement of the previous version, with some checks added on the shape of the candidate regions.
Classification errors in **HAT set**: images **4, 14, 15, 17**.
Classification errors in **NON HAT set**: images **4**.
Some examples of corrected classified images:
[](https://i.stack.imgur.com/j0mUm.png)
[](https://i.stack.imgur.com/ldwBM.png)
Example of a wrong classified image:
[](https://i.stack.imgur.com/H9yES.png)
**OLD VERSION (77,5%)**
```
function hat=is_blackhat_here(filepath)
img_hsv = rgb2hsv(imread(filepath));
img_v = img_hsv(:,:,3);
bw = imerode(~im2bw(img_v), strel('disk', 5, 8));
hat = mean(img_v(bw)) < 0.04;
```
Approach based on image erosion, similar to the solution proposed by Mnemonic, but based on V channel of the HSV image.
Moreover, the mean value of the channel of the selected area is checked (not its size).
Classification errors in **HAT set**: images **4, 5, 10**.
Classification errors in **NON HAT set**: images **4, 5, 6, 7, 13, 14**.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 62.5%
```
<214.O.n'z
```
Accepts the filename of an image file on stdin. Returns `True` if the average of all its RGB color components are greater than 214. You read that right: apparently blackhat images tend to be brighter than no-blackhat images.
(Surely someone can do better—this isn’t [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")!)
[Answer]
# Python 2, ~~65%~~ ~~72.5%~~ 77.5% (= 31/40)
```
import cv2
import numpy as np
from scipy import misc
def blackhat(path):
im = misc.imread(path)
black = (im[:, :, 0] < 10) & (im[:, :, 1] < 10) & (im[:, :, 2] < 10)
black = black.astype(np.ubyte)
black = cv2.erode(black, np.ones((3, 3)), iterations=3)
return 5 < np.sum(black) < 2000
```
This figures out which pixels are black, then erodes away small contiguous pieces. Certainly room for improvement here.
] |
[Question]
[
Note, challenge copied from question asked at [math.stackexchange](https://math.stackexchange.com/q/2094351/196018).
Recently, I attained quite some skill at blowing bubbles. At first I would blow bubbles like this:
[](https://i.stack.imgur.com/BRy52.png)
But then things started getting strange:
[](https://i.stack.imgur.com/9jOdN.png)
After a while, I was blowing some pretty weird bubbles:
[](https://i.stack.imgur.com/phz14.png)
After blowing hundreds, maybe even thousands of such bubbles, my forehead suddenly wrinkled with the question: Given n bubbles, how many different ways can you arrange them? For example if n = 1, there is only 1 arrangement. If n = 2, there are 2 arrangements. If n = 3, there are 4 arrangements. If n = 4, there are 9 arrangements.
Here are the 9 arrangements of 4 bubbles:
[](https://i.stack.imgur.com/yWNl6.png)
[](https://i.stack.imgur.com/GveDF.png)
[](https://i.stack.imgur.com/Bj3EU.png)
[](https://i.stack.imgur.com/ftpFz.png)
[](https://i.stack.imgur.com/yHUBV.png)
[](https://i.stack.imgur.com/eNjti.png)
[](https://i.stack.imgur.com/YBLPw.png)
[](https://i.stack.imgur.com/CQNEt.png)
[](https://i.stack.imgur.com/hXyy8.png)
After blowing all of these marvelous bubbles, I decided that I should share the delight of counting their arrangements with you. So here is your task:
---
## Goal
Write a program, function, or similar that counts the number of ways you can arrange `n` bubbles.
---
## Input
`n`, the number of bubbles. n > 0
---
## Output
The number of ways you can arrange these bubbles.
---
## Winning Criteria
It would be really cool if we can blow a bubble around your code. The smaller you make your code, the easier it will be to do so. So the person who makes the code with the least number of bytes will win the contest.
---
### Extra information
[OEIS](http://oeis.org/A000081)
[Answer]
# Python 2, 92 87 bytes
```
a=lambda n:n<2or sum((k%d<1)*d*a(d)*a(n-k)for k in range(1,n)for d in range(1,1+k))/~-n
```
In plain english: to compute `a(n)` we calculate `d*a(d)*a(n-k)` for every divisor `d` of every positive integer `k` smaller than or equal to `n`, sum all these, and divide by `n-1`.
To make it run faster, run in Python 3 (replacing `/` with `//` in the above function) and memoize:
```
import functools
a = functools.lru_cache(None)(a)
```
If you do this it computes `a(50) = 425976989835141038353` instantly.
[Answer]
# GNU Prolog, 98 bytes
```
b(x,0,x).
b(T/H,N,H):-N#=A+B+1,b(H,A,_),b(T,B,J),H@>=J.
c(X,Y):-findall(A,b(A,X,_),L),length(L,Y).
```
This answer is a great example of how Prolog can struggle with even the simplest I/O formats. It works in true Prolog style via describing the problem, rather than the algorithm to solve it: it specifies what counts as a legal bubble arrangement, asks Prolog to generate all those bubble arrangements, and then counts them. The generation takes 55 characters (the first two lines of the program). The counting and I/O takes the other 43 (the third line, and the newline that separates the two parts). I bet this isn't a problem that the OP expected to cause languages to struggle with I/O! (Note: Stack Exchange's syntax highlighting makes this harder to read, not easier, so I turned it off).
## Explanation
Let's start with a pseudocode version of a similar program that doesn't actually work:
```
b(Bubbles,Count) if map(b,Bubbles,BubbleCounts)
and sum(BubbleCounts,InteriorCount)
and Count is InteriorCount + 1
and is_sorted(Bubbles).
c(Count,NPossibilities) if listof(Bubbles,b(Bubbles,Count),List)
and length(List,NPossibilities).
```
It should be fairly clear how `b` works: we're representing bubbles via sorted lists (which are a simple implementation of multisets that causes equal multisets to compare equal), and a single bubble `[]` has a count of 1, with a larger bubble having a count equal to the total count of the bubbles inside plus 1. For a count of 4, this program would (if it worked) generate the following lists:
```
[[],[],[],[]]
[[],[],[[]]]
[[],[[],[]]]
[[],[[[]]]]
[[[]],[[]]]
[[[],[],[]]]
[[[],[[]]]]
[[[[],[]]]]
[[[[[]]]]]
```
This program is unsuitable as an answer for several reasons, but the most pressing is that Prolog doesn't actually have a `map` predicate (and writing it would take too many bytes). So instead, we write the program more like this:
```
b([], 0).
b([Head|Tail],Count) if b(Head,HeadCount)
and b(Tail,TailCount)
and Count is HeadCount + TailCount + 1
and is_sorted([Head|Tail]).
c(Count,NPossibilities) if listof(Bubbles,b(Bubbles,Count),List)
and length(List,NPossibilities).
```
The other major problem here is that it'll go into an infinite loop when run, because of the way Prolog's evaluation order works. However, we can solve the infinite loop by rearranging the program slightly:
```
b([], 0).
b([Head|Tail],Count) if Count #= HeadCount + TailCount + 1
and b(Head,HeadCount)
and b(Tail,TailCount)
and is_sorted([Head|Tail]).
c(Count,NPossibilities) if listof(Bubbles,b(Bubbles,Count),List)
and length(List,NPossibilities).
```
This might look fairly weird – we're adding together the counts before we know what they are – but GNU Prolog's `#=` is capable of handling that sort of noncausal arithmetic, and because it's the very first line of `b`, and the `HeadCount` and `TailCount` must both be less than `Count` (which is known), it serves as a method of naturally limiting how many times the recursive term can match, and thus causes the program to always terminate.
The next step is to golf this down a bit. Removing whitespace, using single-character variable names, using abbreviations like `:-` for `if` and `,` for `and`, using `setof` rather than `listof` (it has a shorter name and produces the same results in this case), and using `sort0(X,X)` rather than `is_sorted(X)` (because `is_sorted` isn't actually a real function, I made it up):
```
b([],0).
b([H|T],N):-N#=A+B+1,b(H,A),b(T,B),sort0([H|T],[H|T]).
c(X,Y):-setof(A,b(A,X),L),length(L,Y).
```
This is fairly short, but it's possible to do better. The key insight is that `[H|T]` is really verbose as list syntaxes go. As Lisp programmers will know, a list is basically just made of cons cells, which are basically just tuples, and hardly any part of this program is using list builtins. Prolog has several very short tuple syntaxes (my favourite is `A-B`, but my second favourite is `A/B`, which I'm using here because it produces easier-to-read debug output in this case); and we can also choose our own single-character `nil` for the end of the list, rather than being stuck with the two-character `[]` (I chose `x`, but basically anything works). So instead of `[H|T]`, we can use `T/H`, and get output from `b` that looks like this (note that the sort order on tuples is a little different from that on lists, so these aren't in the same order as above):
```
x/x/x/x/x
x/x/x/(x/x)
x/(x/x)/(x/x)
x/x/(x/x/x)
x/(x/x/x/x)
x/x/(x/(x/x))
x/(x/x/(x/x))
x/(x/(x/x/x))
x/(x/(x/(x/x)))
```
This is rather harder to read than the nested lists above, but it's possible; mentally skip the `x`s, and interpret `/()` as a bubble (or just plain `/` as a degenerate bubble with no contents, if there's no `()` after it), and the elements have a 1-to-1 (if disordered) correspondence with the list version shown above.
Of course, this list representation, despite being much shorter, has a major drawback; it's not built into the language, so we can't use `sort0` to check if our list is sorted. `sort0` is fairly verbose anyway, though, so doing it by hand isn't a huge loss (in fact, doing it by hand on the `[H|T]` list representation comes to exactly the same number of bytes). The key insight here is that the program as written checks to see if the list is sorted, if its tail is sorted, if *its* tail is sorted, and so on; there are a lot of redundant checks, and we can exploit that. Instead, we'll just check to ensure that the first two elements are in order (which ensures that the list will end up sorted once the list itself and all its suffixes are checked).
The first element is easily accessible; that's just the head of the list `H`. The second element is rather harder to access, though, and may not exist. Luckily, `x` is less than all the tuples we're considering (via Prolog's generalized comparison operator `@>=`), so we can consider the "second element" of a singleton list to be `x` and the program will work fine. As for actually accessing the second element, the tersest method is to add a third argument (an out argument) to `b`, that returns `x` in the base case and `H` in the recursive case; this means that we can grab the head of the tail as an output from the second recursive call to `B`, and of course the head of the tail is the list's second element. So `b` looks like this now:
```
b(x,0,x).
b(T/H,N,H):-N#=A+B+1,b(H,A,_),b(T,B,J),H@>=J.
```
The base case is simple enough (empty list, return a count of 0, the empty list's "first element" is `x`). The recursive case starts out the same way as before (just with the `T/H` notation rather than `[H|T]`, and `H` as an extra out argument); we disregard the extra argument from the recursive call on the head, but store it in `J` in the recursive call on the tail. Then all we have to do is ensure that `H` is greater than or equal to `J` (i.e. "if the list has at least two elements, the first is greater than or equal to the second) in order to ensure that the list ends up sorted.
Unfortunately, `setof` throws a fit if we try to use the previous definition of `c` together with this new definition of `b`, because it treats unused out parameters in more or less the same way as an SQL `GROUP BY`, which is completely not what we want. It's possible to reconfigure it to do what we want, but that reconfiguration costs characters. Instead, we use `findall`, which has a more convenient default behaviour and is only two characters longer, giving us this definition of `c`:
```
c(X,Y):-findall(A,b(A,X,_),L),length(L,Y).
```
And that's the complete program; tersely generate bubble patterns, then spend a whole load of bytes counting them (we need a rather long `findall` to convert the generator to a list, then an unfortunately verbosely named `length` to check the length of that list, plus the boilerplate for a function declaration).
[Answer]
# Mathematica, 68 bytes
I bet this can be beaten (even in Mathematica) with a from-scratch implementation, but here's the builtin version:
```
<<NumericalDifferentialEquationAnalysis`
Last@ButcherTreeCount[#+1]&
```
`ButcherTreeCount` is 0-indexed, hence the `[#+1]`, and returns a list of all values up to its argument, hence the `Last@`. But otherwise it's just the builtin for this function. However, it requires loading a package, which is what the first line does.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 40 [bytes](https://github.com/abrudz/SBCS)
```
{1≥⍵:⍵⋄w÷⍨+/∊(0=v|⊂⌽v)×v××∘⊂⍨∇¨v←⍳w←⍵-1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v9rwUefSR71brYD4UXdL@eHtj3pXaOs/6ujSMLAtq3nU1fSoZ2@Z5uHpZYenH57@qGMGSKR3xaOO9kMryh61TXjUu7kcTG3VNaz9nwZm9j3qaj603vhR28RHfVODg5yBZIiHZ/D/tEMrDBWMFIwVTBRMFcwUzBUsFCwB "APL (Dyalog Unicode) – Try It Online")
A port of [orlp's Python 2 answer](https://codegolf.stackexchange.com/a/106613/78410), using a vector of nested vectors in place of nested for-loops.
### How it works
```
{1≥⍵:⍵⋄w÷⍨+/∊(0=v|⊂⌽v)×v××∘⊂⍨∇¨v←⍳w←⍵-1} ⍝ Input: n
{1≥⍵:⍵⋄ } ⍝ If n≤1, return n; otherwise,
w←⍵-1 ⍝ w←n-1
v←⍳w ⍝ v←1..n-1
∇¨ ⍝ a←Recursive call on each of v; a(1), .., a(n-1)
×∘⊂⍨ ⍝ Multiply each of a with a, giving nested array
⍝ where [d][n-k] will contain the desired value at each iteration in Python code
v× ⍝ Multiply each of v (the value of d) with each row of the above
× ⍝ Multiply each with
(0=v|⊂⌽v) ⍝ 1 if n-k is divisible by d, 0 otherwise
w÷⍨+/∊ ⍝ Flatten, sum, and divide by n-1
```
] |
[Question]
[
For an ***N*** by ***N*** image, find a set of pixels such that no separation distance is present more than once. That is, if two pixels are separated by a distance ***d***, then they are the only two pixels that are separated by exactly ***d*** (using [Euclidean distance](http://en.wikipedia.org/wiki/Euclidean_distance#Two_dimensions "Wikipedia")). *Note that **d** need not be integer.*
The challenge is to find a larger such set than anyone else.
### Specification
No input is required - for this contest ***N*** will be fixed at 619.
*(Since people keep asking - there's nothing special about the number 619. It was chosen to be large enough to make an optimal solution unlikely, and small enough to let an N by N image be displayed without Stack Exchange automatically shrinking it. Images can be displayed full size up to 630 by 630, and I decided to go with the largest prime that doesn't exceed that.)*
The output is a space separated list of integers.
Each integer in the output represents one of the pixels, numbered in English reading order from 0. For example for ***N*** = 3, the locations would be numbered in this order:
```
0 1 2
3 4 5
6 7 8
```
You may output progress information during running if you wish, as long as the final scoring output is easily available. You may output to STDOUT or to a file or whatever is easiest for pasting into the Stack Snippet Judge below.
### Example
***N*** = 3
Chosen coordinates:
```
(0,0)
(1,0)
(2,1)
```
Output:
```
0 1 5
```
### Winning
The score is the number of locations in the output. Of those valid answers which have the highest score, the earliest to post output with that score wins.
Your code does not need to be deterministic. You may post your best output.
---
### Related areas for research
*(Thanks to **[Abulafia](https://codegolf.stackexchange.com/users/20424/abulafia)** for the Golomb links)*
While neither of these is the same as this problem, they are both similar in concept and may give you ideas on how to approach this:
* [Golomb ruler](https://en.wikipedia.org/wiki/Golomb_ruler "Wikipedia"): the 1 dimensional case.
* [Golomb rectangle](http://www.research.ibm.com/people/s/shearer/golrec.html): a 2 dimensional extension of the Golomb ruler. A variant of the NxN (square) case known as [Costas array](https://en.wikipedia.org/wiki/Costas_array "Wikipedia") is solved for all N.
Note that the points required for this question are not subject to the same requirements as a Golomb rectangle. A Golomb rectangle extends from the 1 dimensional case by requiring that the ***vector*** from each point to each other be unique. This means that there can be two points separated by a distance of 2 horizontally, and also two points separated by a distance of 2 vertically.
For this question, it is the ***scalar*** distance that must be unique, so there cannot be both a horizontal and a vertical separation of 2. Every solution to this question will be a Golomb rectangle, but not every Golomb rectangle will be a valid solution to this question.
---
### Upper bounds
**[Dennis](https://codegolf.stackexchange.com/users/12012/dennis "profile")** helpfully [pointed out in chat](http://chat.stackexchange.com/transcript/message/22515265#22515265 "chat transcript") that 487 is an upper bound on the score, and gave a proof:
>
> According to my CJam code (`619,2m*{2f#:+}%_&,`), there are 118800 unique numbers that can be written as the sum of the squares of two integers between 0 and 618 (both inclusive).
> n pixels require n(n-1)/2 unique distances between each other. For n = 488, that gives 118828.
>
>
>
So there are 118,800 possible different lengths between all the potential pixels in the image, and placing 488 black pixels would result in 118,828 lengths, which makes it impossible for them all to be unique.
I'd be very interested to hear if anyone has a proof of a lower upper bound than this.
---
### Leaderboard
*(Best answer by each user)*

---
# Stack Snippet Judge
```
canvas=document.getElementById('canvas');ctx=canvas.getContext('2d');information=document.getElementById('information');problemList=document.getElementById('problemList');width=canvas.width;height=canvas.height;area=width*height;function verify(){stop();checkPoints();}function checkPoints(){valid=true;numbers=[];points=[];lengths=[];lengthDetails=[];duplicatedLengths=[];clearCanvas();rawData=pointData.value;splitData=rawData.split(' ');for(i=0;i<splitData.length;i++){datum=splitData[i];if(datum!==''){n=parseInt(datum);if(n>=area||n<0){valid=false;information.innerHTML='Out of range:'+n;break;}if(numbers.indexOf(n)>-1){valid=false;information.innerHTML='Duplicated value:'+n;break;}numbers.push(n);x=n%width;y=Math.floor(n/width);points.push([x,y]);}}if(valid){ctx.fillStyle='black';for(i=0;i<points.length-1;i++){p1=points[i];x1=p1[0];y1=p1[1];drawPoint(x1,y1);for(j=i+1;j<points.length;j++){p2=points[j];x2=p2[0];y2=p2[1];d=distance(x1,y1,x2,y2);duplicate=lengths.indexOf(d);if(duplicate>-1){duplicatedLengths.push(lengthDetails[duplicate]);duplicatedLengths.push([d,[numbers[i],numbers[j]],[x1,y1,x2,y2]]);}lengths.push(d);lengthDetails.push([d,[numbers[i],numbers[j]],[x1,y1,x2,y2]]);}}p=points[points.length-1];x=p[0];y=p[1];drawPoint(x,y);if(duplicatedLengths.length>0){ctx.strokeStyle='red';information.innerHTML='Duplicate lengths shown in red';problemTextList=[];for(i=0;i<duplicatedLengths.length;i++){data=duplicatedLengths[i];length=data[0];numberPair=data[1];coords=data[2];line(coords);specificLineText='<b>'+length+': '+numberPair[0]+' to '+numberPair[1]+'</b> [('+coords[0]+', '+coords[1]+') to ('+coords[2]+', '+coords[3]+')]';if(problemTextList.indexOf(specificLineText)===-1){problemTextList.push(specificLineText);}}problemText=problemTextList.join('<br>');problemList.innerHTML=problemText;}else{information.innerHTML='Valid: '+points.length+' points';}}}function clearCanvas(){ctx.fillStyle='white';ctx.fillRect(0,0,width,height);}function line(coords){x1=coords[0];y1=coords[1];x2=coords[2];y2=coords[3];ctx.beginPath();ctx.moveTo(x1+0.5,y1+0.5);ctx.lineTo(x2+0.5,y2+0.5);ctx.stroke();}function stop(){information.innerHTML='';problemList.innerHTML='';}function distance(x1,y1,x2,y2){xd=x2-x1;yd=y2-y1;return Math.sqrt(xd*xd+yd*yd);}function drawPoint(x,y){ctx.fillRect(x,y,1,1);}
```
```
<input id='pointData' placeholder='Paste data here' onblur='verify()'></input><button>Verify data</button><p id='information'></p><p id='problemList'></p><canvas id='canvas' width='619' height='619'></canvas>
```
[Answer]
# Python 3, ~~135~~ ~~136~~ 137
```
10 6830 20470 47750 370770 148190 306910 373250 267230 354030 30390 361470 118430 58910 197790 348450 381336 21710 183530 305050 2430 1810 365832 99038 381324 39598 262270 365886 341662 15478 9822 365950 44526 58862 24142 381150 31662 237614 118830 380846 7182 113598 306750 11950 373774 111326 272358 64310 43990 200278 381014 165310 254454 12394 382534 87894 6142 750 382478 15982 298326 70142 186478 152126 367166 1162 23426 341074 7306 76210 140770 163410 211106 207962 35282 165266 300178 120106 336110 30958 158 362758 382894 308754 88434 336918 244502 43502 54990 279910 175966 234054 196910 287284 288468 119040 275084 321268 17968 2332 86064 340044 244604 262436 111188 291868 367695 362739 370781 375723 360261 377565 383109 328689 347879 2415 319421 55707 352897 313831 302079 19051 346775 361293 328481 35445 113997 108547 309243 19439 199037 216463 62273 174471 207197 167695 296927
```
Found using a greedy algorithm which, at each stage, chooses the valid pixel whose set of distances to the chosen pixels overlaps the least with that of other pixels.
Specifically, the scoring is
```
score(P) = sum(number of pixels with D in its distance set
for each D in P's distance set)
```
and the pixel with the lowest score is chosen.
The search is kicked off with the point `10` (i.e. `(0, 10)`). This part is adjustable, so beginning with different pixels may lead to better or worse results.
It's quite a slow algorithm, so I'm trying to add optimisations/heuristics, and maybe some backtracking. PyPy is recommended for speed.
Anyone trying to come up with an algorithm should test on `N = 10`, for which I've got 9 (but this took a *lot* of tweaking and trying different initial points):

## Code
```
from collections import Counter, defaultdict
import sys
import time
N = 619
start_time = time.time()
def norm(p1, p2):
return (p1//N - p2//N)**2 + (p1%N - p2%N)**2
selected = [10]
selected_dists = {norm(p1, p2) for p1 in selected for p2 in selected if p1 != p2}
pix2dist = {} # {candidate pixel: {distances to chosen}}
dist2pix = defaultdict(set)
for pixel in range(N*N):
if pixel in selected:
continue
dist_list = [norm(pixel, p) for p in selected]
dist_set = set(dist_list)
if len(dist_set) != len(dist_list) or dist_set & selected_dists:
continue
pix2dist[pixel] = dist_set
for dist in dist_set:
dist2pix[dist].add(pixel)
while pix2dist:
best_score = None
best_pixel = None
for pixel in sorted(pix2dist): # Sorting for determinism
score = sum(len(dist2pix[d]) for d in pix2dist[pixel])
if best_score is None or score < best_score:
best_score = score
best_pixel = pixel
added_dists = pix2dist[best_pixel]
selected_dists |= added_dists
del pix2dist[best_pixel]
selected.append(best_pixel)
for d in added_dists:
dist2pix[d].remove(best_pixel)
to_remove = set()
for pixel in pix2dist:
new_dist = norm(pixel, best_pixel)
if (new_dist in selected_dists or new_dist in pix2dist[pixel]
or added_dists & pix2dist[pixel]):
to_remove.add(pixel)
continue
pix2dist[pixel].add(new_dist)
dist2pix[new_dist].add(pixel)
for pixel in to_remove:
for d in pix2dist[pixel]:
dist2pix[d].remove(pixel)
del pix2dist[pixel]
print("Selected: {}, Remaining: {}, Chosen: ({}, {})".format(len(selected), len(pix2dist),
best_pixel//N, best_pixel%N))
sys.stdout.flush()
print(*selected)
print("Time taken:", time.time() - start_time)
```
[Answer]
# SWI-Prolog, score 131
Barely better than the initial answer, but I guess this will get things started a bit more. The algorithm is the same as the Python answer except for the fact that it tries pixels in an alternate way, starting with the top left pixel (pixel 0), then the bottom right pixel (pixel 383160), then pixel 1, then pixel 383159, etc.
```
a(Z) :-
N = 619,
build_list(N,Z).
build_list(N,R) :-
M is N*N,
get_list([M,-1],[],L),
reverse(L,O),
build_list(N,O,[],[],R).
get_list([A,B|C],R,Z) :-
X is A - 1,
Y is B + 1,
(X =< Y,
Z = R
;
get_list([X,Y,A,B|C],[X,Y|R],Z)).
build_list(_,[],R,_,R) :- !.
build_list(N,[A|T],R,W,Z) :-
separated_pixel(N,A,R,W,S),
is_set(S),
flatten([W|S],V),!,
build_list(N,T,[A|R],V,Z)
;build_list(N,T,R,W,Z).
separated_pixel(N,A,L,W,R) :-
separated_pixel(N,A,L,[],W,R).
separated_pixel(N,A,[A|T],R,W,S) :-
separated_pixel(N,A,T,R,W,S).
separated_pixel(N,A,[B|T],R,W,S) :-
X is (A mod N - B mod N)*(A mod N - B mod N),
Y is (A//N - B//N)*(A//N - B//N),
Z is X + Y,
\+member(Z,W),
separated_pixel(N,A,T,[Z|R],W,S).
separated_pixel(_,_,[],R,_,R).
```
### Input:
`a(A).`
### Output:
```
Z = [202089, 180052, 170398, 166825, 235399, 138306, 126354, 261759, 119490, 117393, 281623, 95521, 290446, 299681, 304310, 78491, 314776, 63618, 321423, 60433, 323679, 52092, 331836, 335753, 46989, 40402, 343753, 345805, 36352, 350309, 32701, 32470, 352329, 30256, 28089, 357859, 23290, 360097, 22534, 362132, 20985, 364217, 365098, 17311, 365995, 15965, 15156, 368487, 370980, 371251, 11713, 372078, 372337, 10316, 373699, 8893, 374417, 8313, 7849, 7586, 7289, 6922, 376588, 6121, 5831, 377399, 377639, 4941, 378494, 4490, 379179, 3848, 379453, 3521, 3420, 379963, 380033, 3017, 380409, 2579, 380636, 2450, 2221, 2006, 381235, 1875, 381369, 381442, 381682, 1422, 381784, 1268, 381918, 1087, 382144, 382260, 833, 382399, 697, 382520, 622, 382584, 382647, 382772, 384, 382806, 319, 286, 382915, 382939, 190, 172, 383005, 128, 383050, 93, 383076, 68, 383099, 52, 40, 383131, 21, 383145, 10, 383153, 4, 383158, 1, 383160, 0]
```
### Image from Stack Snippet

[Answer]
# Haskell—~~115~~ ~~130~~ ~~131~~ ~~135~~ 136
My inspiration was the Sieve of Eratosthenes and in particular [The Genuine Sieve of Eratosthenes](http://www.cs.hmc.edu/~oneill/papers/Sieve-JFP.pdf), a paper by Melissa E. O'Neill of Harvey Mudd College. My original version (which considered points in index order) sieved points *extremely* quickly, for some reason I can't recall I decided to shuffle the points before “sieving” them in this version (I think solely to make generating different answers easier by using a new seed in the random generator). Because the points are no longer in any sort of order there's not really any sieving going on anymore, and as a result it takes a couple minutes just to produce this single 115 point answer. A knockout `Vector` would probably be a better choice now.
So with this version as a checkpoint I see two branches, returning to the “Genuine Sieve” algorithm and leveraging the List monad for choice, or swapping out the `Set` operations for equivalents on `Vector`.
**Edit:** So for working version two I veered back toward the sieve algorithm, improved the generation of “multiples” (knocking indices out by finding points at integer coordinates on circles with radius equal to the distance between any two points, akin to generating prime multiples) and making a few constant time improvements by avoiding some needless recalculation.
For some reason I can't recompile with profiling turned on, but I believe that the major bottleneck now is backtracking. I think exploring a bit of parallelism and concurrency will produce linear speedups, but memory exhaustion will probably cap me at a 2x improvement.
**Edit:** Version 3 meandered a bit, I first experimented with a heuristic in taking the next 𝐧 indices (after sieving from earlier choices) and choosing the one that produced the next minimum knockout set. This ended up being far too slow, so I went back to a whole-searchspace brute force method. An idea to order the points by distance from some origin came to me, and led to an improvement by one single point (in the time my patience lasted). This version picks index 0 as the origin, it may be worth trying the center point of the plane.
**Edit:** I picked up 4 points by re-ordering the search space to prioritize the most distant points from the center. If you're testing my code, ~~135~~ 136 is actually the ~~second~~ third solution found. *Fast edit:* This version seems the most likely to keep being productive if left running. I suspect I may tie at 137, then run out of patience waiting for 138.
One thing I noticed (that may be of help to someone) is that if you set the point ordering from the center of the plane (i.e., remove `(d*d -)` from `originDistance`) the image formed looks a bit like a sparse prime spiral.
```
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE BangPatterns #-}
module Main where
import Data.Function (on)
import Data.List (tails, sortBy)
import Data.Maybe (fromJust)
import Data.Ratio
import Data.Set (fromList, toList, union, difference, member)
import System.IO
sideLength :: Int
sideLength = 619
data Point = Point { x :: !Int, y :: !Int } deriving (Ord, Eq)
data Delta = Delta { da :: !Int, db :: !Int }
euclidean :: Delta -> Int
euclidean Delta{..} = da*da + db*db
instance Eq Delta where
(==) = (==) `on` euclidean
instance Ord Delta where
compare = compare `on` euclidean
delta :: Point -> Point -> Delta
delta a b = Delta (min dx dy) (max dx dy)
where
dx = abs (x a - x b)
dy = abs (y a - y b)
equidistant :: Dimension -> Point -> Point -> [Point]
equidistant d a b =
let
(dx, dy) = (x a - x b, y a - y b)
m = if dx == 0 then Nothing else Just (dy % dx) -- Slope
w = if dy == 0 then Nothing else Just $ maybe 0 (negate . recip) m -- Negative reciprocal
justW = fromJust w -- Moral bankruptcy
(px, py) = ((x a + x b) % 2, (y a + y b) % 2) -- Midpoint
b0 = py - (justW * px) -- Y-intercept
f q = justW * q + b0 -- Perpendicular bisector
in
maybe (if denominator px == 1 then map (Point (numerator px)) [0..d - 1] else [])
( map (\q -> Point q (numerator . f . fromIntegral $ q))
. filter ((== 1) . denominator . f . fromIntegral)
)
(w >> return [0..d - 1])
circle :: Dimension -> Point -> Delta -> [Point]
circle d p delta' =
let
square = (^(2 :: Int))
hypoteneuse = euclidean delta'
candidates = takeWhile ((<= hypoteneuse) . square) [0..d - 1]
candidatesSet = fromList $ map square [0..d - 1]
legs = filter ((`member` candidatesSet) . (hypoteneuse -) . square) candidates
pythagoreans = zipWith Delta legs
$ map (\l -> floor . sqrt . (fromIntegral :: Int -> Double) $ hypoteneuse - square l) legs
in
toList . fromList $ concatMap (knight p) pythagoreans
knight :: Point -> Delta -> [Point]
knight Point{..} Delta{..} =
[ Point (x + da) (y - db), Point (x + da) (y + db)
, Point (x + db) (y - da), Point (x + db) (y + da)
, Point (x - da) (y - db), Point (x - da) (y + db)
, Point (x - db) (y - da), Point (x - db) (y + da)
]
type Dimension = Int
type Index = Int
index :: Dimension -> Point -> Index
index d Point{..} = y * d + x
point :: Dimension -> Index -> Point
point d i = Point (i `rem` d) (i `div` d)
valid :: Dimension -> Point -> Bool
valid d Point{..} = 0 <= x && x < d
&& 0 <= y && y < d
isLT :: Ordering -> Bool
isLT LT = True
isLT _ = False
sieve :: Dimension -> [[Point]]
sieve d = [i0 : sieve' is0 [i0] [] | (i0:is0) <- tails . sortBy originDistance . map (point d) $ [0..d*d - 1]]
where
originDistance :: Point -> Point -> Ordering
originDistance = compare `on` ((d*d -) . euclidean . delta (point d (d*d `div` 2)))
sieve' :: [Point] -> [Point] -> [Delta] -> [Point]
sieve' [] _ _ = []
sieve' (i:is) ps ds = i : sieve' is' (i:ps) ds'
where
ds' = map (delta i) ps ++ ds
knockouts = fromList [k | d' <- ds
, k <- circle d i d'
, valid d k
, not . isLT $ k `originDistance` i
]
`union` fromList [k | q <- i : ps
, d' <- map (delta i) ps
, k <- circle d q d'
, valid d k
, not . isLT $ k `originDistance` i
]
`union` fromList [e | q <- ps
, e <- equidistant d i q
, valid d e
, not . isLT $ e `originDistance` i
]
is' = sortBy originDistance . toList $ fromList is `difference` knockouts
main :: IO ()
main = do let answers = strictlyIncreasingLength . map (map (index sideLength)) $ sieve sideLength
hSetBuffering stdout LineBuffering
mapM_ (putStrLn . unwords . map show) $ answers
where
strictlyIncreasingLength :: [[a]] -> [[a]]
strictlyIncreasingLength = go 0
where
go _ [] = []
go n (x:xs) = if n < length x then x : go (length x) xs else go n xs
```
## Output
```
1237 381923 382543 382541 1238 1857 380066 5 380687 378828 611 5571 382553 377587 375113 3705 8664 376356 602 1253 381942 370161 12376 15475 7413 383131 367691 380092 376373 362114 36 4921 368291 19180 382503 26617 3052 359029 353451 29716 382596 372674 352203 8091 25395 12959 382479 381987 35894 346031 1166 371346 336118 48276 2555 332400 46433 29675 380597 13066 382019 1138 339859 368230 29142 58174 315070 326847 56345 337940 2590 382663 320627 70553 19278 7309 82942 84804 64399 5707 461 286598 363864 292161 89126 371267 377122 270502 109556 263694 43864 382957 824 303886 248218 18417 347372 282290 144227 354820 382909 380301 382808 334361 375341 2197 260623 222212 196214 231526 177637 29884 251280 366739 39442 143568 132420 334718 160894 353132 78125 306866 140600 297272 54150 240054 98840 219257 189278 94968 226987 265881 180959 142006 218763 214475
```
[Answer]
# Python 3, score 129
This is an example answer to get things started.
Just a naive approach going through the pixels in order and choosing the first pixel that doesn't cause a duplicate separation distance, until the pixels run out.
### Code
```
width = 619
height = 619
area = width * height
currentAttempt = 0
temporaryLengths = []
lengths = []
points = []
pixels = []
for i in range(area):
pixels.append(0)
def generate_points():
global lengths
while True:
candidate = vacantPixel()
if isUnique(candidate):
lengths += temporaryLengths
pixels[candidate] = 1
points.append(candidate)
print(candidate)
if currentAttempt == area:
break
filename = 'uniquely-separated-points.txt'
with open(filename, 'w') as file:
file.write(' '.join(points))
def isUnique(n):
x = n % width
y = int(n / width)
temporaryLengths[:] = []
for i in range(len(points)):
point = points[i]
a = point % width
b = int(point / width)
d = distance(x, y, a, b)
if d in lengths or d in temporaryLengths:
return False
temporaryLengths.append(d)
return True
def distance(x1, y1, x2, y2):
xd = x2 - x1
yd = y2 - y1
return (xd*xd + yd*yd) ** 0.5
def vacantPixel():
global currentAttempt
while True:
n = currentAttempt
currentAttempt += 1
if pixels[n] == 0:
break
return n
generate_points()
```
### Output
```
0 1 3 7 12 20 30 44 65 80 96 122 147 181 203 251 289 360 400 474 564 592 627 660 747 890 1002 1155 1289 1417 1701 1789 1895 2101 2162 2560 2609 3085 3121 3331 3607 4009 4084 4242 4495 5374 5695 6424 6762 6808 7250 8026 8356 9001 9694 10098 11625 12881 13730 14778 15321 16091 16498 18507 19744 20163 20895 23179 25336 27397 31366 32512 33415 33949 39242 41075 46730 47394 48377 59911 61256 66285 69786 73684 79197 89530 95447 102317 107717 111751 116167 123198 126807 130541 149163 149885 154285 159655 163397 173667 173872 176305 189079 195987 206740 209329 214653 220911 230561 240814 249310 269071 274262 276855 285295 305962 306385 306515 312310 314505 324368 328071 348061 350671 351971 354092 361387 369933 376153
```
### Image from Stack Snippet

[Answer]
# Python 3, 130
For comparison, here's a recursive backtracker implementation:
```
N = 619
def norm(p1, p2):
return (p1//N - p2//N)**2 + (p1%N - p2%N)**2
def solve(selected, dists):
global best
if len(selected) > best:
print(len(selected), "|", *selected)
best = len(selected)
for pixel in (range(selected[-1]+1, N*N) if selected else range((N+1)//2+1)):
# By symmetry, place first pixel in first half of top row
added_dists = [norm(pixel, p) for p in selected]
added_set = set(added_dists)
if len(added_set) != len(added_dists) or added_set & dists:
continue
selected.append(pixel)
dists |= added_set
solve(selected, dists)
selected.pop()
dists -= added_set
print("N =", N)
best = 0
selected = []
dists = set()
solve(selected, dists)
```
It finds the following 130 pixel solution quickly before it starts choking:
```
0 1 3 7 12 20 30 44 65 80 96 122 147 181 203 251 289 360 400 474 564 592 627 660 747 890 1002 1155 1289 1417 1701 1789 1895 2101 2162 2560 2609 3085 3121 3331 3607 4009 4084 4242 4495 5374 5695 6424 6762 6808 7250 8026 8356 9001 9694 10098 11625 12881 13730 14778 15321 16091 16498 18507 19744 20163 20895 23179 25336 27397 31366 32512 33415 33949 39242 41075 46730 47394 48377 59911 61256 66285 69786 73684 79197 89530 95447 102317 107717 111751 116167 123198 126807 130541 149163 149885 154285 159655 163397 173667 173872 176305 189079 195987 206740 209329 214653 220911 230561 240814 249310 269071 274262 276855 285295 305962 306385 306515 312310 314505 324368 328071 348061 350671 351971 354092 361387 371800 376153 378169
```
More importantly, I'm using it to check solutions for small cases. For `N <= 8`, the optimal are:
```
1: 1 (0)
2: 2 (0 1)
3: 3 (0 1 5)
4: 4 (0 1 6 12)
5: 5 (0 1 4 11 23)
6: 6 (0 1 9 23 32 35)
7: 7 (0 2 9 20 21 40 48)
8: 7 (0 1 3 12 22 56 61)
9: 8 (0 1 3 8 15 37 62 77)
10: 9 (0 1 7 12 30 53 69 80 89)
```
Listed in brackets are the first lexicographical optimals.
Unconfirmed:
```
11: 10 (0 2 3 7 21 59 66 95 107 120)
12: 10 (0 1 3 7 33 44 78 121 130 140)
```
[Answer]
# Scala, 132
Scans left-to-right and top-to-bottom like the naive solution, but tries starting at different pixel locations.
```
import math.pow
import math.sqrt
val height, width = 619
val area = height * width
case class Point(x: Int, y: Int)
def generate(n: Int): Set[Point] = {
def distance(p: Point, q: Point) = {
def square(x: Int) = x * x
sqrt(square(q.x - p.x) + square(q.y - p.y))
}
def hasDuplicates(s: Seq[_]) = s.toSet.size != s.size
def rotate(s: Vector[Point]): Vector[Point] = s.drop(n) ++ s.take(n)
val remaining: Vector[Point] =
rotate((for (y <- 0 until height; x <- 0 until width) yield { Point(x, y) }).toVector)
var unique = Set.empty[Point]
var distances = Set.empty[Double]
for (candidate <- remaining) {
if (!unique.exists(p => distances.contains(distance(candidate, p)))) {
val candidateDistances = unique.toSeq.map(p => distance(candidate, p))
if (!hasDuplicates(candidateDistances)) {
unique = unique + candidate
distances = distances ++ candidateDistances
}
}
}
unique
}
def print(s: Set[Point]) = {
def toRowMajor(p: Point) = p.y*height + p.x
println(bestPixels.map(toRowMajor).toSeq.sorted.mkString(" "))
}
var bestPixels = Set.empty[Point]
for (n <- 0 until area) {
val pixels = generate(n)
if (pixels.size > bestPixels.size) bestPixels = pixels
}
print(bestPixels)
```
# Output
```
302 303 305 309 314 322 332 346 367 382 398 424 449 483 505 553 591 619 647 680 719 813 862 945 1014 1247 1459 1700 1740 1811 1861 1979 2301 2511 2681 2913 3114 3262 3368 4253 4483 4608 4753 5202 5522 5760 6246 6474 6579 6795 7498 8062 8573 8664 9903 10023 10567 10790 11136 12000 14153 15908 17314 17507 19331 20563 20941 22339 25131 26454 28475 31656 38328 39226 40214 50838 53240 56316 60690 61745 62374 68522 71208 78598 80204 86005 89218 93388 101623 112924 115702 118324 123874 132852 136186 139775 144948 154274 159730 182200 193642 203150 203616 213145 214149 218519 219744 226729 240795 243327 261196 262036 271094 278680 282306 289651 303297 311298 315371 318124 321962 330614 336472 343091 346698 354881 359476 361983 366972 369552 380486 382491
```
[Answer]
# Python, 134 132
Here's a simple one that randomly culls some of the search space to cover a greater area. It iterates the points in distance from an origin order. It skips points that are same distance from origin, and early-outs if it cannot improve on the best. It runs indefinitely.
```
from random import *
from bisect import *
W = H = 619
pts = []
deepest = 0
lengths = set()
def place(x, y):
global lengths
pos = (x, y)
for px, py in pts:
dist = (x-px)*(x-px) + (y-py)*(y-py)
if dist in lengths:
return False
dists = set((x-px)*(x-px) + (y-py)*(y-py) for px, py in pts)
if len(dists) != len(pts):
return False
lengths |= dists
pts.append(pos)
return True
def unplace():
x, y = pos = pts.pop()
for px, py in pts:
dist = (x-px)*(x-px) + (y-py)*(y-py)
lengths.remove(dist)
def walk(i):
global deepest, backtrack
depth = len(pts)
while i < W*H:
d, x, y, rem = order[i]
if rem+depth <= deepest: # early out if remaining unique distances mean we can't improve
return
i += 1
if place(x, y):
j = i
while j < W*H and order[j][0] == d: # skip those the same distance from origin
j += 1
walk(j)
unplace()
if backtrack <= depth:
break
if not randint(0, 5): # time to give up and explore elsewhere?
backtrack = randint(0, len(pts))
break
backtrack = W*H # remove restriction
if depth >= deepest:
deepest = depth
print (ox, oy), depth, "=", " ".join(str(y*W+x) for x, y in pts)
try:
primes = (0,1,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)
while True:
backtrack = W*H
ox, oy = choice(primes), choice(primes) # random origin coordinates
order = sorted((float((ox-x)**2+(oy-y)**2)+random(), x, y) for x in xrange(W) for y in xrange(H))
rem = sorted(set(int(o[0]) for o in order)) # ordered list of unique distances
rem = {r: len(rem)-bisect_right(rem, r) for r in rem} # for each unique distance, how many remain?
order = tuple((int(d), x, y, rem[int(d)]) for i, (d, x, y) in enumerate(order))
walk(0)
except KeyboardInterrupt:
print
```
It quickly finds solutions with 134 points:
3097 3098 2477 4333 3101 5576 1247 9 8666 8058 12381 1257 6209 15488 6837 21674 19212 26000 24783 1281 29728 33436 6863 37767 26665 14297 4402 43363 50144 52624 18651 9996 58840 42792 6295 69950 48985 34153 10644 72481 83576 63850 29233 94735 74997 60173 43477 101533 102175 24935 113313 88637 122569 11956 36098 79401 61471 135610 31796 4570 150418 57797 4581 125201 151128 115936 165898 127697 162290 33091 20098 189414 187620 186440 91290 206766 35619 69033 351 186511 129058 228458 69065 226046 210035 235925 164324 18967 254416 130970 17753 248978 57376 276798 456 283541 293423 257747 204626 298427 249115 21544 95185 231226 54354 104483 280665 518 147181 318363 1793 248609 82260 52568 365227 361603 346849 331462 69310 90988 341446 229599 277828 382837 339014 323612 365040 269883 307597 374347 316282 354625 339821 372016
For the curious, here are some brute-forced small N:
```
3 = 0 2 3
4 = 0 2 4 7
5 = 0 2 5 17 23
6 = 0 12 21 28 29 30
7 = 4 6 11 14 27 36 42
8 = 0 2 8 11 42 55 56
9 = 0 2 9 12 26 50 63 71
10 = 0 2 7 10 35 75 86 89 93
11 = 0 23 31 65 66 75 77 95 114 117
```
[Answer]
## Fantom 96
I used an evolution algorithm, basically add k random points at a time, do that for j different random sets, then pick the best one and repeat. Pretty terrible answer right now, but that's running it with only 2 children per generation for the sake of speed, which is nearly just random. Gonna play with the parameters a bit to see how it goes, and I probably need a better scoring function than number of free spots left.
```
class Pixel
{
static const Int n := 619
static const Int stepSize := 20
static const Int generationSize := 5
static const |Int, Int -> Int| d := |Int x, Int y -> Int| {
d1 := x%n - y%n
d2 := x/n - y/n
return d1.pow(2) + d2.pow(2)
}
public static Void main(){
//Initialize
[Int: Int[][]] disMap := [:]
Int[] freeSpots := (0..<n*n).toList
Int[] pixels := [,]
Int[] distances := [,]
genNum := 0
children := [,]
while(freeSpots.size > 0){
echo("Generation: ${genNum++} \t Spots Left: ${freeSpots.size} \t Pixels added: $pixels.size \t Distances used: $distances.size uniqueDistances: $distances.unique.size" )
echo(distances)
echo("Pixels: " + pixels.join(" "))
//echo("Distances: $distances")
//Generate children
children = [,]
generationSize.times{
//echo("\tStarting child $it")
i := Int.random(0..<freeSpots.size)
childFreeSpots := freeSpots.dup
childPixels := pixels.dup
childDistances := distances.dup
for(Int step := 0; step < stepSize; step++){
if( i < childFreeSpots.size){
//Choose a pixel
pixel := childFreeSpots.removeAt(i)
//echo("\t\tAdding pixel $pixel")
//Remove neighbors that are the new distances away
///Find distances
newDis := [,]
childPixels.each {
newDis.add(d(pixel, it))
}
//Check that there are no equal distances
if(newDis.size != newDis.unique.size) continue
//Remove neighbors
childPixels.each | Int childPixel|{
newDis.each |Int dis|{
neighbors := getNeighbors(childPixel, dis, disMap)
neighbors.each| Int n |{
index := childFreeSpots.binarySearch(n)
if(index >= 0) childFreeSpots.removeAt(index)
}
}
}
//echo("Removed neighbors: $test")
//Remove all the neighbors of new pixel
childDistances.addAll(newDis)
childDistances.each|Int dis| {
neighbors := getNeighbors(pixel, dis, disMap)
childFreeSpots.removeAll(neighbors)
}
//Add new pixel
childPixels.add(pixel)
}
}
children.add([childPixels.dup, childDistances.dup, childFreeSpots.dup])
echo("\tChild $it: pixels: $childPixels.size \t distances: $childDistances.size \t freeSpots: $childFreeSpots.size")
}
//Score children and keep best one as new parent
Obj?[][] parent := children.max |Int[][] a, Int[][] b -> Int| { return (a.last.size + a.first.size*10000) <=> (b.last.size + b.first.size*10000) }
pixels = parent.first
distances = parent[1]
freeSpots = parent.last
}//End while
//Return result
echo("Size: " + pixels.size)
echo(pixels.join(" "))
}
private static Bool checkValid(Int[] pixels){
distances := [,]
pixels[0..-2].each|Int p, Int i|{
for(Int j := i + 1; j < pixels.size; j++){
distances.add(d(p, pixels[j]))
}
}
if(distances.size > distances.unique.size){
echo("Duplicate distance found!!!!")
echo("Pixel $pixels.last is not valid")
return false
}
return true
}
public static Int[] getNeighbors(Int spot, Int distance, [Int : Int[][]] disMap ){
result := [,]
//Check hash map
pairs := disMap.get(distance, null)
//Find possible int pairs if not already in the map
if(pairs == null){
for(Int i := 0; i*i <= distance; i++ ){
for(Int j := i; j*j + i*i <= distance; j++){
if(i.pow(2) + j.pow(2) == distance){
pairs.add([i, j])
}
}
}
disMap.add(distance, pairs)
}
pairs.each|Int[] pair|{
//Find neighbors with pair
x := pair.first
y := pair.last
2.times{
//Positive x
result.add(spot + x + y*n)
result.add(spot + x - y*n)
//negative x
result.add(spot - x + y*n)
result.add(spot - x - y*n)
//Swap x and y and repeat
temp := x
x = y
y = temp
}
}
return result.findAll |Int i -> Bool| { i >= 0 }.unique
}
}
```
Output
```
17595 17596 17601 17627 17670 17726 17778 17861 17956 18117 18324 18733 19145 19597 20244 21139 21857 22742 24078 25343 28577 30152 32027 34406 37008 39864 42313 44820 48049 52193 55496 59707 64551 69976 74152 79758 84392 91782 98996 104625 150212 158877 169579 178660 189201 201343 213643 225998 238177 251012 263553 276797 290790 304915 319247 332702 347266 359665 373683 125899 144678 170677 195503 220092 244336 269861 289473 308633 326736 343756 358781 374280 131880 172485 212011 245015 277131 302055 321747 347911 363717 379166 249798 284200 313870 331913 360712 378024 9704 141872 249686 293656 357038 357596 370392 381963
```
[Answer]
# Python 3, 119
I no longer remember why I named this function `mc_usp`, though I suspect it had something to do with Markov chains. Here I publish my code that I ran with PyPy for about 7 hours. The program tries to build up 100 different sets of pixels by randomly picking pixels until it has checked every pixel in the image, and returning one of the best sets.
On another note, at some point, we should really attempt to find an upper bound for `N=619` that's better than 488, because judging from the answers on here, that number is way too high. [Rowan Blush's comment](https://codegolf.stackexchange.com/questions/52496/uniquely-separated-pixels/101272#comment126554_52988) about how every new point `n+1` can potentially remove `6*n` points with optimal choice seemed like a good idea. Unfortunately, upon inspection of the formula `a(1) = 1; a(n+1) = a(n) + 6*n + 1`, where `a(n)` is the number of points removed after adding `n` points to our set, this idea may not be the best fit. Checking when `a(n)` is greater than `N**2`, `a(200)` being larger than `619**2` seems promising, but the `a(n)` larger than `10**2` is `a(7)` and we've proved that 9 is the actual upper bound for `N=10`. I'll keep you posted as I try to look a better upper bound, but any suggestions are welcome.
Onto my answer. First, my set of 119 pixels.
```
15092 27213 294010 340676 353925 187345 127347 21039 28187 4607 23476 324112 375223 174798 246025 185935 186668 138651 273347 318338 175447 316166 158342 97442 361309 251283 29986 98029 339602 292202 304041 353401 236737 324696 42096 102574 357602 66845 40159 57866 3291 24583 254208 357748 304592 86863 19270 228963 87315 355845 55101 282039 83682 55643 292167 268632 118162 48494 378303 128634 117583 841 178939 20941 161231 247142 110205 211040 90946 170124 362592 327093 336321 291050 29880 279825 212675 138043 344012 187576 168354 28193 331713 329875 321927 129452 163450 1949 186448 50734 14422 3761 322400 318075 77824 36391 31016 33491 360713 352240 45316 79905 376004 310778 382640 383077 359178 14245 275451 362125 268047 23437 239772 299047 294065 46335 112345 382617 79986
```
Second, my code, which randomly picks a starting point from an octant of the 619x619 square (since the starting point is otherwise equal under rotation and reflection) and then every other point from the rest of the square.
```
import random
import time
start_time = time.time()
print(start_time)
def mc_usp_v3(N, z, k=100, m=1.0):
"""
At m=1.0, it keeps randomly picking points until we've checked every point. Oh dear.
"""
ceil = -(-N//2)
a=random.randint(0,ceil)
b=random.randint(a,ceil)
r=[a*N+b]
best_overall = r[:]
all_best = []
best_in_shuffle = r[:]
num_shuffles = 0
num_missteps = 0
len_best = 1
while num_shuffles < k and len(best_overall) < z:
dist = []
missteps = []
points_left = list(range(N*N))
points_left.remove(r[0])
while len_best + num_missteps < m*N*N and len(points_left):
index = random.randint(0, len(points_left)-1)
point = points_left[index]
points_left.pop(index)
dist, better = euclid(r, point, dist, N)
if better and len(r) + 1 > len_best:
r.append(point)
best_in_shuffle = r[:]
len_best += 1
else:
missteps.append(point)
num_missteps += 1
else:
print(num_shuffles, len(best_overall), len_best, num_missteps, time.time() - start_time)
num_shuffles += 1
num_missteps = 0
missteps = []
if len(best_in_shuffle) == len(best_overall):
all_best.append(best_in_shuffle)
print(best_in_shuffle)
if len(best_in_shuffle) > len(best_overall):
best_overall = best_in_shuffle[:]
all_best = [best_overall]
print(best_overall)
a=random.randint(0,ceil)
b=random.randint(a,ceil)
r=[a*N+b]
best_in_shuffle = r[:]
len_best = 1
return len(best_overall), all_best
def euclid(point_set, new_point, dist, N):
new_dist = []
unique = True
a,b=divmod(new_point, N)
for point in point_set:
c,d=divmod(point, N)
current_dist = (a-c)**2+(b-d)**2
if current_dist in dist or current_dist in new_dist:
unique = False
break
new_dist.append(current_dist)
if unique:
dist += new_dist
return dist, unique
def mcusp_format(mcusp_results):
length, all_best = mcusp_results
return " ".join(str(i) for i in all_best[0])
print(mcusp_format(mc_usp_v3(10, 20, 100, 1.0)))
print(mcusp_format(mc_usp_v3(619, 488, 100, 1.0)))
print(time.time()-start_time)
```
] |
[Question]
[
I like pizza!
# Task
Given the radius of a pizza and a list of ingredients, create the corresponding ascii pizza!
Example size 4 pizza with mozzarella cheese, olives and ham:
```
#####
#@@@@M#
#H@O@@@@#
#M@@@H@@#
#@OO@@@@#
#@@H@@@@#
#M@M@@@@#
#O@@@H#
#####
```
# Input
A positive integer `r` for the size of the pizza and a (possibly empty) list of ingredients (non-empty strings). The list of ingredients can be given in a series of convenient formats, including but not limited to:
* a list of ingredients, such as `["tomato", "ham", "cheese"]`;
* a list of the initials, such as `["t", "h", "c"]`;
* a list of left- or right-padded ingredients, such as `["tomato", "ham ", "cheese"]` or `["tomato", " ham", "cheese"]`;
* a string with the initials, such as `"thc"`.
# Output specs
The pizza is built on a square of size `2r+1` characters, with the centre character having coordinates `(0,0)` for the purposes of this explanation. All characters in the square have integer coordinates. Then,
* a position is crust `#` if its coordinates `x,y` satisfy \$r+1 > \sqrt{x^2 + y^2} \geq r\$;
* a position is dough `@` if its coordinates `x,y` satisfy \$ r > \sqrt{x^2+y^2}\$.
Then, the ingredients must be put randomly on the pizza. Each ingredient will be represented by its initial and you must place `r` of each ingredient randomly in the dough characters. You can assume there will be enough space in the pizza. Ingredients cannot be placed on top of eachother, so in the final pizza there must be exactly `rl` non-dough symbols, in groups of `r`, if the ingredients list has size `l`.
For the randomness in the distributions of ingredients on top of the pizza, it suffices that for a fixed `r` and ingredient list, all ingredient distributions obeying the specs have non-zero probability of occurring.
# Examples
`r = 1`, no ingredients
```
###
#@#
###
```
---
`r = 2`, no ingredients
```
#####
#@@@#
#@@@#
#@@@#
#####
```
---
`r = 5`, no ingredients
```
#######
##@@@@@##
##@@@@@@@##
#@@@@@@@@@#
#@@@@@@@@@#
#@@@@@@@@@#
#@@@@@@@@@#
#@@@@@@@@@#
##@@@@@@@##
##@@@@@##
#######
```
---
`r = 4`, `ingredients = ["bacon", "mozzarela", "tomato"]`
```
#####
#@@b@m#
#@@@@@b@#
#@@@btb@#
#@@@@@@t#
#@@@@@@@#
#@mt@@@@#
#t@mm@#
#####
```
[Reference implementation](https://tio.run/##hVLBUoMwEL3nK3biBQp0WvXkSMf/QMbBEiAMJHEJB/vzdZOArdUZL23Y997uy8uaT9tp9XA@N6hHwErV9CdHo9HC1M1NMwjmobGy3Qo0g9aYTh9oGTviPFnIgd9xVuu57dz5hTNWiwaMPJ2qCFOQqp3iJwZgCC5KOhz1rJxuR@dGI0jiuPmtiDJMMdl7OsAglVg1gdn/YO4TXJgA6Lo7W5HcbO6Tnn7iBZINUM@DoxxywFUR@m8rY4SqI3@XVSEGpzHwfM0OrpMc9n828AFcGkzi7zkceCCZteLQmFHN6rd58hemyIpdeZsNxqGiWldzsbpgyOkgVBTEMVn2PsPwpSN5Lry9chOFW2TXGj98efC1xv55mt@PccG8J1PIsuhLyHPwoy9pfCOLvSLznsqboLMQ9Lo3nG97LVVIy4/320EOjFOisDMq4K9q4Zn4bPKwg49pwd@ro1Y8BT5qKqEYKvdhNa225mXMDEplnegL)
Please include one or two of your favourite pizzas in your answer :)
---
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!
[Answer]
# [APL (Dyalog Extended)](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfn/vzrTQUPjUeeizEdtEx717tJ/1LtV0x7If9S7w9A2T9OhGkjWqjsoK6hH5wGVaBgAFekAsbahJlBJzaOOGXqPevY96l0BFHvUsEwXSMXW/k8Dm9b3qG@qp/@jruZD640ftU0E8oKDnIFkiIdn8H9DhTSFR71ruIygtAmIBipdoe6bX1WVWJSak5OorqDun5NZlloMZHgk5qpzmWIoTkpMzs8DSudCNYH0lOTnJpbkq3OZw1XllhZnFOXn54IMSspJTM5WyIeZW5SaolCQWlCQWgTiFWTmpSYWFOSkIoxRUM/PywTaAQA "APL (Dyalog Extended) – Try It Online"), ~~55~~ 53 [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")
−2 thanks to rabbitgrowth.
Anonymous infix lambda. Takes `r` as left argument (`⍺`) and ingredient initials as right argument (`⍵`).
```
{i@((≢i←⍺/⍵)?≢⍸1=n)@{1=n}'@# '[n←(0⍺,⍺+1)⍸|∘.⌾⍨⍺…-⍺]}
```
[Try it online!][TIO-k6q7nk2n]
`{`…`}` "dfn"; left argument `⍺` (leftmost Greek letter), right argument `⍵` (rightmost Greek letter)
`'@# '[`…`]` index the string with:
`-⍺` negate `r`
`⍺…` generate integer range from `r` to `-r`
`∘.⌾⍨` generate table of complex coordinates
`|` magnitudes
`(`…`)⍸` find the **ɩ**ndices of the [a,b) **ɩ**ntervals in which the magnitudes fall:
`⍺+1` increment `r`
`0⍺,` prepend `[0,r]`
`n←` store in `n` (1: dough; 2: crust; 3: outside pizza)
`i@(`…`)@{1=n}` place the characters of `i` (to be defined) **at** the following subset of positions **at** which `n` is 1 (i.e. we have dough):
`1=n` mask where `n` is 1
`⍸` **ɩ**ndices of trues
`≢` count them
`(`…`)?` pick the following number of random indices from 1 to that:
`⍺/⍵` replicate each ingredient initial letter to `r` copies
`i←` store in `i`
`≢` tally that
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~44~~ ~~43~~ ~~40~~ 34 bytes
```
Q_Zvqt!YytGQ<Zc64bG<(i1GY"7MfynZr(
```
Inputs are: `r` and a string with the initials of ingredients.
Try it online with [ham, onion, pepper and mushroom](https://tio.run/##y00syfn/PzA@qqywRDGyssQ90CYq2cwkyd1GI9PQPVLJ3DetMi@qSOP/f1MudQ//AF91AA)! Or maybe try a [diet pizza](https://tio.run/##y00syfn/PzA@qqywRDGyssQ90CYq2cwkyd1GI9PQPVLJ3DetMi@qSOP/f1MudQUoUAcA).
### Explanation with example
Consider inputs `3` and `'AP'`.
```
Q % Implicit input: r. Add 1
% STACK: 4
_Zv % Symmetric inverse range
% STACK: [4 3 2 1 2 3 4]
q % Subtract 1, element-wise
% STACK: [3 2 1 0 1 2 3]
t! % Duplicate, transpose
% STACK: [3 2 1 0 1 2 3], [3; 2; 1; 0; 1; 2; 3]
Yy % Hypotenuse, element-wise with broadcast
% STACK: [4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426;
3.6056 2.8284 2.2361 2.0000 2.2361 2.8284 3.6056;
3.1623 2.2361 1.4142 1.0000 1.4142 2.2361 3.1623;
3.0000 2.0000 1.0000 0 1.0000 2.0000 3.0000;
3.1623 2.2361 1.4142 1.0000 1.4142 2.2361 3.1623;
3.6056 2.8284 2.2361 2.0000 2.2361 2.8284 3.6056;
4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426]
t % Duplicate.
% STACK: [4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426;
3.6056 2.8284 2.2361 2.0000 2.2361 2.8284 3.6065;
···
4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426],
[4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426;
3.6056 2.8284 2.2361 2.0000 2.2361 2.8284 3.6065;
···
4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426]
GQ< % Less than r plus 1? Element-wise
% STACK: [4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426;
3.6056 2.8284 2.2361 2.0000 2.2361 2.8284 3.6065;
···
4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426],
[0 1 1 1 1 1 0;
1 1 1 1 1 1 1;
1 1 1 1 1 1 1;
1 1 1 1 1 1 1;
1 1 1 1 1 1 1;
1 1 1 1 1 1 1;
0 1 1 1 1 1 0]
Zc % Replace 0 by space and 1 by '#'
% STACK: [4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426;
3.6056 2.8284 2.2361 2.0000 2.2361 2.8284 3.6065;
···
4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426],
[' ##### ';
'#######';
'#######';
'#######';
'#######';
'#######';
' ##### ' ]
64 % Push 64 (ASCII for '@')
% STACK: [4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426;
3.6056 2.8284 2.2361 2.0000 2.2361 2.8284 3.6065;
···
4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426],
[' ##### ';
'#######';
'#######';
'#######';
'#######';
'#######';
' ##### ' ],
64
b % Bubble up
% STACK: [' ##### ';
'#######';
'#######';
'#######';
'#######';
'#######';
' ##### ' ],
64,
[4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426;
3.6056 2.8284 2.2361 2.0000 2.2361 2.8284 3.6065;
···
4.2426 3.6056 3.1623 3.0000 3.1623 3.6056 4.2426]
G< % Less than r? Element-wise
% STACK: [' ##### ';
'#######';
'#######';
'#######';
'#######';
'#######';
' ##### ' ],
64,
[0 0 0 0 0 0 0;
0 1 1 1 1 1 0;
0 1 1 1 1 1 0;
0 1 1 1 1 1 0;
0 1 1 1 1 1 0;
0 1 1 1 1 1 0;
0 0 0 0 0 0 0]
( % Write value 64 (that is, '@') into char matrix at positions indexed by mask
% STACK: [' ##### ';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
' ##### ']
i % Input: string
% STACK: [' ##### ';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
' ##### '],
'AP'
1GY" % Push first input (r) again. Repeat each letter that many times
% STACK: [' ##### ';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
' ##### '],
'AAAPPP'
7Mf % Push 0-1 mask again. Linear index (column-major order) of non-zero entries
% STACK: [' ##### ';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
' ##### '],
'AP',
[9; 10; 11; ...; 41]
yn % Duplicate from below. Number of elements
% STACK: [' ##### ';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
' ##### '],
'AAAPPP',
[9; 10; 11; ...; 41]
6
Zr % Random sample without replacement (example result shown)
% STACK: [' ##### ';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
'#@@@@@#';
' ##### '],
'AAAPPP',
[13; 18; 11; 24; 30; 25]
( % Write 'AAAPPP' into char matrix at positions given by the linear indices
% STACK: [' ##### '
'#@@@P@#';
'#@@P@@#';
'#AAP@@#';
'#@@@@@#';
'#A@@@@#';
' ##### ']
% Implicit display
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~42~~ ~~41~~ ~~40~~ ~~38~~ 34 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
ÝRûãnOtï¹.S…# 1sèƶDþ.rI¹и'@Þ«‡¹·>ô
```
Output as a character-matrix.
-2 bytes because the specs changed (character-list input instead of ingredients-list).
-4 bytes thanks to *@Grimmy*.
[Try it online](https://tio.run/##yy9OTMpM/f//8Nygw7sPL87zLzm8/tBOveBHDcuUFQyLD684ts3l8D69Is9DOy/sUHc4PO/Q6kcNCw/tPLTd7vCW/16Hdv834YpWylXSUVBKBhHFIKIARJRAxGIB) or [verify all test cases](https://tio.run/##yy9OTMpM/W/qpuSZV1BaUmylUGSrZO/pEmqvpJCYl6KQmZdelJqSmZpXUgwWD9PhUvIvLQEqtVJQ0on4f3hu0OHdhxfn@ZccXh@hF/yoYZmygmHx4RXHtrkc3qdXFBlxYYe6w@F5h1Y/algYcWi73eEt/70O7dY5tM3@vyFXdCyXEYgwBREmXNFKSUo6Ckq5IKJECSIC5iSDiGIQUQCRA4vFAgA). (The footer `J»` is to pretty-print the result. Feel free to remove it to see the actual character-matrix result.)
**Explanation:**
```
Ý # Push a list in the range [0, (implicit) input-integer]
R # Reverse it to range [input, 0]
û # Palindromize this list (i.e. [3,2,1,0] → [3,2,1,0,1,2,3])
ã # Take the cartesian product with itself, to get a list of all coordinates
n # Square both the x and y of each coordinate
O # Take the sum of each
t # And then the square-root of that
ï # Truncate it to an integer
¹.S # And compare each to the first input
# (-1 if larger than the input; 0 if equals; -1 if smaller)
…# 1 # Push string "# 1"
sè # And index the list into this string, where the -1 is the trailing character
ƶ # Multiply the 1s by their 1-based index
Dþ # Duplicate the list, and only leave the integers (the indices)
.r # And randomly shuffle those
I # Push the second input-list of ingredient-characters
¹и # Repeat this list the first input amount of times
'@Þ '# Push an infinite list of "@"
« # Append it to the repeated ingredient-characters
‡ # Transliterate the shuffled indices to this list
¹·< # Push the first input again; double it; and decrease it by 1
# (alternative: `Dgt` - Duplicate; length; square-root)
ô # Split the list into parts of that size
# (after which the resulting character-matrix is output implicitly)
```
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), ~~186~~ ~~177~~ 176 bytes
```
from random import*
def f(r,i=[],s=''):i=['@',*next(zip(*i),[])];t=range(-r,R:=r+1);print([s:=s+[' #'[(d:=x*x+y*y)<R*R],choice(i)][d<r*r]+'\n'*(x==r)for y in t for x in t][-1])
```
[Try it online!](https://tio.run/##JZBBT4QwEIXv@ysaPExbugfUjYbdJv4GvJjUHiq00GRpyVAN8Oex6OW9701m8pKZ1jTE8PQ64b47jCNBE7psfpwiJn7qrCOOovBSaTFLAFZnhDcQPNgl0c1PlHsmlGb6mmS@7i09o2hqiWXFrhP6kKiaazmXCsgDKNrVcuFLufKV3RreaNEO0beWeqZVd0OOuoTPAJwuUiJzEclKfCCJHLj8oVbnSrPd0YqdHH085HLIs1DFl2ljKAQpxrhtBu3dHCHF0aRY6GPrRSiYv3uDIOB9ytXZ7Y/F/AofehL@Jx@kHezoW3OHXPUL "Python 3.8 (pre-release) – Try It Online")
[Answer]
# JavaScript (ES7), ~~177 175~~ 172 bytes
Takes input as `(r)(list)`, where *list* is filled with initials. Returns an array of characters.
```
r=>a=>a.map(i=>(g=i=>(s[p=Math.random()*r**3|0]!='@'||(s[p]=i,--n))&&g(i))(i,n=R),s=[...(g=x=>y+r?` #@
`[x+r?((d=x*x--+y*y)<r*r)+(d<R*R):(--y,x=R,3)]+g(x):'')(y=R=r++)])&&s
```
[Try it online!](https://tio.run/##fY1Na4NAEIbv@RWphTizXzRNewkZmz/Qi1cRYqKxG6Iru1JW8L/bXXppL4HhYWCed95b9V25i9XDKHtTN8uVFktZFUZ11QCaMmgp0hUDfVbjl7JVX5sOkFnGdvNL@UTpMZ3nKJSkhZQ94mbTgkYELXrKUTgqlFLhkads4vbjtH4@rk6FDytATZ55KfnEJjxYZpFDfchZjnuQchKecrHDkrfgcZ@mCBPlZDnHMrS45WJ6Z@6NupsWrrBFKBKTlKhuRvcQdFz9N16j0SRinZwjXET3KPAWA@dfLWB85L4H9@95@QE "JavaScript (Node.js) – Try It Online")
### Commented
```
r => a => // r = radius, a[] = list of ingredients
a.map(i => // for each ingredient i in a[]:
( g = i => ( // g is a recursive function taking i
s[ // test s at
p = Math.random() // a random position p in [0 .. r**3 - 1]
* r**3 | 0 //
] != '@' || // abort if it doesn't contain '@'
(s[p] = i, --n) // otherwise, put the ingredient there and decrement n
) && g(i) // do a recursive call if the above result is truthy
)(i, n = R), // initial call to g with i and n = R
s = [... // build the base pizza s[]
( g = x => // g is another recursive function taking x
y + r ? // if y is not equal to -r:
` #@\n`[ // pick the relevant character:
x + r ? // if x is not equal to -r:
( //
(d = x * x-- // d = x² + y²; decrement x
+ y * y) //
< r * r // add 1 if it's less than r² (-> '#')
) + //
(d < R * R) // add 1 if it's less than R² (-> '@')
: // else:
(y--, x = R, 3) // decrement y, set x = R, append a linefeed
] + //
g(x) // recursive call
: // else:
'' // stop recursion
)(y = R = r++) // initial call to g with x = y = R = r; increment r
] //
) && s // end of map(); return s[]
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~51~~ 48 bytes
```
E⊕θ⭆E⊕θ₂⁺×ιι×λλ⎇›θλ@§ #›⊕θλ‖O↑←FηFθ§≔KA‽⌕AKA@§ι⁰
```
[Try it online!](https://tio.run/##bY9BS8QwEIXv/oohXiYQwYuX9WIvLguKpepp2UNIp9tgmqRJdtFfXycrBRFzmbz5MvNezKiTCdotS5usL/isI@68STSRL9TjLBW8FkbHSv6l80kn6kIo2LpTxjc7UUarwDL8EU6Bk3xYU/I6feE2kS6UcK5EgXgQCpqy8z19ooBrVuuLv3aXRVLeX3U0ODLl5UzJcazNe1SweaKhMBtCAhwlXOosocnZHv1q0BJ9NM4hb@u078OEj9b3tfOLcKQaeJ3h/9yy67Ls7xTsRQmTLoFjCjMSZaq3UU@1ROtJx@hIHA7Lzdl9Aw "Charcoal – Try It Online") Link is to verbose version of code. Now supports full topping names by using a less convenient input format, but could save 2 bytes by switching back to initials. Explanation:
```
E⊕θ⭆E⊕θ₂⁺×ιι×λλ⎇›θλ@§ #›⊕θλ
```
Draw the bottom right hand quarter of the pizza base.
```
‖O↑←
```
Reflect to complete the pizza base.
```
FηFθ
```
Loop through each topping repeatedly.
```
§≔KA‽⌕AKA@§ι⁰
```
Find a random dough character and overwrite it with the first letter of the topping.
[Answer]
# [Perl 5](https://www.perl.org/) `-al`, 153 bytes
```
@;=map{//;join"",map{($d=sqrt($_**2+$'**2))<$r?++$n&&1:$d>$r+1?$":"#"}@c}@c=-($r=<>)..$r;@F=((@F)x$r,("@")x($n-@F*$r));say s/1/splice@F,rand@F,1/gre for@
```
[Try it online!](https://tio.run/##FYdLDoIwFAD3nqKpL9jyK9WwAYpdsfMMhgAqBgu@ssAYr27FZDKTmTocUud0rh719BYiv4@9oTT8H4NW2SfODM6@vw9gt5rzAvAYBGA8T2bQloCBPALN6JZ@dLOiIgaoipLHMWCuK8WYrvgCGDKqKV8YmEhXPiDnua1fxAop7DT0TaerEGvTrpHiih25jKidm8mNNJvDd5zmfjTWRWaoXXRK40QmPw "Perl 5 – Try It Online")
Takes the initials of the ingredients (space separated) on the first line of input and the radius on the second.
] |
[Question]
[
Output the following excerpt from Pachelbel's Canon in D as audio:
[](https://i.stack.imgur.com/icQVs.png)
## Rules
* Any format/encoding may be used, so long as a codec existed prior to the creation of this challenge
* Any instrument (a real instrument, MIDI synthesis, etc.) may be used
* The tempo must be 65 BPM (as notated in the sheet music) - if you cannot get exactly 65 BPM, you may use any tempo within the (inclusive) range 64.75 - 65.25
* The sheet music is in concert pitch
* [Equal temperament tuning](https://en.wikipedia.org/wiki/Equal_temperament) must be used (specifically 12-ET with A4 = 440 Hz)
For reference, here is a Stack Snippet that will play the excerpt:
```
<audio controls><source src="https://a.clyp.it/h3y3isar.mp3"></audio>
```
[Answer]
# Mathematica, ~~212~~ ~~152~~ ~~139~~ 135 bytes
```
{#~(s=##~SoundNote~41&)~1&/@LetterNumber@"uursuursuikmnprsrrnprrfgikigifgiggkiggfdfdbdfgikggkikkmnikmnprsu",{14,18,21}~s~16}~Sound~18.5
```
Outputs a `Sound` object that plays Pachelbel's Canon in D when the Play button is pressed. The instrument is MIDI instrument #41 "Violin".
**The Audio**
[Click me!](https://a.clyp.it/h01wadhl.mp3)
**Explanation**
```
LetterNumber@"uursuursuikmnprsrrnprrfgikigifgiggkiggfdfdbdfgikggkikkmnikmnprsu"
```
Find the letter numbers of each character in the string ("a" -> 1, "b" -> 2, and so on), wrapped with a `List`. (This string represents Pachelbel's Canon in D)
```
#~(s=##~SoundNote~41&)~1&/@...
```
Set `s` to `SoundNote` function whose instrument is #41. Set the duration to 1 and map that function to each element in the `List` (thus making `SoundNote` primitive objects).
```
{14,18,21}~s~16
```
Make the last triad. (The duration `16` is there to make the last note 16 times longer--a whole note is sixteen times a sixteenth note.)
```
... ~Sound~18.5
```
Make a `Sound` object, `18.5` seconds long (because the tempo is 65 bpm [5 measures of 4/4 with tempo 65 bpm = approximately 18.5 seconds]).
**126 byte version, non-competing**
```
Sound[{(s=SoundNote)/@LetterNumber@"uursuursuikmnprsrrnprrfgikigifgiggkiggfdfdbdfgikggkikkmnikmnprsu",{14,18,21}~s~16},240/13]
```
Non-competing because the output contains two sixteenth notes instead of an eighth note, and the separation is quite noticeable.
[Answer]
# JavaScript (ES7), ~~249~~ ~~242~~ 241 bytes
```
with(new AudioContext)for(t=i=0;n=parseInt('l43l431db98643o86ogfdbdfdgfdzbdzgigikigfdbzbdv98db9864311480'[i++],36);)with(createOscillator())frequency.value=880*2**(-~-n%20/12),connect(destination),start(t),stop(i>56?t+q*8:t+=n>20?q=6/13:q/2)
```
Thanks to @Neil and @PatrickRoberts for some byte savings!
## Explanation
The notation is packed into the string where each character is a single note as a base-36 digit. The note values are determined by the formula `(19 - pitch) * time + 1` where `pitch` is the number of semitones less than A5 and `time` is `1` for a semiquaver or `20` for a quaver. The `0` at the end stops the `for` loop.
The tempo is ~~65.22bpm~~ *Edit: exactly 65bpm now, for 2 more bytes*.
This explanation/demo uses `Math.pow` instead of `**` for browser compatibility. It also sets the gain of the oscillators to `.3` so that the final chord does not make your ears bleed (default gain is `1`).
```
with(new AudioContext) // use HTML5 audio
for( // iterate through the note pitches and lengths
t=i=0; // t = current time to place the note
n=parseInt( // n = note pitch/length
// Packed notation string
'l43l431db98643o86ogfdbdfdgfdzbdzgigikigfdbzbdv98db9864311480'
[i++],36);
)
with(createOscillator()) // create the note oscillator
// Set the note frequency (using Math.pow for the demo).
//frequency.value=880*2**(-~-n%20/12),
frequency.value=880*Math.pow(2,-~-n%20/12),
// Send the note's sound through the speakers (for the demo, we'll connect it to
// a gain node so we can reduce the volume).
//connect(destination),
connect((g=createGain(),g.gain.value=.3,g.connect(destination),g)),
start(t), // schedule the note to sound
stop( // schedule the end of the note
i>56? // if we are in the final chord
t+ // do not increment the time
q*8 // hard-code the length to a semibreve
:t+=n>20?q=6/13:q/2 // else update the length based on the note value
)
```
You can press the button above to test it in [any browser that supports the HTML5 Web Audio API](http://caniuse.com/#feat=audio-api).
[Answer]
# [Bubblegum](https://esolangs.org/wiki/Bubblegum), 203 bytes
```
00000000: e002 2800 c35d 0026 9509 6f34 76f2 ffad ..(..].&..o4v...
00000010: 4150 0893 a735 bd02 a1eb 1237 18fe 5498 AP...5.....7..T.
00000020: 120a 83e1 6662 8a5e 9709 fe8a 3430 0f48 ....fb.^....40.H
00000030: 5008 54af d19a b44f 2be9 fb3b bf9d 206d P.T....O+..;.. m
00000040: abbf 12f0 2151 6dae 4712 8c18 4d8e f5cd ....!Qm.G...M...
00000050: eb85 404c 17cd bd5c 2775 38bd eb50 ab88 ..@L...\'u8..P..
00000060: e015 fb7e 4b1e 5ddb 515b 144c fc5e c1be ...~K.].Q[.L.^..
00000070: 3d5d 20cd e950 4a1d 256e b56e d364 188b =] ..PJ.%n.n.d..
00000080: 6fa1 afcc 2100 0235 ada0 2f23 411d 95dd o...!..5../#A...
00000090: 6665 3b45 041d cbe2 8e3b 2456 fb8d 4e4c fe;E.....;$V..NL
000000a0: 1a7f b814 a6cf 850e 9b6c 9285 3a6f 1ec3 .........l..:o..
000000b0: 02ed 505c 996b eb4d 209c 2776 a8aa 8380 ..P\.k.M .'v....
000000c0: 42cc b779 218e e75e 8000 00 B..y!..^...
```
[Try it online!](https://tio.run/nexus/bubblegum#TZPLahZBFIT3PkWJlwjCse@XBMEIomiif0DcmAh93WiSlYIbXz1WT/5EezHDMNNf16mquVH7dYihlIFJSqFZ38GngOxVRpjWIYZpMGfpgMgzkQt5KnLtfonIg1uCJsNpr6BStijRetROZNGjQhsbodMc8C4n4HjHjV7WiiKf7xiGDG1UQbJDI4RgkIofyJE65kgF1lmeMF1aOkRmlW/r7pS82zMsGV6pxJPKRNe5oDo3Yeogo9qKOnOHUYGz7Hg216fnIkciuNwzHBml1kkxU8FoTzG9DLioqajpBNfTwPSt3@p4eHYpb3k//eeHX57W5OGUa9CRn9buG0yMHjbVzrd0q9S0zfLqhFvPD34mkd09I2y5aE/dkadXTf96r/Da01NH7my0p@k6Nh1/PjCYs69yslzZMyIZtvs1MSUMRgpXNB99GKjr0m1wDCdV4OUFMbv38uRKrqTfMxIZYRaNMhsn0CyJMgy49EJ7prFMnshMccD18mNL98Wj439@5MUIgbNX56Ecv2910M7BSIzzgUOmDjc4FbM@erO14@jxF5GPJ3tGWf0ocaIm7VBCm0hesR81NGRDs20JTG00e5vLtn6IHF7f66hkKDM6S8I0cg6VQbhlT97CCSiprAYmtRi7c/kup5CDVfU7RltdN7SixpjpB7swIoPg30NnuO//9VrkN/1YPb25@Qs "Bubblegum – TIO Nexus")
This is a hexdump (reverse with `xxd -r`) of the source code. The MIDI file it produces is as follows (also a hexdump):
```
00000000: 4d54 6864 0000 0006 0001 0002 01e0 4d54 MThd..........MT
00000010: 726b 0000 0019 00ff 5902 0200 00ff 5804 rk......Y.....X.
00000020: 0402 1808 00ff 5103 0e15 c500 ff2f 004d ......Q....../.M
00000030: 5472 6b00 0001 f200 c000 00ff 0405 5069 Trk...........Pi
00000040: 616e 6f00 9051 5f81 5880 5100 1890 4e5f ano..Q_.X.Q...N_
00000050: 6c80 4e00 0c90 4f5f 6c80 4f00 0c90 515f l.N...O_l.O...Q_
00000060: 8158 8051 0018 904e 5f6c 804e 000c 904f .X.Q...N_l.N...O
00000070: 5f6c 804f 000c 9051 5f6c 8051 000c 9045 _l.O...Q_l.Q...E
00000080: 5f6c 8045 000c 9047 5f6c 8047 000c 9049 _l.E...G_l.G...I
00000090: 5f6c 8049 000c 904a 5f6c 804a 000c 904c _l.I...J_l.J...L
000000a0: 5f6c 804c 000c 904e 5f6c 804e 000c 904f _l.L...N_l.N...O
000000b0: 5f6c 804f 000c 904e 5f81 5880 4e00 1890 _l.O...N_.X.N...
000000c0: 4a5f 6c80 4a00 0c90 4c5f 6c80 4c00 0c90 J_l.J...L_l.L...
000000d0: 4e5f 8158 804e 0018 9042 5f6c 8042 000c N_.X.N...B_l.B..
000000e0: 9043 5f6c 8043 000c 9045 5f6c 8045 000c .C_l.C...E_l.E..
000000f0: 9047 5f6c 8047 000c 9045 5f6c 8045 000c .G_l.G...E_l.E..
00000100: 9043 5f6c 8043 000c 9045 5f6c 8045 000c .C_l.C...E_l.E..
00000110: 9042 5f6c 8042 000c 9043 5f6c 8043 000c .B_l.B...C_l.C..
00000120: 9045 5f6c 8045 000c 9043 5f81 5880 4300 .E_l.E...C_.X.C.
00000130: 1890 475f 6c80 4700 0c90 455f 6c80 4500 ..G_l.G...E_l.E.
00000140: 0c90 435f 8158 8043 0018 9042 5f6c 8042 ..C_.X.C...B_l.B
00000150: 000c 9040 5f6c 8040 000c 9042 5f6c 8042 ...@[[email protected]](/cdn-cgi/l/email-protection)_l.B
00000160: 000c 9040 5f6c 8040 000c 903e 5f6c 803e ...@_l.@...>_l.>
00000170: 000c 9040 5f6c 8040 000c 9042 5f6c 8042 ...@[[email protected]](/cdn-cgi/l/email-protection)_l.B
00000180: 000c 9043 5f6c 8043 000c 9045 5f6c 8045 ...C_l.C...E_l.E
00000190: 000c 9047 5f6c 8047 000c 9043 5f81 5880 ...G_l.G...C_.X.
000001a0: 4300 1890 475f 6c80 4700 0c90 455f 6c80 C...G_l.G...E_l.
000001b0: 4500 0c90 475f 8158 8047 0018 9049 5f6c E...G_.X.G...I_l
000001c0: 8049 000c 904a 5f6c 804a 000c 9045 5f6c .I...J_l.J...E_l
000001d0: 8045 000c 9047 5f6c 8047 000c 9049 5f6c .E...G_l.G...I_l
000001e0: 8049 000c 904a 5f6c 804a 000c 904c 5f6c .I...J_l.J...L_l
000001f0: 804c 000c 904e 5f6c 804e 000c 904f 5f6c .L...N_l.N...O_l
00000200: 804f 000c 9051 5f6c 8051 000c 904a 5f00 .O...Q_l.Q...J_.
00000210: 904e 5f00 9051 5f8e 4c80 4a00 0080 4e00 .N_..Q_.L.J...N.
00000220: 0080 5100 8360 ff2f 00 ..Q..`./.
```
[Answer]
# BBC BASIC, 141 ASCII characters (65.217BPM)
```
*TEMPO1
F.i=2TO71j=i>65SOUND1-j*(479+i/2),-9,ASCM." \\VX\\VX\DHLNRVXVVNRVV>@DHD@D>@D@@HD@@>:>:6:>@DH@@HDHHLNLDHLNRVXNNVV\\",i)*2,23-j*161N.
```
Revised to accomodate limit on tempo. Will update explanation later.
# BBC BASIC, 123 ASCII characters (noncompeting as 60BPM)
Download interpreter at <http://www.bbcbasic.co.uk/bbcwin/download.html>
Plays the song directly when run.
```
F.i=1TO67j=i>64SOUND1-j*(447+i),-9,ASCM."\\VX\\VX\DHLNRVXVVNRVV>@DHD@D>@D@@HD@@>:>:6:>@DH@@HDHHLNLDHLNRVXNV\",i)*2,5-j*75N.
```
**Ungolfed**
```
FOR i = 1 TO 67
j = i > 64: REM j=0 for the first four bars composed of 16th notes, j=-1 for the final chord (whole note)
SOUND 1 - j * (447 + i), -9, ASC(MID$("\\VX\\VX\DHLNRVXVVNRVV>@DHD@D>@D@@HD@@>:>:6:>@DH@@HDHHLNLDHLNRVXNV\", i)) * 2, 5 - j * 75
NEXT i
```
**Explanation**
`j` is a flag indicating whether we are in the first 4 bars or the final chord. TRUE is `-1` in BBC BASIC.
The `SOUND` statement takes 4 parameters:
CHANNEL: for the first 4 bars this is channel 1. For the 3 notes of the chord in the 5th bar, the channel numbers are 201, 202 and 203 hex (513,514 and 515 decimal.) This means play on channels 1,2 and 3, the initial 2 meaning play simultaneously with 2 notes on other channels (i.e play a 3 note chord).
VOLUME: Given as a negative value because positive values represent other effects (sound envelopes.). Set at -9 (will go up to -15 which is loudest.)
PITCH: For this tune, ranges from D4=108 to A5=184. Each integer step is 1/4 of a semitone. Values are stored as ASCII codes in the range 54 to 92 and doubled to regenerate the correct value. 1/8th notes are stored as duplicate 1/16th notes. The final chord is stored as 3 separate pitches and the note length varied to whole note as below.
DURATION: in 1/20 of a second. Duration of 1/16th note is 5/20 of a second so 60 1/4 notes per minute (there is insufficient resolution to make the tempo more precise.) The whole note is 5-(-75)=80 units (4 seconds) long.
[Answer]
# Befunge, 242 bytes
The tune is written to stdout in the format of a MIDI file. You'll need to redirect that output to a *.mid* file in order to play the excerpt.
```
<v:"MThd"0006000101"MTrk"001+"~e"0*3"UQ"30*5"-\"9
v>9#:-#,_0"QONLJIGEJIGEGCGECB@>@B@BCEGCECBECEGECBNLJNONLJIGEQONQONQ"0\:
_v#:\%+77+1,"@",\,*8*82,+3*4!*-3::\,"@",:,*:*62,1
v>"QNJQNJ"0\:
_v#:\+1,"@",\,-**82/3\*:*62:,+!\**97!-3::\
@>,\"/U"3*,,,
```
[Try it online!](http://befunge.tryitonline.net/#code=PHY6Ik1UaGQiMDAwNjAwMDEwMSJNVHJrIjAwMSsifmUiMCozIlVRIjMwKjUiLVwiOQp2PjkjOi0jLF8wIlFPTkxKSUdFSklHRUdDR0VDQkA+QEJAQkNFR0NFQ0JFQ0VHRUNCTkxKTk9OTEpJR0VRT05RT05RIjBcOgpfdiM6XCUrNzcrMSwiQCIsXCwqOCo4MiwrMyo0ISotMzo6XCwiQCIsOiwqOio2MiwxCnY+IlFOSlFOSiIwXDoKX3YjOlwrMSwiQCIsXCwtKio4Mi8zXCo6KjYyOiwrIVwqKjk3IS0zOjpcCkA+LFwiL1UiMyosLCw&input=), although I don't think it's currently possible to save the output in such a way that it'll retain the binary integrity of the data.
**Explanation**
The first line is essential just a hard coded MIDI header, which is output at the start of line two. The rest of line two encodes the sequence of notes as their MIDI values, which are conveniently ASCII. The third line writes out the MIDI commands for playing those notes, with the duration being automatically calculated (every note is a semiquaver unless i%14 == 0). The final chord is handled as a special case on lines four and five (since that requires multiple keys being pressed simultaneously), and the sixth line writes out the final MIDI end of track marker.
[Answer]
# C, ~~248 228 210 198 193~~ 191 bytes
```
#define y(x)cos(.346*t*exp(x/17.))
d=1846,t;main(c){for(;t++<d*80;putchar(c=((t<d*64?y(("TTQRTTQRTHJLMOQRQQMOQQEFHJHFHEFHFFJHFFECECACEFHJFFJHJJLMHJLMOQRT"[t/d]-72)):y(12)+y(9)+y(5))+3)*42));}
```
This produces a sequence of 8 bit unsigned samples intended to be played at 8000 samples per second. If you have an older UNIX/Linux setup, you can redirect the output to `/dev/audio`. On some newer Linux distros, you may have to pipe the output to the ALSA command line player `aplay`
[Answer]
# SmileBASIC, 115 bytes
```
BGMPLAY"@305T65L16[A8F+G]2A{r}F#8>F#GABAGAF#GAG8BAG8F#EF#EDEF#GABG8BAB8<C#D{r}AA1:1[R1]4F#1:2[R1]4D1{r=>AB<C#DEF#G}
```
Using a nice instrument was worth 4 extra bytes :)
[Answer]
# JavaScript (ES6) using [WAV.js](https://gist.github.com/patrickroberts/3b065ab94ce5094baacf45ed23e2a16e), 325 bytes
```
w=new WAV();w.addProgression(btoa`9‘¹9‘¹8€¹‘9‘¹‘y‘9‘y¸€x¸x€8¸€8¸888¸€x¸€8€x
ù€x
ù‘y9`.replace(/[CF]./g,'$&#').split(/(?=[A-G])/g).map((f=t=>n=>({note:n,time:t}))(15/65)));['D5','F5#','A5'].map(n=>w.addNote(f(48/13)(n),.3,[],1,1));new Audio(URL.createObjectURL(w.toBlob())).play()
```
```
<script src="https://cdn.rawgit.com/patrickroberts/3b065ab94ce5094baacf45ed23e2a16e/raw/9c367e292fbee8341e1019d0d5953a2234449882/wav.babel.js"></script>
```
] |
[Question]
[
Given three mutually tangent circles, [we can always find](http://en.wikipedia.org/wiki/Descartes%27_theorem) two more circles which are tangent to all three of those. These two are called *Apollonian circles*. Note that one of the Apollonian circles might actually be *around* the three initial circles.
Starting from three tangent circles, we can create a fractal called an [Apollonian gasket](http://en.wikipedia.org/wiki/Apollonian_gasket), by the following process:
1. Call the initial 3 circles the *parent circles*
2. Find the parent circles' two Apollonian circles
3. For each Apollonian circle:
4. For each pair of the three pairs of parent circles:
5. Call the Apollonian circle and the two parent circles the new set of parent circles and start over from step 2.
E.g. starting with circles of equal size, we get:

Image found on Wikipedia
There's one more bit of notation we need. If we have a circle of radius *r* with centre *(x, y)*, we can define it's curvature as *k = ±1/r*. Usually *k* will be positive, but we can use negative *k* to denote the circle that encloses all the other circles in the gasket (i.e. all tangents touch that circle from the inside). Then we can specify a circle with a triplet of numbers: ***(k, x\*k, y\*k)***.
For the purpose of this question, we will assume positive integer *k* and rational *x* and *y*.
Further examples for such circles can be found [in the Wikipedia article](http://en.wikipedia.org/wiki/Apollonian_gasket#Integral_Apollonian_circle_packings).
There's also some interesting stuff about integral gaskets [in this article](http://www.artofproblemsolving.com/blog/34543) (among other fun things with circles).
## The Challenge
You will be given **4** circle specifications, each of which will look like `(14, 28/35, -112/105)`. You can use any list format and division operator that is convenient, such that you can simply `eval` the input if you wish to. You may assume that the 4 circles are indeed tangent to each other, and that the first of them has negative curvature. That means you are already given the surrounding Apollonian circle of the other three. For a list of valid example inputs, see the bottom of the challenge.
Write a program or function which, given this input, draws an Apollonian gasket.
You may take input via function argument, ARGV or STDIN and either render the fractal on screen or write it to an image file in a format of your choice.
If the resulting image is rasterised, it must be at least 400 pixels on each side, with less than 20% padding around the largest circle. You may stop recursing when you reach circles whose radius is less than a 400th of the largest input circle, or circles which are smaller than a pixel, whichever happens first.
You must draw only circle outlines, not full discs, but the colours of background and lines are your choice. The outlines must not be wider than a 200th of the outer circles diameter.
This is code golf, so the shortest answer (in bytes) wins.
## Example Inputs
Here are all integral gaskets from the Wikipedia article converted to the prescribed input format:
```
[[-1, 0, 0], [2, 1, 0], [2, -1, 0], [3, 0, 2]]
[[-2, 0, 0], [3, 1/2, 0], [6, -2, 0], [7, -3/2, 2]]
[[-3, 0, 0], [4, 1/3, 0], [12, -3, 0], [13, -8/3, 2]]
[[-3, 0, 0], [5, 2/3, 0], [8, -4/3, -1], [8, -4/3, 1]]
[[-4, 0, 0], [5, 1/4, 0], [20, -4, 0], [21, -15/4, 2]]
[[-4, 0, 0], [8, 1, 0], [9, -3/4, -1], [9, -3/4, 1]]
[[-5, 0, 0], [6, 1/5, 0], [30, -5, 0], [31, -24/5, 2]]
[[-5, 0, 0], [7, 2/5, 0], [18, -12/5, -1], [18, -12/5, 1]]
[[-6, 0, 0], [7, 1/6, 0], [42, -6, 0], [43, -35/6, 2]]
[[-6, 0, 0], [10, 2/3, 0], [15, -3/2, 0], [19, -5/6, 2]]
[[-6, 0, 0], [11, 5/6, 0], [14, -16/15, -4/5], [15, -9/10, 6/5]]
[[-7, 0, 0], [8, 1/7, 0], [56, -7, 0], [57, -48/7, 2]]
[[-7, 0, 0], [9, 2/7, 0], [32, -24/7, -1], [32, -24/7, 1]]
[[-7, 0, 0], [12, 5/7, 0], [17, -48/35, -2/5], [20, -33/35, 8/5]]
[[-8, 0, 0], [9, 1/8, 0], [72, -8, 0], [73, -63/8, 2]]
[[-8, 0, 0], [12, 1/2, 0], [25, -15/8, -1], [25, -15/8, 1]]
[[-8, 0, 0], [13, 5/8, 0], [21, -63/40, -2/5], [24, -6/5, 8/5]]
[[-9, 0, 0], [10, 1/9, 0], [90, -9, 0], [91, -80/9, 2]]
[[-9, 0, 0], [11, 2/9, 0], [50, -40/9, -1], [50, -40/9, 1]]
[[-9, 0, 0], [14, 5/9, 0], [26, -77/45, -4/5], [27, -8/5, 6/5]]
[[-9, 0, 0], [18, 1, 0], [19, -8/9, -2/3], [22, -5/9, 4/3]]
[[-10, 0, 0], [11, 1/10, 0], [110, -10, 0], [111, -99/10, 2]]
[[-10, 0, 0], [14, 2/5, 0], [35, -5/2, 0], [39, -21/10, 2]]
[[-10, 0, 0], [18, 4/5, 0], [23, -6/5, -1/2], [27, -4/5, 3/2]]
[[-11, 0, 0], [12, 1/11, 0], [132, -11, 0], [133, -120/11, 2]]
[[-11, 0, 0], [13, 2/11, 0], [72, -60/11, -1], [72, -60/11, 1]]
[[-11, 0, 0], [16, 5/11, 0], [36, -117/55, -4/5], [37, -112/55, 6/5]]
[[-11, 0, 0], [21, 10/11, 0], [24, -56/55, -3/5], [28, -36/55, 7/5]]
[[-12, 0, 0], [13, 1/12, 0], [156, -12, 0], [157, -143/12, 2]]
[[-12, 0, 0], [16, 1/3, 0], [49, -35/12, -1], [49, -35/12, 1]]
[[-12, 0, 0], [17, 5/12, 0], [41, -143/60, -2/5], [44, -32/15, 8/5]]
[[-12, 0, 0], [21, 3/4, 0], [28, -4/3, 0], [37, -7/12, 2]]
[[-12, 0, 0], [21, 3/4, 0], [29, -5/4, -2/3], [32, -1, 4/3]]
[[-12, 0, 0], [25, 13/12, 0], [25, -119/156, -10/13], [28, -20/39, 16/13]]
[[-13, 0, 0], [14, 1/13, 0], [182, -13, 0], [183, -168/13, 2]]
[[-13, 0, 0], [15, 2/13, 0], [98, -84/13, -1], [98, -84/13, 1]]
[[-13, 0, 0], [18, 5/13, 0], [47, -168/65, -2/5], [50, -153/65, 8/5]]
[[-13, 0, 0], [23, 10/13, 0], [30, -84/65, -1/5], [38, -44/65, 9/5]]
[[-14, 0, 0], [15, 1/14, 0], [210, -14, 0], [211, -195/14, 2]]
[[-14, 0, 0], [18, 2/7, 0], [63, -7/2, 0], [67, -45/14, 2]]
[[-14, 0, 0], [19, 5/14, 0], [54, -96/35, -4/5], [55, -187/70, 6/5]]
[[-14, 0, 0], [22, 4/7, 0], [39, -12/7, -1/2], [43, -10/7, 3/2]]
[[-14, 0, 0], [27, 13/14, 0], [31, -171/182, -10/13], [34, -66/91, 16/13]]
[[-15, 0, 0], [16, 1/15, 0], [240, -15, 0], [241, -224/15, 2]]
[[-15, 0, 0], [17, 2/15, 0], [128, -112/15, -1], [128, -112/15, 1]]
[[-15, 0, 0], [24, 3/5, 0], [40, -5/3, 0], [49, -16/15, 2]]
[[-15, 0, 0], [24, 3/5, 0], [41, -8/5, -2/3], [44, -7/5, 4/3]]
[[-15, 0, 0], [28, 13/15, 0], [33, -72/65, -6/13], [40, -25/39, 20/13]]
[[-15, 0, 0], [32, 17/15, 0], [32, -161/255, -16/17], [33, -48/85, 18/17]]
```
[Answer]
## GolfScript (289 bytes vector / 237 bytes raster)
At 289 bytes and executing in a reasonable time:
```
'/'/n*','/']['*0,`1/*~1.$[]*(~-400*:&;{1+1=*}/:D;{{1+2<~D@*\/}%}%'<svg><g fill="none" stroke="red">'puts.{[[~@:b[D&*\abs]{@&*[b]+}2*]{'.0/'*'"#{
}"'n/*~}%'<circle r="
" cx="
" cy="
" />'n/\]zip puts}:|/[{.([.;]+}3*]{(:?zip{)\~++2*\-}%:c.|0=D&*<{?);[c]+[{([.;]+.}3*;]+}*.}do'</g></svg>'
```
This takes input on stdin and generates an SVG file to stdout. Unfortunately it takes a bit too long for an online demo, but a [tweaked version which aborts early](http://golfscript.apphb.com/?c=OydbWy0yLCAwLCAwXSwgWzMsIDEvMiwgMF0sIFs2LCAtMiwgMF0sIFs3LCAtMy8yLCAyXV0nCgonLycvbionLCcvJ11bJyowLGAxLyp%2BMS4kW10qKH4tNDAwKjomO3sxKzE9Kn0vOkQ7e3sxKzI8fkRAKlwvfSV9JSc8c3ZnPjxnIGZpbGw9Im5vbmUiIHN0cm9rZT0icmVkIj4ncHV0cy57W1t%2BQDpiW0QmKlxhYnNde0AmKltiXSt9MipdeycuMC8nKiciI3sKfSInbi8qfn0lJzxjaXJjbGUgcj0iCiIgY3g9IgoiIGN5PSIKIiAvPiduL1xdemlwIHB1dHN9OnwvW3suKFsuO10rfTMqXXsoOj96aXB7KVx%2BKysyKlwtfSU6Yy58MD1EJioxMC88ez8pO1tjXStbeyhbLjtdKy59Myo7XSt9Ki59ZG8nPC9nPjwvc3ZnPic%3D) can give you an idea.
Given input `[[-2, 0, 0], [3, 1/2, 0], [6, -2, 0], [7, -3/2, 2]]` the [output](http://pastebin.com/raw.php?i=mPDxhJip) (converted to PNG with InkScape) is

---
At 237 bytes and taking far too long (I extrapolate that it would take just over a week to produce similar output to the above, although in one-bit black and white):
```
'/'/n*','/']['*0,`1/*~1.$[]*(~-400*:&;{1+1=*}/:D;{{1+2<~D@*\/}%}%.[{.([.;]+}3*]{(:?[zip{)\~++2*\-}%:c]@+\0c=D&*<{?);[c]+[{([.;]+.}3*;]+}*.}do;:C;'P1 ''801 '2*.~:B*,{:P;C{:?[0=2/.D&*-.*\D&*+.*]{2,{P{B/}2$*B%400-?0=*\)?=&*-.*}/+<},,1=},!}/
```
Output is NetPBM format without newlines, so possibly doesn't strictly follow the spec, although the GIMP will still load it. If strict conformance is required, insert an `n` after the last `!`.
The rasterisation is by testing each pixel against each circle, so the time taken is pretty much linear in the number of pixels times the number of circles. By downscaling everything by a factor of 10,
```
'/'/n*','/']['*0,`1/*~1.$[]*(~-40*:&;{1+1=*}/:D;{{1+2<~D@*\/}%}%.[{.([.;]+}3*]{(:?[zip{)\~++2*\-}%:c]@+\0c=D&*<{?);[c]+[{([.;]+.}3*;]+}*.}do;:C;'P1 ''81 '2*.~:B*,{:P;C{:?[0=2/.D&*-.*\D&*+.*]{2,{P{B/}2$*B%40-?0=*\)?=&*-.*}/+<},,1=},!}/
```
will run in 10 minutes and produce

(converted to PNG with the GIMP). Given 36 hours it produced the 401x401

[Answer]
## JavaScript (418 410 bytes)
Implemented as a function:
```
function A(s){P='<svg><g fill=none stroke=red transform=translate(400,400)>';Q=[];s=eval(s);S=-400*s[0][0];function d(c){P+='<circle r='+Math.abs(p=S/c[0])+' cx='+p*c[1]+' cy='+p*c[2]+' />'}for(c=4;c--;d(s[0]),s.push(s.shift()))Q.push(s.slice());for(;s=Q.shift();d(c)){c=[];for(i=4;i--;)c[i]=2*(s[0][i]+s[1][i]+s[2][i])-s[3][i];for(i=6;c[0]<S&&i;)Q.push([s[i--%3],s[i--%3],c,s[i%3]])}document.body.innerHTML=P}
```
[Online demo](http://jsfiddle.net/8L8kwa1p/4/) (note: doesn't work in browsers which fail to honour the SVG spec's requirements with respect to implicit sizing, so I offer a [slightly longer version](http://jsfiddle.net/8L8kwa1p/2/) which works around that bug; browsers may also render the SVG less accurately than e.g. Inkscape, although Inkscape is a bit stricter on quoting attributes).
Note that 8 bytes could be saved by using `document.write`, but that seriously borks jsFiddle.
[Answer]
# Mathematica 289 characters
By solving the bilinear system as per <http://arxiv.org/pdf/math/0101066v1.pdf> Theorem 2.2 (highly inefficient).
Spaces not needed, still golfing it:
```
w = {k, x, y};
d = IdentityMatrix;
j = Join;
p_~f~h_ := If[#[[-1, 1]] < 6! h,
q = 2 d@4 - 1;
m = #~j~{w};
r = Complement[w /. NSolve[ And @@ j @@
MapThread[Equal, {[[email protected]](/cdn-cgi/l/email-protection), 4 d@3 {0, 1, 1}}, 2], w], a];
If[r != {},
a~AppendTo~# & @@ r;
Function[x, x~j~{#}~f~h & /@ r]@#]] & /@ p~Subsets~{3};
Graphics[Circle @@@ ({{##2}, 1}/# & @@@ (f[a = #, -Tr@#]; a))] &
```
A reduced size animation with input `{{-13, 0, 0}, {23, 10/13, 0}, {30, -84/65, -1/5}, {38, -44/65, 9/5}}`

[Answer]
## Maple (960 bytes)
I used Descartes Theorem to generate the Apollonian Gasket and then use Maple's plotting system to plot it. If I have time I want to further golf this and and change it to Python (Maple is definitely not the best for fractals). Here is a link to [a free Maple player](http://www.maplesoft.com/products/maple/mapleplayer/) if you want to run my code.
```
X,Y,Z,S,N:=abs,evalf,member,sqrt,numelems;
f:=proc(J)
L:=map((x)->[x[1],(x[2]+x[3]*I)/x[1]+50*(1+I)/X(J[1][2])],J);
R:=Vector([L]);
T,r:=X(L[1][3]),L[1][4];
A(L[1][5],L[2][6],L[3][7],L[1][8],L[2][9],L[3][10],R,T,r);
A(L[1][11],L[2][12],L[4][13],L[1][14],L[2][15],L[4][16],R,T,r);
A(L[1][17],L[3][18],L[4][19],L[1][20],L[3][21],L[4][22],R,T,r);
A(L[2][23],L[3][24],L[4][25],L[2][26],L[3][27],L[4][28],R,T,r);
plots[display](seq(plottools[circle]([Re(R[i][29]),Im(R[i][30])],X(1/R[i][31])),i=1..N(R))):
end proc:
A:=proc(a,b,c,i,j,k,R,E,F)
K:=i+k+j+2*S(i*k+i*j+k*j);
if K>400*E then
return;
end if;
C:=(a*i+c*k+b*j+2*S(a*c*i*k+b*c*j*k+a*b*i*j))/K;
C2:=(a*i+c*k+b*j-2*S(a*c*i*k+b*c*j*k+a*b*i*j))/K;
if Y(X(C-F))<1/E and not Z([K,C],R) then
R(N(R)+1):=[K,C];
A(a,b,C,i,j,K,R,E,F);
A(a,c,C,i,k,K,R,E,F);
A(b,c,C,j,k,K,R,E,F);
end if:
if Y(X(C2-F))<1/E and not Z([K,C2],R) then
R(N(R)+1):=[K,C2];
A(a,b,C2,i,j,K,R,E,F);
A(a,c,C2,i,k,K,R,E,F);
A(b,c,C2,j,k,K,R,E,F);
end if:
end proc:
```
Some sample gaskets
```
f([[-1, 0, 0], [2, 1, 0], [2, -1, 0], [3, 0, 2]]);
```

```
f([[-9, 0, 0], [14, 5/9, 0], [26, -77/45, -4/5], [27, -8/5, 6/5]]);
```

] |
[Question]
[
As we all know, [it's turtles all the way down](https://en.wikipedia.org/wiki/Turtles_all_the_way_down). But is it primes all the way down too?
A number is considered a "turtle-prime" if it satisfies the following conditions:
```
1) It is prime.
2) It is possible to remove a single digit leaving a prime number.
3) Step 2 can be repeated until left with a single digit prime.
```
For example, `239` is a "turtle-prime", as it can be reduced to `23` then either `2` or `3`, both of which are prime. It also can be reduced to `29` then `2`. `151` is not a turtle prime, as it reduces to `15` (not prime), `51` (not prime), or `11`. `11` is prime, but can only reduce to `1`, which is not.
Given a positive integer, determine if it is a "turtle-prime". Your output can be in any form so long as it gives the same output for any truthy or falsey value.
Test cases:
```
input -> output
1 -> false
2 -> true
17 -> true
19 -> false
239 -> true
389 -> false
```
# Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest answer in each language wins!
[Answer]
# [Haskell](https://www.haskell.org/), ~~104~~ ~~102~~ ~~99~~ ~~98~~ ~~97~~ ~~95~~ 91 bytes
```
p x=product[2..x-1]^2`mod`x>0
f[]=1>0
f x|y<-zip[0..]x=or[f[snd b|b<-y,b/=a]|a<-y,p$read x]
```
[Try it online!](https://tio.run/##FcxBDoMgEEDRfU9BjMuCYtKd9CKTaYQiKakCQZuMDXendfXf6r/09p6XpdbESKUc7ee5wyAEcYmPYVqjnejeXxygkmcZlWPkX5@gFwJJxQwOtmCZKWbkx9V0SmPRJ1ObZ20ZYV21D/@5D3vrGnmTTf0B "Haskell – Try It Online")
## Explanation
First we set up a primality test
```
p x=product[2..x-1]^2`mod`x>0
```
This uses [Wilson's Theorem](https://en.wikipedia.org/wiki/Wilson%27s_theorem) to determine the primality of an input.
We then declare a base case, which will assert that the empty string is truthy.
```
f[]=1>0
```
Now we define the actual function
```
f x|y<-zip[0..]x=or[f[snd b|b<-y,b/=a]|a<-y,p$read x]
```
We use a pattern guard to bind `zip[0..]x` to `y`, because we need to use it twice later. We then assert the answer is
```
or[f[snd b|b<-y,b/=a]|a<-y,p$read x]
```
`[[snd b|b<-y,b/=a]|a<-y]` is all of the numbers that are a digit removed from our input. So we are asserting that at least one of these numbers is truthy for `f`. In order to ensure that composite numbers are falsy we add in `prime$read x`. If the number is not prime the list will become empty and the `any` of a empty list is false.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 16 bytes
```
DŒPḊṖLÐṀḌ߀¬Ȧ<ÆP
```
[Try it online!](https://tio.run/##y0rNyan8/9/l6KSAhzu6Hu6c5nN4wsOdDQ939Bye/6hpzaE1J5bZHG4L@H90z@F2IN/9/39DHQUjHQVDcyC2BDKNgYSxhSUA "Jelly – Try It Online")
### How it works
```
DŒPḊṖLÐṀḌ߀¬Ȧ<ÆP Main link. Argument: n
D Decimal; convert n to base 10.
ŒP Powerset; get all sub-arrays of n's decimal digits.
Ḋ Dequeue; remove the first sub-array (empty array).
Ṗ Pop; remove the last sub-array (all of n's digits).
LÐṀ Maximal by length; keep those of the remaining subarrays that
have maximal length. This keep exactly those sub-arrays that have
one (and only one) digit removed. If n < 10, this yields an empty
array. Without Ḋ, it would yield [[]] instead.
Ḍ Undecimal; turn the generated digit arrays into integers.
߀ Recursively map the main link over the generated integers.
¬ Negate; map 1 to 0 and 0 to 1.
Ȧ Any and all; yield 0 if the array is empty (n < 10) or any of the
recursive calls returned 1 (mapped to 0). If all calls returned
0, this will yield 1.
ÆP Test n for primality, yielding 1 for primes, 0 otherwise.
< Test if the result to the left is less than the result to the
right. This is possible only if the left result is 0 (n < 10 or
removing a digit results in a turtle prime) and the right result
is 1 (n itself is prime).
```
[Answer]
# R, ~~124~~ ~~122~~ ~~120~~ ~~113~~ ~~95~~ ~~93~~ ~~106~~ 105 bytes
```
g=pryr::f(`if`(gmp::isprime(sum(x*10^((l<-sum(x|1)-1):0))),any(!l,sapply(0:l+1,function(z)g(x[-z]))),!1))
```
Which evaluates to the function:
```
function (x)
if (gmp::isprime(sum(x * 10^((l <- sum(x | 1) - 1):0)))) any(!l,
sapply(0:l + 1, function(z) g(x[-z]))) else !1
```
Recursive solution. Takes input as a list of digits.
Has 2 logical statements:
1. Is `x` prime when concatenated?
2. Is any of the following `TRUE`:
1. Is the length of `x` nonzero? This is our final terminating condition.
2. Is `f` `TRUE` for any subset of `x`?
The first statement ensures we keep working with primes only. The second does the actual recursion.
Saved two bytes thanks to @Giuseppe.
I had to revert some of my golfs because of a bug, where I was testing with a previous function definition by accident.
# R, 98 bytes, non-competing
Like I mentioned in the comments, I made a [package](https://github.com/JarkoDubbeldam/RG). Since the challenge predates that, this is non-competing, but I wanted to showcase it a bit. It's not much so far, but we'll get there.
```
g=pryr::f(`if`(gmp::isprime(RG::C(x)),any(!(l<-sum(x|1)-1),sapply(0:l+1,function(z)g(x[-z]))),!1))
```
`C()` is the first function in the package, and takes care of concatenating digits into a numeric.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
DJḟЀ`ịDḌḟ0߀¬Ȧ¬aÆP
```
[Try it online!](https://tio.run/##y0rNyan8/9/F6@GO@YcnPGpak/Bwd7fLwx09QL7B4flAgUNrTiw7tCbxcFvA/8PtQP7//4Y6RjqG5jqGljpGxpY6xhaWAA "Jelly – Try It Online")
## How it works
```
DJḟЀ`ịDḌḟ0߀¬Ȧ¬aÆP input:239
D decimal [2,3,9]
J range@length [1,2,3]
ḟЀ` filter out each [[2,3],[1,3],[1,2]]
ịD index&decimal [[3,9],[2,9],[2,3]]
Ḍ undecimal [39,29,23]
ḟ0 filter out 0 [39,29,23]
߀ this@each [1,1,1]
¬ logical not [0,0,0]
Ȧ any and all 0
¬ logical not 1
aÆP and&is_prime 1
```
Recursion without base case ftw.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~27~~ 26 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
DµœcL’$Ḍµ€FÆPÐf
×⁵WÇÐĿFṪ<8
```
A monadic link taking and returning integers (`1` for turtle `0` otherwise).
**[Try it online!](https://tio.run/##AToAxf9qZWxsef//RMK1xZNjTOKAmSThuIzCteKCrEbDhlDDkGYKw5figbVXw4fDkMS/RuG5qjw4////MjM5 "Jelly – Try It Online")**
### How?
```
DµœcL’$Ḍµ€FÆPÐf Link 1: primes by digit removal: list of numbers e.g. [19790]
D cast to decimal list (vectorises) [[1,9,7,9,0]]
µ µ€ monadic chain for €ach:
$ last two links as a monad:
L length 5
’ decrement 4
œc combinations without replacement [[1,9,7,9],[1,9,7,0],[1,9,9,0],[1,7,9,0],[9,7,9,0]]
Ḍ cast from decimal list (vectorises) [1979,1970,1990,1790,9790]
F flatten (from a list of lists form the for €ach to a single list)
Ðf filter keep if:
ÆP is prime?
×⁵WÇÐĿFṪ<8 Main Link: number, n e.g. 1979
⁵ literal 10
× multiply 19790
(this is so the first number is tested as prime too)
W wrap in a list [19790]
ÐĿ loop, collecting results (including the input×10) while change still occurs:
Ç call the last (1) link as a monad [[19790],[1979],[197,199,179],[19,17,97,19,19,17,19,79],[7,7,7,7],[]]
F flatten [19790,1979,197,199,179,19,17,97,19,19,17,19,79,7,7,7,7]
Ṫ tail 7
<8 less than 8? 1
(if a single digit prime was reached this will be 1
otherwise it will be 0
e.g. an input of 4 yields 40 at the end which is not <8)
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~72~~ 57+8 = ~~80~~ 65 bytes
Uses the `-rprime` flag. -15 bytes from histocrat!
```
f=->n{n==''||n.to_i.prime?&!n.scan(/./){f[$`+$']&&break}}
```
[Try it online!](https://tio.run/##Hc3dCoIwGIDh8@8qpg4twsmSKAPrQkKW2cxRbmObRKi33vo5e08eXjNcXt63ZXqQoyzLJJkmSZxigmgjen6MA0lsU8tFRrLl2J7weYWTKo4vhtf3efbPTjw4unFnAWFGmk71OgCkB2dRGGG2R9FPsWoOgcurp7AGugVaAN18Oy8g3xVvpZ1Q0vrU/K8f "Ruby – Try It Online")
[Answer]
# Java, 220 bytes
[Try it online!](https://tio.run/##XZDBbsIwDIbvPIU1aVKilqiww8YKlbbDJG6T2G3aIUDKzEJaJS4DoT47c1u6oUWyYyX2Z/vf6r0eFqVx2/XXeWV1CDAPc3p6qzxZ8@pxZ@A0GACU1dLiCgJp4mtf4Bp2Gp1YkEe3ef8A7TdBci7wyQsPAh0BwiM48w0cc8oJRjGMYxjds004vGN39zCBui8EWBwDmZ0qKlIlk8k6gRDBDQwzdlFL@z@hkIrE3JHZGK@o6EYSKKVMW2o9aKxZwuNek@m3WBaFNdpBLrYsg6oIrcortyIsnGLeyyWePneJGeRxswq4fl5vqPIMULos7VG4tmF97sF0kYcLTk2dnTlljdvQp5Ap5iIXh2F2YrU6sWbjFKeHVPLP4RajaDZL5KXDaJqkl/CQjdI6bnXoVua2sqmx0/FvepakxgYDf@yE2bZlk3AqVMvQyZTEKKPrhyjC2DLxCnU1RH2uzz8)
Golfed:
```
boolean t(String n){int l=n.length();if(f(x->{for(int i=2;i<x;)if(x%i++==0)return 1<0;return x>1;},new Integer(n)))if(l<2)return 1>0;else for(int i=0;i<l;)if(t(n.substring(0,i)+n.substring(++i,l)))return 1>0;return 1<0;}
```
Ungolfed:
```
boolean t(String n) {
int l = n.length();
if (f(x -> {
for (int i = 2; i < x;) {
if (x % i++ == 0) {
return 1 < 0;
}
}
return x > 1;
} , new Integer(n))) {
if (l < 2) {
return 1 > 0;
}
else {
for (int i = 0; i < l;) {
if (t(n.substring(0, i) + n.substring(++i, l))) {
return 1 > 0;
}
}
}
}
return 1 < 0;
}
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~132~~ ~~124~~ 119 bytes
-8 Thanks to @WheatWizard
-5 Thanks to @LeakyNun
```
p=lambda i:i>1and all(i%v for v in range(2,i))
f=lambda n:n<'0'or any(f(n[:i]+n[i+1:])for i in range(len(n)))*p(int(n))
```
[Try it online!](https://tio.run/##RY3BDoIwDIbP9Cl2MWziwYJGWMSn8EY4zADSZJZlAoanx3Ewnvo3//e1bhn7gdN1daU1r0djBGm6oeFGGGsl7WbRDV7Mglh4w89WpgdSCrofzpqv8TEOjOFFdpIrTXXCFSWoa7W59Hdty5KVUnsnicctrp@ebCvufmo1RFy@Rx8qN40yPImcD5gIR9WaZgUgIiCEmSOctv2MkAJeIMuLLw "Python 2 – Try It Online")
Can't think of anything to hone it down without some builtin prime checker. Takes the number as a string (I assumed this given the OP allowed a list of digits, but if not then +14 bytes for another lambda), and recursively computes each "turtled" number's turtleness.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~28~~ 27 bytes
Iterative solution.
```
¸[D0èg2‹#εæ¨D€gZQÏDpÏ}˜]p1å
```
[Try it online!](https://tio.run/##ATUAyv8wNWFiMWX//8K4W0Qww6hnMuKAuSPOtcOmwqhE4oKsZ1pRw49EcMOPfcucXXAxw6X//zIzOQ "05AB1E – Try It Online")
**Explanation**
```
¸ # wrap input in a list
[ # start a loop
D0èg2‹# # if the length of the first element is less than 2, break
ε # apply to each element in the list
æ # compute powerset
¨ # remove last element (the full number)
D€gZQÏ # keep only the elements whose length is the max length
DpÏ # keep only primes
} # end apply
˜ # flatten list
] # end loop
p1å # is any element in the resulting list prime
```
[Answer]
# C#, 355 bytes
```
namespace System{using B=Numerics.BigInteger;class A{static void Main(){Console.WriteLine(D(Console.ReadLine()));}static bool P(B x){if(x<2)return 1<0;B r=1;for(int i=1;i<=x-1;i++)r*=i;return(r+1)%x==0;}static bool D(string x){if(x.Length==0)return 1>0;bool b;if(b=P(B.Parse(x))){var n=1<0;for(int i=0;i<x.Length;i++)n|=D(x.Remove(i,1));b&=n;}return b;}}}
```
[Try it online!](https://tio.run/##VY9BT4QwEIX/Si@a1nUJ7MHElJqIXExWs1kPngs7i5NAa6aFYJDfjl1k3XiayeTNe98r3bq0BNNkdAPuU5fA3r6ch2ZoHZqKZeq1bYCwdFGG1bPxUAHJstbOscfBee2xZJ3FA3vRaLgYnqxxtobondDDFg3wnJ9ve9CH@SSEkOPyXFhbsx3PWC8GPPI@3QgC35JhSRrLjJFK5NESR@MZhh1T1a/DWK0E3SiUv2JOq0Rc9UrF/41z7jydiizu0RZM5T@C7i/lIZaztJBBUKiAEu00OeB9wBw6TcyoE8oFIg4QZ6cZxHyrPHjvobEdcLxNQr/iWhk5LiGFHMdxmjZ39z8 "Try It Online")
My first code golf, so I hope I did it alright. I couldn't think of a way to make it even smaller (other than using int instead of BigInteger, but I did it so it would work for all provided test cases). Anyway, here's the same properly formatted:
```
namespace System
{
using B = Numerics.BigInteger;
class A
{
static void Main()
{
Console.WriteLine(D(Console.ReadLine()));
}
static bool P(B x)
{
if (x < 2)
return 1<0;
B r = 1;
for (int i = 1; i <= x - 1; i++)
r *= i;
return (r + 1) % x == 0;
}
static bool D(string x)
{
if (x.Length == 0)
return 1>0;
bool b;
if (b = P(B.Parse(x)))
{
var n = 1<0;
for (int i = 0; i < x.Length; i++)
n |= D(x.Remove(i, 1));
b &= n;
}
return b;
}
}
}
```
[Answer]
# [Perl 6](http://perl6.org/), 65 bytes
```
my&f={.is-prime&&(10>$_||?grep {f +[~] .list},m:ex/^(.*).(.*)$/)}
```
[Try it online!](https://tio.run/##FcrdCsIgAAbQV/kYItqPyw0qt1oPEiVd6BAmiXbR2NarW92cqxNMHPY5@5Ha8yRc2obovKGUyV1H9Dxf@mgCJov19XODGFx6LRvfmHd5Z2LFxR9S8iW3SI8RBdHNbzOi@VLAPiNOEhXkAVKhqhXqo@ra/AU "Perl 6 – Try It Online")
[Answer]
# [PHP](https://php.net/), 164 bytes
```
function t($n){for($i=1;++$i<$n;)if($n%$i<1)return 0;if($n<10)return $n>1;foreach($r=str_split($n)as$k=>$v){$q=$r;array_splice($q,$k,1);$z|=t(join($q));}return $z;}
```
[Try it online!](https://tio.run/##dY/BTsMwDIbvfQqrMlKi7bCwA5QsnTjwBtwomqIupaFTmrnpBBt79pJ2DE7k5Pz/78@2r/2wWvvaJ4aopQ0Z31Kw7o0JLoeqd2WwrYPA0PFT1RJDq4SczdCu0Eluq2jcxI/gZEJPDhZy0lZicVXQ5ULGVqPLmiGpLtCm8zs7MXWHjcrxwE@4V0hSE@nPyS4Nw/0cm3lcBI9fKrD31rqocS7PV/RRngcMpgug4EWovNK7zszhVuWB@liIu98q@3OX2VVd3megcpiMV5n8bAnswtQdYDP6cT84JRAfmjiJ4QHWkI6IFB4gndpTLi8JPSbicQ3/P2TKuoX0eRyCTeGePrwpg9lGfOEey9DrXeQUrnCpTM7DNw "PHP – Try It Online")
Starts off by testing the number for primality, then loops through the digits as an array, popping each one out and joining the rest back together and feeding them recursively through the function again. Each link downwards does a logical OR with the lower paths, only returning `true` if there exists at least one path of all primes.
[Answer]
# Javascript 167 bytes
```
n=>{a=[];for(i=1;i++<=n;)a.every(x=>i%x)?a.push(i):0;b=k=>(s=''+k,a.indexOf(k)>-1&&(k<10||[...s].some((x,i)=>(r=[...s],r.splice(i,1),b(~~(r.join('')))))));return b(n)}
```
## Explanation
```
n=>{
a=[]; // create array to store primes in
for(i=1;i++<=n;) // iterate from 2 to n
a.every(x=>i%x)?a.push(i):0; // if i % x is truthy for all x in a,
// then i is prime
b=k=>( // function to test is k is turtle prime
s=''+k, // convert k to a string
a.indexOf(k)>-1 && ( // if k is prime and
k<10 || // k is a single digit or
[...s].some((x,i)=>( // iterate over the digits of k
// and check to see if, by removing each
// any of the resulting numbers is turtle prime
// ... is spread operator
// [...s] converts string s to an array of characters
r=[...s], // convert s to an array again,
// importantly, this cannot be the same array
// we created above, as we need to
r.splice(i,1), // splice out the ith element of the array
b(~~(r.join(''))) // join the array to a string, convert to int,
// and check if this number is turtle prime
// ~ is bitwise negate, implicitly converts to int first before negating
// ~~ negates the negation, getting us the int
))
)
);
return b(n)
}
```
```
F=n=>{a=[];for(i=1;i++<=n;)a.every(x=>i%x)?a.push(i):0;b=k=>(s=''+k,a.indexOf(k)>-1&&(k<10||[...s].some((x,i)=>(r=[...s],r.splice(i,1),b(~~(r.join('')))))));return b(n)}
$('#input').on('keyup', () => $('#output').text(F(parseInt($('#input').val(), 10))))
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="input" />
<span id="output"></span>
```
] |
[Question]
[
# Introduction
Everyone knows the FizzBuzz sequence. It goes something like this:
```
1
2
Fizz
4
Buzz
Fizz
7
8
Fizz
Buzz
11
Fizz
13
14
FizzBuzz
.
.
.
```
In case you don't know, if the number is divisible by 3, it's `Fizz`. If it is divisible by 5, it's `Buzz`. If it is divisible by both, it's `FizzBuzz`. If it is not divisible by both, it's just the original number.
# Task
Take two inputs, for example (space separated here)
```
Fizz 3
```
For this specific example input, you should output `9`, the third `Fizz`. To be more general, take a `word` and a `number`, output the `number`th `word`.
The `word` input may be `Number`, and in this case, you should output the `number`th number in the FizzBuzz sequence that is not `Fizz`, `Buzz`, or `FizzBuzz`.
You may choose any 4 distinct, consistent inputs representing `Fizz`, `Buzz`, `FizzBuzz` and `Number`.
# Test Cases
```
Fizz 3 => 9
Buzz 4 => 25
FizzBuzz 2 => 30
Number 312 => 584
```
# Scoring
Shortest code wins!
# Rules
* No standard loopholes.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 10 bytes
```
³3,5ḍḄ⁼ʋ#Ṫ
```
[Try it online!](https://tio.run/##y0rNyan8///QZmMd04c7eh/uaHnUuOdUt/LDnav@/zdQ0LVT8CvNTUot4jIEsZ1Kq6q4jEAst0wgyxjGAon/N/hvCgA "Jelly – Try It Online")
This uses `0 = Number`, `1 = Buzz`, `2 = Fizz` and `3 = FizzBuzz`
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
1g15=ɗ#Ṫ
```
[Try it online!](https://tio.run/##y0rNyan8/98w3dDU9uR05Yc7V/0H8v6bAgA "Jelly – Try It Online")
Thanks to [Lynn](https://codegolf.stackexchange.com/users/3852/lynn). This uses `1 = Number`, `3 = Fizz`, `5 = Buzz`, `15 = FizzBuzz`. Included separately as the numbers could encode extra data
## How they work
```
³3,5ḍḄ⁼ʋ#Ṫ - Main link. Takes W=0,1,2,3 on the left, n on the right
ʋ - Last 4 links as a dyad f(k, W):
3,5ḍ - Divisible by 3 or 5? Yields [0,0], [0,1], [1,0], [1,1]
Ḅ - From binary; Yields 0, 1, 2, 3
⁼ - Equals W?
³ #Ṫ - Starting from W, count up k = W, W+1, ..., returning the nth integer such that f(k, W) is true
```
```
1g15=ɗ#Ṫ - Main link. Takes W=1,3,5,15 on the left, n on the right
ɗ - Last 3 links as a dyad f(k, W):
g15 - GCD(k, 15)
= - Does that equal W?
1 #Ṫ - Count up k = 1, 2, ..., returning the nth integer such that f(k, W) is true
```
[Answer]
# JavaScript (ES6), 44 bytes
Expects `(s)(n)` with s=0 for *Number*, s=1 for *Fizz*, s=2 for *Buzz* and s=3 for *FizzBuzz*.
```
(s,k=0)=>g=n=>n?g(n-=s==!(++k%3)+2*!(k%5)):k
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@1@jWCfb1kDT1i7dNs/WLs8@XSNP17bY1lZRQ1s7W9VYU9tIS1EjW9VUU9Mq@39yfl5xiYJfqK@Ta5CCrYKBNRdExM0zKgrIN4TxnULBfCNkeaiYsTUXWDA/J1UvJz9dI00DJKmpYaypqQAC@voKlmgKQDo1NUwQCoxMsRgBUWUEVAVUYWyApgLiZqA1hlAVphYm/wE "JavaScript (Node.js) – Try It Online")
---
### Cheaty version, 35 bytes
Expects 4680 for *Fizz*, 1056 for *Buzz*, 1 for *FizzBuzz* and 27030 for *Number*.
```
(s,k=0)=>g=n=>n?g(n-=s>>++k%15&1):k
```
[Try it online!](https://tio.run/##bc5dC4IwFAbge3/FbooNM8/86JMtCAq6qIvAG@/KVMrYIqO/b3MzDekwdvWc97y30/tUJs/r4@UIeUmrjFW4HBUMCOM5E4yLVY6Fw0rObbsY0HBIyaKoEinKF9ru4hjVw1AwmcESIddFcAagPw8sg9dRiymEkw4bZb4vrpP1gsJLvdXibmiDD9F@vTnqZG8KvuqhMaW6gW6hfktreU/Hd5njDNcnCPYJ@cbPe6C@T3DQAS/8E2GUp5QSPvSEqabO0EaEs6D6AA "JavaScript (Node.js) – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 47 bytes
```
f=lambda n,c,k=1:n and-~f(n-(k**4%15==c),c,k+1)
```
[Try it online!](https://tio.run/##TY3BCoMwEETvfsVeColdIZtYD0K@RDyksWnFukrw0kt/PTUttL0MPOYNsz6228I6pWDvbj4PDhg9TpZaBsdD9QyCKzGVZX2gk7Ve5vZIMoUlgoeRoSNskBSqvi1gjSNv3b5BLyErnJXo@HoRhGBI9kXxlj4JQRiERn6pRiD1Q43wR4Y07tcv "Python 2 – Try It Online")
Take in the category label `c` as:
```
Number -> 1
Fizz -> 6
Buzz -> 10
FizzBuzz -> 0
```
We fingerprint the category for `k` using `k**4%15`, which produces the corresponding value as listed above. This is wrapped in a [recursive function for the n'th number meeting a condition](https://codegolf.stackexchange.com/a/91128/20260).
---
**[Python 2](https://docs.python.org/2/), 54 bytes**
```
lambda n,c:([n*7/8-3*~n/4%2,~-n/4,~-n/2,0][c/2%4]+n)*c
```
[Try it online!](https://tio.run/##TYzBDoIwEETvfMVeSFpcUreFaEj8ktoDVqskuBDCxQu/Xgsm6mUmb/Iy42t@DKxjOJ1j3z4v1xYYfSMsFwd1LE2xsKpyjUuZekuNe2e90nnldiwLH8MwgYeOwRIarJFq12QwTh3PNoj0JmFVeFWmlu83QQiGpMuyTfokBGHSLL9UIdQ/0gj0h4Y0koxv "Python 2 – Try It Online")
A short at writing direct formulas for each case, with input `c` as one of `1,3,5,15`.
[Answer]
# [Perl 5](https://www.perl.org/) -p, ~~52~~ 47 bytes
Saved 5 bytes thanks to @Dom Hastings.
```
/ /;$_=332312332132330x$';/(.*?$`){$'}/g;$_=pos
```
[Try it online!](https://tio.run/##K0gtyjH9/19fQd9aJd7W2NjI2NAISBoCGcYGFSrq1voaelr2Kgma1SrqtfrpIEUF@cX//xspGHMZKphwGSgYcRkrADX9yy8oyczPK/6vm1iQAwA "Perl 5 – Try It Online")
Where 0=FizzBuzz, 1=Buzz, 2=Fizz, 3=Number in the first of the two inputs. Finds the position of the n'th occurrence of what's wanted with a regexp search in a repeated 15 char string encoding number, fizz, buzz and fizzbuzz in their right places.
[Answer]
# [Python 2](https://docs.python.org/2/), 51 bytes
```
lambda d,n,k=0:n and-~f(d,n-(k%3/2*2+k%5/4==d),k+1)
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFFJ08n29bAKk8hMS9Fty5NAyigq5GtaqxvpGWkna1qqm9ia5uiqZOtbaj5v6AoM69EI03DWEfBSFNTQVnBLbOqyqm0qooLJmOko2AMl4GLGuoomIBFUdQaANUaQszxK81NSi36DwA "Python 2 – Try It Online")
-2 bytes thanks to AnttiP; becomes -4 using Python 2
-3 bytes thanks to ovs
0 for Number, 1 for Buzz, 2 for Fizz, 3 for FizzBuzz.
[Answer]
# [R](https://www.r-project.org/), ~~56~~ ~~54~~ 52 bytes
*Edit: -4 bytes thanks to pajonk*
```
function(n,i){while(n<-n-!(!T%%3)-i+2*!T%%5)T=T+1;T}
```
[Try it online!](https://tio.run/##K/qfV5IRn5ZZVZVUWlVl@z@tNC@5JDM/TyNPJ1OzujwjMydVI89GN09XUUMxRFXVWFM3U9tIC8Q01QyxDdE2tA6pRTFCw1jHUFNBWcENyFcwVrC1U7DkQpE30TECyTsB2QomIHkjU1QFRjrGMAPAioxAiowNUBUZGxrpGICU@ZXmJqUWKQD5IGWmFib/AQ "R – Try It Online")
~~This really seems to have too many parentheses...~~
*Edit: This is really pajonk's answer, now, after removing all the useless parentheses that I left in the original...*
[Answer]
# [Python 2](https://docs.python.org/2/), 77 bytes
0 for *Number*, 1 for *Buzz*, 2 for *Fizz*, 3 for *FizzBuzz*. The formula for *Number* is taken from [A229829](http://oeis.org/A229829).
```
t,n=input()
g=n-1
print[g/8*15+g%8*12/5+1+g%8/-3,(n+g/4)*3,(n+g/2)*5,n*15][t]
```
[Try it online!](https://tio.run/##LYxBCsMgEEX3nmI2xagTrGOEUsgtugtZFTFCmUowpD19aqCr9x58fvnW5c107Et@RXisW7xD/MQnSCmPijxmLlvtlEgj906UNXOdkr1pF0y6NJANxp1qe48dm2QHpf9GSgfkNp2nOh/no0PwghAG4RFIXFs6@gE "Python 2 – Try It Online")
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
µN53SÖ2βQ
```
First input is the \$number\$; second is a digit \$0\$ for `Number`, \$1\$ for `Fizz`, \$2\$ for `Buzz`, and \$3\$ for `FizzBuzz`.
Uses the legacy version of 05AB1E, because it'll implicitly output the index `N` after a while-loop `µ`. In the new 05AB1E version, an explicit trailing `}N` should be added to accomplish that.
[Try it online](https://tio.run/##MzBNTDJM/f//0FY/U@Pgw9OMzm0K/P/fmMsQAA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W6WJ/bqtfppJfaW5SapGCW2ZVlYJTKZAAsUAMJeXKwytqaw9vOLxXSUHj8H5NhUdtkxSU7CsTQv8f2upnahx8eJrRuU0Rgf9r/XT0Dm39Hx1trGMYq6MQbaJjBKKMdIxBlLGhkY5BbCwA).
**Explanation:**
```
µ # Loop until the counter_variable is equal to the first (implicit) input
N # Push the loop-index
53S # Push [5,3]
Ö # Check if the loop-index is divisible by either 5 or 3
# (resulting in [0,0], [1,0], [0,1], or [1,1])
2β # Convert it from a base-2 list to an integer
# ([0,0],[1,0],[0,1],[1,1] will become 0,1,2,3 respectively)
Q # And check if it's equal to the second (implicit) input
# (if this is truthy: implicitly increase the counter_variable by 1)
# (after the loop, the loop-index `N` is output implicitly)
```
---
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 6 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
µN15¿Q
```
First input is the \$number\$; second is an integer \$1\$ for `Number`, \$3\$ for `Fizz`, \$5\$ for `Buzz`, and \$15\$ for `FizzBuzz`.
Port of [*@Lynn*'s Jelly comment](https://codegolf.stackexchange.com/questions/239702/nth-fizzbuzz-number#comment541531_239706) (I now also notice my original program above uses a similar approach as [*@cairdCoinheringaahing*'s 10-bytes Jelly program](https://codegolf.stackexchange.com/a/239706/52210), even though we came up with it independently. Not too surprising, since it's a pretty straight-forward approach.)
[Try it online](https://tio.run/##MzBNTDJM/f//0FY/Q9ND@wP//zfmMgYA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9W6WJ/bqtfppJbZlWVglMpkACxwAy/0tyk1CIl5Uprm8MramsPbzi8V0lB4/B@TYVHbZMUlOwrE0L/H9rqZ2h6aH9E4P9aPx29Q1v/R0cb6xjH6ihEm@iYgigjHUMwbWwIZMXGAgA).
**Explanation:**
```
µ # Loop until the counter_variable is equal to the first (implicit) input
N # Push the loop-index
15¿ # Get the GCD (Greatest Common Divisor) of this index and 15
Q # And check if it's equal to the second (implicit) input
# (if this is truthy: implicitly increase the counter_variable by 1)
# (after the loop, the loop-index `N` is output implicitly)
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 60 bytes
```
L$`^.
$'*$&¶$'*$(NNFNBFNNFBNFNNZ
L$`(.)+¶(?<-1>.*?\1)+
$.>%`
```
[Try it online!](https://tio.run/##K0otycxLNPyvquGe8N9HJSFOj0tFXUtF7dA2EKXh5@fm5@QGJJ2ADL8oLqAKDT1N7UPbNOxtdA3t9LTsYww1tblU9OxUE/7/dzPmcjLhijLi8jM2NAIA "Retina – Try It Online") Link includes test cases. Takes input as the letter `F`, `B`, `Z` or `N` followed by the number `n`. Explanation:
```
L$`^.
```
Match the letter. At this point, `$'` refers to the number `n` following it.
```
$'*$&¶$'*$(NNFNBFNNFBNFNNZ
```
Repeat the letter `n` times, then on the next line repeat the Fizz Buzz sequence `15n` times.
```
L$`(.)+¶(?<-1>.*?\1)+
```
Match `n` copies of the letter on the first line, and use those to find the `n`th match of the letter on the second line.
```
$.>%`
```
Output the offset (`.``) of the end (`>`) of the match relative to the start of the second line (`%`).
[Answer]
# [Desmos](https://desmos.com/calculator), ~~112~~ 99 bytes
Input into the function \$f(n,k)\$, where \$n\$ is the number, and \$k\$ is the word.
Number = 0, Fizz = 3, Buzz = 5, FizzBuzz = 15
```
h(n)=floor(n)
a=mod(n-1,8)
f(n,k)=\{k=0:15h(n/8-1/8)+2a+h(2a/5+1)-h(a/3+2/3),k=15:kn,kn+kh(kn/15)\}
```
[Try It On Desmos!](https://www.desmos.com/calculator/nibnotpzok)
[Try It On Desmos! - Prettified](https://www.desmos.com/calculator/tajkd7nadz)
Uses formula in [OEIS A229829](http://oeis.org/A229829):
`a(n) = 15*floor((n-1)/8) +2*f(n) +floor((2*f(n)+5)/5) -floor((f(n)+2)/3), where f(n) = (n-1) mod 8.`
99.99% sure this could be golfed. Maybe I could shorten the OEIS formula somehow.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
!¥⁰m⌋15N
```
[Try it online!](https://tio.run/##yygtzv7/X/HQ0keNG3If9XQbmvr9///f@L8pAA "Husk – Try It Online")
Input as `1`=number, `3`=Fizz, `5`=Buzz, `15`=FizzBuzz. Same approach as [Lynn's comment to caird coinheringaahing's answer](https://codegolf.stackexchange.com/a/239706/95126).
---
Alternative versions with successively less pre-processing squeezed into the values chosen as input:
**12 bytes**, with input as `[0,0]`=number, `[1,0]`=Fizz, `[0,1]`=Buzz & `[1,1]`=FizzBuzz.
```
!fo≡⁰§e¦3¦5N
```
[Try it online!](https://tio.run/##ASMA3P9odXNr//8hZm/iiaHigbDCp2XCpjPCpjVO////WzEsMF3/NQ)
The [Husk](https://github.com/barbuz/Husk) `congr` command - `≡` - checks whether two lists have the same distribution of truthy/falsy elements: in this case, divisibility (`¦`) by `3` and `5`.
or **14 bytes**, finally with input just as `0`=number, `1`=Fizz, `2`=Buzz & `3`=FizzBuzz.
```
!¥mȯḋm¬§e%5%3N
```
[Try it online!](https://tio.run/##ASMA3P9odXNr//8hZm/iiaHigbDCp2XCpjPCpjVO////WzEsMF3/NQ)
Treats list of not-modulo (`¬` & `%`) 3 or 5 as binary digits (`ḋ`).
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
15ġ⁰=)ȯt
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiMTXEoeKBsD0pyK90IiwiIiwiMywgM1xuNCwgNVxuMiwgMTVcbjMxMiwgMSJd)
Port of the other answers.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 22 bytes
```
I⊕§⌕A×”{⊞‴¡*RX⭆eR”NS⊖θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMM5sbhEwzMvuSg1NzWvJDVFw7HEMy8ltULDLTMvxTEnRyMkMze1WEPJz8/Nz8kNSDoBGX5RSjoKnnkFpSV@pblJqUUamppQfnAJ0NR0MN8lFWFooSYIWP//b2xopOD3X7csBwA "Charcoal – Try It Online") Link is to verbose version of code. Takes the number as the first input and one of the letters `F`, `B`, `Z` or `N` as the second input. Explanation:
```
... Compressed string `NNFNBFNNFBNFNNZ`
× Repeated by
N First input as a number
⌕A Find all indices of
S Second input
§ Indexed by
θ First input
⊖ Decremented
⊕ Incremented
I Cast to string
Implicitly print
```
] |
[Question]
[
On Math Stack Exchange, I asked a question about the [smallest region that can contain all free n-ominos](https://math.stackexchange.com/q/2831675/121988).
I'd like to add this sequence to the [On-Line Encyclopedia of Integer Sequences](https://oeis.org/) once I have more terms.
# Example
A nine-cell region is the smallest subset of the plane that can contain all twelve free [5-ominoes](https://en.wikipedia.org/wiki/Pentomino), as illustrated below. (A free polyomino is one that can be rotated and flipped.)
[](https://i.stack.imgur.com/Rq4ro.png)
(A twelve-cell region is the smallest subset of the plane the can contain all 35 free [6-ominoes](https://en.wikipedia.org/wiki/Hexomino).)
---
# The Challenge
Compute upper bounds on the smallest regions of the plane that can contain all n-ominoes as a function of n.
Such a table begins:
```
n | size
--+-------
1 | 1*
2 | 2*
3 | 4*
4 | 6*
5 | 9*
6 | 12*
7 | 37
8 | 50
9 | 65
*These values are the smallest possible.
```
---
# Example submission
```
1-omino: 1
#
2-omino: 2
##
3-omino: 4
###
#
4-omino: 6
####
##
5-omino: 9
#
#####
###
6-omino: 12
####
######
##
7-omino: <= 37
#######
######
######
######
######
######
```
---
# Scoring
Run your program for as long as you'd like, and post your list of upper bounds together with the shapes that achieve each.
The winner will be the participant whose table is lexicographically the earliest (with "infinity" appended to the shorter submissions.) If two participants submit the same results, then the earlier submission wins.
For example, if the submissions are
```
Aliyah: [1,2,4,6,12,30,50]
Brian: [1,2,4,6,12,37,49,65]
Clare: [1,2,4,6,12,30]
```
then Aliyah wins. She beats Brian because 30 < 37, and she beats Clare because 50 < infinity.
[Answer]
## C# and SAT: 1, 2, 4, 6, 9, 12, 17, 20, 26, 31, 37, 43
If we limit the bounding box, there is a fairly obvious expression of the problem in terms of [SAT](https://en.wikipedia.org/wiki/Boolean_satisfiability_problem): each translation of each orientation of each free polyomino is a large conjunction; for each polyomino we form a disjunction over its conjunctions; and then we require each disjunction to be true and the total number of cells used to be limited.
To limit the number of cells my initial version built a full adder; then I used bitonic sort for unary counting (similar to [this earlier answer](https://codegolf.stackexchange.com/a/45477/194) but generalised); finally I settled on the approach described by Bailleux and Boufkhad in [Efficient CNF encoding of Boolean cardinality constraints](http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.458.7676&rep=rep1&type=pdf).
I wanted to make the post self-contained, so I dug out a C# implementation of a SAT solver with a BSD licence which was state-of-the-art about 15 years ago, replaced its NIH list implementation with `System.Collections.Generic.List<T>` (gaining a factor of 2 in speed), golfed it from 50kB down to 31kB to fit in the 64kB post limit, and then did some aggressive work on reducing memory usage. This code can obviously be adapted to output a DIMACS file which can then be passed to more modern solvers.
## Solutions found
```
#
##
###
..#
####
.##.
..#..
#####
..###
.####.
######
.##...
....#..
#######
#####..
.####..
########
..######
.....###
.....###
#########
#######..
..#####..
....##...
....###..
##########
########..
..######..
....####..
.....###..
..#######..
..#########
###########
..####.....
..####.....
..##.......
...#######..
...#########
############
..#####....#
..#####.....
...####.....
```
To find 43 for n=12 took a bit over 7.5 hours.
### Polyomino code
```
using MiniSAT;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace PPCG167484
{
internal class SatGenerator
{
public static void Main()
{
for (int n = 1; n < 13; n++)
{
int width = n;
int height = (n + 1) >> 1;
var polys = FreePolyomino.All(n);
(var solver, var unaryWeights) = Generate(polys, width, height);
int previous = width * height + 1;
while (true)
{
Stopwatch sw = new Stopwatch(); sw.Start();
if (solver.Solve())
{
// The weight of the solution might be smaller than the target
int weight = Enumerable.Range(0, width * height).Count(x => solver.Model[x] == Solver.l_True);
Console.Write($"{n}\t<={weight}\t{sw.Elapsed.TotalSeconds:F3}s\t");
int cell = 0;
for (int y = 0; y < height; y++)
{
if (y > 0) Console.Write('_');
for (int x = 0; x < width; x++) Console.Write(solver.Model[cell++] == Solver.l_True ? '#' : '.');
}
Console.WriteLine();
// Now knock out that weight
for (int i = weight - 1; i < previous - 1; i++) solver.AddClause(~unaryWeights[i]);
previous = weight;
}
else
{
Console.WriteLine("--------");
break;
}
}
}
}
public static Tuple<Solver, Solver.Lit[]> Generate(IEnumerable<FreePolyomino> polys, int width, int height)
{
var solver = new Solver();
if (width == 12) solver.Prealloc(6037071 + 448, 72507588 + 6008); // HACK!
// Variables: 0 to width * height - 1 are the cells available to fill.
for (int i = 0; i < width * height; i++) solver.NewVar();
foreach (var poly in polys)
{
// We naturally get a DNF: each position of each orientation is a conjunction of poly.Weight variables,
// and we require any one. Therefore we add an auxiliary variable per.
var polyAuxs = new List<Solver.Lit>();
foreach (var orientation in poly.OrientedPolyominos)
{
int maxh = height;
// Optimisation: break symmetry
if (orientation.BBHeight == 1) maxh = ((height + 1) >> 1);
for (int dy = 0; dy + orientation.BBHeight <= maxh; dy++)
{
for (int dx = 0; dx + orientation.BBWidth <= width; dx++)
{
var currentAux = solver.NewVar();
for (int y = 0; y < orientation.BBHeight; y++)
{
uint tmp = orientation.Rows[y];
for (int x = 0; tmp > 0; x++, tmp >>= 1)
{
if ((tmp & 1) == 1) solver.AddClause(~currentAux, new Solver.Lit((y + dy) * width + x + dx));
}
}
polyAuxs.Add(currentAux);
}
}
}
solver.AddClause(polyAuxs.ToArray());
}
// Efficient CNF encoding of Boolean cardinality constraints, Bailleux and Boufkhad, http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.458.7676&rep=rep1&type=pdf
var unaryWeights = _BBSum(0, width * height, solver);
return Tuple.Create(solver, unaryWeights);
}
private static Solver.Lit[] _BBSum(int from, int num, Solver solver)
{
var sum = new Solver.Lit[num];
if (num == 1) sum[0] = new Solver.Lit(from);
else
{
var left = _BBSum(from, num >> 1, solver);
var right = _BBSum(from + left.Length, num - left.Length, solver);
for (int i = 0; i < num; i++) sum[i] = solver.NewVar();
for (int alpha = 0; alpha <= left.Length; alpha++)
{
for (int beta = 0; beta <= right.Length; beta++)
{
var sigma = alpha + beta;
// C_1 = ~left[alpha-1] + ~right[beta-1] + sum[sigma-1]
if (alpha > 0 && beta > 0) solver.AddClause(~left[alpha - 1], ~right[beta - 1], sum[sigma - 1]);
else if (alpha > 0) solver.AddClause(~left[alpha - 1], sum[sigma - 1]);
else if (beta > 0) solver.AddClause(~right[beta - 1], sum[sigma - 1]);
// C_2 = left[alpha] + right[beta] + ~sum[sigma]
if (alpha < left.Length && beta < right.Length) solver.AddClause(left[alpha], right[beta], ~sum[sigma]);
else if (alpha < left.Length) solver.AddClause(left[alpha], ~sum[sigma]);
else if (beta < right.Length) solver.AddClause(right[beta], ~sum[sigma]);
}
}
}
return sum;
}
}
class FreePolyomino : IEquatable<FreePolyomino>
{
internal FreePolyomino(OrientedPolyomino orientation)
{
var orientations = new HashSet<OrientedPolyomino>();
orientations.Add(orientation);
var tmp = orientation.Rot90(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
tmp = tmp.FlipV(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
OrientedPolyominos = orientations.OrderBy(x => x).ToArray();
}
public IReadOnlyList<OrientedPolyomino> OrientedPolyominos { get; private set; }
public OrientedPolyomino CanonicalOrientation => OrientedPolyominos[0];
public static IEnumerable<FreePolyomino> All(int numCells)
{
if (numCells < 1) throw new ArgumentOutOfRangeException(nameof(numCells));
if (numCells == 1) return new FreePolyomino[] { new FreePolyomino(OrientedPolyomino.Unit) };
// We do this in two phases because identifying two equal oriented polyominos is faster than first building
// free polyominos and then identifying that they're equal.
var oriented = new HashSet<OrientedPolyomino>();
foreach (var smaller in All(numCells - 1))
{
// We can add a cell to a side. The easiest way to do this is to add to the bottom of one of the rotations.
// TODO Optimise by distinguishing the symmetries.
foreach (var orientation in smaller.OrientedPolyominos)
{
int h = orientation.BBHeight;
var bottomRow = orientation.Rows[h - 1];
for (int deltax = 0; deltax < orientation.BBWidth; deltax++)
{
if (((bottomRow >> deltax) & 1) == 1)
{
var rows = orientation.Rows.Concat(Enumerable.Repeat(1U << deltax, 1)).ToArray();
oriented.Add(new OrientedPolyomino(rows));
}
}
}
// We can add a cell in the middle, provided it connects up.
var canon = smaller.CanonicalOrientation;
uint prev = 0, curr = 0, next = canon.Rows[0];
for (int y = 0; y < canon.BBHeight; y++)
{
(prev, curr, next ) = (curr, next, y + 1 < canon.BBHeight ? canon.Rows[y + 1] : 0);
uint valid = (prev | next | (curr << 1) | (curr >> 1)) & ~curr;
for (int x = 0; x < canon.BBWidth; x++)
{
if (((valid >> x) & 1) == 1)
{
var rows = canon.Rows.ToArray(); // Copy
rows[y] |= 1U << x;
oriented.Add(new OrientedPolyomino(rows));
}
}
}
}
// Now cluster the oriented polyominos into equivalence classes under dihedral symmetry.
return new HashSet<FreePolyomino>(oriented.Select(orientation => new FreePolyomino(orientation)));
}
public bool Equals(FreePolyomino other) => other != null && CanonicalOrientation.Equals(other.CanonicalOrientation);
public override bool Equals(object obj) => Equals(obj as FreePolyomino);
public override int GetHashCode() => CanonicalOrientation.GetHashCode();
}
[DebuggerDisplay("{ToString()}")]
struct OrientedPolyomino : IComparable<OrientedPolyomino>, IEquatable<OrientedPolyomino>
{
public static readonly OrientedPolyomino Unit = new OrientedPolyomino(1);
public OrientedPolyomino(params uint[] rows)
{
if (rows.Length == 0) throw new ArgumentException("We don't support the empty polyomino", nameof(rows));
if (rows.Any(row => row == 0) || rows.All(row => (row & 1) == 0)) throw new ArgumentException("Polyomino is not packed into the corner", nameof(rows));
var colsUsed = rows.Aggregate(0U, (accum, row) => accum | row);
BBWidth = Helper.Width(colsUsed);
if (colsUsed != ((1U << BBWidth) - 1)) throw new ArgumentException("Polyomino has empty columns", nameof(rows));
Rows = rows;
}
public IReadOnlyList<uint> Rows { get; private set; }
public int BBWidth { get; private set; }
public int BBHeight => Rows.Count;
#region Dihedral symmetries
public OrientedPolyomino FlipV() => new OrientedPolyomino(Rows.Reverse().ToArray());
public OrientedPolyomino Rot90()
{
uint[] rot = new uint[BBWidth];
for (int y = 0; y < BBHeight; y++)
{
for (int x = 0; x < BBWidth; x++)
{
rot[x] |= ((Rows[y] >> x) & 1) << (BBHeight - 1 - y);
}
}
return new OrientedPolyomino(rot);
}
#endregion
#region Identity
public int CompareTo(OrientedPolyomino other)
{
// Favour wide-and-short orientations for the canonical one.
if (BBHeight != other.BBHeight) return BBHeight.CompareTo(other.BBHeight);
for (int i = 0; i < BBHeight; i++)
{
if (Rows[i] != other.Rows[i]) return Rows[i].CompareTo(other.Rows[i]);
}
return 0;
}
public bool Equals(OrientedPolyomino other) => CompareTo(other) == 0;
public override int GetHashCode() => Rows.Aggregate(0, (h, row) => h * 37 + (int)row);
public override bool Equals(object obj) => (obj is OrientedPolyomino other) && Equals(other);
public override string ToString()
{
var width = BBWidth;
return string.Join("_", Rows.Select(row => Helper.ToString(row, width)));
}
#endregion
}
static class Helper
{
public static int Width(uint x)
{
int w = 0;
if ((x >> 16) != 0) { w += 16; x >>= 16; }
if ((x >> 8) != 0) { w += 8; x >>= 8; }
if ((x >> 4) != 0) { w += 4; x >>= 4; }
if ((x >> 2) != 0) { w += 2; x >>= 2; }
switch (x)
{
case 0: break;
case 1: w++; break;
case 2:
case 3: w += 2; break;
default: throw new Exception("Unreachable code");
}
return w;
}
internal static string ToString(uint x, int width)
{
char[] chs = new char[width];
for (int i = 0; i < width; i++)
{
chs[i] = (char)('0' + (x & 1));
x >>= 1;
}
return new string(chs);
}
internal static uint Weight(uint v)
{
// https://graphics.stanford.edu/~seander/bithacks.html
v = v - ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
}
}
```
### SAT solver code
```
/******************************************************************************************
MiniSat -- Copyright (c) 2003-2005, Niklas Een, Niklas Sorensson
MiniSatCS -- Copyright (c) 2006-2007 Michal Moskal
GolfMiniSat -- Copyright (c) 2018 Peter Taylor
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and
associated documentation files (the "Software"), to deal in the Software without restriction,
including without limitation the rights to use, copy, modify, merge, publish, distribute,
sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or
substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT
NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
**************************************************************************************************/
using System;
using System.Diagnostics;
using System.Collections.Generic;
// NOTE! Variables are just integers. No abstraction here. They should be chosen from 0..N, so that they can be used as array indices.
using Var = System.Int32;
using System.Linq;
namespace MiniSAT
{
public static class Ext
{
private static int TargetCapacity(int size) =>
size < 65536 ? (size << 1) :
size < 1048576 ? (size + (size >> 1)) :
size + (size >> 2);
public static void Push<T>(this List<T> list, T elem)
{
// Similar to List<T>.Add but with a slower growth rate for large lists
if (list.Count == list.Capacity) list.Capacity = TargetCapacity(list.Count + 1);
list.Add(elem);
}
public static void Pop<T>(this List<T> list) => list.RemoveAt(list.Count - 1);
public static T Peek<T>(this List<T> list) => list[list.Count - 1];
public static void GrowTo<T>(this List<T> list, int size, T pad)
{
if (size > list.Count)
{
// Minimise resizing
if (size > list.Capacity) list.Capacity = size;
while (list.Count < size) list.Add(pad);
}
}
public static void ShrinkTo<T>(this List<T> list, int size)
{
list.RemoveRange(size, list.Count - size);
int targetCap = TargetCapacity(size);
if (list.Capacity > targetCap) list.Capacity = targetCap;
}
}
public delegate bool IntLess(int i1, int i2);
public class Heap
{
IntLess Cmp;
List<int> Heap_ = new List<int>(); // heap of ints
List<int> Indices = new List<int>(); // index in Heap_
static int Left(int i) => i << 1;
static int Right(int i) => (i << 1) | 1;
static int Parent(int i) => i >> 1;
void UpHead(int i)
{
int x = Heap_[i];
while (Parent(i) != 0 && Cmp(x, Heap_[Parent(i)]))
{
Heap_[i] = Heap_[Parent(i)];
Indices[Heap_[i]] = i;
i = Parent(i);
}
Heap_[i] = x;
Indices[x] = i;
}
void DownHeap(int i)
{
int x = Heap_[i];
while (Left(i) < Heap_.Count)
{
int child = Right(i) < Heap_.Count && Cmp(Heap_[Right(i)], Heap_[Left(i)]) ? Right(i) : Left(i);
if (!Cmp(Heap_[child], x)) break;
Heap_[i] = Heap_[child];
Indices[Heap_[i]] = i;
i = child;
}
Heap_[i] = x;
Indices[x] = i;
}
bool Ok(int n) => n >= 0 && n < Indices.Count;
public Heap(IntLess c) { Cmp = c; Heap_.Add(-1); }
public void SetBounds(int size) { Solver.Assert(size >= 0); Indices.GrowTo(size, 0); if (size > Heap_.Capacity) Heap_.Capacity = size; }
public bool InHeap(int n) { Solver.Assert(Ok(n)); return Indices[n] != 0; }
public void Increase(int n) { Solver.Assert(Ok(n)); Solver.Assert(InHeap(n)); UpHead(Indices[n]); }
public bool IsEmpty => Heap_.Count == 1;
public void Push(int n)
{
Solver.Assert(Ok(n));
Indices[n] = Heap_.Count;
Heap_.Add(n);
UpHead(Indices[n]);
}
public int Pop()
{
int r = Heap_[1];
Heap_[1] = Heap_.Peek();
Indices[Heap_[1]] = 1;
Indices[r] = 0;
Heap_.Pop();
if (Heap_.Count > 1) DownHeap(1);
return r;
}
}
public class Solver
{
#region lbool ~= Nullable<bool>
public struct LBool
{
public static readonly LBool True = new LBool { Content = 1 };
public static readonly LBool False = new LBool { Content = -1 };
public static readonly LBool Undef = new LBool { Content = 0 };
private sbyte Content;
public static bool operator ==(LBool a, LBool b) => a.Content == b.Content;
public static bool operator !=(LBool a, LBool b) => a.Content != b.Content;
public static LBool operator ~(LBool a) => new LBool { Content = (sbyte)-a.Content };
public static implicit operator LBool(bool b) => b ? True : False;
}
public static readonly LBool l_True = LBool.True;
public static readonly LBool l_False = LBool.False;
public static readonly LBool l_Undef = LBool.Undef;
#endregion
#region Literals
const int var_Undef = -1;
public struct Lit
{
public Lit(Var var) { Index = var << 1; }
public bool Sign => (Index & 1) != 0;
public int Index { get; private set; }
public int Var => Index >> 1;
public bool SatisfiedBy(List<LBool> assignment) => assignment[Var] == (Sign ? l_False : l_True);
public static Lit operator ~(Lit p) => new Lit { Index = p.Index ^ 1 };
public static bool operator ==(Lit p, Lit q) => p.Index == q.Index;
public static bool operator !=(Lit p, Lit q) => !(p == q);
public override int GetHashCode() => Index;
public override bool Equals(object other) => other is Lit that && this == that;
public override string ToString() => (Sign ? "-" : "") + "x" + Var;
}
static public readonly Lit lit_Undef = ~new Lit(var_Undef);
#endregion
#region Clauses
public abstract class Clause
{
protected Clause(bool learnt)
{
IsLearnt = learnt;
}
public bool IsLearnt { get; private set; }
public float Activity;
public abstract int Size { get; }
public abstract Lit this[int i] { get;set; }
public abstract bool SatisfiedBy(List<LBool> assigns);
public static Clause Create(bool learnt, List<Lit> ps)
{
if (ps.Count < 2) throw new ArgumentOutOfRangeException(nameof(ps));
if (ps.Count == 2) return new BinaryClause(learnt, ps[0], ps[1]);
return new LargeClause(learnt, ps);
}
}
public class BinaryClause : Clause
{
public BinaryClause(bool learnt, Lit p0, Lit p1) : base(learnt)
{
l0 = p0; l1 = p1;
}
private Lit l0;
private Lit l1;
public override Lit this[int i]
{
get { return i == 0 ? l0 : l1; }
set { if (i == 0) l0 = value; else l1 = value; }
}
public override int Size => 2;
public override bool SatisfiedBy(List<LBool> assigns) => l0.SatisfiedBy(assigns) || l1.SatisfiedBy(assigns);
}
public class LargeClause : Clause
{
public static int[] SizeDistrib = new int[10];
internal LargeClause(bool learnt, List<Lit> ps) : base(learnt)
{
Data = ps.ToArray();
SizeDistrib[Size >= SizeDistrib.Length ? SizeDistrib.Length - 1 : Size]++;
}
public Lit[] Data { get; private set; }
public override int Size => Data.Length;
public override Lit this[int i]
{
get { return Data[i]; }
set { Data[i] = value; }
}
public override bool SatisfiedBy(List<LBool> assigns) => Data.Any(lit => lit.SatisfiedBy(assigns));
public override string ToString() => "[" + string.Join(", ", Data) + "]";
}
#endregion
#region Utilities
// Returns a random float 0 <= x < 1. Seed must never be 0.
static double Rnd(ref double seed)
{
seed *= 1389796;
int k = 2147483647;
int q = (int)(seed / k);
seed -= (double)q * k;
return seed / k;
}
[Conditional("DEBUG")]
static public void Assert(bool expr) => Check(expr);
// Just like 'assert()' but expression will be evaluated in the release version as well.
static void Check(bool expr) { if (!expr) throw new Exception("assertion violated"); }
#endregion
#region VarOrder
public class VarOrder
{
readonly List<LBool> Assigns; // Pointer to external assignment table.
readonly List<float> Activity; // Pointer to external activity table.
internal Heap Heap_;
double RandomSeed;
public VarOrder(List<LBool> ass, List<float> act)
{
Assigns = ass;
Activity = act;
Heap_ = new Heap(Lt);
RandomSeed = 91648253;
}
bool Lt(Var x, Var y) => Activity[x] > Activity[y];
public virtual void NewVar()
{
Heap_.SetBounds(Assigns.Count);
Heap_.Push(Assigns.Count - 1);
}
// Called when variable increased in activity.
public virtual void Update(Var x) { if (Heap_.InHeap(x)) Heap_.Increase(x); }
// Called when variable is unassigned and may be selected again.
public virtual void Undo(Var x) { if (!Heap_.InHeap(x)) Heap_.Push(x); }
// Selects a new, unassigned variable (or 'var_Undef' if none exists).
public virtual Lit Select(double random_var_freq)
{
// Random decision:
if (Rnd(ref RandomSeed) < random_var_freq && !Heap_.IsEmpty)
{
Var next = (Var)(Rnd(ref RandomSeed) * Assigns.Count);
if (Assigns[next] == l_Undef) return ~new Lit(next);
}
// Activity based decision:
while (!Heap_.IsEmpty)
{
Var next = Heap_.Pop();
if (Assigns[next] == l_Undef) return ~new Lit(next);
}
return lit_Undef;
}
}
#endregion
#region Solver state
public bool Ok { get; private set; } // If false, the constraints are already unsatisfiable. No part of the solver state may be used!
List<Clause> Clauses = new List<Clause>(); // List of problem clauses.
List<Clause> Learnts = new List<Clause>(); // List of learnt clauses.
double ClaInc = 1; // Amount to bump next clause with.
const double ClaDecay = 1 / 0.999; // INVERSE decay factor for clause activity: stores 1/decay.
public List<float> Activity = new List<float>(); // A heuristic measurement of the activity of a variable.
float VarInc = 1; // Amount to bump next variable with.
const float VarDecay = 1 / 0.95f; // INVERSE decay factor for variable activity: stores 1/decay. Use negative value for static variable order.
VarOrder Order; // Keeps track of the decision variable order.
const double RandomVarFreq = 0.02;
List<List<Clause>> Watches = new List<List<Clause>>(); // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
public List<LBool> Assigns = new List<LBool>(); // The current assignments.
public List<Lit> Trail = new List<Lit>(); // Assignment stack; stores all assigments made in the order they were made.
List<int> TrailLim = new List<int>(); // Separator indices for different decision levels in 'trail'.
List<Clause> Reason = new List<Clause>(); // 'reason[var]' is the clause that implied the variables current value, or 'null' if none.
List<int> Level = new List<int>(); // 'level[var]' is the decision level at which assignment was made.
List<int> TrailPos = new List<int>(); // 'trail_pos[var]' is the variable's position in 'trail[]'. This supersedes 'level[]' in some sense, and 'level[]' will probably be removed in future releases.
int QHead = 0; // Head of queue (as index into the trail -- no more explicit propagation queue in MiniSat).
int SimpDBAssigns = 0; // Number of top-level assignments since last execution of 'simplifyDB()'.
long SimpDBProps = 0; // Remaining number of propagations that must be made before next execution of 'simplifyDB()'.
// Temporaries (to reduce allocation overhead)
List<LBool> AnalyzeSeen = new List<LBool>();
List<Lit> AnalyzeStack = new List<Lit>();
List<Lit> AnalyzeToClear = new List<Lit>();
#endregion
#region Main internal methods:
// Activity
void VarBumpActivity(Lit p)
{
if (VarDecay < 0) return; // (negative decay means static variable order -- don't bump)
if ((Activity[p.Var] += VarInc) > 1e100) VarRescaleActivity();
Order.Update(p.Var);
}
void VarDecayActivity() { if (VarDecay >= 0) VarInc *= VarDecay; }
void ClaDecayActivity() { ClaInc *= ClaDecay; }
// Operations on clauses
void ClaBumpActivity(Clause c) { if ((c.Activity += (float)ClaInc) > 1e20) ClaRescaleActivity(); }
// Disposes of clause and removes it from watcher lists. NOTE! Low-level; does NOT change the 'clauses' and 'learnts' vector.
void Remove(Clause c)
{
RemoveWatch(Watches[(~c[0]).Index], c);
RemoveWatch(Watches[(~c[1]).Index], c);
if (c.IsLearnt) LearntsLiterals -= c.Size;
else ClausesLiterals -= c.Size;
}
bool IsLocked(Clause c) => c == Reason[c[0].Var];
int DecisionLevel => TrailLim.Count;
#endregion
#region Public interface
public Solver()
{
Ok = true;
Order = new VarOrder(Assigns, Activity);
}
public void Prealloc(int numVars, int numClauses)
{
Activity.Capacity = numVars;
AnalyzeSeen.Capacity = numVars;
Assigns.Capacity = numVars;
Level.Capacity = numVars;
Reason.Capacity = numVars;
Watches.Capacity = numVars << 1;
Order.Heap_.SetBounds(numVars + 1);
Trail.Capacity = numVars;
TrailPos.Capacity = numVars;
Clauses.Capacity = numClauses;
}
// Helpers (semi-internal)
public LBool Value(Lit p) => p.Sign ? ~Assigns[p.Var] : Assigns[p.Var];
public int nAssigns => Trail.Count;
public int nClauses => Clauses.Count;
public int nLearnts => Learnts.Count;
// Statistics
public long ClausesLiterals, LearntsLiterals;
// Problem specification
public int nVars => Assigns.Count;
public void AddClause(params Lit[] ps) => NewClause(new List<Lit>(ps), false);
// Solving
public List<LBool> Model = new List<LBool>(); // If problem is satisfiable, this vector contains the model (if any).
#endregion
#region Operations on clauses:
List<Lit> BasicClauseSimplification(List<Lit> ps)
{
List<Lit> qs = new List<Lit>(ps);
var dict = new Dictionary<Var, Lit>(qs.Count);
int ptr = 0;
for (int i = 0; i < qs.Count; i++)
{
Lit l = qs[i];
Var v = l.Var;
if (dict.TryGetValue(v, out var other))
{
if (other != l) return null; // other = ~l, so always satisfied
}
else
{
dict[v] = l;
qs[ptr++] = l;
}
}
qs.ShrinkTo(ptr);
return qs;
}
void NewClause(List<Lit> ps, bool learnt)
{
if (!Ok) return;
Assert(ps != null);
if (!learnt)
{
Assert(DecisionLevel == 0);
ps = BasicClauseSimplification(ps);
if (ps == null) return;
int j = 0;
for (int i = 0; i < ps.Count; i++)
{
var lit = ps[i];
if (Level[lit.Var] == 0)
{
if (Value(lit) == l_True) return; // Clause already sat
if (Value(lit) == l_False) continue; // Literal already eliminated
}
ps[j++] = lit;
}
ps.ShrinkTo(j);
}
// 'ps' is now the (possibly) reduced vector of literals.
if (ps.Count == 0) Ok = false;
else if (ps.Count == 1)
{
if (!Enqueue(ps[0], null)) Ok = false;
}
else
{
var c = Clause.Create(learnt, ps);
if (!learnt)
{
Clauses.Add(c);
ClausesLiterals += c.Size;
}
else
{
// Put the second watch on the literal with highest decision level:
int max_i = 1;
int max = Level[ps[1].Var];
for (int i = 2; i < ps.Count; i++)
if (Level[ps[i].Var] > max)
{
max = Level[ps[i].Var];
max_i = i;
}
c[1] = ps[max_i];
c[max_i] = ps[1];
Check(Enqueue(c[0], c));
// Bumping:
ClaBumpActivity(c); // (newly learnt clauses should be considered active)
Learnts.Push(c);
LearntsLiterals += c.Size;
}
// Watch clause:
Watches[(~c[0]).Index].Push(c);
Watches[(~c[1]).Index].Push(c);
}
}
// Can assume everything has been propagated! (esp. the first two literals are != l_False, unless
// the clause is binary and satisfied, in which case the first literal is true)
bool IsSatisfied(Clause c)
{
Assert(DecisionLevel == 0);
return c.SatisfiedBy(Assigns);
}
#endregion
#region Minor methods
static bool RemoveWatch(List<Clause> ws, Clause elem) // Pre-condition: 'elem' must exists in 'ws' OR 'ws' must be empty.
{
if (ws.Count == 0) return false; // (skip lists that are already cleared)
int j = 0;
for (; ws[j] != elem; j++) Assert(j < ws.Count - 1);
for (; j < ws.Count - 1; j++) ws[j] = ws[j + 1];
ws.Pop();
return true;
}
public Lit NewVar()
{
int index = nVars;
Watches.Add(new List<Clause>()); // (list for positive literal)
Watches.Add(new List<Clause>()); // (list for negative literal)
Reason.Add(null);
Assigns.Add(l_Undef);
Level.Add(-1);
TrailPos.Add(-1);
Activity.Add(0);
Order.NewVar();
AnalyzeSeen.Add(l_Undef);
return new Lit(index);
}
// Returns FALSE if immediate conflict.
bool Assume(Lit p)
{
TrailLim.Add(Trail.Count);
return Enqueue(p, null);
}
// Revert to the state at given level.
void CancelUntil(int level)
{
if (DecisionLevel > level)
{
for (int c = Trail.Count - 1; c >= TrailLim[level]; c--)
{
Var x = Trail[c].Var;
Assigns[x] = l_Undef;
Reason[x] = null;
Order.Undo(x);
}
Trail.RemoveRange(TrailLim[level], Trail.Count - TrailLim[level]);
TrailLim.ShrinkTo(level);
QHead = Trail.Count;
}
}
#endregion
#region Major methods:
int Analyze(Clause confl, List<Lit> out_learnt)
{
List<LBool> seen = AnalyzeSeen;
int pathC = 0;
Lit p = lit_Undef;
// Generate conflict clause
out_learnt.Push(lit_Undef); // (placeholder for the asserting literal)
var out_btlevel = 0;
int index = Trail.Count - 1;
do
{
Assert(confl != null); // (otherwise should be UIP)
if (confl.IsLearnt) ClaBumpActivity(confl);
for (int j = (p == lit_Undef) ? 0 : 1; j < confl.Size; j++)
{
Lit q = confl[j];
var v = q.Var;
if (seen[v] == l_Undef && Level[v] > 0)
{
VarBumpActivity(q);
seen[v] = l_True;
if (Level[v] == DecisionLevel) pathC++;
else
{
out_learnt.Push(q);
out_btlevel = Math.Max(out_btlevel, Level[v]);
}
}
}
// Select next clause to look at
while (seen[Trail[index--].Var] == l_Undef) ;
p = Trail[index + 1];
confl = Reason[p.Var];
seen[p.Var] = l_Undef;
pathC--;
} while (pathC > 0);
out_learnt[0] = ~p;
// Conflict clause minimization
{
uint min_level = 0;
for (int i = 1; i < out_learnt.Count; i++) min_level |= (uint)(1 << (Level[out_learnt[i].Var] & 31)); // (maintain an abstraction of levels involved in conflict)
AnalyzeToClear.Clear();
int j = 1;
for (int i = 1; i < out_learnt.Count; i++)
if (Reason[out_learnt[i].Var] == null || !AnalyzeRemovable(out_learnt[i], min_level)) out_learnt[j++] = out_learnt[i];
// Clean up
for (int jj = 0; jj < out_learnt.Count; jj++) seen[out_learnt[jj].Var] = l_Undef;
for (int jj = 0; jj < AnalyzeToClear.Count; jj++) seen[AnalyzeToClear[jj].Var] = l_Undef; // ('seen[]' is now cleared)
out_learnt.ShrinkTo(j);
}
return out_btlevel;
}
// Check if 'p' can be removed. 'min_level' is used to abort early if visiting literals at a level that cannot be removed.
bool AnalyzeRemovable(Lit p_, uint min_level)
{
Assert(Reason[p_.Var] != null);
AnalyzeStack.Clear(); AnalyzeStack.Add(p_);
int top = AnalyzeToClear.Count;
while (AnalyzeStack.Count > 0)
{
Clause c = Reason[AnalyzeStack.Peek().Var];
Assert(c != null);
AnalyzeStack.Pop();
for (int i = 1; i < c.Size; i++)
{
Lit p = c[i];
if (AnalyzeSeen[p.Var] == l_Undef && Level[p.Var] != 0)
{
if (Reason[p.Var] != null && ((1 << (Level[p.Var] & 31)) & min_level) != 0)
{
AnalyzeSeen[p.Var] = l_True;
AnalyzeStack.Push(p);
AnalyzeToClear.Push(p);
}
else
{
for (int j = top; j < AnalyzeToClear.Count; j++) AnalyzeSeen[AnalyzeToClear[j].Var] = l_Undef;
AnalyzeToClear.ShrinkTo(top);
return false;
}
}
}
}
AnalyzeToClear.Push(p_);
return true;
}
bool Enqueue(Lit p, Clause from)
{
if (Value(p) != l_Undef) return Value(p) == l_True;
Var x = p.Var;
Assigns[x] = !p.Sign;
Level[x] = DecisionLevel;
TrailPos[x] = Trail.Count;
Reason[x] = from;
Trail.Add(p);
return true;
}
Clause Propagate()
{
Clause confl = null;
while (QHead < Trail.Count)
{
SimpDBProps--;
Lit p = Trail[QHead++]; // 'p' is enqueued fact to propagate.
List<Clause> ws = Watches[p.Index];
int i, j, end;
for (i = j = 0, end = ws.Count; i != end;)
{
Clause c = ws[i++];
// Make sure the false literal is data[1]
Lit false_lit = ~p;
if (c[0] == false_lit) { c[0] = c[1]; c[1] = false_lit; }
Assert(c[1] == false_lit);
// If 0th watch is true, then clause is already satisfied.
Lit first = c[0];
LBool val = Value(first);
if (val == l_True) ws[j++] = c;
else
{
// Look for new watch
for (int k = 2; k < c.Size; k++)
if (Value(c[k]) != l_False)
{
c[1] = c[k]; c[k] = false_lit;
Watches[(~c[1]).Index].Push(c);
goto FoundWatch;
}
// Did not find watch -- clause is unit under assignment
ws[j++] = c;
if (!Enqueue(first, c))
{
if (DecisionLevel == 0) Ok = false;
confl = c;
QHead = Trail.Count;
while (i < end) ws[j++] = ws[i++]; // Copy the remaining watches
}
FoundWatch:;
}
}
ws.ShrinkTo(j);
}
return confl;
}
void ReduceDB()
{
double extra_lim = ClaInc / Learnts.Count; // Remove any clause below this activity
Learnts.Sort((x, y) => x.Size > 2 && (y.Size == 2 || x.Activity < y.Activity) ? -1 : 1);
int i, j;
for (i = j = 0; i < Learnts.Count / 2; i++)
{
if (Learnts[i].Size > 2 && !IsLocked(Learnts[i])) Remove(Learnts[i]);
else Learnts[j++] = Learnts[i];
}
for (; i < Learnts.Count; i++)
{
if (Learnts[i].Size > 2 && !IsLocked(Learnts[i]) && Learnts[i].Activity < extra_lim) Remove(Learnts[i]);
else Learnts[j++] = Learnts[i];
}
Learnts.ShrinkTo(j);
}
void SimplifyDB()
{
if (!Ok) return;
Assert(DecisionLevel == 0);
if (Propagate() != null) { Ok = false; return; }
if (nAssigns == SimpDBAssigns || SimpDBProps > 0) return; // (nothing has changed or performed a simplification too recently)
// Clear watcher lists:
for (int i = SimpDBAssigns; i < nAssigns; i++)
{
Lit p = Trail[i];
Watches[p.Index].Clear();
Watches[(~p).Index].Clear();
}
// Remove satisfied clauses:
for (int type = 0; type < 2; type++)
{
List<Clause> cs = type != 0 ? Learnts : Clauses;
int j = 0;
for (int i = 0; i < cs.Count; i++)
{
if (!IsLocked(cs[i]) && IsSatisfied(cs[i])) Remove(cs[i]);
else cs[j++] = cs[i];
}
cs.ShrinkTo(j);
}
SimpDBAssigns = nAssigns;
SimpDBProps = ClausesLiterals + LearntsLiterals;
}
LBool Search(int nof_conflicts, int nof_learnts)
{
if (!Ok) return l_False;
Assert(0 == DecisionLevel);
int conflictC = 0;
Model.Clear();
while (true)
{
Clause confl = Propagate();
if (confl != null)
{
// CONFLICT
conflictC++;
var learnt_clause = new List<Lit>();
if (DecisionLevel == 0) return l_False; // Contradiction found
CancelUntil(Analyze(confl, learnt_clause));
NewClause(learnt_clause, true);
if (learnt_clause.Count == 1) Level[learnt_clause[0].Var] = 0;
VarDecayActivity();
ClaDecayActivity();
}
else
{
// NO CONFLICT
if (nof_conflicts >= 0 && conflictC >= nof_conflicts)
{
// Reached bound on number of conflicts
CancelUntil(0);
return l_Undef;
}
// Simplify the set of problem clauses
if (DecisionLevel == 0) { SimplifyDB(); if (!Ok) return l_False; }
// Reduce the set of learnt clauses
if (nof_learnts >= 0 && Learnts.Count - nAssigns >= nof_learnts) ReduceDB();
// New variable decision
Lit next = Order.Select(RandomVarFreq);
if (next == lit_Undef)
{
// Model found
Model.Clear();
Model.Capacity = nVars;
Model.AddRange(Assigns);
CancelUntil(0);
return l_True;
}
Check(Assume(next));
}
}
}
void VarRescaleActivity()
{
for (int i = 0; i < nVars; i++) Activity[i] *= 1e-100f;
VarInc *= 1e-100f;
}
void ClaRescaleActivity()
{
for (int i = 0; i < Learnts.Count; i++) Learnts[i].Activity *= 1e-20f;
ClaInc *= 1e-20;
}
public bool Solve()
{
SimplifyDB();
Assert(DecisionLevel == 0);
double nof_conflicts = 100;
double nof_learnts = nClauses / 3;
while (true)
{
if (Search((int)nof_conflicts, (int)nof_learnts) != l_Undef)
{
CancelUntil(0);
return Ok;
}
nof_conflicts *= 1.5;
nof_learnts *= 1.1;
}
}
#endregion
}
}
```
### Optimality
The code above keeps reducing the target size until it finds an unsatisfiable constraint, so it guarantees that the output is optimal (under the bounding box assumption) up to and including \$n=11\$. However, it runs out of memory (3GB for a 32-bit process or 4GB for a 64-bit process) with \$n=12\$ after producing a region with weight 43.
To run the search for \$n=12\$ to completion I found it necessary to reduce the memory considerably, special-casing binary clauses and not keeping empty watch lists. However, by changing the order in which clauses are considered it changes the results, so I present the change as a patch and leave the list of solutions above untouched.
```
--- MiniSAT.cs.old
+++ MiniSAT.cs
@@ -346,6 +346,7 @@ namespace MiniSAT
const double RandomVarFreq = 0.02;
List<List<Clause>> Watches = new List<List<Clause>>(); // 'watches[lit]' is a list of constraints watching 'lit' (will go there if literal becomes true).
+ List<List<Lit>> BinaryWatches = new List<List<Lit>>();
public List<LBool> Assigns = new List<LBool>(); // The current assignments.
public List<Lit> Trail = new List<Lit>(); // Assignment stack; stores all assigments made in the order they were made.
List<int> TrailLim = new List<int>(); // Separator indices for different decision levels in 'trail'.
@@ -381,7 +382,9 @@ namespace MiniSAT
void Remove(Clause c)
{
RemoveWatch(Watches[(~c[0]).Index], c);
+ if (Watches[(~c[0]).Index] != null && Watches[(~c[0]).Index].Count == 0) Watches[(~c[0]).Index] = null;
RemoveWatch(Watches[(~c[1]).Index], c);
+ if (Watches[(~c[1]).Index] != null && Watches[(~c[1]).Index].Count == 0) Watches[(~c[1]).Index] = null;
if (c.IsLearnt) LearntsLiterals -= c.Size;
else ClausesLiterals -= c.Size;
@@ -408,6 +411,7 @@ namespace MiniSAT
Level.Capacity = numVars;
Reason.Capacity = numVars;
Watches.Capacity = numVars << 1;
+ BinaryWatches.Capacity = numVars << 1;
Order.Heap_.SetBounds(numVars + 1);
Trail.Capacity = numVars;
TrailPos.Capacity = numVars;
@@ -500,7 +504,7 @@ namespace MiniSAT
if (!learnt)
{
- Clauses.Add(c);
+ if (c.Size > 2) Clauses.Add(c);
ClausesLiterals += c.Size;
}
else
@@ -526,8 +530,20 @@ namespace MiniSAT
}
// Watch clause:
- Watches[(~c[0]).Index].Push(c);
- Watches[(~c[1]).Index].Push(c);
+ if (c.Size == 2 && !learnt)
+ {
+ if (BinaryWatches[(~c[0]).Index] == null) BinaryWatches[(~c[0]).Index] = new List<Lit>();
+ BinaryWatches[(~c[0]).Index].Push(c[1]);
+ if (BinaryWatches[(~c[1]).Index] == null) BinaryWatches[(~c[1]).Index] = new List<Lit>();
+ BinaryWatches[(~c[1]).Index].Push(c[0]);
+ }
+ else
+ {
+ if (Watches[(~c[0]).Index] == null) Watches[(~c[0]).Index] = new List<Clause>();
+ Watches[(~c[0]).Index].Push(c);
+ if (Watches[(~c[1]).Index] == null) Watches[(~c[1]).Index] = new List<Clause>();
+ Watches[(~c[1]).Index].Push(c);
+ }
}
}
@@ -545,7 +561,7 @@ namespace MiniSAT
static bool RemoveWatch(List<Clause> ws, Clause elem) // Pre-condition: 'elem' must exists in 'ws' OR 'ws' must be empty.
{
- if (ws.Count == 0) return false; // (skip lists that are already cleared)
+ if (ws == null || ws.Count == 0) return false; // (skip lists that are already cleared)
int j = 0;
for (; ws[j] != elem; j++) Assert(j < ws.Count - 1);
for (; j < ws.Count - 1; j++) ws[j] = ws[j + 1];
@@ -556,8 +572,10 @@ namespace MiniSAT
public Lit NewVar()
{
int index = nVars;
- Watches.Add(new List<Clause>()); // (list for positive literal)
- Watches.Add(new List<Clause>()); // (list for negative literal)
+ Watches.Add(null); // (list for positive literal)
+ Watches.Add(null); // (list for negative literal)
+ BinaryWatches.Add(null);
+ BinaryWatches.Add(null);
Reason.Add(null);
Assigns.Add(l_Undef);
Level.Add(-1);
@@ -716,45 +734,85 @@ namespace MiniSAT
SimpDBProps--;
Lit p = Trail[QHead++]; // 'p' is enqueued fact to propagate.
- List<Clause> ws = Watches[p.Index];
- int i, j, end;
- for (i = j = 0, end = ws.Count; i != end;)
{
- Clause c = ws[i++];
- // Make sure the false literal is data[1]
- Lit false_lit = ~p;
- if (c[0] == false_lit) { c[0] = c[1]; c[1] = false_lit; }
+ List<Clause> ws = Watches[p.Index];
+ if (ws != null)
+ {
+ int i, j, end;
+ for (i = j = 0, end = ws.Count; i != end;)
+ {
+ Clause c = ws[i++];
+ // Make sure the false literal is data[1]
+ Lit false_lit = ~p;
+ if (c[0] == false_lit) { c[0] = c[1]; c[1] = false_lit; }
- Assert(c[1] == false_lit);
+ Assert(c[1] == false_lit);
- // If 0th watch is true, then clause is already satisfied.
- Lit first = c[0];
- LBool val = Value(first);
- if (val == l_True) ws[j++] = c;
- else
- {
- // Look for new watch
- for (int k = 2; k < c.Size; k++)
- if (Value(c[k]) != l_False)
+ // If 0th watch is true, then clause is already satisfied.
+ Lit first = c[0];
+ LBool val = Value(first);
+ if (val == l_True) ws[j++] = c;
+ else
{
- c[1] = c[k]; c[k] = false_lit;
- Watches[(~c[1]).Index].Push(c);
- goto FoundWatch;
+ // Look for new watch
+ for (int k = 2; k < c.Size; k++)
+ if (Value(c[k]) != l_False)
+ {
+ c[1] = c[k]; c[k] = false_lit;
+ if (Watches[(~c[1]).Index] == null) Watches[(~c[1]).Index] = new List<Clause>();
+ Watches[(~c[1]).Index].Push(c);
+ goto FoundWatch;
+ }
+
+ // Did not find watch -- clause is unit under assignment
+ ws[j++] = c;
+ if (!Enqueue(first, c))
+ {
+ if (DecisionLevel == 0) Ok = false;
+ confl = c;
+ QHead = Trail.Count;
+ while (i < end) ws[j++] = ws[i++]; // Copy the remaining watches
+ }
+ FoundWatch:;
}
+ }
- // Did not find watch -- clause is unit under assignment
- ws[j++] = c;
- if (!Enqueue(first, c))
+ if (j == 0) Watches[p.Index] = null;
+ else ws.ShrinkTo(j);
+ }
+ }
+ // TODO BinaryWatches
+ {
+ List<Lit> ws = BinaryWatches[p.Index];
+ if (ws != null)
+ {
+ int i, j, end;
+ for (i = j = 0, end = ws.Count; i != end;)
{
- if (DecisionLevel == 0) Ok = false;
- confl = c;
- QHead = Trail.Count;
- while (i < end) ws[j++] = ws[i++]; // Copy the remaining watches
+ var first = ws[i++];
+
+ // If 0th watch is true, then clause is already satisfied.
+ LBool val = Value(first);
+ if (val == l_True) ws[j++] = first;
+ else
+ {
+ // Did not find watch -- clause is unit under assignment
+ ws[j++] = first;
+ var c = new BinaryClause(false, first, ~p); // Needed for consistency of interface
+ if (!Enqueue(first, c))
+ {
+ if (DecisionLevel == 0) Ok = false;
+ confl = c;
+ QHead = Trail.Count;
+ while (i < end) ws[j++] = ws[i++]; // Copy the remaining watches
+ }
+ }
}
- FoundWatch:;
+
+ if (j == 0) Watches[p.Index] = null;
+ else ws.ShrinkTo(j);
}
}
- ws.ShrinkTo(j);
}
return confl;
@@ -792,8 +850,10 @@ namespace MiniSAT
for (int i = SimpDBAssigns; i < nAssigns; i++)
{
Lit p = Trail[i];
- Watches[p.Index].Clear();
- Watches[(~p).Index].Clear();
+ Watches[p.Index] = null;
+ Watches[(~p).Index] = null;
+ BinaryWatches[p.Index] = null;
+ BinaryWatches[(~p).Index] = null;
}
// Remove satisfied clauses:
```
### Distinct solutions
Counting solutions to a SAT problem is straightforward, if sometimes slow: you find a solution, add a new clause which directly rules it out, and run again. Here it's easy to generate the equivalence class of solutions under the symmetries of the rectangle, so the following code suffices to generate all distinct solutions.
```
// Force it to the known optimal weight
for (int i = optimal[n]; i < unaryWeights.Length; i++) solver.AddClause(~unaryWeights[i]);
while (solver.Solve())
{
var rows = new uint[height];
int cell = 0;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
if (solver.Model[cell++] == Solver.l_True) rows[y] |= 1U << x;
}
}
var poly = new FreePolyomino(new OrientedPolyomino(rows));
Console.WriteLine(poly.CanonicalOrientation);
foreach (var orientation in poly.OrientedPolyominos)
{
if (orientation.BBWidth != width || orientation.BBHeight != height) continue;
// Exclude it
List<Solver.Lit> soln = new List<Solver.Lit>(previous);
cell = 0;
for (int y = 0; y < height; y++)
{
uint row = orientation.Rows[y];
for (int x = 0; x < width; x++, cell++)
{
if ((row & 1) == 1) soln.Add(~new Solver.Lit(cell));
row >>= 1;
}
}
solver.AddClause(soln.ToArray());
}
}
```
This may be useful for people to generate or test hypotheses about the "typical" structure which can guide searches for higher \$n\$.
```
100_111
010_111
0110_1111
1100_1111
01000_11111_01110
00100_11111_11100
011000_111111_011110
110000_111111_111100
011000_011110_111111
001100_111100_111111
110000_111100_111111
001100_111111_111100
0010000_0111100_0111110_1111111
0001000_1111000_1111111_1111100
0001000_0111000_1111111_1111110
0100000_1111000_1111111_1111100
0100000_1111000_1111100_1111111
0001000_0111000_1111110_1111111
0001000_0111110_1111111_1111000
0100000_1111000_0111110_1111111
0001000_1111100_1111111_1111000
1100000_1110000_1111100_1111111
0100000_1111111_1111100_0111100
0011000_0111000_0111110_1111111
1010000_1110000_1111100_1111111
0011000_1110000_1111100_1111111
0010100_0011100_1111100_1111111
0011000_1011100_1111111_1111000
0100000_1111111_0111110_0111100
1100000_1110000_1111111_1111100
0100000_1111100_1111111_0111100
1010000_1110000_1111111_1111100
1110000_0110000_1111111_0111110
0110000_1110000_1111100_1111111
0110000_1110000_1111111_1011110
0111000_0011000_1111111_0011111
0011100_0011000_1111111_0011111
1000100_1111111_0011110_0111100
0010000_1111111_0011111_0011110
0011000_0111000_1111111_0101111
0011000_0011101_1111111_0001111
0101000_0111000_0111110_1111111
0001000_0111100_1111100_1111111
1000100_1111111_0111100_0111100
0110000_1110000_1111111_1111100
1010000_1110000_1111111_0111110
0101000_0111000_1111111_0011111
0001000_1111111_1111100_1111000
0110000_0111010_1111111_0011110
0011000_0001110_0111110_1111111
0010000_1111111_0111110_0011110
0101000_0111000_1111111_0111110
0010000_1111100_1111111_0011110
0010000_0011100_1111111_1111110
0110000_0111000_1111111_0111110
0010000_0011100_1111111_0111111
0011000_0111010_1111111_0011110
0110000_1110100_1111111_0111100
0110000_0011100_1111100_1111111
0001000_0111100_1111111_1111100
0010000_0111100_1111111_1011110
0011000_0011100_1111111_1111100
0110000_0111000_0111110_1111111
0011000_0011100_1111100_1111111
0011000_0011100_0011111_1111111
0010000_0111100_0011111_1111111
0010000_0011100_1111110_1111111
0011000_0111000_1111111_0111110
0010000_0111100_1111111_0111110
0010000_0011110_1111111_0111110
0010000_0111100_1111111_0011111
0011000_0011100_1111111_0011111
0010100_0011100_1111111_1111100
0010000_0111101_1111111_0011110
0010000_0111110_1111111_0011110
01110000_01110000_11111111_01111110
11100000_11100000_11111100_11111111
00111000_00111000_00111111_11111111
11100000_11100000_11111111_11111100
00111000_00111000_11111111_00111111
01110000_01110000_01111110_11111111
011000000_111000000_111111111_111111100_011111000
001110000_000110000_001111100_001111111_111111111
000110000_001110000_111111111_001111111_000111110
001100000_011100000_111111111_011111110_001111100
001100000_011100000_111111100_111111111_001111100
011100000_001100000_011111000_011111110_111111111
000110000_000111000_001111111_111111111_000011111
000110000_000111000_111111100_111111111_111110000
000110000_001110000_011111110_111111111_000111110
001100000_001110000_011111110_111111111_000111110
1110000000_1111000000_1111110000_1111111100_1111111111
1110000000_1111000000_1111110000_1111111111_1111111100
1111000000_0111000000_0111111000_1111111111_0111111110
0011100000_0011110000_0011111100_0011111111_1111111111
0111000000_0111100000_0111111000_0111111110_1111111111
0111000000_0111100000_0111111000_1111111111_0111111110
0111000000_1111000000_0111111000_1111111111_1111111001
0111000000_1111000000_0111111000_1111111111_1111111010
0011100000_0011110000_0011111100_1111111111_0011111111
0111100000_0011100000_0011111100_1111111111_0011111111
0011100000_0111100000_0011111100_1111111111_0111111101
```
[Answer]
In the interest of getting the process started, here's a quick (but not very optimal) answer.
### Pattern:
```
n = 8:
########
######
#####
####
###
##
```
Take a triangle with length n - 1, stick an extra square onto the corner, and cut off the bottom square.
### Proof that all n-ominos fit:
Note that any n-omino can fit in a rectangle with length + width at most n + 1.
If an n-omino fits in a rectangle with length + width at most n, it fits nicely in the triangle (which is the union of all such rectangles). If it happens to use the cut-off square, transposing it will fit in the triangle.
Otherwise, we have a chain with at most one branch. We can always fit one end of the chain into the extra square (prove this with casework), and the rest fits into a rectangle with length + width at most n, reducing to the case above.
The only case where the above doesn't work is the case where we use both the extra square and the cut-off square. There's only one such n-omino (the long L), and that one fits inside the triangle transposed.
### Code (Python 2):
```
def f(n):
if n < 7:
return [0, 1, 2, 4, 6, 9, 12][n]
return n * (n - 1) / 2
```
### Table:
```
1: 1
2: 2
3: 4
4: 6
5: 9
6: 12
7: 21
8: 28
9: 36
10: 45
11: 55
12: 66
13: 78
14: 91
15: 105
16: 120
17: 136
18: 153
19: 171
20: 190
... more cases can be generated if necessary.
```
[Answer]
## C#, score: 1, 2, 4, 6, 9, 12, 17, 20, 26, 31, 38, 44
```
#
##
#..
###
.##.
####
..#..
#####
###..
##....
######
####..
..##...
.###...
#######
.#####.
..###...
..###...
..######
########
..##.....
.###.....
#######..
#########
..#####..
.###......
.####.....
.######...
##########
.########.
.###.......
.####......
.####......
.#######...
###########
.#########.
.####.......
#####.......
.#####......
############
.##########.
.########...
```
---
The output format of the program is a bit more compact.
This uses a seeded random approach, and I've optimised the seeds. I enforce a bounding box constraint which is both plausible and consistent with the known data for small values of n. If that constraint is indeed valid then
1. The output is optimal up to n=8 (by brute force validation, not included).
2. The number of optimal solutions (distinct up to symmetry) begins `1, 1, 2, 2, 2, 6, 63, 6`.
```
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
namespace Sandbox
{
class FreePolyomino : IEquatable<FreePolyomino>
{
public static void Main()
{
for (int i = 1; i < 12; i++)
{
int seed;
switch (i) {
default: seed = 1103199029; break;
case 9: seed = 693534956; break; // 26
case 10: seed = 2005746461; break; // 31
case 11: seed = 377218946; break; // 38
case 12: seed = 1281379414; break; // 44
}
var rnd = new Random(seed);
var polys = FreePolyomino.All(i);
var minUnion = FreePolyomino.RandomMinimalUnion2(polys, rnd, i, (i + 1) >> 1);
Console.WriteLine($"{i}\t{minUnion.Weight}\t{minUnion}");
}
}
internal FreePolyomino(OrientedPolyomino orientation)
{
var orientations = new HashSet<OrientedPolyomino>();
orientations.Add(orientation);
var tmp = orientation.Rot90(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
tmp = tmp.FlipV(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
tmp = tmp.Rot90(); orientations.Add(tmp);
OrientedPolyominos = orientations.OrderBy(x => x).ToArray();
}
public IReadOnlyList<OrientedPolyomino> OrientedPolyominos { get; private set; }
public OrientedPolyomino CanonicalOrientation => OrientedPolyominos[0];
public static IEnumerable<FreePolyomino> All(int numCells)
{
if (numCells < 1) throw new ArgumentOutOfRangeException(nameof(numCells));
if (numCells == 1) return new FreePolyomino[] { new FreePolyomino(OrientedPolyomino.Unit) };
// We do this in two phases because identifying two equal oriented polyominos is faster than first building
// free polyominos and then identifying that they're equal.
var oriented = new HashSet<OrientedPolyomino>();
foreach (var smaller in All(numCells - 1))
{
// We can add a cell to a side. The easiest way to do this is to add to the bottom of one of the rotations.
// TODO Optimise by distinguishing the symmetries.
foreach (var orientation in smaller.OrientedPolyominos)
{
int h = orientation.BBHeight;
var bottomRow = orientation.Rows[h - 1];
for (int deltax = 0; deltax < orientation.BBWidth; deltax++)
{
if (((bottomRow >> deltax) & 1) == 1) oriented.Add(orientation.Union(OrientedPolyomino.Unit, deltax, h));
}
}
// We can add a cell in the middle, provided it connects up.
var canon = smaller.CanonicalOrientation;
uint prev = 0, curr = 0, next = canon.Rows[0];
for (int y = 0; y < canon.BBHeight; y++)
{
(prev, curr, next ) = (curr, next, y + 1 < canon.BBHeight ? canon.Rows[y + 1] : 0);
uint valid = (prev | next | (curr << 1) | (curr >> 1)) & ~curr;
for (int x = 0; x < canon.BBWidth; x++)
{
if (((valid >> x) & 1) == 1) oriented.Add(canon.Union(OrientedPolyomino.Unit, x, y));
}
}
}
// Now cluster the oriented polyominos into equivalence classes under dihedral symmetry.
return new HashSet<FreePolyomino>(oriented.Select(orientation => new FreePolyomino(orientation)));
}
internal static OrientedPolyomino RandomMinimalUnion2(IEnumerable<FreePolyomino> polys, Random rnd, int maxWidth, int maxHeight, int target = int.MaxValue)
{
var union = OrientedPolyomino.Unit;
foreach (var poly in polys.Shuffle(rnd).ToList())
{
union = poly.MinimalUnion(union, rnd, maxWidth, maxHeight);
if (union.Weight > target) throw new Exception("Too heavy");
}
return new FreePolyomino(union).CanonicalOrientation;
}
private OrientedPolyomino MinimalUnion(FreePolyomino other, Random rnd, int maxWidth, int maxHeight)
{
// Choose the option which does least work.
return OrientedPolyominos.Count <= other.OrientedPolyominos.Count ?
MinimalUnion(other.CanonicalOrientation, rnd, maxWidth, maxHeight) :
other.MinimalUnion(CanonicalOrientation, rnd, maxWidth, maxHeight);
}
private OrientedPolyomino MinimalUnion(OrientedPolyomino other, Random rnd, int maxWidth, int maxHeight)
{
OrientedPolyomino best = default(OrientedPolyomino);
int containsWeight = Math.Min(CanonicalOrientation.Weight, other.Weight);
int bestWeight = int.MaxValue;
int ties = 0;
foreach (var orientation in OrientedPolyominos)
{
// Bounding boxes must overlap, but otherwise we brute force
for (int dx = 1 - orientation.BBWidth; dx < other.BBWidth; dx++)
{
for (int dy = 1 - orientation.BBHeight; dy < other.BBHeight; dy++)
{
var union = other.Union(orientation, dx, dy, maxWidth, maxHeight);
if (union.Rows == null) continue;
if (union.Weight == containsWeight) return union;
if (union.Weight < bestWeight)
{
best = union;
bestWeight = union.Weight;
ties = 1;
}
else if (union.Weight == bestWeight)
{
ties++;
if (rnd.Next(ties) == 0) best = union;
}
}
}
}
if (best.Rows == null) throw new Exception();
return best;
}
public bool Equals(FreePolyomino other) => other != null && CanonicalOrientation.Equals(other.CanonicalOrientation);
public override bool Equals(object obj) => Equals(obj as FreePolyomino);
public override int GetHashCode() => CanonicalOrientation.GetHashCode();
}
[DebuggerDisplay("{ToString()}")]
struct OrientedPolyomino : IComparable<OrientedPolyomino>, IEquatable<OrientedPolyomino>
{
public static readonly OrientedPolyomino Unit = new OrientedPolyomino(1);
public OrientedPolyomino(params uint[] rows)
{
if (rows.Length == 0) throw new ArgumentException("We don't support the empty polyomino", nameof(rows));
if (rows.Any(row => row == 0) || rows.All(row => (row & 1) == 0)) throw new ArgumentException("Polyomino is not packed into the corner", nameof(rows));
var colsUsed = rows.Aggregate(0U, (accum, row) => accum | row);
BBWidth = Helper.Width(colsUsed);
if (colsUsed != ((1U << BBWidth) - 1)) throw new ArgumentException("Polyomino has empty columns", nameof(rows));
Rows = rows;
}
public IReadOnlyList<uint> Rows { get; private set; }
public int BBWidth { get; private set; }
public int BBHeight => Rows.Count;
#region Dihedral symmetries
public OrientedPolyomino FlipH()
{
int width = BBWidth;
return new OrientedPolyomino(Rows.Select(x => Helper.Reverse(x, width)).ToArray());
}
public OrientedPolyomino FlipV() => new OrientedPolyomino(Rows.Reverse().ToArray());
public OrientedPolyomino Rot90()
{
uint[] rot = new uint[BBWidth];
for (int y = 0; y < BBHeight; y++)
{
for (int x = 0; x < BBWidth; x++)
{
rot[x] |= ((Rows[y] >> x) & 1) << (BBHeight - 1 - y);
}
}
return new OrientedPolyomino(rot);
}
#endregion
#region Conglomeration
public OrientedPolyomino Union(OrientedPolyomino other, int deltax, int deltay, int maxWidth = int.MaxValue, int maxHeight = int.MaxValue)
{
// NB deltax or deltay could be negative
int minCol = Math.Min(0, deltax);
int maxCol = Math.Max(BBWidth - 1, other.BBWidth - 1 + deltax);
int width = maxCol + 1 - minCol; if (width > maxWidth) return default(OrientedPolyomino);
int minRow = Math.Min(0, deltay);
int maxRow = Math.Max(BBHeight - 1, other.BBHeight - 1 + deltay);
int height = maxRow + 1 - minRow; if (height > maxHeight) return default(OrientedPolyomino);
uint[] unionRows = new uint[height];
for (int y = 0; y < BBHeight; y++)
{
unionRows[(deltay < 0 ? -deltay : 0) + y] |= Rows[y] << (deltax < 0 ? -deltax : 0);
}
for (int y = 0; y < other.BBHeight; y++)
{
unionRows[(deltay < 0 ? 0 : deltay) + y] |= other.Rows[y] << (deltax < 0 ? 0 : deltax);
}
return new OrientedPolyomino(unionRows);
}
#endregion
#region Identity
public int CompareTo(OrientedPolyomino other)
{
// Favour wide-and-short orientations for the canonical one.
if (BBHeight != other.BBHeight) return BBHeight.CompareTo(other.BBHeight);
for (int i = 0; i < BBHeight; i++)
{
if (Rows[i] != other.Rows[i]) return Rows[i].CompareTo(other.Rows[i]);
}
return 0;
}
public bool Equals(OrientedPolyomino other) => CompareTo(other) == 0;
public override int GetHashCode() => Rows.Aggregate(0, (h, row) => h * 37 + (int)row);
public override bool Equals(object obj) => (obj is OrientedPolyomino other) && Equals(other);
public override string ToString()
{
var width = BBWidth;
return string.Join("_", Rows.Select(row => Helper.ToString(row, width)));
}
#endregion
public int Weight => Rows.Sum(row => (int)Helper.Weight(row));
}
static class Helper
{
public static int Width(uint x)
{
int w = 0;
if ((x >> 16) != 0) { w += 16; x >>= 16; }
if ((x >> 8) != 0) { w += 8; x >>= 8; }
if ((x >> 4) != 0) { w += 4; x >>= 4; }
if ((x >> 2) != 0) { w += 2; x >>= 2; }
switch (x)
{
case 0: break;
case 1: w++; break;
case 2:
case 3: w += 2; break;
default: throw new Exception("Unreachable code");
}
return w;
}
public static uint Reverse(uint x, int width)
{
uint rev = 0;
while (width-- > 0)
{
rev = (rev << 1) | (x & 1);
x >>= 1;
}
return rev;
}
internal static string ToString(uint x, int width)
{
char[] chs = new char[width];
for (int i = 0; i < width; i++)
{
chs[i] = (char)('0' + (x & 1));
x >>= 1;
}
return new string(chs);
}
internal static uint Weight(uint v)
{
// https://graphics.stanford.edu/~seander/bithacks.html
v = v - ((v >> 1) & 0x55555555);
v = (v & 0x33333333) + ((v >> 2) & 0x33333333);
return ((v + (v >> 4) & 0xF0F0F0F) * 0x1010101) >> 24;
}
public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> elts, Random rnd = null)
{
rnd = rnd ?? new Random();
T[] arr = elts.ToArray();
int n = arr.Length;
while (n > 0)
{
int idx = rnd.Next(n - 1);
yield return arr[idx];
arr[idx] = arr[n - 1];
arr[n - 1] = default(T); // Help GC if T is a class
n--;
}
}
}
}
```
[Online demo](https://tio.run/##zVpbc9s2Fn7Xr0DdnYZcy4wkKxdbtjOJkzTZaeqd2GkevJ4dmIRFNhShkqAkjqP@9ew5AEjxAlLyprOz8owlkjgXnBu@A9BNDlwes2/f0iSIpuQySwSbTXrlK@echyFzRcCjxPmZRSwO3NqI1wGdRjwRgZvUnvwSRH9Mer2Izlgypy4jlzTybvmqd98j8HFDmiTkbczYP3mY8VkQcXJM3r/5I6WC3obspPLoTNIoSvzM09swcEkiKEgmCx545AMNIssuRmzG4ueOx8QKIkECckqGE/g6IcND@N7ftysDq2T4QaqEMW/SeJIsA@H6wNc2kOHHY3c0DcWxpEfBw8Hh8OhoMDqakNuY0S8TI5lLE0aOCqqnR4dPDsdHT57mROTxYzJ62k46HBS0o8HgybPx0/HTYZn4cNhBPCyID589Gw2fH40rgg@fd9CONlMdPR8ePjsaD8dl4vG4QbzuNW4taEziCLlEbEk@QtjwmYV87Ylx7ByiJIHRlYhxXoYheMZMAQM@RRDVDSIl7EMQBTMayiEjS7Lvo0Z9EvTB3WSfDG1ydgb/m@zPIVd4yJzPcSAY5ACz/rZ3H6z/Je5zoc5nFkx9Ub613qtxWvcM9oFIZHFEw6rO1kUcMHjibfKIyzsU87YtIdAKpWGJNvY7mviXTJw0eJ5ZNQ3LxM5Lz7PKQicNWWI2BxGlMc5HLo4GwLXJCcbWOChq@P8/pXobBvPf/q813EZVIWv4NKl6JHEuYo/FrzJrRU7PyMp2rvjLOKZZ2fWlcNQ1@P1HRr2LKMx@CRJT4Jjk3pMpExMyj4MFFQxqBlw0OTcD@5xGPApcGl5s1EZdmyKuBzeTXsty8f5NlM5YbFhliCwaUPBhwDkLw6QtfYI7YuVjcCmxifBjvpQ59DKeAvtIXKTi4g4KypS9WblsjrpauBryu4LUrnm2wvb0FPnGTKRxJBlXdL2@ASs27jaLgQMFRthkXQsGKMafGfE46B0kUFmIWHIy96GKJ@SWuTSFch54wCq4y3BRx8cM1uZQRwwU@fnGn8DijsKqD3nu04jcBXEiyG0ahB7Q1uXegcJlYii5QMaiqjyfCrybPYqZEuy01C/mPbh2ARpgFFdu5JJApQ9Bc7ABer8w/wFYfxs2UFZ0YcrU8wglLlASweFXApNxyJUPytMkYGCOJc3wUWHyRA4EMoF3GLnlQvAZ4XeERwy/8GbM89w0yb66eH1BLiCyZgG46zYjHqQgWC8NEl8ZEXIrm82YAJMYWFTsUKoEaAttFqeZWnaDjxn9YB75taL/6tU7ufiZgQ@qoczwEXKpvlwsk2sfvXJjJi4gnsdCQaGEkcEk/31SU@Jz4Ak/f1qHgN2zytPUsjaaAhRQrGzyE@asytw8POuroyOX/JZM7WtOfeLbtnmi610wlDEyMc0hJGaB54WsD@WXLyBMPRII4vIoAqSfkHTuGCGTi6UXjJrHhakUN/VN0SHzmC3QHX3ipnGsfkVsJeCX5Kp8OzD4tfBpptyZgScVSRFIJDP5z@w7CzVRWmgNwFfE2lz3QQKAu4YU8qKsqRxzA93KoMVDctYLGgZYmqRQ8lXJ@6qkkRO5ZuRXEkpi7PyJl1vCW0f2qqSkDuf/OpKVqme45rcGsJLVHboQtdlDorYjhiF@f4XMcsNULyvMvPBEQq5LgCNCFkGTKdtKWMPSCKAM1EOfeTEsWroKZtXYLq2t@eJRxQNWYYJLho1wOY0RdzTX3zIKts24qYDxGo40YY6pC@kALbpBUVS6T4FAmdGVDIziSsWyuhQ0BggGoQQXzge6@o2GKetqFlLdL5l937G@onZYeaSWzqWf3t2FzAItEV8iZrS2LrO5bGThlM1iySe6N9vMt5irIRYx4tNSG0bOtC3KEG4D2PauOCc@o4us2aK1xVI1IqQwe0u9LINfDYqbYVGZeXXnhEOCxDuHQJufIenOfc4BS8h8kxYgSz8AV3ockioELANAhsdfjHnUhArOOU9B8MmpUtBpHfGi4afKZBW1yYQdvifHDaaKT4X1A5l@j8sMjfpf4rYm31sEnKf5/lNTcL3tiCQAEDSIEp0Vp@QDFT6aymghnTx9bdHPpmxDrqhIwbFcappDBUBUubT1doWo26CpEa@/gnjDrgSA5goEzmB9IXzB4pDO@9CyCDWjJQLqJWDqOAW/ghIuawcnHi7JQ4CmZpAp4ac0U@ne7qBlIyYzislxkJeV5GxuPhwTlKu94qeTsJwgHqz1XrZr0W0WXwRSCDOiNAxtGXxBhFGxA2keT6e1mC16ZTnsIaxOSnFqt5K1Www/OuW07G0ji5wo69FNpvNj2D5q3fqEhdjOGyz4/fNGtfb3u1VHyVDcnF8BAltIIBHmwN7RaOu/AlCiDiiuFnmmNb@@cabDCqm7NsJuOQ8Jnl@EiWl1thEwyl/kByWd/PSTcUfL0UzaV71SimnhWMJiaOYqWvDb3wG0EviSwjd3Ca0dvXQwxNLzMxMIkM@5xyzJyqh2ZZRiqK10/ZrdptMpi18HyTykmbV3f8UvRQx12LLXe/aNHJWIOAV1m8vZMXl/zmdzqtBvc3@nXz43aj7uPDuC5cXjEUDUplgEtnpvqfHQGtqT7RuWFuo8S2RDeH1DINQ6dxTxufMLi6bC1wnS3FUsQVO5gRc9EiRJ53Mey/0ywmZzkW1apD1obNWeoxRu2G@UQl9GGf5A18ovKfzrV6IehmH@UH7nLeLA3qLgxpRBQiIuyJy6X3C/IdJ7Xi6PIxZ36yg3H3iYfErkTp/SaDqN2RQglzX41CcWdd101sdHMjjlJZHK13jpBRjYvGPhHIELXlo5e4N1CsmQs5Y1/ISdu@Ziqy3CXU3gQ84p5wDPdBYl3dNWZUpOd/fdd4yzM0Vq3mKvUWNu5zZ5AIHeFDlVohSEL2XDj@AbhA@va903FP4d9vjx1OVd60EuKrDUPszhVFsf1kxHqa5u5eUhhw6DjwyqXcIsADWSuV06@@g8/DCr/5sqkh065AKrcrZz1wc@LcYpykxetuQNbaabSW/b1lrHptp9b5cNqe6tKDOQAG2vVzfkK@aX2l67KW9FQb5ZRcQdSPybGRDmutd@1RkSIN7s4R9Z5KlAbkb2OY@mIcftGFF53uq3LQ3gZtu69DurNoO1BqrWG@64k4Pbaq/yXXFwoBIEFSkNPQA4YCOoqsGCNXIOtD0HYFFqCwf5VrWh7QO1yqPpysqrDHiwX@2GpFP323nl2a557ssQUOpMZIlWA84KQxV9QFf7a5qgOnRoTDAzT7A8Wk5wE6P9Wh9WnqKJm5@7ULMt5ggXao5@vldV2t7YYZaG4iCxtl5cihKh2N/UzPLdJaKQdW3pQDshA/KCHOgr3EGHyWYy@/Pcx4Qvjm02o1eG/fb1VnXr/fB3KD0ABbQHC50V@1bNC5LVznuHzQJV6PPwMvVeHqiKrGdaxhWiZle8rSx11JC3dMHTGFOTHdDIO0h8hJ@V90nQGxLi5Z0CHms6DXxVpMgPpzVnFQGe33A2GtdGtsVtoAIhqMTtLq98gWLSqcHNRi99o1BLXze0ysft4vFB2aUd7WSbh2QrVpWvkPkD27mPNVANmNrf4Gmf/J0cPoOgR6PaVVT9gPZTNp7QCLROBtrhcufbISWRrSPZ9JAdBxe7oEXFz/kHh7K/928A5mWgqFsfDRULmXC7QIu7p2YpAT9XUfRlOiu6LLRz3qHIUfjErvbUun9V71GqwZ2NrhQp2x15PLnqRNjNjVh5UriSR5VPbcwKKN33MHD/FG4g@js7U7/WLWTPa1TPc6Ln7TTjGs04pxm304xqNKOcZlSnyd/fXG2rB/LlxsFx2zub6t3HY7Lc3590jhkdm@8fHheqtpAXb5Iaz6g@RXKTHLc/AMp5bLejqmVXY6ODRoZK3qyouOlvUFlXH0L0oX9Vk6UfgI4Ksh0cAJ4ZbLO9YmPhV3FovpKtQdNKOggn23sBYLfT2Wy90OxsAvBGDGjL9XOcJW8suxqx0mq1VF3UDksVCMBVCt9iAAG29WjwCAu1stB3mQiVVtMH1sluR9nppq4pUy06QIQvxDw5fvx4GtO5H7iJA0wisIbnMC99/GfCKJ7hP74NhE/dL4nji1lYre4w7QUAZctaqFcoYNKD1RP9qW8joY0WcsSh/iCO07Qju/rEuErg2H2iCMaK4O1A/tmwQg5Ww4H8k68Gj8Y7ZFf5TP/qjOizcfhpyVfEao8BSFZO@Ynew26xsBqB/1@8KL9IXZvbFUQplW/lIH/TK5/5ooDnQTBSb1Aa8zraJaNlrMszs@JMIJJbac1ozQIGfak2P8i@BjrDa0L5E6XgddTyltjmWels9MqWb6bjAkp@Psd15ApBClULa4NHdHDQ/qa2@r/@9u0/)
[Answer]
# Greedy placement in random order
```
[1, 2, 4, 6, 9, 12, 17, 21, 27, 32]
```
The regions found are given below, as well as the [rust](https://www.rust-lang.org/en-US/) program that generated them. Call it with a command line parameter equal to the n you'd like to search up to. I've run it up to n=10 so far. Note that it is not optimized for speed yet, I'll do that later and probably speed things up a lot.
The algorithm is straightforward, I shuffle the polyominoes in a (seeded) random order, then place them one at a time in the position with the maximum overlap possible with the region so far. I do this 100 times and output the best resulting region.
### Regions
```
Size 1: 1
#
Size 2: 2
##
Size 3: 4
###
#
Size 4: 6
####
##
Size 5: 9
###
#####
#
Size 6: 12
######
####
##
Size 7: 17
####
#####
#######
#
Size 8: 21
#
###
#####
####
##
###
##
#
Size 9: 27
#########
#######
#####
###
###
Size 10: 32
##
##
###
###
####
#####
#####
######
#
#
```
### Program
Note: requires nightly, but just change the seeding to get rid of that, if you care.
```
#![feature(int_to_from_bytes)]
extern crate rand;
use rand::{ChaChaRng, Rng, SeedableRng};
use std::fmt;
use std::collections::HashSet;
#[derive(Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
struct Poly(Vec<(isize, isize)>);
impl Poly {
fn new(mut v: Vec<(isize, isize)>) -> Self {
v.sort();
Poly(v)
}
fn flip_hor(&self) -> Self {
Poly::new(self.0.iter().map(|&(a, b)| (-a, b)).collect())
}
fn flip_vert(&self) -> Self {
Poly::new(self.0.iter().map(|&(a, b)| (a, -b)).collect())
}
fn transpose(&self) -> Self {
Poly::new(self.0.iter().map(|&(a, b)| (b, a)).collect())
}
fn offset_by(&self, x: isize, y: isize) -> Self {
Poly::new(self.0.iter().map(|&(a, b)| (a+x, b+y)).collect())
}
fn offset_canon(&self) -> Self {
let (mut min_x, mut min_y) = self.0[0];
for &(x, y) in &self.0 {
if x < min_x {
min_x = x;
}
if y < min_y {
min_y = y;
}
}
self.offset_by(-min_x, -min_y)
}
fn transformations(&self) -> Vec<Self> {
vec!(
self.offset_canon(),
self.flip_hor().offset_canon(),
self.flip_vert().offset_canon(),
self.flip_vert().flip_hor().offset_canon(),
self.transpose().offset_canon(),
self.transpose().flip_hor().offset_canon(),
self.transpose().flip_vert().offset_canon(),
self.transpose().flip_vert().flip_hor().offset_canon(),
)
}
fn canonicalize(&self) -> Self {
self.transformations().into_iter().min().unwrap().transpose()
}
fn max_box(&self) -> (isize, isize) {
let (mut max_x, mut max_y) = self.0[0];
for &(x, y) in &self.0 {
if x > max_x {
max_x = x;
}
if y > max_y {
max_y = y;
}
}
(max_x, max_y)
}
fn extend(&self) -> HashSet<Self> {
let elems: HashSet<(isize, isize)> = self.0.iter().cloned().collect();
let mut perim: HashSet<(isize, isize)> = HashSet::new();
let mut neighbors: HashSet<Self> = HashSet::new();
for &(x, y) in &self.0 {
for (dx, dy) in vec!((0, 1), (1, 0), (-1, 0), (0, -1)) {
let p = (x + dx, y + dy);
if !elems.contains(&p) {
if !perim.contains(&p) {
let mut poly_points = self.0.clone();
poly_points.push(p);
let new_poly = Poly::new(poly_points).canonicalize();
neighbors.insert(new_poly);
perim.insert(p);
}
}
}
}
neighbors
}
}
impl fmt::Display for Poly {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
let p = self.offset_canon();
let (max_x, max_y) = p.max_box();
let (max_x, max_y) = (max_x as usize, max_y as usize);
let mut grid = vec![vec![" "; max_x+1]; max_y+1];
for &(x, y) in &p.0 {
grid[y as usize][x as usize] = "#"
}
let s = grid.into_iter().map(|r| r.concat()).collect::<Vec<String>>().join("\n");
write!(f, "{}", s)
}
}
fn all_polys(n: usize) -> HashSet<Poly> {
let mut polys = HashSet::new();
polys.insert(Poly::new(vec!((0, 0))));
for _ in 0..n-1 {
let mut next_polys = HashSet::new();
for poly in polys {
next_polys.extend(poly.extend());
}
polys = next_polys;
}
polys
}
fn overlap_polys(polys: &Vec<Poly>, seed: u64) -> Poly {
let mut seq = polys.clone();
let mut seed_array = [0; 32];
for i in 0..32 {
seed_array[i] = seed.to_be().to_bytes()[i%8];
}
let mut rng = ChaChaRng::from_seed(seed_array);
rng.shuffle(&mut seq);
let mut points: HashSet<(isize, isize)> = seq[0].0.iter().cloned().collect();
for poly in seq {
let max_x = points.iter().map(|a| a.0).max().unwrap();
let max_y = points.iter().map(|a| a.1).max().unwrap();
let mut best_overlap_amount = 0;
let mut best_placement = poly.clone();
for t_poly in poly.transformations() {
let (t_max_x, t_max_y) = t_poly.max_box();
for x in -t_max_x ..= max_x {
for y in -t_max_y ..= max_y {
let mut overlap_amount = 0;
let st_poly = t_poly.offset_by(x, y);
for point in &st_poly.0 {
if points.contains(point) {
overlap_amount += 1;
}
}
if overlap_amount > best_overlap_amount {
best_overlap_amount = overlap_amount;
best_placement = st_poly;
}
}
}
}
for &point in &best_placement.0 {
points.insert(point);
}
}
Poly::new(points.into_iter().collect()).canonicalize()
}
fn main() {
let seed_start = 123456789;
let iters = 100;
let max_poly = std::env::args().nth(1).unwrap().parse().unwrap();
let mut sizes = vec!();
for i in 1..=max_poly {
let mut ap: Vec<Poly> = all_polys(i).into_iter().collect();
ap.sort();
let mut best_result = overlap_polys(&ap, seed_start);
let mut best_score = best_result.0.len();
for i in 1..iters {
let result = overlap_polys(&ap, seed_start + i);
if result.0.len() < best_score {
best_score = result.0.len();
best_result = result;
}
}
println!("Size {}: {}\n{}\n", i, best_result.0.len(), best_result);
sizes.push(best_result.0.len());
}
println!("{:?}", sizes);
}
```
] |
[Question]
[
```
Given a width and a block of
text containing possible hyphen-
ation points, format it fully-
justified (in monospace).
```
Fully justified means it is aligned on the left *and* the right, and is achieved by increasing the spacing between words until each line fits.
Related:
* [Justify a text by adding spaces](https://codegolf.stackexchange.com/questions/4238/justify-a-text-by-adding-spaces)
* [Align the text to a block](https://codegolf.stackexchange.com/questions/61266/align-the-text-to-a-block)
* And in a way this can be considered the next step in [Text Processing #1: Hyphenation](https://codegolf.stackexchange.com/questions/55939/text-processing-1-hyphenation) (which seems to have never been posted).
## Input
You can take input in any format you like. You will be given:
* A target width (in characters), in the range 5-100 (inclusive);
* A block of text containing possibly hyphenated words. This could be a space-separated string, an array of words, or an array of arrays of word fragments (or any other data representation you desire).
A typical input might be:
```
Width: 25
Text: There's no bu-si-ne-ss lik-e s-h-o-w busine-ss, n-o bus-iness I know.
```
Where the hyphens denote possible hyphenation points, and the spaces denote word boundaries. A possible alternative representation of the text:
```
[["There's"], ["no"], ["bu", "si", "ne", "ss"], ["lik", "e"], (etc.)]
```
## Output
The input text with spaces added between words, newlines at the column width, and hyphenation points chosen to fully-justify it to the column width. For functions, an array of strings (one for each line) can be returned instead of using newline separation.
A possible output for the above input might be:
```
There's no business like
show business, no bus-
iness I know.
```
Note that all hyphens have been removed except the one in the final "bus-iness", which is kept to show that the word wraps to the next line, and was chosen to ensure the second line contains as much text as possible.
## Rules
* Within each line, the number of spaces between words cannot vary by more than 1, but where you insert the extra spaces is otherwise up to you:
```
hello hi foo bar <-- not permitted (1,1,5)
hello hi foo bar <-- not permitted (2,1,4)
hello hi foo bar <-- OK (2,2,3)
hello hi foo bar <-- OK (2,3,2)
hello hi foo bar <-- OK (3,2,2)
```
* No line can begin or end with spaces (except the last line, which can end with spaces).
* The last line should be left justified, containing single spaces between each word. It can be followed by arbitrary whitespace / a newline if desired, but this is not required.
* Words will consist of A-Z, a-z, 0-9 and simple punctuation (`.,'()&`)
* You can assume that no word fragment will be longer than the target width, and it will always be possible to fill lines according to the rules (i.e. there will be at least 2 word fragments on each line, or 1 word fragment which fills the line perfectly)
* You must choose hyphenation points which maximise the number of word characters on earlier lines (i.e. words must be consumed greedily by lines), for example:
```
This is an input stri-ng with hyph-en-at-ion poi-nts.
This is an input stri- <-- not permitted
ng with hyphenation points.
This is an input string with hyph- <-- not permitted
enation points.
This is an input string with hyphen- <-- OK
ation points.
```
* Shortest code in bytes wins
## Examples
```
Width: 20
Text: The q-uick brown fox ju-mp-s ove-r t-h-e lazy dog.
The quick brown fox
jumps over the lazy
dog.
```
---
```
Width: 32
Text: Given a width and a block of text cont-ain-ing pos-sible hyphen-ation points, for-mat it ful-ly-just-ified (in mono-space).
Given a width and a block of
text containing possible hyphen-
ation points, format it fully-
justified (in monospace).
```
---
```
Width: 80
Text: Pro-gram-ming Puz-zles & Code Golf is a ques-tion and ans-wer site for pro-gram-ming puz-zle enth-usi-asts and code golf-ers. It's built and run by you as part of the St-ack Exch-ange net-work of Q&A sites. With your help, we're work-ing to-g-et-her to build a lib-rary of pro-gram-ming puz-zles and their sol-ut-ions.
Programming Puzzles & Code Golf is a question and answer site for programming
puzzle enthusiasts and code golfers. It's built and run by you as part of the
Stack Exchange network of Q&A sites. With your help, we're working together to
build a library of programming puzzles and their solutions.
```
---
```
Width: 20
Text: Pro-gram-ming Puz-zles & Code Golf is a ques-tion and ans-wer site for pro-gram-ming puz-zle enth-usi-asts and code golf-ers. It's built and run by you as part of the St-ack Exch-ange net-work of Q&A sites. With your help, we're work-ing to-g-et-her to build a lib-rary of pro-gram-ming puz-zles and their sol-ut-ions.
Programming Puzzles
& Code Golf is a
question and answer
site for programming
puzzle enthusiasts
and code golfers.
It's built and run
by you as part of
the Stack Exchange
network of Q&A
sites. With your
help, we're working
together to build a
library of program-
ming puzzles and
their solutions.
```
---
```
Width: 5
Text: a b c d e f g h i j k l mm nn oo p-p qq rr ss t u vv ww x yy z
a b c
d e f
g h i
j k l
mm nn
oo pp
qq rr
ss t
u vv
ww x
yy z
```
---
```
Width: 10
Text: It's the bl-ack be-ast of Araghhhhh-hhh-h-hhh-h-h-h-hh!
It's the
black be-
ast of
Araghhhhh-
hhhhhhhhh-
hhh!
```
[Answer]
# JavaScript (ES6), 218 bytes
```
w=>s=>s.map((c,i)=>c.map((p,j)=>(k+p)[l="length"]-w-(b=!i|j>0)+(j<c[l]-1)<0?k+=b?p:" "+p:(Array(w-k[l]-b).fill(h=k.split` `).map((_,i)=>h[i%(h[l]-1)]+=" "),o.push(h.join` `+(b?"-":"")),k=p)),o=[],k="")&&o.join`
`+`
`+k
```
Takes arguments in currying syntax (`f(width)(text)`) and the text input is in the double array format described in the challenge. Strings are converted to that format via `.split` `.map(a=>a.split`-`))`. Also, the newlines are literal newlines inside template strings.
## Un-golfed and rearranged
```
width=>string=> {
out=[];
line="";
string.map((word,i)=> {
word.map((part,j)=> {
noSpaceBefore = i==0 || j>0;
if ((line+part).length - width - noSpaceBefore + (j<word.length-1) < 0) {
line += noSpaceBefore ? part : " "+part;
}
else {
words=line.split` `;
Array(width - line.length - noSpaceBefore).fill()
.map((_,i) => words[i % (words.length-1)] += " ");
out.push(words.join(" ") + (noSpaceBefore? "-" : ""));
line=part;
}
});
});
return out.join("\n") + "\n"+line
}
```
The idea here was to step through each part of the entire string and build up each line one part at a time. Once a line was complete, it increases the word spacing from left to right until all extra spaces are placed.
## Test Snippet
```
f=
w=>s=>s.map((c,i)=>c.map((p,j)=>(k+p)[l="length"]-w-(b=!i|j>0)+(j<c[l]-1)<0?k+=b?p:" "+p:(Array(w-k[l]-b).fill(h=k.split` `).map((_,i)=>h[i%(h[l]-1)]+=" "),o.push(h.join` `+(b?"-":"")),k=p)),o=[],k="")&&o.join`
`+`
`+k
```
```
<style>*{font-family:Consolas,monospace;}</style>
<div oninput="O.innerHTML=f(+W.value)(S.value.split` `.map(a=>a.split`-`))">
Width: <input type="number" size="3" min="5" max="100" id="W">
Tests: <select id="T" style="width:20em" oninput="let x=T.value.indexOf(','),s=T.value;W.value=s.slice(0,x);S.value=s.slice(x+2)"><option></option><option>20, The q-uick brown fox ju-mp-s ove-r t-h-e lazy dog.</option><option>32, Given a width and a block of text cont-ain-ing pos-sible hyphen-ation points, for-mat it ful-ly-just-ified (in mono-space).</option><option>80, Pro-gram-ming Puz-zles & Code Golf is a ques-tion and ans-wer site for pro-gram-ming puz-zle enth-usi-asts and code golf-ers. It's built and run by you as part of the St-ack Exch-ange net-work of Q&A sites. With your help, we're work-ing to-g-et-her to build a lib-rary of pro-gram-ming puz-zles and their sol-ut-ions.</option><option>20, Pro-gram-ming Puz-zles & Code Golf is a ques-tion and ans-wer site for pro-gram-ming puz-zle enth-usi-asts and code golf-ers. It's built and run by you as part of the St-ack Exch-ange net-work of Q&A sites. With your help, we're work-ing to-g-et-her to build a lib-rary of pro-gram-ming puz-zles and their sol-ut-ions.</option><option>5, a b c d e f g h i j k l mm nn oo p-p qq rr ss t u vv ww x yy z</option><option>10, It's the bl-ack be-ast of Araghhhhh-hhh-h-hhh-h-h-h-hh</option></select><br>
Text: <textarea id="S" cols="55" rows="4"></textarea>
</div>
<pre id="O" style="border: 1px solid black;display:inline-block;"></pre>
```
[Answer]
# JavaScript (ES6), 147 bytes
Takes input as `(width)(text)`.
```
w=>F=(s,p=S=' ')=>(g=([c,...b],o='',h=c=='-')=>c?o[w-1]?c==S&&o+`
`+F(b):o[w+~h]?o+c+`
`+F(b):c>S?g(b,h?o:o+c):g(b,o+p)||g(b,o+p+c):o)(s)||F(s,p+S)
```
[Try it online!](https://tio.run/##dZLRa9swEMbf@1d8y0Nsk1xYOwajww1lrGVvHRnsoStUdhRbqSI5khzHpexfz07uRkm3GWzkO92nT7@7tdgJXzrVBDJ2KQ@r/NDlF1d56qdNvsgTJFl@kVZ5eltOZ7NZcTe1eZJM67zM84Rispzb245O7@YcWYzHdnJ/cj@5SovsnOOTn/Xd3E7Kl2B5sZhXaTGt5/acE9l5/LGTJnt6@r2KQZulniNX0cZkkR1Ka7zVcqZtla7Ss7dZOvpWS2ypVeUDCmc7g5XdY93SpiEPu5PkEKgmCS0eeyxtNRtlmCD5YZLs5ORY8N0ZC16rnTQQ6NQy1BBmyetCW9a3KwS5D@CiQEIZUqZCYz15VWiJum9qaUgEZQ2HlQl@ym4cbUSACli1mnRP69YHUisll0iVwcYaS74RpcyOnA0n5RjdOEuVExvaxNNu2kd61NJjjE/cJ1xbvYLybHHbSk/D0YNl46mTDl4FGT2gOZJpnmUgTaip9YqED34oLKNqxaoknZ/hS0g8ilbpMGRda1D06G0L4dEIFwYo3IIFE2FEn/dlTcJUEkYG6qwbqH0dXw5OWPC7Yqhc71BL3UzRycRJxI0DzcAuiStr9h7scHLkr1VBTrg@iv3zJs/m2YjiO1tNLSPm1s5GH1/3OA5NZPuC@jj/4a/8qw3veUZ4IlBiCWaLCjUU1niAxmYDY2AtGmqw3cKxG4@AFrsdug579D0e/z@Ap3GiB@aRaaEHpoWM7YlXv3SiquNDw/vnO6zevKgefgE "JavaScript (Node.js) – Try It Online")
### Commented
```
w => // w = requested width
F = ( // F is a recursive function taking:
s, // s = either the input string (first iteration) or an
// array of remaining characters (next iterations)
p = // p = current space padding
S = ' ' // S = space character
) => ( //
g = ( // g is a recursive function taking:
[c, // c = next character
...b], // b[] = array of remaining characters
o = '', // o = output for the current line
h = c == '-' // h = flag set if c is a hyphen
) => //
c ? // if c is defined:
o[w - 1] ? // if the line is full:
c == S && // fail if c is not a space
o + `\n` + F(b) // otherwise, append o + a linefeed and process the
// next line
: // else:
o[w + ~h] ? // if this is the last character and c is a hyphen:
o + c + `\n` + F(b) // append o + c + a linefeed and process the next
// line
: // else, we process the next character:
c > S ? // if c is not a space:
g(b, h ? o : o + c) // append c if it's not a hyphen
: // else:
g(b, o + p) || // append either the current space padding
g(b, o + p + c) // or the current padding and one extra space
: // else:
o // success: return o
)(s) // initial call to g() with s
|| F(s, p + S) // in case of failure, try again with a larger padding
```
[Answer]
# GNU sed `-r`, 621 bytes
Takes input as two lines: The width as a unary number first and the string second.
I'm certain this could be golfed much more but I've already dumped way too much time into it.
```
x;N
G
s/\n/!@/
:
/@\n/bZ
s/-!(.*)@ /\1 !@/
s/!(.*[- ])(@.*1)$/\1!\2/
s/@(.)(.*)1$/\1@\2/
s/-!(.*-)(@.*)\n$/\1!\2\n1/
s/(\n!@) /\1/
s/-!(.* )(@.*)\n$/\1!\2\n1/
s/-!(.*-)(@.*1)$/\1!\21/
s/!(.*)-@([^ ]) /\1\2!@ /
t
s/ !@(.*)\n$/\n!@\1#/
s/!(.*-)@(.*)\n$/\1\n!@\2#/
s/!(.*)(@ | @)(.*)\n$/\1\n!@\3#/
s/-!(.*[^-])@([^ ]) (.*)\n$/\1\2\n!@\3#/
s/!(.+)@([^ ].*)\n$/\n!@\1\2#/
/#|!@.*\n$/{s/#|\n$//;G;b}
:Z
s/-?!|@.*//g
s/ \n/\n/g
s/^/%/
:B
G
/%.*\n.+\n/!bQ
:C
s/%([^\n])(.*)1$/\1%\2/
tC
s/([^\n]+)%\n/%\1\n/
:D
s/%([^ \n]* )(.*)1$/\1 %\2/
tD
s/(^|\n)([^\n]+)%(.*1)$/\1%\2\3/
tD
s/%([^\n]*)\n(.*)\n$/\1\n%\2/
tB
:Q
s/%(.*)\n1*$/\1/
```
[Try it online!](https://tio.run/##bVFLb9pAEL77V4xFnXih65XJDQ51k1aolyqoh0rFINmwYCvOmu6uRR70r5fOrDEhFQikZb7HfDNj5OpweBp/9yaeEakSfiK8kScSfOa/sMT9MOqzBEQaA2FGUGHGYc7CJOrH7AMifjokJAkjRuyYaklbc3ruuCxVR3KqYsLCVPkJI@sTEy4zz1xOHeMuDONJOFtgIHJKhz6G9SximDfsvLBRGvc6BWdvSOyw4QnDJrCHhP1HuOmdcswWfM66lme04RkReYMj510E10j09j5OQtVXg3/oIcaTcf7HG7mdf/L3iAuxoSnwEvil50IEeJxbPJUISB4N6GD51BvdIRpgt1TN3y4Q0AUsQS0yYAHyAxoIbb4cJeg/p7V3KmhlBIcLjMZO4rBbPjLSmyPn2JVmPN9Ya3LrjaaO45C4T5g4HOILH@9e13yjs0f@WKoN3Dcv/KWSBq7grl5JmNTVGkoDGfxupOG2rBVkaoU/w3dSgymthHWtYfvOZtvagFS24I0peWasccIluW7QlUttIvhmrw3kTVlZh@pGQf4Mz3UDmYFtpi3Ua7CFhB@WZ8sH@Pq0LHimNhKUtHxX6wciTK8@uyRo@LO0Bek1FLLafoSdvNYSiMgpmMWUHJUFZre164zDQFXmXGf6mcwuTtKGxyAlzlxXvLEcV2Giv/WWdmIOXP8D "sed – Try It Online")
## Explanation
The program works in two phases: 1. Split, and 2. Justify. For the below, suppose our input is:
>
>
> ```
> 111111111111
> I re-mem-ber a time of cha-os, ru-ined dreams, this was-ted land.
>
> ```
>
>
### Setup
First we read the input, moving the first line (the width as a unary number) to the hold space (`x`), then appending the next line (`N`) and then a copy of the width from the hold space (`G`) to the pattern space. Since `N` left us with a leading `\n` we replace it with `!@`, which we'll use as cursors in Phase 1.
```
x;N
G
s/\n/!@/
```
Now the content of the hold space is `1111111111111` (and won't change henceforth) and the pattern space is (in the format of sed's "print unambiguously" `l` command):
>
>
> ```
> !@I re-mem-ber a time of cha-os, ru-ined dreams, this was-ted land.\n111111111111$
>
> ```
>
>
### Phase 1
In Phase 1, the main `@` cursor advances one character at a time, and for each character a `1` is removed from the "counter" at the end of the pattern space. In other words, `@foo\n111$`, `f@oo\n11$`, `fo@o\n1$`, etc.
The `!` cursor trails behind the `@` cursor, marking places we could break if the counter reaches 0 in the middle of the line. A couple rounds would look like this:
>
>
> ```
> !@I re-mem-ber a time of cha-os, ru-ined dreams, this was-ted land.\n111111111111$
> !I@ re-mem-ber a time of cha-os, ru-ined dreams, this was-ted land.\n11111111111$
> !I @re-mem-ber a time of cha-os, ru-ined dreams, this was-ted land.\n1111111111$
>
> ```
>
>
Here there's a pattern we recognize: a space immediately followed by the `@` cursor. Since the counter is greater than 0, we advance the break marker, then keep advancing the main cursor:
>
>
> ```
> I !@re-mem-ber a time of cha-os, ru-ined dreams, this was-ted land.\n1111111111$
> I !r@e-mem-ber a time of cha-os, ru-ined dreams, this was-ted land.\n111111111$
> I !re@-mem-ber a time of cha-os, ru-ined dreams, this was-ted land.\n11111111$
> I !re-@mem-ber a time of cha-os, ru-ined dreams, this was-ted land.\n1111111$
>
> ```
>
>
Here's another pattern: `-@`, and we still have 7 in the counter, so we advance the break cursor again and keep advancing:
>
>
> ```
> I re-!mem-@ber a time of cha-os, ru-ined dreams, this was-ted land.\n111$
>
> ```
>
>
Here's a different pattern: A hyphen immediately preceding the break cursor and another preceding the main cursor. We remove the first hyphen, advance the break cursor, and, since we removed a character, add 1 to the counter.
>
>
> ```
> I remem-!@ber a time of cha-os, ru-ined dreams, this was-ted land.\n1111$
>
> ```
>
>
We keep advancing the main cursor:
>
>
> ```
> I remem-!ber@ a time of cha-os, ru-ined dreams, this was-ted land.\n1$
>
> ```
>
>
Similar to before, but this time the main cursor precedes a space rather than following a hyphen. We remove the hyphen, but since we're also advancing the main cursor we neither increment no decrement the counter.
>
>
> ```
> I remember !@a time of cha-os, ru-ined dreams, this was-ted land.\n1$
> I remember !a@ time of cha-os, ru-ined dreams, this was-ted land.\n$
>
> ```
>
>
Finally, our counter has reached zero. Since the character after the main cursor is a space, we insert a newline and put both cursors immediately after it. Then we replenish the counter (`G`) and start again.
>
>
> ```
> I remember a\n!@ time of cha-os, ru-ined dreams, this was-ted land.\n111111111111$
>
> ```
>
>
Phase 1 continues, advancing the cursors and matching various patterns, until the `@` cursor reaches the end of the string.
```
# Phase 1
:
# End of string; branch to :Z (end of phase 1)
/@\n/bZ
# Match -!.*@_
s/-!(.*)@ /\1 !@/
# Match [-_]@ and >0
s/!(.*[- ])(@.*1)$/\1!\2/
# Advance cursor
s/@(.)(.*)1$/\1@\2/
# Match -!.*-@ and 0; add 1
s/-!(.*-)(@.*)\n$/\1!\2\n1/
# Match \n!@_
s/(\n!@) /\1/
# Match -!.*_@ and 0; add 1
s/-!(.* )(@.*)\n$/\1!\2\n1/
# Match -!.*-@ and >0; add 1
s/-!(.*-)(@.*1)$/\1!\21/
# Match -@[^_]_
s/!(.*)-@([^ ]) /\1\2!@ /
# If there were any matches, branch to `:`
t
# Match _!@ and 0
s/ !@(.*)\n$/\n!@\1#/
# Match -@ and 0
s/!(.*-)@(.*)\n$/\1\n!@\2#/
# Match @_|_@ and 0
s/!(.*)(@ | @)(.*)\n$/\1\n!@\3#/
# Match -!.*[^-]@[^_]_ and 0
s/-!(.*[^-])@([^ ]) (.*)\n$/\1\2\n!@\3#/
# Match !.+@[^_] and 0
s/!(.+)@([^ ].*)\n$/\n!@\1\2#/
# Match marked line (#) or !@ and 0
/#|!@.*\n$/{
# Remove mark; append width and branch to `:`
s/#|\n$//
G
b
}
:Z
# Cleanup
s/-?!|@.*//g
s/ \n/\n/g
```
At the end of Phase 1, our pattern space looks like this:
>
>
> ```
> I remember a\ntime of cha-\nos, ruined\ndreams, this\nwasted land.
>
> ```
>
>
Or:
>
>
> ```
> I remember a
> time of cha-
> os, ruined
> dreams, this
> wasted land.
>
> ```
>
>
### Phase 2
In Phase 2 we use `%` as a cursor and use the counter in a similar way, beginning like this:
>
>
> ```
> %I remember a\ntime of cha-\nos, ruined\ndreams, this\nwasted land.\n111111111111$
>
> ```
>
>
First, we count the characters on the first line by advancing the cursor and removing 1s from the counter, after which we have;
>
>
> ```
> I remember a%\ntime of cha-\nos, ruined\ndreams, this\nwasted land.\n$
>
> ```
>
>
Since the counter is 0, we don't do anything else on this line. The second line also has the same number of characters as the counter, so let's skip to the third line:
>
>
> ```
> I remember a\ntime of cha-\nos, ruined%\ndreams, this\nwasted land.\n11$
>
> ```
>
>
The counter is greater than 0, so we move the cursor back to the beginning of the line. Then we find the first run of spaces and add a space, decrementing the counter.
>
>
> ```
> I remember a\ntime of cha-\nos, % ruined\ndreams, this\nwasted land.\n1$
>
> ```
>
>
The counter is greater than 0; since the cursor is already in the last (only) run of spaces on the line, we move it back to the beginning of the line and do it again:
>
>
> ```
> I remember a\ntime of cha-\nos, % ruined\ndreams, this\nwasted land.\n$
>
> ```
>
>
Now the counter is 0, so we move the cursor to the beginning of the next line. We repeat this for every line except the last. That's the end of phase 2 and the end of the program! The final result is:
>
>
> ```
> I remember a
> time of cha-
> os, ruined
> dreams, this
> wasted land.
>
> ```
>
>
```
# Phase 2
# Insert cursor
s/^/%/
:B
# Append counter from hold space
G
# This is the last line; branch to :Q (end of phase 1)
/%.*\n.+\n/!bQ
:C
# Count characters
s/%([^\n])(.*)1$/\1%\2/
tC
# Move cursor to beginning of line
s/([^\n]+)%\n/%\1\n/
:D
# Add one to each space on the line as long as counter is >0
s/%([^ \n]* )(.*)1$/\1 %\2/
tD
# Counter is still >0; go back to beginning of line
s/(^|\n)([^\n]+)%(.*1)$/\1%\2\3/
tD
# Counter is 0; move cursor to next line and branch to :B
s/%([^\n]*)\n(.*)\n$/\1\n%\2/
tB
:Q
# Remove cursor, any remaining 1s
s/%(.*)\n1*$/\1/
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~129 123 121 118 111 109 107 104 100~~ 95 bytes[SBCS](https://github.com/abrudz/sbcs)
```
{⊃⌽m←⍺≥-⌿c⍪+\⊢⌿c←' -'∘.≠⍵:⊂⍵/⍨⊢⌿c⋄(⊂∊l⊣l[(⍺-≢l)⍴⍸' '=l],←⊃0⍴l←⍵/⍨n×⊣⌿c⊖⍨1⌽n),⍺∇⍵/⍨~n←⌽∨\⌽m>×⌿c}
```
[Try it online!](https://tio.run/##bZLPa9RAFMfv/hXPS9PivrpVBBEUikjxVlHwYD1Mkkky7WQmOzPZ3azowUrdrl2pB38cpSIUzwoiFA/@J/OP1DezbUEwkMnL5L3P@77vhDUS845JXZ76t@@F9nuH/dOC1md@tusPTmoK/fyX3/@K/uB35uffrmz52VGM9w4TwMRPP636/c9@/uOWn72kx1U/Pz5PefNqOWxOZ9LPvsgny4RCv38kV/z8u5//TCC5LZ/2Qo/Zbp/2ZGwXEerPR6qJlNkHel8jNWqlF8RMX5/lvFAh/@DET4@3gtg7VEMFz0/DMFmX5IWyCYnIKS0XtpGsu0Txu2v9InlUcRhgK7IdSI0eKSj0GLZbrBu0oIccDTiskINkkw5yXa4msfb6tSLZEEOugMFI5K4CpnKKU6kJpQtwfOwg08ohEwqFKqHRFq1IJYeqayqukDmhFW0L5WyPGhusmQPhoGglyg63W@tQFILnsCwU1FpptA3L@AqJsMH4TaOxNKzGOjTYbCc4kdzCEtzVOYcNLQsQllQNWm4xdosqlcURN2CF46EtEC24nzT/4JoFDrhyFbZWILPORkAW6CXRkRu7CvddklhIWyFd/GxaBWl3Qe10C8xCw4yLxpDjD8kVsuneOKuQqZKD4g5H2kTnHiytR2lEfizIWKo3UHHZ9C6QI54khkOoiNY60o2EqGgqp6OUcBhSpGiY6QL1v7MtxjmnkjJBrmiJLfmulT0765v9Auz5H3MW3SgSOmzIIAfyEEqoQMA27ICEugalQGtosIHBAAwxLThoYTiE0QjG0HUwWaDX6Bdc2BdsSWW0JeXB6iB63bCyChfG@3yN0eXkLw "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), ~~51~~ 50 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
éS┴k╖♀╡¶┐'▼jÆD╨◙♠ß╒└╧rî{♀EÜ╢a┌ùLiƒ7ÉøΩS╜╪åⁿM◙┴,○9H
```
[Run and debug it](https://staxlang.xyz/#p=8253c16bb70cb514bf271f6a9244d00a06e1d5c0cf728c7b0c459ab661da974c699f379000ea53bdd886fc4d0ac12c093948&i=%22There%27s+no+bu-si-ne-ss+lik-e+s-h-o-w+busine-ss,+n-o+bus-iness+I+know.%22+25%0A%22The+q-uick+brown+fox+ju-mp-s+ove-r+t-h-e+lazy+dog.%22+20%0A%22Given+a+width+and+a+block+of+text+cont-ain-ing+pos-sible+hyphen-ation+points,+for-mat+it+ful-ly-just-ified+%28in+mono-space%29.%22+32%0A%22Pro-gram-ming+Puz-zles+%26+Code+Golf+is+a+ques-tion+and+ans-wer+site+for+pro-gram-ming+puz-zle+enth-usi-asts+and+code+golf-ers.+It%27s+built+and+run+by+you+as+part+of+the+St-ack+Exch-ange+net-work+of+Q%26A+sites.+With+your+help,+we%27re+work-ing+to-g-et-her+to+build+a+lib-rary+of+pro-gram-ming+puz-zles+and+their+sol-ut-ions.%22+80%0A%22Pro-gram-ming+Puz-zles+%26+Code+Golf+is+a+ques-tion+and+ans-wer+site+for+pro-gram-ming+puz-zle+enth-usi-asts+and+code+golf-ers.+It%27s+built+and+run+by+you+as+part+of+the+St-ack+Exch-ange+net-work+of+Q%26A+sites.+With+your+help,+we%27re+work-ing+to-g-et-her+to+build+a+lib-rary+of+pro-gram-ming+puz-zles+and+their+sol-ut-ions.%22+20%0A%22a+b+c+d+e+f+g+h+i+j+k+l+mm+nn+oo+p-p+qq+rr+ss+t+u+vv+ww+x+yy+z%22+5%0A%22It%27s+the+bl-ack+be-ast+of+Araghhhhh-hhh-h-hhh-h-h-h-hh%21%22+10%0A&a=1&m=2)
[Answer]
# [Python 2](https://docs.python.org/2/), 343 bytes
```
W,T=input()
T+=' '
L,l=[],len
while T:
p,r=0,''
for i in range(l(T)):
s=T[:i].replace('-','')
if'-'==T[i]:s+='-'
if T[i]in' -'and W-l(s)>=0:p,r=i,s
R=r.split()
if R:
d,k=W-l(''.join(R)),0
for j in range(d):
R[k]+=' '
k+=1
if k==l(R)-1:k=0
L+=[''.join(R)]
T=T[p+1:]
print'\n'.join(L[:-1])
print' '.join(L[-1].split())
```
[Try it online!](https://tio.run/##bZBBb9swDIXv/hVED5WNmEHSowENGIZhGJBDlxnIwfNBSZSYtSppkows/fMZ5XYrBuxk@ZHv8SP9NQ3OPtxuu7qVZP2UyqpoF1KAKDa1kV1fG22Ly0BGQ9sU4OsgV7UQBZxcAAKyEJQ969KUbVVxA0TZdg31y6C9UQddChTcX3GFTvyWXKa@iTwDxSxCFsgKQKHsEXZoylh9kKsmz6I6FrCVYRm9oQyXDds851iPMvcKsXxyZMttVdUr1jPX0zvXcYaCbTf2r2vxz7iQ6/zlqFFKw1ZcN6PM7s1Cdu@JPSstA/vFuukLH8gm8cO@lTddg@u@epPhr8riH9rqduseVvXdY3B4DuoZn8me4XF6wRejI9zDJ3fU8MWZE1AEBT8nHTGRs5AvoWzEiw4QKel5Lf9PjH@NAW3TgFMkVDHF2XjIqWdORR3iEr4mEWE/kUlzNUwW9le4uglUBK9CAneCNGj4nlAdRvj86zBgPh5YnfDiwpgbvt1/nEk4cEdpyP4Agza@hosWQUNuxAyWmBLZOTB7cvNkXgYM7TGocM1h/93kFZ5BiHd2BqeEfIq4vOt/Aw "Python 2 – Try It Online")
```
The input is a block of text
containing possibly hyphenated
words. For each space/hyphen
position p the code computes
l(p) the length of the line
induced by slipping the text
to this space/hyphen. Then the
code choses the position p for
which the length l(p) is the
closest to the given width W
(and l(p)<=W). If l(p)<W the
code adds spaces fairly in-
between the words to achieve
the length W.
```
] |
[Question]
[
If you're going to invent some fake news, you'll want to fabricate some data to back it up. You must already have some preconceived conclusions and you want some statistics to strengthen the argument of your faulty logic. This challenge should help you!
Given three input numbers:
* *N* - number of data points
* *μ* - mean of data points
* *σ* - standard deviation of data points, where *μ* and *σ* are given by:
[](https://i.stack.imgur.com/nusv7.png)
Output an unordered list of numbers, *ùë•i*, which would generate the given *N*, *Œº*, and *œÉ*.
I'm not going to be too picky about I/O formats, but I do expect some sort of decimals for *μ*, *σ*, and the output data points. As a minimum, at least 3 significant figures and magnitude of at least 1,000,000 should be supported. IEEE floats are just fine.
* *N* will always be an integer, where 1 ‚â§ N ‚â§ 1,000
* *μ* can be any real number
* *σ* will always be ≥ 0
* data points can be any real number
* if *N* is 1, then *σ* will always be 0.
Note that most inputs will have many possible outputs. You only need to give one valid output. The output may be deterministic or non-deterministic.
### Examples
```
Input (N, μ, σ) -> Possible Output [list]
2, 0.5, 1.5 -> [1, 2]
5, 3, 1.414 -> [1, 2, 3, 4, 5]
3, 5, 2.160 -> [2, 6, 7]
3, 5, 2.160 -> [8, 4, 3]
1, 0, 0 -> [0]
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~44~~ ~~35~~ 34 bytes
```
~~?eA.DhQ2+eQ\*G,-eQJ\*E@hc1thQ2+eQJ\*G,-eQKE+eQK~~
~~.N?eA.DN2+T\*G+LT\_B\*Y@hc1tN2\*G+LT\_BY~~
.N?eA.DN2+T*G+LT_B*Y@cNtN2*G+LT_BY
```
[Try it online!](http://pyth.herokuapp.com/?code=.N%3FeA.DN2%2BT%2aG%2BLT_B%2aY%40cNtN2%2aG%2BLT_BY%3A.%2a&test_suite=1&test_suite_input=5%2C+3%2C+1.414%0A2%2C+0.5%2C+1.5&debug=0)
(The code above defines a function. `:.*` is appended on the link to invoke the function.)
## The maths
This constructs the data symmetrically. If `N` is even, then the data are just the mean plus or minus the standard deviation. However, if `N` is odd, then we just opened a can of worms, since the mean has to be present for the data to be symmetric, and so the fluctuations have to be multiplied by a certain factor.
### If `n` is even
* Half of the data are `μ+σ`.
* Half of the data are `μ-σ`.
### If `n` is odd
* One datum is `μ`.
* Less than half of the data are `μ+σ*sqrt(n/(n-1))`.
* Less than half of the data are `μ-σ*sqrt(n/(n-1))`.
[Answer]
# [MATL](https://github.com/lmendo/MATL), 22 bytes
*Thanks to [@DigitalTrauma](https://codegolf.stackexchange.com/users/11259/digital-trauma) for a correction.*
```
:t&1Zs/tYm-*+tZN?3G9L(
```
Input order is: `N`, `σ`, `μ`.
[Try it online!](https://tio.run/nexus/matl#@29VomYYVaxfEpmrq6VdEuVnX2Hs/v@/MZcpl5GeoZkBAA)
Or see a [modified version](https://tio.run/nexus/matl#@29VomYYVaxfEpmrq6VdEuVnb@xu6aPxPzbCSwEIVBWS8wsqFTLzSvIVknMyC5LyE4tSFLy4vCJzIdIFicUlqQqJeSlAhbkFpUB2bmpiHpcXyFDs8sUlQB7IlJTUsszEksz8vP/GXKZcRnqGZgYA) that also computes the mean and standard deviation of the produced data, as a check.
### Explanation
The code is divided into four parts:
1. `:` generates the array `[1 2 ... N]` where `N` is taken as implicit input.
2. `t&1Zs/` divides those numbers by their empirical standard deviation (computed normalizing by `N`), and `tYm-` subtracts the empirical mean of the resulting values. This ensures that the results have empirical mean `0` and empirical standard deviation `1`.
3. `*` multiplies by `σ` and `+` adds `μ`, both taken as implicit inputs.
4. `tZN?x3G` handles the special case that `N = 1`, `σ = 0`, for which the output should be `μ`. If this is indeed the case, then the empirical standard deviation computed in the second step was `0`, the division gave `inf`, and multiplying by `σ` in the third step gave `NaN`. So what the code does is: if the obtained array consists of all `NaN` values (code `tZN?`), delete it (`x`) and push the third input (`3G`), which is `μ`.
[Answer]
## R, ~~83~~ ~~62~~ 53 bytes
```
function(n,m,s)`if`(n>1,scale(1:n)*s*sqrt(1-1/n)+m,m)
```
If `n=1`, then it returns `m` (since `scale` would return `NA`), otherwise it scales the data `[1,...,n]` to have mean 0 and (sample) standard deviation 1, so it multiplies by `s*sqrt(1-1/n)` to get the correct population standard deviation, and adds `m` to shift to the appropriate mean. Thanks to Dason for introducing me to the scale function and dropping those bytes!
[Try it online!](https://tio.run/nexus/r#bY7BboMwDIbveQpLOzShgeJQLlN5la0RuBSJhIyEirdnyYrWw3bzZ/vz761vbottwzBZbqWRXlyH25XbpsFErR6J47sVmc/81xw45niy4mgEY8xN7tN3cMnh98QqnlunkWwf7pEzvxjO19yQTmPxoYSANxiMG8mQDdRBmKCdjFsCQbgTaOfmyc2DjuyDtp2eO@joERsxIsbOgw38EMgHaLUnwINgKzY9V7IsaolFnZg9E1Hsf/6Uf2WVZBXlWkIlAYsznlNn19VLV//pVdIraKDnKLGUZcLdrV5uLNm2fQM)
[Answer]
# [Python](https://docs.python.org/3/), 50 bytes
```
lambda n,m,s:[m+s*(n-1)**.5]+[m-s/(n-1%n)**.5]*~-n
```
[Try it online!](https://tio.run/nexus/python3#XZDNboMwDMfP@ClymZSkISVp2QGJJ2Ec2AoaUhwqzKae9urMCT1MkxLFP3/8bWdq3/Yw4PttENGgoabDE2kZS6e0tnV/6rCkc@KXeHj0Txn3Ge/Lugkctk8AHIcoWvGUCY2zlaYvlEGdwxj5AbqN338zpLPPUE7sHlp7MS2reIg5itCrMmmmsPZ8K1sDbCNtxCKd9Eawxwhna2UkG5dkX92ViU12eOteK2XEf3RcyUf1AB9hoZHl0gp2powAaYb8D2mO3LGBInDaJLNbQYE@VR3jQUGJ0nqZ7uscN5m1JBr03PMAMpTg2Llto9p/AQ "Python 3 – TIO Nexus")
Uses the following `n`-element distribution with mean `0` and sdev `1`:
* With probability `1/n` (i.e. `1` element), output `(n-1)**0.5`
* With probability `1-1/n` (i.e. `n-1` elements), output `-(n-1)**(-0.5)`
This is rescaled to mean `m` and sdev `s` by transforming `x->m+s*x`. Annoyingly, `n=1` gives a division by zero error for a useless value, so we hack it away by doing `/(n-1%n)**.5`, with `1%n` giving `0` for `n==1` and `1` otherwise.
You might think `(n-1)**.5` can be shortened to `~-n**.5`, but the exponentiation happens first.
A `def` is one byte longer.
```
def f(n,m,s):a=(n-1%n)**.5;print[m+s*a]+[m-s/a]*~-n
```
[Answer]
# [R](https://www.r-project.org/), ~~50~~ 46 bytes
```
function(n,m,s,l=n-1)m+s*c(rep(l^-.5,l),-l^.5)
```
[Try it online!](https://tio.run/##VY7BDoIwEETP9DM4dXVLKFhv/RND0tQihlIIrVyM345NBY2nfTPZ2Z15Ja3qjQ8qeLm2D6fDfXTU4YAerXSMw3D0B01nM1HbsEKgBWS2KQSsujO6l/8heJJsGid//fkLDEY5SheW5gLQVBAPkEw5L7/vtzzJtArUGncLHY0LgCmVKB3@YH4JOUaK4HIgL5LK0ApjQx7LbVpgHeWJn3ajRoFVwc@75lhiCesb "R – Try It Online")
(Reading the other answers now after posting, I realise that this is the same approach as [xnor's Python answer](https://codegolf.stackexchange.com/a/117540/95126))
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 20 [bytes](https://github.com/DennisMitchell/jelly)
```
÷_Ḃ$©$*.;N$ṁ®;0ṁ⁸×⁵+
```
**[Try it online!](https://tio.run/nexus/jelly#@394e/zDHU0qh1aqaOlZ@6k83Nl4aJ21AZB61Ljj8PRHjVu1////b/rf@L@hnomhCQA "Jelly – TIO Nexus")**
Full program taking three command line arguments: **n**, **μ**, **σ**.
### How?
Creates **floor(n / 2)** values equidistant from the mean and a value at the mean if **n** is odd such that the standard deviation is correct...
```
÷_Ḃ$©$*.;N$ṁ®;0ṁ⁸×⁵+ - Main link: n, μ (σ expected as third input, the 5th command argument)
$ - last two links as a monad:
_ - n minus:
Ḃ - n mod 2 i.e. n-1 if n is odd, n if n is even
© - copy value to register
√∑ - n divided by that
. - literal 0.5
* - exponentiate = (n / (n - (n mod 2))) ^ 0.5
- i.e. 1 if n is even; or (n/(n-1))^0.5 if n is odd
$ - last two links as a monad:
N - negate
; - concatenate i.e. [1,-1] or [(n/(n-1))^0.5,-(n/(n-1))^0.5]
® - recall value from register
ṁ - mould the list like something of that length
;0 - concatenate a zero
⁸ - link's left argument, n
ṁ - mould the list like something of length n (removes the zero for even n)
⁵ - fifth command argument, third program argument (σ)
√ó - multiply (vectorises)
+ - add μ (vectorises)
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 56 bytes
```
(N,m,s)=>[...Array(N)].map(_=>N--?m-s/a:m+s*a,a=--N**.5)
```
[Try it online!](https://tio.run/##ZctBCsIwEADAuy/J1t21SYkHJRU/kA@IyFJbUZqmJCL4@ige63mYh7wkd@k@P2mK174MriiPATO49sTMx5TkrTycOcisLq71RIdAeSO7sM6VoDgiX1VsoexXXZxyHHse400NyiBb1F@BBVhs0PzOUhq0aFhv/0BjjTVA@QA "JavaScript (Node.js) – Try It Online")
Port of Python solution
# JavaScript (Node.js)], 70 bytes
```
(N,u,s)=>g=(...L)=>1/L[N-1]?L:g(1/L[1]?u:u+u-L[0]||u+s*(N/2)**.5,...L)
```
[Try it online!](https://tio.run/##bYtBDoIwEEX3nmRahqEtqQsMeoGGCxAWBIFICDXWuuLutXVp2L3/X97Sf3o3vB7Pd77Z@ximOkCDHh2rr3MNRGQiycK0TS67m6lmSCOir3zmc9OKbt995jg0hWKck8ZfFC6nwW7OriOtdoYJFEYlSTNg7E9pLFGl9MCVqFGRPB8oiQJF@sMX "JavaScript (Node.js) – Try It Online")
Without a calculator in question I need to find one somewhere else
] |
[Question]
[
Imagine a bunch of rectangles drawn in the plane, each rectangle with its vertices at integer coordinates and its sides parallel to the axes:

The rectangles partition the plane into a number of disjoint regions, coloured red and blue below:

Your goal is to find the number of such regions which are perfect squares. In the example above, there are three:

Note that the big square in the middle is not counted as it is not a single region, but is instead made up of several smaller disjoint regions.
## Input
You may write a function or a full program for this challenge.
Input will be `4n` nonnegative integers defining `n` rectangles in the plane. Each rectangle is represented by two opposing vertices, e.g. `4 9 7 8` represents the rectangle with opposing vertices `(4, 9)` and `(7, 8)`. Note that this rectangle could also be represented as `7 8 4 9` or `4 8 7 9`.
The exact input format is flexible (e.g. space-separated string, comma-separated string, single array of integers, list of coordinate tuples, and so on) but please [be reasonable](http://meta.codegolf.stackexchange.com/questions/1061/standard-loopholes-which-are-no-longer-funny) and give an example of how to run your code in your post. You may not reorder the input.
For simplicity, you can assume that no two edges will be overlapping — this includes overlapping at a vertex. In particular, this implies that no two rectangles will be touching edge-to-edge or corner-to-corner, and the rectangles will have nonzero area.
## Output
Your program should print or return a single integer, which is the number of square regions.
## Scoring
This is code golf, so the code in the fewest bytes wins.
---
## Test cases
**Input:**
```
0 0 5 5
6 8 10 4
14 16 11 13
19 1 18 2
```
**Output:**
```
4
```
This is simply four disjoint squares:

---
**Input:**
```
2 1 3 11
1 10 5 19
6 10 11 3
8 8 15 15
13 13 9 5
15 1 19 7
17 19 19 17
```
**Output:**
```
3
```
This is the example test case at the start of the post.
---
**Input:**
```
0 9 15 12
6 3 18 15
9 6 12 20
13 4 17 8
```
**Output:**
```
7
```

---
**Input:**
```
5 9 11 10
5 12 11 13
6 8 7 14
9 8 10 14
13 8 14 9
13 10 14 14
```
**Output:**
```
14
```

---
**Input:**
```
0 99999 100000 0
```
**Output:**
```
0
```
This is just one big rectangle.
---
**Input:**
```
0 99999 100000 0
2 1 142857 285714
```
**Output:**
```
1
```
Two big rectangles which overlap.
[Answer]
# Python 2, ~~480 436 386~~ 352 bytes
```
exec u"""s=sorted;H=[];V=[]
FRIinput():
S=2*map(s,zip(*R))
FiI0,1,2,3:
c=S[i][i/2];a,b=S[~i]
FeIs(H):
C,(A,B)=e
if a<C<b&A<c<B:e[:]=C,(A,c);H+=[C,(c,B)],;V+=[c,(a,C)],;a=C
V+=[c,(a,b)],;H,V=V,H
print sum(a==A==(d,D)&c==C==(b,B)&B-b==D-d&1-any(d<X[0]<D&b<y<B Fy,XIH)Fb,aIH FB,AIH Fd,cIV FD,CIV)""".translate({70:u"for ",73:u" in ",38:u" and "})
```
Takes a list of coordinate pairs through STDIN in the format:
```
[ [(x, y), (x, y)], [(x, y), (x, y)], ... ]
```
and prints the result to STDOUT.
The actual program, after string replacement, is:
```
s=sorted;H=[];V=[]
for R in input():
S=2*map(s,zip(*R))
for i in 0,1,2,3:
c=S[i][i/2];a,b=S[~i]
for e in s(H):
C,(A,B)=e
if a<C<b and A<c<B:e[:]=C,(A,c);H+=[C,(c,B)],;V+=[c,(a,C)],;a=C
V+=[c,(a,b)],;H,V=V,H
print sum(a==A==(d,D) and c==C==(b,B) and B-b==D-d and 1-any(d<X[0]<D and b<y<B for y,X in H)for b,a in H for B,A in H for d,c in V for D,C in V)
```
## Explanation
Instead of fiddling with complex polygons, this program deals with simple line segments.
For each input rectangle, we add each of its four edges to a collective segment list, individually.
Adding a segment to the list goes as follows:
we test each of the existing segments for intersection with the new segment;
if we find an intersection, we divide both segments at the point of intersection and continue.
To make things easier, we actually keep two separate segment lists: a horizonal one and a vertical one.
Since segments don't overlap, horizontal segments can only intersect vertical segments and vice versa.
Better yet, it means that all intersections (not considering the edges of the same rectangle) are "proper," i.e., we don't have T-shaped intersections, so "both sides" of each segment are truly divided.
Once we've constructed the segment list(s), we start counting squares.
For each combination of four segments (particularly, two horizontal segments and two vertical ones,) we test if they form a square.
Furthermore, we verify that no vertex lies within this square (which can happen if, for example, we have a small square inside a bigger one.)
This gives us the desired quantity. Note that even though the program tests each combination four times in different orders, the particular ordering of the segment coordinates guarantees that we count each square only once.
[Answer]
## SQL (POSTGIS), ~~286~~ ~~269~~ ~~261~~ ~~240~~ ~~226~~ ~~218~~ 216
This is a query for the PostGIS extension to PostgreSQL.
I haven't counted the input values in the total.
```
SELECT SUM(1)FROM(SELECT(ST_Dump(ST_Polygonize(g))).geom d FROM(SELECT ST_Union(ST_Boundary(ST_MakeEnvelope(a,b,c,d)))g FROM(VALUES
-- Coordinate input
(2, 1, 3, 11)
,(1, 10, 5, 19)
,(6, 10, 11, 3)
,(8, 8, 15, 15)
,(13, 13, 9, 5)
,(15, 1, 19, 7)
,(17, 19, 19, 17)
)i(a,b,c,d))i)a WHERE(ST_XMax(d)-ST_XMin(d))^2+(ST_YMax(d)-ST_YMin(d))^2=ST_Area(d)*2
```
**Explanation**
The query builds geometries for each coordinate pair. Unions the exterior rings to properly node the lines. Turns the results into polygons and tests ~~the width against height and~~ the area doubled against the sum of each side squared.
It will run as a standalone query on any PostgreSQL database with the PostGIS Extension.
**Edit** Found a couple more.
[Answer]
# Haskell, ~~276 266 250 237 225 222~~ 217 bytes
It keeps getting shorter... and more obfuscated.
```
(x#i)l=mapM id[[min x i..max x i-1],l]
(y!j)l f=and[p l==p(f[y,j])|p<-map elem$f[y..j]]
s[h,v]=sum[1|[x,j]<-h,[y,i]<-v,x<i,i-x==j-y,(y!j)h$x#i,(x!i)v$y#j]
n=s.foldr(\(x,y,i,j)->zipWith(++)[x#i$[y,j],y#j$[x,i]])[[],[]]
```
Evaluate `n [(0,0,5,5),(6,8,10,4),(14,16,11,13),(19,1,18,2)]` for the first test case. I think I'm getting close to the limits of golfing this algorithm on Haskell.
This function is so slow (at least *O(n3)* where *n* is the total perimeter of all rectangles in the input) that I cannot evaluate it on the last two test cases. When I compiled it with optimizations turned on and run it on the 400-times shrunk version `[(0,249,250,0),(2,1,357,714)]` of the last test, it finished in a little over 12 seconds. Based on this, the actual test case would finish in about 25 years.
### Explanation (partial, I will expand this when I have time)
We first build two lists `h` and `v` as follows. For each rectangle in the input, we split its border into segments of length 1. The west endpoints of horizontal segments are stored in `h`, and the south endpoints of vertical segments in `v`, as lists `[x,y]` of length 2. The coordinates in `v` are stored in a reversed form as `[y,x]` for golfing reasons. Then we just loop over both lists and search for horizontal edge `[x,j]` and vertical edge `[i,y]` such that `x < i` and `i-x == j-y` (so they are the northwest and southeast corners of a square), and check that the borders of the square are in the correct lists `h` and `v`, while the interior coordinates are not. The number of the positive instances of the search is the output.
] |
[Question]
[
## Introduction
You have recently accepted a job offer at a Pretty Good Software Company. You're pretty content with the size of your office, but do you have the **biggest** office? Its kinda hard to tell from just eyeballing your co-workers' offices when you stop by. The only way to figure this out is to examine the blueprints for the building...
## Your Task
Write a program, script, or function that takes a floor plan for your building and indicates whether your office is the largest. The floor plan is easy to read because the building is an *n* by *n* square.
The input will consist of *n+1* `\n`-delimited lines. The first line will have the number *n* on it. The next *n* lines will be the floorplan for the building. A simple example input:
```
6
......
. . .
.X . .
. . .
. . .
......
```
The rules for the floorplan are as follows:
* `.` (ASCII 46) Will be used to represent walls. (Space [ASCII 32]) will be used to represent open space.
* You are represented by an `X` (ASCII 88). You are in your office.
* The floorplan will be *n* lines, each with *n* characters.
* The building is totally surrounded by walls on all sides. This implies that the 2nd line of input (the first line of the floorplan) and the last line of input will be all `.`s. It also implies that the first and last characters of every floorplan line will be `.`s.
* An office size is defined as the sum of adjacent spaces (contiguous by moving in 4 directions, N, S, E, W, without going through a wall).
* For the purpose of office size, the X representing you counts as a (open space)
* 4 <= *n* <= 80
You should output whether or not your office is strictly bigger than all the other offices. The output can be anything that unambiguously signifies True or False in your programming language of choice and adheres to standard conventions of zero, null, and empty signifying False. True implies your office is strictly the biggest.
Sample output for above input:
```
1
```
Because your office is 8 square feet, and the only other office is 4 square feet.
## I/O Guidelines
* The input may be read from stdin, and answer output to stdout.
Or
* The input may be a single string argument to a function, and answer be the return value of that function.
## FAQ
* The entire building consists of walls and offices.
* The building is only one floor
* There is guaranteed to be an X in the input, but there are not guaranteed to be any spaces. You could have a 1x1 office and the rest of the building is walls (You have the biggest office! hooray!).
### Other Example
```
10
..........
. . . .
. . . .
. . . .
. .. . .
.. .
..........
. X .
. .
..........
```
Here there are 3 offices, your south office is rectangular, the northwest office is a triangle(ish) and the northeast office is strangely misshapen, yet bigger than yours. The output should be False.
This is a challenge to write the shortest code, happy [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'")ing!
[Answer]
## Ruby 2.0, 133 characters
A collaboration with @Ventero. Always a good sign when it starts breaking the syntax highlighter!
This is a recursive flood-fill solution. Reads from STDIN and outputs to STDOUT:
```
f=->*a{a.product([~n=$_.to_i,-1,1,n+1]){|p,d|a|=[p]if$_[p+=d]<?.}!=a ?f[*a]:a.size}
gets(p).scan(/ /){$*<<f[$`.size]}
p$*.max<f[~/X/]
```
See it [running on Ideone](http://ideone.com/8A8MBD).
[Answer]
## GolfScript (85 bytes)
```
n/(~.*:N:^;{{5%[0.^(:^N]=}/]}%{{{.2$*!!{[\]$-1=.}*}*]}%zip}N*[]*0-:A{.N=A@-,2*+}$0=N=
```
[Online demo](http://golfscript.apphb.com/?c=O1snNgouLi4uLi4KLiAgLiAuCi5YIC4gLgouICAuIC4KLiAgLiAuCi4uLi4uLicKCicxMAouLi4uLi4uLi4uCi4gICAuICAuIC4KLiAgLiAgIC4gLgouICAuICAgLiAuCi4gLi4gICAuIC4KLi4gICAgICAgLgouLi4uLi4uLi4uCi4gICAgICBYIC4KLiAgICAgICAgLgouLi4uLi4uLi4uJwoKJzcKLi4uLi4uLgouIC4gLiAuCi4gLiAuIC4KLiAuWC4gLgouIC4gLiAuCi4gLiAuIC4KLi4uLi4uLiddewojIEVuZCBvZiB0ZXN0aW5nIGZyYW1ld29yayBwcmVmaXgKCm4vKH4uKjpOOl47e3s1JVswLl4oOl5OXT19L119JXt7ey4yJCohIXtbXF0kLTE9Ln0qfSpdfSV6aXB9TipbXSowLTpBey5OPUFALSwyKit9JDA9Tj0KCiMgU3RhcnQgb2YgdGVzdGluZyBmcmFtZXdvcmsgc3VmZml4CnB9LwoK)
This has three sections:
1. An initial input transformation which produces a 2D array using `0` to represent a wall, `N` (the total number of cells) to represent my starting position, and a distinct number between those for each other open space.
```
n/(~.*:N:^;{{5%[0.^(:^N]=}/]}%
```
2. A flood-fill.
```
{{{.2$*!!{[\]$-1=.}*}*]}%zip}N*
```
3. The final counting. This uses a variant on the tip for [most common element in an array](https://codegolf.stackexchange.com/a/25737/194), adding a tie-breaker which biases against `N`.
```
[]*0-:A{.N=A@-,2*+}$0=N=
```
[Answer]
# Javascript (E6) 155 ~~292~~
```
F=(a,n=parseInt(a)+1,x,y)=>[...a].map((t,p,b,e=0,f=p=>b[p]==' '|(b[p]=='X'&&(e=1))&&(b[p]=1,1+f(p+n)+f(p-n)+f(p+1)+f(p-1)))=>(t=f(p))&&e?y=t:t<x?0:x=t)|y>x
```
**Ungolfed base version**
```
F=a=>
{
var k, max=0, my=0, k=1, t, n = parseInt(a)+1;
[...a].forEach(
(e,p,b) =>
{
x=0;
F=p=>
{
var r = 1;
if (b[p] == 'X') x = 1;
else if (b[p] != ' ') return 0;
b[p] = k;
[n,1,-n,-1].forEach(q => r+=F(q+p));
return r;
}
t = F(p);
if (t) {
if (x) my = t;
if (t > max) max = t;
k++;
console.log(b.join(''));
}
}
)
return my >= max
}
```
**Test**
Javascript console in firefox
`F('6\n......\n. . .\n.X . .\n. . .\n. . .\n......')`
```
1
```
`F('10\n..........\n. . . .\n. . . .\n. . . .\n. .. . .\n.. .\n..........\n. X .\n. .\n..........\n')`
```
0
```
[Answer]
### C#, ~~444~~ 372/(342 thanks HackerCow)bytes
Rather poor score and late to the party, but seems to work. Outputs 1 when you have the single biggest office, 0 when you do not. I've not been very intricate with the golfing yet. Works by building up disjoint sets from the input (first loop), tallying the size of each set (second loop) and then looking to see if my set is the largest (third loop).
Two versions are provided, one is a compilable program tat accepts the input from the command line, the other is just a function that expects a string as input and returns an int as the result (and is just a reworked copy of the first) - it does not need any using clauses or the like, should be able to put it anywhere and it will work.
Program *372bytes*:
```
using System;class P{static void Main(){int s=int.Parse(Console.ReadLine()),e=0,d=s*s,a=d;int[]t=new int[d],r=new int[d];Func<int,int>T=null,k=v=>t[T(v)]=t[v]>0?a:0;T=v=>t[v]!=v?T(t[v]):v;for(;a>0;)foreach(var m in Console.ReadLine()){a--;if(m!=46){t[a]=a;e=m>46?a:e;k(a+s);k(a+1);}}for(a=d;a-->2;)r[T(a)]++;for(;d-->1;)a=d!=T(e)&&r[d]>=r[T(e)]?0:a;Console.WriteLine(a);}}
```
Function *342bytes*:
```
static int F(string g){var b=g.Split('\n');int s=int.Parse(b[0]),e=0,d=s*s,a=d;int[]t=new int[d],r=new int[d];System.Func<int,int>T=null,k=v=>t[T(v)]=t[v]>0?a:0;T=v=>t[v]!=v?T(t[v]):v;for(;a>0;)foreach(var m in b[a/s]){a--;if(m!=46){t[a]=a;e=m>46?a:e;k(a+s);k(a+1);}}for(a=d;a-->2;)r[T(a)]++;for(;d-->1;)a=d!=T(e)&&r[d]>=r[T(e)]?0:a;return a;
```
Less golfed:
```
using System;
class P
{
static int F(string g)
{
var b=g.Split('\n');
int s=int.Parse(b[0]),e=0,d=s*s,a=d;
int[]t=new int[d],r=new int[d];
System.Func<int,int>T=null,k=v=>t[T(v)]=t[v]>0?a:0;
T=v=>t[v]!=v?T(t[v]):v;
for(;a>0;)
foreach(var m in b[a/s])
{
a--;
if(m!=46)
{
t[a]=a;
e=m>46?a:e;
k(a+s);
k(a+1);
}
}
for(a=d;a-->2;)
r[T(a)]++;
for(;d-->1;)
a=d!=T(e)&&r[d]>=r[T(e)]?0:a;
return a;
}
static void Main()
{
/* F() test
var s=Console.ReadLine();
int i=int.Parse(s);
for(;i-->0;)
{
s+="\n"+Console.ReadLine();
}
Console.WriteLine(F(s));*/
int s=int.Parse(Console.ReadLine()),e=0,d=s*s,a=d;
int[]t=new int[d],r=new int[d];
Func<int,int>T=null,k=v=>t[T(v)]=t[v]>0?a:0;
T=v=>t[v]!=v?T(t[v]):v;
for(;a>0;)
foreach(var m in Console.ReadLine())
{
a--;
if(m!=46)
{
t[a]=a;
e=m>46?a:e;
k(a+s);
k(a+1);
}
}
for(a=d;a-->2;)
r[T(a)]++;
for(;d-->1;)
a=d!=T(e)&&r[d]>=r[T(e)]?0:a;
Console.WriteLine(a);
}
}
```
[Answer]
## CJam, 106 bytes
A different approach to flood fill. Although, makes it longer ...
```
liqN-'Xs0aer\_:L*{_A=' ={[AAL-A(]1$f=$:D1=Sc<{D2<(aer}*D0=_' ={T):T}@?A\t}*}fAT),\f{\a/,}_$W%_2<~>@@0=#0=&
```
[Try it here](http://cjam.aditsu.net/)
[Answer]
# Python 2 - 258 bytes
```
r=range;h=input();m="".join(raw_input()for x in r(h))
w=len(m)/h;n=0;f=[x!='.'for x in m]
for i in r(w*h):
if f[i]:
a=[i];M=s=0
while a:
i=a.pop();s+=1;M|=m[i]=='X';f[i]=0
for j in(i-1,i+1,i-w,i+w):a+=[[],[j]][f[j]]
n=max(s,n)
if M:A=s
print A==n
```
uses stdin for input
Note: first `if` is indented by a single space, other indented lines are either using a single tab char or a tab and a space.
[Answer]
## J : 150 121 bytes
```
(({~[:($<@#:I.@,)p=1:)=([:({.@#~(=>./))/@|:@}.({.,#)/.~@,))(>./**@{.)@(((,|."1)0,.0 _1 1)&|.)^:_[(*i.@:$)2>p=:' X'i.];._2
```
*Edit*: `id` and `comp` were ridiculously complicated and slow.
Now it works shifting the map 4 times, instead of scanning it with a 3x3 window using `cut` (`;.`).
Takes as argument the blueprint as string. Explained below:
```
s =: 0 :0
..........
. . . .
. . . .
. . . .
. .. . .
.. .
..........
. X .
. .
..........
)
p=:' X' i. ];._2 s NB. 0 where space, 1 where X, 2 where wall
id=:*i.@:$2>p NB. Give indices (>0) to each space
comp =: (>./ * *@{.)@shift^:_@id NB. 4 connected neighbor using shift
shift =: ((,|."1)0,.0 _1 1)&|. NB. generate 4 shifts
size=:|:}.({.,#)/.~ , comp NB. compute sizes of all components
NB. (consider that wall is always the first, so ditch the wall surface with }.)
NB. is the component where X is the one with the maximal size?
i=: $<@#:I.@, NB. find index where argument is 1
(comp {~ i p=1:) = {.((=>./)@{: # {.) size
NB. golfed:
(({~[:($<@#:I.@,)p=1:)=([:({.@#~(=>./))/@|:@}.({.,#)/.~@,))(>./**@{.)@(((,|."1)0,.0 _1 1)&|.)^:_[(*i.@:$)2>p=:' X'i.];._2 s
0
```
[Answer]
# Python 2 - 378 bytes
*Wow.* I'm out of practice.
```
def t(l,x,y,m,c=' '):
if l[y][x]==c:l[y][x]=m;l=t(l,x-1,y,m);l=t(l,x+1,y,m);l=t(l,x,y-1,m);l=t(l,x,y+1,m)
return l
def f(s):
l=s.split('\n');r=range(int(l.pop(0)));l=map(list,l);n=1
for y in r:
for x in r:l=t(l,x,y,*'0X')
for y in r:
for x in r:
if l[y][x]==' ':l=t(l,x,y,`n`);n+=1
u=sum(l,[]).count;o=sorted(map(u,map(str,range(n))));return n<2or u('0')==o[-1]!=o[-2]
```
This is a function answer, but it pollutes the global namespace. If this is unacceptable, it can be fixed at the cost of 1 byte:
* Add a space to the beginning of line 1 (+1)
* Replace the space at the beginning of lines 2 and 3 with a tab character (+0)
* Move line 4 to the beginning (+0)
I had a whole long explanation written out, but apparently it didn't save properly and I'm not doing that again l m a o
] |
[Question]
[
Write a function or program than can do simple arithmetic (addition, subtraction, multiplication and division) in both base 10 and base 2.
The function will take a mathematical expression as input, and output the correct result in the correct base. The input will be `n` numbers separated by one or several operators (`+ - * /`).
If all input values contain only 0 and 1, all values are considered to be binary. If at least one digit is `2-9`, all values are considered to be base 10.
**Rules:**
* You can assume there will only be one operator between numbers (`10*-1` will not appear)
* You can assume there will be no parentheses.
* Normal operator precedence (try the expression in the google calculator if you're in doubt).
* You can not assume there will only be integers
* There will be no leading zeros in input or output
* You can assume only valid input will be given
* You can assume all input values are positive (but the minus operator may make negative output possible, `1-2=-1` and `10-100=-10`)
* REPL is not accepted
* You may choose to take the input as separate arguments, or as a single argument, but the input *has* to be in the correct order.
+ I.e. you may represent `1-2` with the input arguments `1`, `-`, `2`, but not `1`, `2`, `-`.
* You must accept the symbols `+ - * /` in the input, not `plus`, `minus` etc.
* You must support floating point values (or up to the maximum limit of your language, however supporting only integers is not accepted).
* `eval` is accepted
**Examples:**
```
1+1
10
1010+10-1
1011
102+10-1
111
1+2+3
6
10*10*10
1000
11*11*11
11011
10*11*12+1
1321
10.1*10.1
110.01
20.2*20.2
408.04
10/5
2
110/10
11
Also accepted (optional line or comma-separated input):
10
+
10
-
1
11 <-- This is the output
```
This is code golf, so the shortest code in bytes will win.
[Answer]
## JavaScript ES6, ~~87~~ ~~971~~ ~~1002~~ ~~1063~~ ~~102~~ ~~101~~ ~~98~~ ~~1004~~ ~~93~~ ~~88~~ 86 bytes
```
e=>eval(e.match`[2-9]`?e:`(${e.replace(/[\d.]+/g,"('0b'+$&e14)/16384")}).toString(2)`)
```
Demo + explanation:
```
function c(e){
return eval(
e.match`[2-9]`? //check if there are numbers 2 to 9
e: //if there're, just compute the result
"("+
e.replace( //otherwise replace...
/[\d.]+/g, //any number...
"(('0b'+$&e14)/16384)" //...with itself converted to base 10
)
+").toString(2)" //compute the result and convert it to binary
)
}
document.write(
c("1.1*1.1")+"<br>"+
c("1010+10-1")+"<br>"+
c("102+10-1")+"<br>"+
c("1+2+3")+"<br>"+
c("10*10*10")+"<br>"+
c("11*11*11")+"<br>"+
c("10*11*12+1")+"<br>"+
c("10.1*10.1")+"<br>"+
c("20.2*20.2")+"<br>"+
c("10/5")+"<br>"+
c(`10
+
10
-
1`)
)
```
---
1 - forgot about floats
2 - again floats problem: parseInt floors binary so I have to multiply by 1e14 and then divide by 16384
3 - hope that's achieved the given task, now start to golf :D
4 - there was a bug with dividing
[Answer]
## Japt, ~~77~~ ~~72~~ ~~62~~ ~~60~~ ~~62\*~~ ~~60~~ ~~59~~ 51 bytes
```
OvUf"[2-9]" ?U:"({Ur"[\\d.]+""º$&e14+P n2 /2pE¹"})¤
```
Explanation (more or less the same as for the JS answer):
```
Ov //eval...
Uf"[2-9]" //if input contains the digits 2 to 9
U: //then it's base 10, just compute
Ur"[\\d.]+" //otherwise replace all the numbers
"º$&e14+P n2 /2pE¹" //with their base 10 equivalents
//I.e., take every number, multiple by 10^14, convert to
//base 10 and divide by 2^14
// º and ¹ are multiple brackets
¤ //means "s2", i.e. convert the result to binary
```
[Try it online!](http://ethproductions.github.io/japt?v=master&code=T3ZVZiJbMi05XSIgP1U6Iih7VXIiW1xcZC5dKyIiuiQmZTE0K1AgbjIgLzJwRbkifSmk&input=IjEwLjEqMTAuMSI=)
---
\* didn't divide properly
[Answer]
# Jolf, 31 bytes, noncompeting
I added a decent amount of functions inspired by this challenge, and, as thus, it is considered noncompeting. I'm happy because I finally implemented unary functions (like `(H,S,n)=>val` in ES6, but are supported in ES5!)
```
? hi"[2-9]"~eiB~epT mpvid|m'H2H
? hi"[2-9]" if the input contains any of 2..9
~ei evaluate i (implicitly print)
else
_mpvid map the input split into number groups
m'H2 to H as a binary float
| H (or keep H, if that doesn't work)
pT join by spaces
~e evaluate
B convert to binary (implicitly print)
```
[Test suite](http://conorobrien-foxx.github.io/Jolf/#code=PyBoaSJbMi05XSJ-ZWlCfmVwVCBtcHZpZHxtJ0gySA&input=MSsxCgoxMDEwKzEwLTEKCjEwMisxMC0xCgoxKzIrMwoKMTAqMTAqMTAKCjExKjExKjExCgoxMCoxMSoxMisxCgoxMC4xKjEwLjEKCjIwLjIqMjAuMgoKMTAvNQoKMTEwLzEw), [Try your own input](http://conorobrien-foxx.github.io/Jolf/#code=PyBoaSJbMi05XSJ-ZWlCfmVwVCBtcHZpZHxtJ0gySA), [or manually set the input](http://conorobrien-foxx.github.io/Jolf/#code=b2kiWU9VUiBRVUVSWSBIRVJFIgo_IGhpIlsyLTldIn5laUJ-ZXBUIG1wdmlkfG0nSDJI).
[Answer]
# Bash, 60 bytes
```
[ -z `tr -dc 2-9<<<$1` ]&&s='obase=2;ibase=2;';bc -l<<<$s$1
```
Example Run:
```
$ ./bin_dec_add.sh 1+1
10
$ ./bin_dec_add.sh 1+2
3
```
[Answer]
# ùîºùïäùïÑùïöùïü 2, 46 chars / 72 bytes
```
ë(ïđ/[2-9]⎞?ï:`(⦃ïē/[\d.]+⌿,↪(Յ+$*ḊⁿḎ)/Ẁ²)})ⓑ`
```
`[Try it here (Firefox only).](http://molarmanful.github.io/ESMin/interpreter2.html?eval=false&input=10.1*10.1&code=%C3%AB%28%C3%AF%C4%91%2F%5B2-9%5D%E2%8E%9E%3F%C3%AF%3A%60%28%E2%A6%83%C3%AF%C4%93%2F%5B%5Cd.%5D%2B%E2%8C%BF%2C%E2%86%AA%28%D5%85%2B%24*%E1%B8%8A%E2%81%BF%E1%B8%8E%29%2F%E1%BA%80%C2%B2%29%7D%29%E2%93%91%60)`
# Explanation
```
ë(ïđ/[2-9]⎞?ï:`(⦃ïē/[\d.]+⌿,↪(Յ+$*ḊⁿḎ)/Ẁ²)})ⓑ` // implicit: ï=input, Ḋ=10, Ḏ=14, Ẁ=128
ë( // eval
ïđ/[2-9]⎞? // does ï have 2-9?
ï // if so, eval input
: // else, eval:
`(⦃ïē/[\d.]+⌿, // replace the binary numbers
// with their base 10 equivalents:
‚Ü™(’Ö+ // translates to `0b`
$*ḊⁿḎ // matched number * 10^14
)/Ẁ² // divided by 128^2
)})‚ìë` // converted to binary
// implicit output
```
[Answer]
# PowerShell, 107 bytes
```
param($e)iex(("{0}String($($e-replace'(\d+)','{0}Int32("$1",2)'),2)"-f'[Convert]::To'),$e)[$e-match'[2-9]']
```
# Ungolfed
```
param($e) # Accept single argument
Invoke-Expression # Eval
( # Expression, resulting in an array of 2 elements
(
"{0}String( # Binary
$( # Inline subexpression
$e -replace'(\d+)', '{0}Int32("$1",2)'
# "1010+10-1" becomes "{0}Int32("1010",2)+{0}Int32("10",2)-{0}Int32("1",2)"
)
,2)"
-f '[Convert]::To'
# "{0}Int32("1010",2)+{0}Int32("10",2)-{0}Int32("1",2)" becomes
"[Convert]::ToString([Convert]::ToInt32("1010",2)+[Convert]::ToInt32("10",2)-[Convert]::ToInt32("1",2),2)"
),
$e # Plain
)
[$e-match'[2-9]'] # Return 1st element of array if regex matches, else 0
```
# Example
```
PS > .\Calc.ps1 1010+10-1
1011
PS > .\Calc.ps1 20.2*20.2
408,04
```
] |
[Question]
[
Write a program that takes in a string containing only spaces, newlines, and angle brackets: `<`, `>` (*[chevrons](https://en.wikipedia.org/wiki/Bracket#History)*). Output a string of spaces, newlines, and slashes: `/`, `\` (*[soliduses](https://en.wiktionary.org/wiki/solidus#English)*) whose shapes correspond to the input, **but rotated a quarter turn clockwise, with a column of spaces inserted between each row of the original input** (for aesthetics).
For example, if the input is this:
```
<>
```
The output would be this:
```
/\
\/
```
If the input is this:
```
><<<>
<><
```
The output would be this:
```
\/
/\ /\
\/ /\
/\ /\
\/
```
If the input is this:
```
>> <<
<> <>
<
><
```
The output would be this:
```
/\ \/
\/ \/
\/ /\
/\
/\ /\
\/ /\
```
Notice how there is a single column of spaces between the original input rows in the last two examples.
You may write a full program that takes the input in any usual way (command line, stdin) and prints the output, or you may write a function with a string argument, that prints or returns the output.
Empty leading and trailing rows or columns of whitespace in the input do not need to be present in the output. Additionally, there may be any amount of leading and/or trailing spaces and/or newlines in the output, in any locations, as long as the resulting shapes are correct. In other words, **the translation of the ascii art does not matter, only the shapes and their relation to one another do**.
You may optionally assume the input has a trailing newline.
**The shortest code in bytes wins.**
[Answer]
# CJam, 35 bytes
```
qN/_s,S*f+{iD%[S3*" \/"_$]=}f%W%zN*
```
[Try it online here](http://cjam.aditsu.net/#code=qN%2F_s%2CS*f%2B%7BiD%25%5BS3*%22%20%5C%2F%22_%24%5D%3D%7Df%25W%25zN*&input=%3E%3E%20%20%3C%3C%0A%3C%3E%20%20%3C%3E%0A%20%20%3C%0A%20%20%3E%3C)
[Answer]
# Python 2, 105 bytes
```
def f(s):
for row in map(None,*s.split("\n")):print" ".join("\/ /\ "[1-cmp(c,"<")::3]for c in row[::-1])
```
For all the wrong reasons, this has got to be one of the nicest uses of `map(None, ...)` I've had so far. The output even pads to perfect rectangle.
Let's take the second example:
```
><<<>
<><
```
`map(None,*s.split("\n"))` performs a poor man's `zip_longest`, giving:
```
[('>', ' '), ('<', '<'), ('<', '>'), ('<', '<'), ('>', None)]
```
Notice how the second line is shorter than the first, so we get a `None` at the end. Normally this would be a problem, but for *some* reason almost everything is comparable in Python 2, and in particular
```
>>> None < ""
True
```
This means that the expression `1-cmp(c,"<")` returns `0, 1, 2` for `">", "<", None` respectively, allowing us to use the string slicing trick to extract one of `"\/", "/\", " "`. Using this, we print the output line by line, joining the 2-char groups with spaces.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 19 bytes
```
Ỵz⁶UµOHØ^ṙaf⁶;`$)€G
```
[Try it online!](https://tio.run/##y0rNyan8///h7i1Vjxq3hR7a6u9xeEbcw50zE9OAfOsEFc1HTWvc/x@d/HDn4sPtQHbW//82dly6XHY2NkBawcbOBsSxU1CwseGyAVFAQQUbILaz@Q@UAQA "Jelly – Try It Online")
While I was writing this, it tormented me to no end that the whole mess with `af⁶;`$` could just be `«`, if the codepoint of backslash were somewhere closer to the ballpark of its forward companion. This can *definitely* be golfed further.
```
Ỵ Split the input on newlines.
z⁶ Transpose with space as filler.
U Reverse each row.
µ )€ For each character in each row:
Ø^ṙ rotate "/\" by
H half of
O the character's codepoint;
a vectorizing logical and with
; concatenate
f⁶ $ the character filtered to spaces
` to itself.
a (The slashes are unaffected if the filter removes everything.)
G Grid format: this builtin can do a lot of things,
but in this case it joins each row on spaces
then joins the rows on newlines.
```
[Answer]
# CJam, 37 bytes
```
qN/_z,S*f{+"< >""/\ \/ "3/er}W%zN*
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%2F_z%2CS*f%7B%2B%22%3C%20%3E%22%22%2F%5C%20%20%20%20%5C%2F%20%223%2Fer%7DW%25zN*&input=%3E%3E%20%20%3C%3C%0A%3C%3E%20%20%3C%3E%0A%20%20%3C%0A%20%20%3E%3C).
### How it works
```
qN/ e# Read from STDIN and split at linefeeds.
_z, e# Zip a copy and push the results length.
e# This computes the maximum line length.
S* e# Repeat " " that many times.
f{ } e# For each line:
e# Push the string of spaces.
+ e# Append it to the line.
"< >""/\ \/ "3/ e# Push "< >" and ["/\ " " " "\/ "].
er e# Perform transliteration.
W%z e# Reverse the lines and zip.
e# This rotates by 90 degrees.
N* e# Join, separating by linefeeds.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 21 bytes
```
ƛ`<> `k/m6↲ǒĿð+;Ṙ∩øɽ⁋
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyIiLCIiLCLGm2A8PiBgay9tNuKGsseSxL/DsCs74bmY4oipw7jJveKBiyIsIiIsIltbXCI+XCIsXCI8XCIsXCI8XCIsXCI8XCIsXCI+XCJdLFtcIiBcIixcIjxcIixcIj5cIixcIjxcIl1dIl0=)
```
ƛ ; # For each line
Ŀ # Replace
`<> ` # Each of "<> "
k/m6↲ǒ # with corresponding elements of "/\", "\/", " "
ð+ # Append a space to each
Ṙ∩ # Rotate 90°
øɽ⁋ # Right align and join by newlines
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 30 bytes
```
mȯσ" "" "σ"<""/¦"σ">""¦/"T' ↔
```
[Try it online!](https://tio.run/##yygtzv7/qKnx0Lb/uSfWn29WUlBSUlBQAjJslJT0Dy0DseyUlA4t01cKUVd41Dbl////dnYKCjY2XDYgyo4LSACxnQ0A "Husk – Try It Online")
I made the clunkiest possible solution.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 19 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
Ǻòî@f┬U☺≥•:Γ_ƒ←⌠Φô
```
[Run and debug it](https://staxlang.xyz/#p=80a7958c4066c25501f2073ae25f9f1bf4e893&i=%3E%3E++%3C%3C%0A%3C%3E++%3C%3E%0A++%3C%0A++%3E%3C)
[Answer]
# Scala, ~~201~~ ~~188~~ 180 characters
```
(s:String)⇒(Seq("")→0/:s.lines.flatMap(l⇒Seq(l,l))){case((v,i),l)⇒(l.map(c⇒if(Set('>','<')(c))if(c%4==i)'/'else'\\'else c)+:v,2-i)}._1.init.transpose.map(_.mkString).mkString("\n")
```
### note:
this only works if the provided string has all lines with equal length (i.e. padded with spaces)
## explanation:
I'm using fold with initial value of tuple of a `Seq[String]` and an `Int` (instead of writing `Seq.empty[String]` im writing the shorter `Seq("")` and `.init` after the fold), the fold operates on a collection of strings, each string is a line in the original input, and every line is doubled. the trick here was to test for modulo of the char. since `'<'` value is 60, and `'>'` value is 62, testing for modulo 4, will yield 0 or 2. that's why the fold also carry a flipping `Int` set to 0. and flipped between 0 and 2 with `2-i`. every odd line should map `'>'` to `'/'` and `'<'` to `'\\'`, and every even line should map `'>'` to `'\\`' and `'<'` to `'/'`. this is why i test for `c%4==i` and hit 2 birds with 1 stone. the fold "rebuilds" the initial sequence of strings in reverse, and then (after dropping the last line), I transpose the sequence (this is why all strings must be of exact same length). because of the implicits involved, I need to `_.mkString` on each line (previously column), and then `mkString("\n")` for the final output.
[Answer]
# Perl - 119
```
@l=map[/./g],reverse<>;do{print;$_=join(' ',map({'<'=>'/\\','>'=>'\/'}->{$_->[$b]}||' ',@l))."\n";$b++;}while(/[^
]/)
```
First, `@l` is assigned as a list of lists representing the characters on each line of input with lines in reverse order. Then it loops through the columns of characters, replacing the angle brackets with the corresponding slashes, joining the elements with spaces, and printing the joined slashes as a line.
] |
[Question]
[
In this challenge, your task is to take an anion and a cation, and output the chemical formula of the compound.
## Input rules
* Take in 2 strings (in any order) representing the anion and cation, e.g. `F`, `NH_4`, or `Al`.
* To take in the charge of each ion, you can either have it as part of the string separated by a caret (e.g. `F^-1`) or take in additional numerical arguments.
* **Note:** As long as your numeric input type is signed, then the anion's charge will be passed in as a negative number.
* The symbols will always be real, and charges accurate.
## Output rules
* Use `_` for subscripts: Fe2O3 would be `Fe_2O_3`.
* Cation first: NaCl, not ClNa.
* Neutral molecule: Li2O, not LiO or LiO-.
* Lowest possible coefficients: Fe2O3, not Fe4O6.
* No subscript ones: NaCl, not Na1Cl1.
* No shifting: NH4OH, not NH5O.
* Conditional parentheses:
* Do not use parentheses on a single-atom ion: MgCl2, not Mg(Cl)2.
* Do not use parentheses if there is only one of the ion per molecule: KClO3, not K(ClO3).
* DO use parentheses if there are two or more of a polyatomic ion: Be3(PO4)2, not Be3PO42 or Be3P2O8.
## Testcases
```
Input Output
Fe^+3, O^-2 Fe_2O_3
Fe^+2, O^-2 FeO
H^+1, SO_4^-2 H_2SO_4
Al^+3, SO_4^-2 Al_2(SO_4)_3
NH_4^+1, SO_4^-2 (NH_4)_2SO_4
Hg_2^+2, PO_4^-3 (Hg_2)_3(PO_4)_2
NH_4^+1, OH^-1 NH_4OH
Hg_2^+2, O_2^-2 Hg_2O_2
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), the shortest answer in bytes wins!
[Answer]
# C, ~~208~~ ~~205~~ ~~175~~ 169 bytes
`argv[1]` : cation
`argv[2]` : anion
Charges of ions are taken on stdin.
```
#define z(b)for(i=*++v;*++i>95;);printf(b>1?*i?"(%s)_%d":"%s_%d":"%s",*v,b);
main(c,v,d,e,g,h,i)char**v,*i;{scanf("%d%d",&c,&d);for(e=c,h=-d;g=h;e=g)h=e%g;z(-d/e)z(c/e)}
```
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~86~~ 80 bytes
*Thanks to Neil for saving 6 bytes.*
```
^
(
\^.+
)_$&$*
(1+)(\1|¶.+)+_(\1)+$
$#3$2_$#2
_1$
m)T`()``.+\)$|\(.[a-z]?\)
¶
```
[Try it online!](https://tio.run/##TYuxCsIwFEX39xt9Sp4vDSR1FxfJZIW6GZN0KCKogzhJv6sf0B@LjaI43XO49967x/nWppkQTZTJgwDnFQMFnOMChGYSTvfjoJg4TEiMgEWFJmBhIGgEuNI@CopRsSPsnVCHtnweV45gHCClTee5krUvDWQ0H7SetWzqsMyyvuTJ17Z2yr/WnoLJv93bq19fW1/qFw "Retina – Try It Online")
Input is linefeed-separated (test suite uses comma-separation for convenience).
### Explanation
```
^
(
```
We start by prepending a `(` to each molecule. The `^` matches on *line* beginnings because the `m)` towards the end of the program sets multiline mode for all preceding stages.
```
\^.+
)_$&$*
```
We replace the `^[-+]n` part with `)_`, followed by `n` copies of `1` (i.e. we convert the charges to unary, dropping the signs).
```
(1+)(\1|¶.+)+_(\1)+$
$#3$2_$#2
```
This stage does three things: it divides both charges by their GCD, converts them back to decimal and swaps them. The GCD can be found quite easily in regex, by matching the longest `1+` that lets us match both charges using only the backreference `\1`. To divide by this, we make use of Retina's "capture count" feature, which tells us how often a group has been used. So `$#2` is the first charge divided by the GCD and `$#3` is the second charge divided by the GCD (both in decimal).
```
_1$
```
We remove `_1`s from the ends of both parts.
```
m)T`()``.+\)$|\(.[a-z]?\)
```
And we drop the parentheses from lines which end in a `)` (i.e. those that had a `_1` there), as well as lines that only contain a single atom.
```
¶
```
Finally, we concatenate the two molecules by dropping the linefeed.
[Answer]
# [APL (Dyalog)](https://www.dyalog.com/), ~~60~~ ~~59~~ 61 bytes
+2 since charges must be given signed.
Anonymous infix function. Takes list of ions (anion, cation) as left argument and list of corresponding charges as right argument.
```
{∊(⍺{⍵∧1<≢⍺∩⎕D,⎕A:1⌽')(',⍺⋄⍺}¨m),¨(m←s≠1)/¨'_',∘⍕¨s←⍵÷⍨∧/⍵}∘|
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqRx1dGo96d1U/6t36qGO5oc2jzkVA7qOOlY/6prroAAlHK8NHPXvVNTXUdUAS3S1AsvbQilxNnUMrNHKBRhQ/6lxgqKl/aIV6PFBJx4xHvVMPrSgGSgCNPLz9Ue8KoLn6QHYtUK7m/391t1R1BXV/dYU0BWOFQ@uNuJAEjCACHkB@sH@8CUjIECLkmIMkBtXn5wHioqv0SI83AooGQEVBRhrD1fp7wFQaAu3Nh4uAVBkCAA "APL (Dyalog Unicode) – Try It Online")
`{`…`}∘|` function where `⍺` is left argument and `⍵` is right argument's magnitude:
‚ÄÉ`‚àß/‚çµ`‚ÄÉLCM of the charges
 `⍵÷⍨` divide the charges by that
‚ÄÉ`s‚Üê`‚ÄÉstore in `s` (for **s**ubscripts)
 `'_',∘⍕¨` format (stringify) and prepend underbar to each
 `(`…`)/` replicate each letter of each with the corresponding value from:
  `s≠1` Is `s` different from `1`? (gives 1 or 0)
  `m←` store in `m` (for **m**ultiple)
 `(`…`),¨` prepend the following respectively to those:
  `⍺{`…`}¨m` for each, call this function with ions and `m` as arguments:
   `⎕D,⎕A` **D**igits followed by uppercase **A**lphabet
   `⍺∩` intersection of ion and that
   `≢` tally the number of characters in that
   `1<` Is one less than that? (i.e. do we have a multi-element ion?)
   `⍵∧` and do we need multiple of that ion?
   `:` if so, then:
    `')(',⍺` prepend the string to the ion
    `1⌽` cyclically rotate one step to the left (puts `)` on the right)
   `⋄` else
    `⍺` return the ion unmodified
 `∊` **ϵ**nlist (flatten)
[Answer]
# [Haskell](https://www.haskell.org/), ~~101~~ 97 bytes
```
(s#t)n m|let x#i|j<-div(lcm n m)i=l$x:[l(x:['(':x++")"|l x<':'])++'_':show j|j>1]=s#n++t#m
l=last
```
[Try it online!](https://tio.run/##ZZBRa4MwFIXf8ysuOjAh88G4J6mDMigZbE2hj6WKbLLaRVdmuglzv93dxGHXLg@G8517z71mV7SvpdbDQFvfsAbqXpcGOr/q97Pwufqg@qkGxKxK9VWXbDTFT0CDpOPcY16voZsFSbBlnAd5kLS7t0/Y9/vbaJu2fsO58WuiU120ZqiLqoEU6uLwCIejWZv3hwY21FuUnu8pj8UgruEkxSglqrXKbzwWjWCuJ/LbsZQoLqrkSy6QrRwTEP@pU9JWRZbcUWSC5THipcLLGltCvkJy3@COcH7U0SAkizLjGKiyUEzWoswFBjhP/PMUkRnHiXbFk4OjLSBz7fLOzLnOBbUElyN28ct@uzmaY4L9Wzd35QpiV2AhdtOVSxGnFCWzMBrHWKYkmd7B@fYlACZmJQm/hx8 "Haskell – Try It Online") Example usage: `Fe^+3, O^-2` is taken as `("Fe"#"O")3 2`.
[Answer]
# RPL (HP48 S/SX), 294.5 bytes
Yes, ridiculously large submission, not sure how competitive it will be...
```
DIR
M
¬´ S ROT S SWAP ABS 4 PICK ABS
DUP2 WHILE DUP2 REPEAT MOD SWAP END DROP2
SWAP OVER / 4 ROLL J 3 ROLLD / ROT J
ROT 0 > IF THEN SWAP END + »
S
¬´ DUP "^" POS DUP2 1 + OVER SIZE SUB OBJü°¢
3 ROLLD 1 - 1 SWAP SUB »
J
IF OVER 1 ==
THEN SWAP DROP
ELSE DUP SIZE DUP2 DUP SUB "Z" > - 1 >
IF
THEN "(" SWAP + ")" +
END
"_" + SWAP +
END
END
```
3 routines packaged neatly in a directory. `M` is the main one. It expects 2 strings on the stack formatted as ions and pushes a molecule string onto the stack.
`S` splits the ion into charge as a number and the element formula as a string. For example, `"PO_4^-3"` would be taken from the stack and `-3` and `"PO_4"` pushed onto the stack.
`J` joins the number of ions with the formula and decides whether to wrap the formula into brackets. The bit before `ELSE` deals with 1 ion, leaving the string as it is. For example, if `1` and `"PO_4"` are on the stack, they are replaced by `"PO_4"`. `1` and `"H"` gives `"H"`.
The rest deals with multiple ions; if it's a single atom it's not in brackets, otherwise it is. To decide whether it is, I check the length of the string and check if the last character is `>"Z"`. Boolean expressions return 1 for true and 0 for false. By subtracting the result of this comparison from the length of the string, I get 1 or less when it's single atom, otherwise more: length 1 is a single atom; length 2 will have a letter as the last character; for a single atom it's lower case, so `>"Z"`, making result 1, otherwise 2; length 3 or more means more than 1 atom and with 0 or 1 subtracted from the length the result will be at least 2. For example, `3` and `"PO_4"` gives `"(PO_4)_3"`. `3` and `"Al"` gives `"Al_3"`.
`M` first splits each ion using `S`. After the first line the level 5 of the stack (so the deepest buries object) contains charge of the second ion, level 4 second ion's formula, level 3 first ion's formula, level 2 absolute value of the first ion's charge and level 1 absolute value of the second ion's charge again. For example, if given ions on the stack are `"Al^+3"`, `"SO_4^-2"`, we get `-2`, `"SO_4"`, `"Al"`, `3`, `2`.
Second line calculates gcd of the 2 charges (leaving the charges intact).
Third line divides each charge by the gcd (to calculate the multiples) and joins it with the ion's formula using `J`. So we have two strings each with one given ion with charge removed (or a multiple of it) and a charge of the second one buried behind them. For example, `-2`, `"Al_2"`, `"(SO_4)_3"` (-2 is the charge of SO\_4).
Fourth line unburies the charge and if it's positive it swaps the two strings (so that the cation comes first) before joining them. So in example above, because it's negative, they are joined in the order as they are: `"Al_2(SO_4)_3"`.
[Answer]
# [Python 3](https://docs.python.org/3/), 131 bytes
```
lambda c,a,C,A:g(c,A/gcd(C,A))+g(a,C/gcd(C,A))
from math import*
g=lambda s,n:[s,[s,'(%s)'%s][sum(c<'`'for c in s)>1]+'_%d'%n][n>1]
```
[Try it online!](https://tio.run/##jY3BCoJAFEX3fcVs5M3Ug1BbSQUShKsMWpqYjTkKziiOLfp6GyOK0EXwNvdczn3Noytq5fb55txXqbxmKeGY4g59T1CO/lLwjJrE2EJQw795lre1JDLtClLKpm67@Uxs3hMalRdpNAfU0gwsHUf6LilfwwXyuiWclIpotrXjBSRWBpaKI2VS37Sl6mhOYX8DhBDQRcf8GmHnF/uVwacwWY2E4FPY/yqHYIDTViASx3THV@egO@GFwWDZjPVP "Python 3 – Try It Online")
# [Python 2](https://docs.python.org/2/), ~~196~~ ~~174~~ ~~170~~ ~~155~~ ~~149~~ ~~140~~ 136 bytes
```
lambda c,a,C,A:g(c,A/gcd(C,A))+g(a,C/gcd(C,A))
from fractions import*
g=lambda s,n:[s,[s,'(%s)'%s][sum(c<'`'for c in s)>1]+'_'+`n`][n>1]
```
[Try it online!](https://tio.run/##jYzBioMwFEX3fkU25SXjg2I6K6kFKRRXdaBLR9SmTSpoIold9OudtJQOM85i4G3uufe84TZejOaTTD6nrumPp4YIbHCLaayowHSpxIn6xFioqOffOZDW9ETaRoyt0Y60/WDs@Bao5PnHoY4Lh/6ALhyDhSsLd@2pWEMN0lgiSKuJY5uoDKGCsNZ1WWifpsG2eiSSwu4MCDngCjkLZpT/oGnn6SGv3n/PsxeP/ifsszv708lUxX318ag4ruZWnt2diE1f "Python 2 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 129 bytes
```
lambda E,e,I,i,m=lambda e,i:(len(e)>2<=i)*"("+e+(len(e)>2<=i)*")"+"_%d"%i*(i>1):m(E,i/gcd(i,I))+m(e,I/gcd(i,I))
from math import*
```
[Try it online!](https://tio.run/##jZDPa4MwFMfv@SskUHzRwDDuJLPQQ0t6WQrbUQhOYw0YldQd9te7pJUN1x52yY/Ph@97jzd@Te3Qp3OTF3NXmo@6DPZU0SPV1OQLUFRn0KkeFNmyl1yTCAOOVfyHERxjuanxRkegtwnJDOypfjpXNWh6JCQ24Ar//lFjBxOYcmoDbcbBTtE8Wt1PgN9bFVh1@eymS1BalRV90WOC0E03EB5USEMR0pQyV@cOszXedQ6/Cfl8F@A/Ivlv5JV7@DjFz5I5d7o6RtMHOcF9KnmQEv68Tb44jDFCfhfVYK2qptVOEEIHJZmQqbsF2nWSgR@KOMAl8881BD8BWQz4po7C6WoZ8lJw5LEbxHUm8zc "Python 3 – Try It Online")
---
If we need to handle negative charges of the anions, then **153 bytes:**
```
lambda E,e,I,i,a=abs,m=lambda e,i:(len(e)>2<=i)*"("+e+(len(e)>2<=i)*")"+"_%d"%i*(i>1):m(E,a(i)/gcd(a(i),a(I)))+m(e,a(I)/gcd(a(i),a(I)))
from math import*
```
[Try it online!](https://tio.run/##jZBBa4MwGIbv@RUSKH5fzRiNO5VZ6KHFXpbCdhyEtMYaMCqpO@zXu8RJYa6DXZLP5@Elr1/32Vdtkw5l9j7Uyp4KFe2YZgdmmMrU6cpsNmHNzBpq3YDGDX/ODC4p0EQnM4Y0oXJR0IVZgtmscG1hxxQYfLycCwiD/zogYmJBj@NckNK1NrKqryJju9b1y6FzpumBUvpW6cjp60fdXyPl9JoQD5F8@xLivY5ZLGKWsgeOdzif8W3t@auQT78j@c2s/h96yQP9I5dfJPfyOErfJL2TFPmYW93JiXBOP0BuGyEk7OTcOqfP/Ww3ZK8lFzL1tyDbWnIIxdCDXPIw/oQQOuBkILzqKRxHy0mQIicB@yZh7cMX "Python 3 – Try It Online")
[Answer]
# JavaScript, 145 bytes
```
(c,a,p,n,g=(a,b)=>b?g(b,a%b):a)=>`(${c})_${n/-g(p,-n)}(${a})_${p/g(p,-n)}`.replace(/\(((\w+)\)(?=_1)|([A-Z][a-z]*)\))/g,"$2$3").replace(/_1/g,"")
```
Takes arguments `c` is cation, `a` is anion, `p` is positive charge, `n` is negative charge.
] |
[Question]
[
## Background
This challenge is in honor of [apsillers](https://codegolf.stackexchange.com/users/7796/apsillers), who won the [Not as simple as it looks](http://meta.codegolf.stackexchange.com/a/11192/32014) category in Best of PPCG 2016 with their challenge [Can my 4-note music box play that song?](https://codegolf.stackexchange.com/q/70221/32014)
Congratulations!
On their "About Me" page, this user has a really neat simulator for the [Game of Life](https://en.wikipedia.org/wiki/Conway's_Game_of_Life) cellular automaton.
(Seriously, go check it out.)
On the other hand, the word [aspillera](https://es.wikipedia.org/wiki/Aspillera) is Spanish for "arrowslit".
In light of these facts, this challenge is about arrowslits in Game of Life.
## Game of Life arrowslits
In GoL, we will represent an arrow by a [glider](https://en.wikipedia.org/wiki/Glider_%28Conway's_Life%29), and a wall by a sequence of [blocks](https://en.wikipedia.org/wiki/Still_life_%28cellular_automaton%29#Blocks).
A single glider approaches the wall from above, and tries to fly through a gap in the wall (the arrowslit).
Your task is to check whether the glider passes through the arrowslit or crashes into the wall.
## Input
Your input is a grid of bits, which represents a GoL configuration.
You can take it in any reasonable format (multiline string of any two distict printable ASCII characters, list of strings, 2D array of integers, 2D array of booleans etc).
For clarity, I will use multiline strings of the characters `.#` in the following.
The input is guaranteed to have several properties.
First, its height is **2N** for some **N ≥ 6**, and its width is at least **2N+2**.
The input will be all `.`s, except that somewhere on the top three rows is a glider, and on the two middle rows there is a wall of blocks.
The glider will be heading southwest or southeast, and its position is such that if the walls are removed, it will not pass through a side edge before reaching the bottom edge (but it may reach a corner of the grid).
The glider is initially separated from the left and right edges by at least one step of `.`s.
It can be in any phase.
The wall consists of blocks, which are separated by one column of `.`s, except in one place, where they will be separated by at least two columns of `.`s.
Like the glider, the leftmost and rightmost blocks are also separated from the edges by one step of `.`s.
There will always be at least one block on the left edge and one block on the right edge.
Here is an example of a valid input grid:
```
....#......................
..#.#......................
...##......................
...........................
...........................
...........................
.##.##............##.##.##.
.##.##............##.##.##.
...........................
...........................
...........................
...........................
...........................
...........................
```
## Output
As stated, your task is to determine whether the glider crashes into the wall or makes it through to the south edge.
For the purposes of this challenge, a crash occurs if the configuration no longer consists of a single glider and the wall of blocks, regardless of what happens later in the simulation.
The following diagrams show the smallest gaps that a southeast glider can go through without crashing in the two distinct phases (the condition for southwest gliders is symmetric).
```
...#...........
.#.#...........
..##...........
...............
...............
##...........##
##...........##
...#...........
....#..........
..###..........
...............
...............
##...........##
##...........##
```
If the glider flies through the wall, you shall output a truthy value, and otherwise a falsy value.
For the example above, the correct output is falsy, since the glider will crash into the left part of the wall.
For the purposes of this challenge, you can assume that if you simulate GoL on the input for **2\*(height - 3)** steps, the glider is on the bottom row in the expected position and the wall is intact, then the output is truthy.
## Rules and scoring
You can write a full program or a function.
The lowest byte count wins.
## Test cases
I have collected the test cases into a [GitHub repository](https://github.com/iatorm/arrowslits), since they are quite large.
Here are links to the individual files:
* [Truthy test cases as 2D arrays of bits](https://raw.githubusercontent.com/iatorm/arrowslits/master/arrowslits_true.txt)
* [Falsy test cases as 2D arrays of bits](https://raw.githubusercontent.com/iatorm/arrowslits/master/arrowslits_false.txt)
* [All test cases in human-readable format](https://raw.githubusercontent.com/iatorm/arrowslits/master/arrowslits_pretty.txt)
[Answer]
# [Python 2](https://docs.python.org/2/), ~~142~~ ~~136~~ 135 bytes
-6 bytes thanks to ElPedro
-1 byte thanks to TuukkaX
```
p=input()
z=p[2].index(1)
m=(p[1][z]-p[1][z+1]<1)*2-1
k=i=0
for b in p[3:]:x=p[2][::m].index(1)+i;k|=1in b[::m][x-2:x+8];i+=1
print 1-k
```
[Try it online!](https://tio.run/nexus/python2#vY5NC8IwDIbv/RU9bnaVZl6kM78k5DJUCGO1yIQy/O9TJ35cCoIi7yGB9@FJpogS4mkoSjVipJqXEra7VECpeiwiAdPI9j4N8AbKRW1BdSjo1P5w1K2WoCOtPPs0C8j7/mUx0nRnhCvTzgUlW/tk1tyIQVDxKGHQYLtpInLVLVC5XLiixw457slA3vTmcV8z@Ttz8zHzq3/@xfAF "Python 2 – TIO Nexus") or [Verify all test cases](https://tio.run/nexus/python2#7Z3dbtpAEIXv/RS@CxSofOhNRerbPkHvLKtqFJCsJBQlREJR3z0FkhYUsD27nh0bOEEikby7n3fP/KxtmLzeTmfxrLfoT6L4JV1k4/xzMb@drnroR/FD2ltkyLOXfPT2e4D8G/qfxiNE8V1apEkUz34/xjdxMY8X2ZdJPlltx8gmk4fdQIPi@u5PinWbm@2BbDUaT1aDr/l1MUjXIy0ei/kyxujudflzOX1aDmfbX3G6HnbxvOz1o@itydWPx@dpvDn2dBVtwMUG/NZpff6zXrFr@v3X/dNh29l@29ds/ZMMNy8Mk7JXPsz@/Y2ydv/boHykvXGSxm3KOdsj4jZa52PVZt1oTw3JSBLFQMWCKwaRYhC1SehjHfExPVWpmI5ix@ZVPdLeilTQUDsOFdNRrF4NCGigYqaKQcV/qFhXfExTVSqmkcdKIqBs7OHBbsWhFzxYidcZavXC@1whmNlHm3Lt1f3V6Havj1YPZxq8etUrTaun1VtZvevLweZ9z3Ho4SkqrMSMlZBlztqPN9Xv7hZaFdtCs2gbZF0SyyWDwS2uN5oZmpEcVxG0DmawZtmj7N2cRdsgixksxAvGs3vPt4Y8WKtHHnmBrz/9rhj9r0F1eLQX8si7DN5uBwPTCGrLU7imp8WQd5Y7mMZX/o73ICx4tBfyyLu0HUzAu@yNZhtotyNk4xxUJpvs1tgSH9K6R3N859QOm7ZGNtlkn85TM7Q0c7TIFu7xaOlkX9iOTfdd4IOts2lrZJNNtvqObbNly@pqgRyNVVVXsVVzqj12OGbVVXNtjDQ/Vr4LLjvT6s9INZ/huawoRH4EQW0OVkoJ28anGlFdJGE1IhvFpBW/6n2MtW2sfCwR@obEx0DFgioGkY9B1CZhHjOMihBERTSOnFTMJo/p@SEVs8tjen5IxXQUK3lao1DxC1SsAxW/IK6qRx/rSuXKRFy5kj4WXrF6/5FUbQN9zNzHoJKj6GM2PqZVz5c@1p08pumHVCx0HtP0QyqWqFeHlenTWDG/WKr1bDxgnUy/b8EpfQqbvdz3Ag403zt9OPm1p9WfotX71nmFZ69zW3vZpzH9qq7R6q1ivfSJgEO8l/wfClo9rb5VqxfvvMOeo3tOachy/t4z6yGS5RgRy7@toVkvJTSLtkEWWWFYp5GZYbiKYGYmi5mZmZkssk4sM8NoZo1qdjmvIszmRUtkZg6SP81ZtA2yyLq8zNyI5pWZQesgi5mZmZksstrOzHn@Fw "Python 2 – TIO Nexus")
### Checking orientation (east/west):
[](https://i.stack.imgur.com/87ak1.png)
Using `z=p[2].index(1)` to get the first square on 3rd row (represented by the red square), and then `m=(p[1][z]-p[1][z+1]<1)*2-1` to subtract the value on the right (green) from the one on the left (blue), this way all the 4 gliders states that are going to southwest result in `1` (top row in the image), while the ones going to southeast result in `0` or `-1`.
Then convert : `1 -> -1` and `0,-1 -> 1` to be used on parameter to reverse the lists when dealing with west ones. This way the gliders going southwest are threated the same as the one going southeast.
### Glider movement
[](https://i.stack.imgur.com/zyH0G.gif)
This is the movement that the glider going southeast do, it has a "ladder" pattern, and the leftmost block on 3rd line is constant to every pattern. Using it as starting point, the surrounding 3 blocks on left and right, and the middle 4 blocks are checked for the presence of `1`s (that would be the wall).
[](https://i.stack.imgur.com/9wkEI.png)
[](https://i.stack.imgur.com/L3Brg.png)
[Answer]
# Octave , ~~123~~ ~~122~~ 108 bytes
Thanks to @LuisMendo saved 2 bytes
```
B=A=input("");B(1:3,:)=0;do;until nnz((A=A&(s=conv2(A,(m=-1:1)|m','same'))>1&s<4|~A&s==3)-B)-5;any(A(end,:))
```
[Try it online!](https://tio.run/nexus/octave#vY7dCoJAEIVfJbzQGdiFnawbtwnW1xAvJL0QcgxWg0J6dfuBopuFoIhzM3A@vjlzzo5bOYwDRBHaHChLVYZsbN3bUYZ2vxA5Azh2MXje9XJcglPQsaaMcOoSlfiqaxLELcV@s5ouLvbMKeoc9dpWcgIHjdQ3Kc5zURh1DykTSmmL500h7sVQ2PTmMV8z4T@P5mPmV3v@xZRX "Octave – TIO Nexus")
Or
[Verify all test cases](https://tio.run/nexus/octave#7Z3BTttAEIbvPIXVA7ElI3mgvSR1JXPgCXpDPUSQVBHERjhpVUL66tRJgEaA7dn17NhJfixCEu/u591/ZmdtJ8Pv4X06SX962Xj8NJ6nV7NJlnpZfOEnweDIK37O4@T5iU/9s7AfxNHm9XW2@TtPZ5NbL00ffD@Jk2M/j6@y9Nepn4T@ND6hPgWP017Yy4fTUS8IvtFx/vXz49/kOI/js@DkPDj5smkni4fpHz/xR@l1QSnoxZOjp9kon@Ve7C163@/nI2/9shd6vYvhbf7ycjk4SuJJejef@Z8@FRXH2b13U9Sh/unmSCf5nb8uurhZBuu3VkUeViXS@XR06yevO17LX6zfXDwsg82O1dEUv0@LxeVlFK42CqOy7cfg8uU5lZV7LUPlLW21EzUuU85Z72GXkToerTJFoS01OC1xFCMo5lwxYilGrDIRfKwjPianKhSTUeyjflW3tDUiFTSqbQeKyShWrwYxaATFVBUjEf@BYl3xMUlVoZhEHCuZAXlth@9WKwa1yIIVWR2hVC167isxevbWpkxrdX80ul3rrdWTMY2satUrDauH1WtZvelmYPO2xxhaeIoIK1JjRWCps7bnm@pHcwutmttcs2AbYB0SyySCkdm83qhn1IxkOIoE60AEaxY9yh7VWbANsBDBXGyk3LvneKvII231wAPP8fmn3Rmj/TmoDA/2Ah54h8H7v4Ih1RlUlydwTg@LAW8vVzCNz/wNr0Fo8GAv4IF3aCsYh1fZG/XW0WqHyaZ9UBlssFtjc3xI6hrNxyundtiwNbDBBnt37ppRSz2nFtnMNR4sHewDW7HJPjJ8sHU2bA1ssMEWX7EtB@tML2R@j63qLLaqT7X73rdZddZcO0eq7ytfBZcdafVnpJr3cF9GlFh@RIzcHMiU4raMTTaiupkE2Yh0FONm/Kr3MeS20fKxiOkbHB8jKOZUMWL5GLHKRIhjirMiMWZFajxzQjGdOCbnh1BML47J@SEUk1Gs5G6NQMYvgmIdyPhF7Kx68LGuZK6M2Jkr4WPuFav3H07WNoKPqfsYicQo@JiOj0nl84WPdSeOSfohFHMdxyT9EIpF4tlhefo0VsxuLpW6N@4wT6bdt@CEPoWNWuZrAQOa7ZU@2vmxh9XvotXb5nkly1r7Nva8T2PaZV2D1WvN9dw7AgbzPef/UMDqYfWtWj175e32GM1jSkOW8feekQ8RLMMZsfzbGpL5UlyzYBtggeWGtRuRmRRHkRCZwUJkRmQGC6wdi8yk1LNGObuMR5HU@gVLRGR2Ej/VWbANsMA6vMjciGYVmQnWARYiMyIzWGC1HZmXy38 "Octave – TIO Nexus")
Thanks to Rod preparing test cases.
```
B=A=input("");
B(1:3,:)=0;
do
until nnz((A=A&(s=conv2(A,(m=-1:1)|m','same'))>1&s<4|~A&s==3)-B)-5
any(A(end,:))
```
Previous answer:
```
B=A=input("");
B(1:3,:)=0;
while nnz(A~=B)==5
s=conv2(A,(m=-1:1)|m','same');
x=~A;
A&=~A|~(s<2|s>3);
A|=x&s==3;
end;
any(A(end,:))
```
First extract wall pattern as variable `B`.
Do GoL simulation until the wall pattern and the simulated pattern have more/less than 5 different cells.
If the glider has received the last row the function returns true.
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~101~~ ~~93~~ 91 bytes
Byte count assumes ISO 8859-1 encoding.
```
O$#^`.(?=(.*¶)*(?<=#_.\2.+##.(.*¶)\D+))
$#1
¶(?>_(_)*#+_+¶_+¶(?<1>_+¶)*)(?>(?<-1>.)+)_{11}
```
[Try it online!](https://tio.run/nexus/retina#7VpLjqMwEN37Gq9HgqApid5mCJvez2J6GTW5x2iulQPkYhkiWmqg/CdJp0ghuhVsP0zV8yvbUKej2Zr3Ax32nflz2LZN02xb86Pof59/v@DjQEXbFLQ5HctN0f5q0NH@lSqAhsL9W1WW5gW1OR2LdtcVXblB1VWn4@WvR9S7y49yU/a1/eXPekdlVXZ/6/rf@UxEoPFhLv@AWcmkYGhDoZIJpr@wlcTcJ6uk9@JgCW/HbYNE28Bt4yyBVsJblLVCbPvqbtZueJZJG0CmbcwSMCTk2oYwS2vhLc5aGXobj0SyV8FZBSeKaFFVf@dpKKPPIm/V1R/j2lVf3ocLCXcVs1u9n@l912F3PgVQdl7CKMpBkVjUME5mp9Oh0wGXilqrDx8e5dKYQ1mB/oCsp8TTcharkPGZi9Jx/2Aai5hv8nB5bAO5FioucRb1TI/eeTQCpzw8Je4zxiBvjGbiwvO9cni/GBNcAjjWEek45eGZY0za2t3fc0rkMenbjStYreglaM5QTIQZxacFaGVM0bfao2FB/1iEtgU95fybYlvkyRlcilbGFJ0W2@DcuU3nWePpedRyOj@zMZl9NYvD4/vO3k8F@7zTs4JzxbI6sJoclpl19kwrGbbZcsYYb2LzcyyccN4gzzZw3ri6QEL1Bs4bVxdoFXqLYlKs3qKYFGLbeNsTzBnDKnLGYMv1k8obY8mWoymSN8YST4yDZN4QVpdQ3mLyhlejtzgmJeotjkkp85vLpKBtnuEas4tPyu70fMCLefv9oNmdcC9rfatC3NqAdXvfl0DryZLFvQywvAT1JMGJzWwGubcGnl0D1PvX8L41kKe/h3V9jTY5IM2hdI3FyaeRuAyXVJR6XhTqJnpG1lNC9ax6VtTt9IyM/gJpYoZyYMpZhJ4DEs1FqeefWs8BmEmem5Uz1bOiYo// "Retina – TIO Nexus")
Certainly not optimal yet.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 47 [bytes](https://github.com/abrudz/SBCS)
```
{p←0⍪⍣3⊢3↓⍵⋄1∊⊢⌿({≢⍸⍵}⌺3 3∊¨3+0,¨⊢)⍣{5≠≢⍸p≠⍺}⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT/9fYviobcKjtomP@qZ6Bfv7qUdHG@iAoKGOAS4YqxMNYxviUgdXY4jbJCRzDChWg9sesAzRaqjlHnqpiVXnKjEiOQqpCaFBS1/78CYsmthHNzhq36h9ZOQ/Q4J5AlkNBeSA2DeaXkbtG7VvZNgHbNKk4WiVYhYxhJ2J1DTBo8ZwtFVK3VZpmhFxUUgYGtI1xZLYrqTALpJbsPTMiaN2DUG7iG9ZUbcFSGu7RtPGqF2jdtGqtfW/ugBYVRs86l31qHex8aOuRcaP2iY/6t36qLvF8FFHF1DgUc9@jepHnYse9e4Aitc@6tllrGAMlDq0wljbQOfQCqASTaDeatNHnQsgygpArN5dtSDl/9NALYHevkddzYfWG0OaBMFBzkAyxMMz@H@aQokhV5rCo569YLrECMoB0WlQGTCdBpVJMwIA "APL (Dyalog Unicode) – Try It Online")
Uses the idea from [rahnema1's Octave answer](https://codegolf.stackexchange.com/a/112280/78410):
>
> Do GoL simulation until the wall pattern and the simulated pattern have more/less than 5 different cells. If the glider has received the last row the function returns true.
>
>
>
The GoL simulation part is from [the APLcart entry](https://aplcart.info/?q=game%20of%20life#).
### How it works
```
{
⍝ ⍵←initial GoL pattern
p←0⍪⍣3⊢3↓⍵ ⍝ Extract the wall pattern
3↓⍵ ⍝ Remove first 3 rows
0⍪⍣3⊢ ⍝ Prepend a zero row three times
p← ⍝ Assign to p
1∊⊢⌿({≢⍸⍵}⌺3 3∊¨3+0,¨⊢)⍣{5≠≢⍸p≠⍺}⍵ ⍝ Run the simulation and check
({≢⍸⍵}⌺3 3∊¨3+0,¨⊢) ⍵ ⍝ Run GoL on the input pattern
⍣{ } ⍝ until
≢⍸p≠⍺ ⍝ the difference between the pattern and p
5≠ ⍝ is not 5
⊢⌿ ⍝ Extract the last row
1∊ ⍝ Check if it has at least one alive cell
}
```
] |
[Question]
[
**Context:**
>
> A reclusive billionaire has created a game show to attract the world's best and brightest programmers. On Mondays at the stroke of midnight, he chooses one person from a pool of applicants to be the contestant of the week, and provides them with a game. You are this week's lucky contestant!
>
>
>
**This week's game:**
>
> The host provides you with API access to a stack of 10,000 digital envelopes. These envelopes are randomly sorted, and contain within them a dollar value, between $1 and $10,000 (no two envelopes contain the same dollar value).
>
>
> You have 3 commands at your disposal:
>
>
> 1. Read(): Read the dollar figure in the envelope at the top of the stack.
> 2. Take(): Add the dollar figure in the envelope to your game show wallet, and pop the envelope off the stack.
> 3. Pass(): Pop off the envelope on the top of the stack.
>
>
>
**The Rules:**
>
> 1. If you use Pass() on an envelope, the money within is lost forever.
> 2. If you use Take() on an envelope containing $X, from that point forward, you may never use Take() on an envelope containing < $X. Take() on one of these envelopes will add $0 to your wallet.
>
>
>
Write an algorithm that finishes the game with the maximal amount of money.
If you're writing a solution in Python, feel free to use this controller to test out algorithms, courtesy of @Maltysen: <https://gist.github.com/Maltysen/5a4a33691cd603e9aeca>
If you use the controller, you cannot access globals, you can only use the 3 provided API commands, and local scoped variables. (@Beta Decay)
Notes: "Maximal" in this case means the median value in your wallet after N > 50 runs. I expect, though I would love to be proven wrong, that the median value for a given algorithm will converge as N increases to infinity. Feel free to try to maximize the mean instead, but I have a feeling that the mean is more likely to be thrown off by a small N than the median is.
Edit: changed the number of envelopes to 10k for easier processing, and made Take() more explicit.
Edit 2: The prize condition has been removed, in light of [this post](http://meta.codegolf.stackexchange.com/questions/5677/the-community-is-against-cash-prizes-but-should-that-be-advice-or-a-rule) on meta.
Current high scores:
PhiNotPi - $805,479
Reto Koradi - $803,960
Dennis - $770,272 (Revised)
Alex L. - $714,962 (Revised)
[Answer]
# CJam, ~~$87,143~~ ~~$700,424~~ ~~$720,327~~ ~~$727,580~~ $770,272
```
{0:T:M;1e4:E,:)mr{RM>{RR(*MM)*-E0.032*220+R*<{ERM--:E;R:MT+:T;}{E(:E;}?}&}fRT}
[easi*]$easi2/=N
```
This program simulates the entire game multiple times and calculates the median.
### How to run
I've scored my submission by doing 100,001 test runs:
```
$ time java -jar cjam-0.6.5.jar take-it-or-leave-it.cjam 100001
770272
real 5m7.721s
user 5m15.334s
sys 0m0.570s
```
### Approach
For each envelope, we do the following:
* *Estimate* the amount of money that will inevitably be lost by taking the envelope.
If **R** is the content and **M** is the maximum that has been taken, the amount can be estimated as **R(R-1)/2 - M(M+1)/2**, which gives the money all envelopes with contents **X** in the interval **(M,R)** contain.
If no envelopes had been passed yet, the estimation would be perfect.
* Calculate the amount of money that will inevitably be lost by passing the envelope.
This is simply the money the envelope contains.
* Check if the quotient of both is less than **110 + 0.016E**, where **E** is the number of remaining envelopes (not counting envelopes that cannot be taken anymore).
If so, take. Otherwise, pass.
[Answer]
## Python, ~~$680,646~~ $714,962
```
f = (float(len(stack)) / 10000)
step = 160
if f<0.5: step = 125
if f>0.9: step = 190
if read() < max_taken + step:
take()
else:
passe()
```
Takes larger and larger amounts in steps of size between $125 and $190. Ran with N=10,000 and got a median of $714962. These step sizes came from trial and error and are certainly not optimal.
The full code, including a modified version of [@Maltysen's controller](https://gist.github.com/Maltysen/5a4a33691cd603e9aeca) which prints a bar chart while it runs:
```
import random
N = 10000
def init_game():
global stack, wallet, max_taken
stack = list(range(1, 10001))
random.shuffle(stack)
wallet = max_taken = 0
def read():
return stack[0]
def take():
global wallet, max_taken
amount = stack.pop(0)
if amount > max_taken:
wallet += amount
max_taken = amount
def passe():
stack.pop(0)
def test(algo):
results = []
for _ in range(N):
init_game()
for i in range(10000):
algo()
results += [wallet]
output(wallet)
import numpy
print 'max: '
output(max(results))
print 'median: '
output(numpy.median(results))
print 'min: '
output(min(results))
def output(n):
print n
result = ''
for _ in range(int(n/20000)):
result += '-'
print result+'|'
def alg():
f = (float(len(stack)) / 10000)
step = 160
if f<0.5: step = 125
if f>0.9: step = 190
if read() < max_taken + step:
#if read()>max_taken: print read(), step, f
take()
else:
passe()
test(alg)
```
BitCoin address: 1CBzYPCFFBW1FX9sBTmNYUJyMxMcmL4BZ7
**Wow OP delivered! Thanks @LivingInformation!**
[Answer]
# C++, $803,960
```
for (int iVal = 0; iVal < 10000; ++iVal)
{
int val = game.read();
if (val > maxVal &&
val < 466.7f + 0.9352f * maxVal + 0.0275f * iVal)
{
maxVal = val;
game.take();
}
else
{
game.pass();
}
}
```
Reported result is the median from 10,001 games.
[Answer]
# C++, ~$815,000
Based on Reto Koradi's solution, but switches to a more sophisticated algorithm once there's 100 (valid) envelopes left, shuffling random permutations and computing the heaviest increasing subsequence of them. It will compare the results of taking and not taking the envelope, and will greedily select the best choice.
```
#include <algorithm>
#include <iostream>
#include <vector>
#include <set>
void setmax(std::vector<int>& h, int i, int v) {
while (i < h.size()) { h[i] = std::max(v, h[i]); i |= i + 1; }
}
int getmax(std::vector<int>& h, int n) {
int m = 0;
while (n > 0) { m = std::max(m, h[n-1]); n &= n - 1; }
return m;
}
int his(const std::vector<int>& l, const std::vector<int>& rank) {
std::vector<int> h(l.size());
for (int i = 0; i < l.size(); ++i) {
int r = rank[i];
setmax(h, r, l[i] + getmax(h, r));
}
return getmax(h, l.size());
}
template<class RNG>
void shuffle(std::vector<int>& l, std::vector<int>& rank, RNG& rng) {
for (int i = l.size() - 1; i > 0; --i) {
int j = std::uniform_int_distribution<int>(0, i)(rng);
std::swap(l[i], l[j]);
std::swap(rank[i], rank[j]);
}
}
std::random_device rnd;
std::mt19937_64 rng(rnd());
struct Algo {
Algo(int N) {
for (int i = 1; i < N + 1; ++i) left.insert(i);
ival = maxval = 0;
}
static double get_p(int n) { return 1.2 / std::sqrt(8 + n) + 0.71; }
bool should_take(int val) {
ival++;
auto it = left.find(val);
if (it == left.end()) return false;
if (left.size() > 100) {
if (val > maxval && val < 466.7f + 0.9352f * maxval + 0.0275f * (ival - 1)) {
maxval = val;
left.erase(left.begin(), std::next(it));
return true;
}
left.erase(it);
return false;
}
take.assign(std::next(it), left.end());
no_take.assign(left.begin(), it);
no_take.insert(no_take.end(), std::next(it), left.end());
take_rank.resize(take.size());
no_take_rank.resize(no_take.size());
for (int i = 0; i < take.size(); ++i) take_rank[i] = i;
for (int i = 0; i < no_take.size(); ++i) no_take_rank[i] = i;
double take_score, no_take_score;
take_score = no_take_score = 0;
for (int i = 0; i < 1000; ++i) {
shuffle(take, take_rank, rng);
shuffle(no_take, no_take_rank, rng);
take_score += val + his(take, take_rank) * get_p(take.size());
no_take_score += his(no_take, no_take_rank) * get_p(no_take.size());
}
if (take_score > no_take_score) {
left.erase(left.begin(), std::next(it));
return true;
}
left.erase(it);
return false;
}
std::set<int> left;
int ival, maxval;
std::vector<int> take, no_take, take_rank, no_take_rank;
};
struct Game {
Game(int N) : score_(0), max_taken(0) {
for (int i = 1; i < N + 1; ++i) envelopes.push_back(i);
std::shuffle(envelopes.begin(), envelopes.end(), rng);
}
int read() { return envelopes.back(); }
bool done() { return envelopes.empty(); }
int score() { return score_; }
void pass() { envelopes.pop_back(); }
void take() {
if (read() > max_taken) {
score_ += read();
max_taken = read();
}
envelopes.pop_back();
}
int score_;
int max_taken;
std::vector<int> envelopes;
};
int main(int argc, char** argv) {
std::vector<int> results;
std::vector<int> max_results;
int N = 10000;
for (int i = 0; i < 1000; ++i) {
std::cout << "Simulating game " << (i+1) << ".\n";
Game game(N);
Algo algo(N);
while (!game.done()) {
if (algo.should_take(game.read())) game.take();
else game.pass();
}
results.push_back(game.score());
}
std::sort(results.begin(), results.end());
std::cout << results[results.size()/2] << "\n";
return 0;
}
```
[Answer]
# Java, $806,899
This is from a trial of 2501 rounds. I am still working on optimizing it. I wrote two classes, a wrapper and a player. The wrapper instantiates the player with the number of envelopes (always 10000 for the real thing), and then calls the method `takeQ` with the top envelope's value. The player then returns `true` if they take it, `false` if they pass it.
## Player
```
import java.lang.Math;
public class Player {
public int[] V;
public Player(int s) {
V = new int[s];
for (int i = 0; i < V.length; i++) {
V[i] = i + 1;
}
// System.out.println();
}
public boolean takeQ(int x) {
// System.out.println("look " + x);
// http://www.programmingsimplified.com/java/source-code/java-program-for-binary-search
int first = 0;
int last = V.length - 1;
int middle = (first + last) / 2;
int search = x;
while (first <= last) {
if (V[middle] < search)
first = middle + 1;
else if (V[middle] == search)
break;
else
last = middle - 1;
middle = (first + last) / 2;
}
int i = middle;
if (first > last) {
// System.out.println(" PASS");
return false; // value not found, so the envelope must not be in the list
// of acceptable ones
}
int[] newVp = new int[V.length - 1];
for (int j = 0; j < i; j++) {
newVp[j] = V[j];
}
for (int j = i + 1; j < V.length; j++) {
newVp[j - 1] = V[j];
}
double pass = calcVal(newVp);
int[] newVt = new int[V.length - i - 1];
for (int j = i + 1; j < V.length; j++) {
newVt[j - i - 1] = V[j];
}
double take = V[i] + calcVal(newVt);
// System.out.println(" take " + take);
// System.out.println(" pass " + pass);
if (take > pass) {
V = newVt;
// System.out.println(" TAKE");
return true;
} else {
V = newVp;
// System.out.println(" PASS");
return false;
}
}
public double calcVal(int[] list) {
double total = 0;
for (int i : list) {
total += i;
}
double ent = 0;
for (int i : list) {
if (i > 0) {
ent -= i / total * Math.log(i / total);
}
}
// System.out.println(" total " + total);
// System.out.println(" entro " + Math.exp(ent));
// System.out.println(" count " + list.length);
return total * (Math.pow(Math.exp(ent), -0.5) * 4.0 / 3);
}
}
```
## Wrapper
```
import java.lang.Math;
import java.util.Random;
import java.util.ArrayList;
import java.util.Collections;
public class Controller {
public static void main(String[] args) {
int size = 10000;
int rounds = 2501;
ArrayList<Integer> results = new ArrayList<Integer>();
int[] envelopes = new int[size];
for (int i = 0; i < envelopes.length; i++) {
envelopes[i] = i + 1;
}
for (int round = 0; round < rounds; round++) {
shuffleArray(envelopes);
Player p = new Player(size);
int cutoff = 0;
int winnings = 0;
for (int i = 0; i < envelopes.length; i++) {
boolean take = p.takeQ(envelopes[i]);
if (take && envelopes[i] >= cutoff) {
winnings += envelopes[i];
cutoff = envelopes[i];
}
}
results.add(winnings);
}
Collections.sort(results);
System.out.println(
rounds + " rounds, median is " + results.get(results.size() / 2));
}
// stol... I mean borrowed from
// http://stackoverflow.com/questions/1519736/random-shuffling-of-an-array
static Random rnd = new Random();
static void shuffleArray(int[] ar) {
for (int i = ar.length - 1; i > 0; i--) {
int index = rnd.nextInt(i + 1);
// Simple swap
int a = ar[index];
ar[index] = ar[i];
ar[i] = a;
}
}
}
```
A more detailed explanation is coming soon, after I finish optimizations.
The core idea is to be able to estimate the reward from playing a game from a given set of envelopes. If the current set of envelopes is {2,4,5,7,8,9}, and the top envelope is the 5, then there are two possibilities:
* Take the 5 and play a game with {7,8,9}
* Pass the 5 and play a game of {2,4,7,8,9}
If we calculate the expected reward of {7,8,9} and compare it to the expected reward of {2,4,7,8,9}, we will be able to tell if taking the 5 is worth it.
Now the question is, given a set of envelopes like {2,4,7,8,9} what is the expected value? I found the the expected value seems to be proportional to the total amount of money in the set, but inversely proportional to the square root of the number of envelopes that the money is divided into. This came from "perfectly" playing several small games in which all of the envelopes have almost identical value.
The next problem is how to determine the "*effective* number of envelopes." In all cases, the number of envelopes is known exactly by keeping track of what you've seen and done. Something like {234,235,236} is definitely three envelopes, {231,232,233,234,235} is definitely 5, but {1,2,234,235,236} should really count as 3 and not 5 envelopes because the 1 and 2 are nearly worthless, and you would never PASS on a 234 so you could later pick up a 1 or 2. I had the idea of using Shannon entropy to determine the effective number of envelopes.
I targeted my calculations to situations where the envelope's values are uniformly distributed over some interval, which is what happens during the game. If I take {2,4,7,8,9} and treat that as a probability distribution, its entropy is 1.50242. Then I do `exp()` to get 4.49254 as the effective number of envelopes.
The estimated reward from {2,4,7,8,9} is `30 * 4.4925^-0.5 * 4/3 = 18.87`
The exact number is `18.1167`.
This isn't an exact estimate, but I am actually really proud of how well this fits the data when the envelopes are uniformly distributed over an interval. I'm not sure of the correct multiplier (I am using 4/3 for now) but here is a data table excluding the multiplier.
```
Set of Envelopes Total * (e^entropy)^-0.5 Actual Score
{1,2,3,4,5,6,7,8,9,10} 18.759 25.473
{2,3,4,5,6,7,8,9,10,11} 21.657 29.279
{3,4,5,6,7,8,9,10,11,12} 24.648 33.125
{4,5,6,7,8,9,10,11,12,13} 27.687 37.002
{5,6,7,8,9,10,11,12,13,14} 30.757 40.945
{6,7,8,9,10,11,12,13,14,15} 33.846 44.900
{7,8,9,10,11,12,13,14,15,16} 36.949 48.871
{8,9,10,11,12,13,14,15,16,17} 40.062 52.857
{9,10,11,12,13,14,15,16,17,18} 43.183 56.848
{10,11,12,13,14,15,16,17,18,19} 46.311 60.857
```
Linear regression between expected and actual gives an **R^2 value of 0.999994**.
My next step to improve this answer is to improve estimation when the number of envelopes starts to get small, which is when the envelopes are not approximately uniformly distributed and when the problem starts to get granular.
---
Edit: If this is deemed worthy of bitcoins, I just got an address at `1PZ65cXxUEEcGwd7E8i7g6qmvLDGqZ5JWg`. Thanks! (This was here from when the challenge author was handing out prizes.)
] |
[Question]
[
## Introduction
My calculator is behaving weird. Sometimes when I type in an `8` it displays a `2`. And sometimes when I type in a `6` it displays a `+`. Some buttons are mixed up!
Could anyone help me determine which?
## Challenge:
**Input:** List of *incorrect* equations, with *correct* results.
**Output:** The two buttons that are swapped.
**For example:**
An input could be:
```
123 = 3
8423 = 252
4+4 = 8
4*7-10 = 417
9/3 = 3
42-9 = -36
```
For which the expected outputs are: `2` and `*`.
Why? Because ALL the equations would be correct if we swap the 2's and \*'s:
```
1*3 = 3
84*3 = 252
4+4 = 8
427-10 = 417
9/3 = 3
4*-9 = -36
```
## Challenge rules:
* Input can be in any reasonable format. Can be a single string with space delimited; a string-list or -array; a list with equations and another list with the correct results. Your call. Please state which input format you've used!
NOTE: This also means you are allowed to input the test case `-5--15` as `-5- -15` or `-5 - -15`. However, a number resulting in `--` should either be inputted without spaces or with a space between every digit. So test case `9119` can be inputted like `9119` or `9 1 1 9` (reason `91 19` isn't allowed is because you can then be guided by the space for finding `- -`). So spaces are (somewhat) optional and allowed.
* Output format can be in any reasonable format as well. Can be two characters; a single two-character string; a string-list containing the two characters. Your call. Again, please state which output format you've used!
* You are allowed to use any distinct 14 outputs that map to `0123456789+-*/`. So you are even allowed to output two distinct integers if you want to (again, please specify the mapping you've used, if any).
* You only have to support integers. So there won't be any test cases like `1/8=0.125` or `1/8=0`.
* Arithmetic operands you'll have to support: addition (`+`); subtraction (`-`); multiplication (`*` or `×` or `·`); division (`/` or `÷`). (NOTE: Characters between parenthesis are only added as clarification.)
* You'll have to support negative numbers. This means `-` can be interpreted in the equation as both a mathematical operand or a negative indicator.
* You can assume the given incorrect equations and supposed correct equations are always valid (so there won't be things like `4-/2` or `9+-+8` for example).
* The incorrect input-equations can contain a division by 0, but the corrected and expected equations will never contain division by 0.
* The incorrect input-equations can already be correct even if you swap the intended buttons back.
* A given input equation can be irrelevant for the buttons to swap (like the `4+4=8` and `9/3=3` equations, with the swapped buttons `2` and `*`).
* You can assume there will always be only one possible swap that can be made with the given test cases.
* Both buttons to swap will always be present in at least one of the incorrect equations.
## 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:
```
Input:
123 = 3
8423 = 252
4+4 = 8
4*7-10 = 417
9/3 = 3
42-9 = -36
Output: 2 *
Input:
4/2 = 6
3/0 = 3
0/8+2 = 4
95-5 = 90
4+2 = 2
Output: + /
Input:
7+4 = 11
5-15 = 46
212-23 = -2121
Output: 1 -
Input:
4+8/2-9*1 = -5
99/3-13 = 20
1+2+3+4 = 10
4-3-2-1 = -6
Output: 2 4
Input:
18/18 = 1
98-8 = 90
55*88 = 4840
-5--15 = 10
Ouput: 5 8
Input:
9119 = 18
5-3 = 513
8*-9 = 152
13116/3 = -1
Output: 1 -
```
[Answer]
# JavaScript (ES7), ~~159~~ 158 bytes
*Edit: new version to comply with the updated rules regarding `--`*
*Saved 1 byte thanks to [@Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)*
Takes input in currying syntax `(e)(r)` where ***e*** is the array of equations and ***r*** is the array of expected results. Returns an array of characters.
```
e=>r=>(l=[...2**29+'4+-*/']).filter(x=>l.some(y=>eval("try{eval((S=(s=`[${e}]`).replace(/./g,c=>c==x?y:c==y?x:c)).split`--`.join`+`)+''==r&S!=s}catch(e){}")))
```
### Test cases
```
let f =
e=>r=>(l=[...2**29+'4+-*/']).filter(x=>l.some(y=>eval("try{eval((S=(s=`[${e}]`).replace(/./g,c=>c==x?y:c==y?x:c)).split`--`.join`+`)+''==r&S!=s}catch(e){}")))
console.log(JSON.stringify(f
([ '123', '8423', '4+4', '4*7-10', '9/3', '42-9' ])
([ 3, 252, 8, 417, 3, -36 ])
));
console.log(JSON.stringify(f
([ '4/2', '3/0', '0/8+2', '95-5', '4+2' ])
([ 6, 3, 4, 90, 2 ])
));
console.log(JSON.stringify(f
([ '7+4', '5-15', '212-23' ])
([ 11, 46, -2121 ])
));
console.log(JSON.stringify(f
([ '4+8/2-9*1', '99/3-13', '1+2+3+4', '4-3-2-1' ])
([ -5, 20, 10, -6 ])
));
console.log(JSON.stringify(f
([ '18/18', '98-8', '55*88', '-5--15' ])
([ 1, 90, 4840, 10 ])
));
console.log(JSON.stringify(f
([ '9119', '5-3', '8*-9', '13116/3' ])
([ 18, 513, 152, -1 ])
));
```
### Formatted and commented
```
e => r => // given e and r
(l = [...2 ** 29 + '4+-*/']) // generate l = [...'5368709124+-*/']
.filter(x => // for each character x of l
l.some(y => // for each character y of l
eval("try { // we need to 'try', because we don't know
eval( // whether the following expression is valid
(S = (s = `[${e}]`). // s = list of equations coerced to a string
replace(/./g, c => // S =
c == x ? y : c == y ? x : c // s with x and y exchanged
) // end of replace()
).split`--`.join`+` // replace '--' with '+'
) + '' == r // does the resulting list match r?
& S != s // and was at least one character modified?
} catch(e){}") // if we try, we oughta catch
) // end of some()
) // end of filter()
```
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), ~~132~~ 113 bytes
*Thanks to Jo King for -19 bytes.*
```
->\e,$r {first {($!=e.trans($_=>.flip))ne e&&try "all {$!.&{S:g/\-/- /}} Z==$r".EVAL},[X~] (|^10,|<+ - * />)xx 2}
```
[Try it online!](https://tio.run/##VY9NT8JAEIbv/IqBNPRzusy0C7tqSTxw82ZijKKGQzEklZDCAVLqX6@zkJiyh9mPd993ntmVdTXtfk7graHocL4sE6@GZr2p9wdoAm9YlOmhXm33gfdVzNN1tdmF4baEcjw@1CcYraoKGm@Yjpvnu2@1RIWg2hbeisKrR@ni5fGpTd5ffz8gOH/SJDk/xIAQgZqHxyNw2@1XrnXgk7XkJwO4Lp/98H7wr3GWgMldzeNcSjRDyQKr3Auj7RnlhTXLd1FoloDcMZv203IlcqbEP1EmlrPVqF0y92KmF6f0svLvBmbmCDSSWJgYOeu5iMQjVhSFbnrGRglnJLoVaiQJp5jj7DIOZsjYn97xsDR2Q@INPBlFMpo1KFXryMiGGgWnj3HFzk1@yRB/9wc "Perl 6 – Try It Online")
Input is a comma-separated string of equations and a comma-separated string of results (hope this is OK). Output is a string containing the two swapped buttons.
Correctly handles `--`. Might product false positives for `---`, `++`, `**`, or `//`, but I couldn't come up with a test case.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~204~~, ~~199~~, ~~193~~, ~~173~~, 165 bytes
* From 199 bytes to 193 bytes thanks to Mr. Xcode
* From 193 bytes to
173 bytes thanks to Halvard Hummel
```
s=input()
r=str.replace
t=set(''.join(zip(*s)[0]))
for i in t:
for j in t:
try:
if all(eval(r(r(r(e,i,'$'),j,i),'$',j))==v*(i<j)for e,v in s):print i,j
except:0
```
[Try it online!](https://tio.run/##LYxRi8IwEISfza/Iw0F2y9ZrxUIs5peID0UibihpSPbKeX@@GjkGhvmYYdJTHks8bFtxHNOPAKrsiuR99mmebl6JK17AmH1YOMIfJ2gKXrororovWbPmqGVUukL4h53k59s13/U0z@DXaYb8kScm82WQAjHWRAHRubUBPgesH57W@lJwTJmjaKagdv735pOM3bZdwPT2u7eGdI8E5mRbazSdugrD0Nh3c7THD7ZD2/ZDXXZ4fQE "Python 2 – Try It Online")
[Answer]
# Oracle SQL & PL/SQL, 458 Bytes
>
> Input can be in any reasonable format. [...] a list with equations and another list with the correct results.
>
>
>
Compile the PL/SQL function (210 bytes):
```
CREATE FUNCTION f(x CHAR,y CHAR)RETURN NUMBER IS o NUMBER;BEGIN EXECUTE IMMEDIATE 'BEGIN :1:='||REPLACE(x,'--','- -')||';END;'USING OUT o;RETURN CASE o WHEN y THEN 1 END;EXCEPTION WHEN OTHERS THEN RETURN 0;END;
```
Run the SQL (248 bytes):
```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM T,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM T)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0
```
After having create a table `T` with the test data:
```
CREATE TABLE T(X,Y) AS
SELECT '123', 3 FROM DUAL UNION ALL
SELECT '8423', 252 FROM DUAL UNION ALL
SELECT '4+4', 8 FROM DUAL UNION ALL
SELECT '4*7-10', 417 FROM DUAL UNION ALL
SELECT '9/3', 3 FROM DUAL UNION ALL
SELECT '42-9', -36 FROM DUAL
```
Output:
```
V V_1
- ---
2 *
* 2
```
**Previous Version**:
Assumed a string input like `'123 = 3'`:
Same PL/SQL function and the SQL (322 bytes):
```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15),y(x,y)AS(SELECT REGEXP_SUBSTR(t,'[^=]+'),REGEXP_SUBSTR(t,'-?\d+$')FROM T)SELECT r.v,s.v FROM y,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM T)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0
```
After having create a table `T` with the test data:
```
CREATE TABLE T(T) AS
SELECT '123 = 3' FROM DUAL UNION ALL
SELECT '8423 = 252' FROM DUAL UNION ALL
SELECT '4+4 = 8' FROM DUAL UNION ALL
SELECT '4*7-10 = 417' FROM DUAL UNION ALL
SELECT '9/3 = 3' FROM DUAL UNION ALL
SELECT '42-9 = -36' FROM DUAL;
```
Output:
```
V V_1
- ---
2 *
* 2
```
**Update - Testing**:
[SQL Fiddle](http://sqlfiddle.com/#!4/a6746/1)
**Oracle 11g R2 Schema Setup**:
```
CREATE FUNCTION F(x CHAR,y CHAR)RETURN NUMBER IS o NUMBER;BEGIN EXECUTE IMMEDIATE 'BEGIN :1:='||REPLACE(x,'--','- -')||';END;'USING OUT o;RETURN CASE o WHEN y THEN 1 END;EXCEPTION WHEN OTHERS THEN RETURN 0;END;
/
CREATE TABLE A(X,Y) AS
SELECT '123', 3 FROM DUAL UNION ALL
SELECT '8423', 252 FROM DUAL UNION ALL
SELECT '4+4', 8 FROM DUAL UNION ALL
SELECT '4*7-10', 417 FROM DUAL UNION ALL
SELECT '9/3', 3 FROM DUAL UNION ALL
SELECT '42-9', -36 FROM DUAL
/
CREATE TABLE B(X,Y) AS
SELECT '4/2', 6 FROM DUAL UNION ALL
SELECT '3/0', 3 FROM DUAL UNION ALL
SELECT '0/8+2', 4 FROM DUAL UNION ALL
SELECT '95-5', 90 FROM DUAL UNION ALL
SELECT '4+2', 2 FROM DUAL
/
CREATE TABLE C(X,Y) AS
SELECT '7+4', 11 FROM DUAL UNION ALL
SELECT '5-15', 46 FROM DUAL UNION ALL
SELECT '212-23', -2121 FROM DUAL
/
CREATE TABLE D(X,Y) AS
SELECT '4+8/2-9*1', -5 FROM DUAL UNION ALL
SELECT '99/3-13', 20 FROM DUAL UNION ALL
SELECT '1+2+3+4', 10 FROM DUAL UNION ALL
SELECT '4-3-2-1', -6 FROM DUAL
/
CREATE TABLE E(X,Y) AS
SELECT '18/18', 1 FROM DUAL UNION ALL
SELECT '98-8', 90 FROM DUAL UNION ALL
SELECT '55*88', 4840 FROM DUAL UNION ALL
SELECT '-5--15', 10 FROM DUAL
/
CREATE TABLE G(X,Y) AS
SELECT '9119', 18 FROM DUAL UNION ALL
SELECT '5-3', 513 FROM DUAL UNION ALL
SELECT '8*-9', 152 FROM DUAL UNION ALL
SELECT '13116/3', -1 FROM DUAL
/
```
**Query 1**:
```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM A,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM A)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0
```
**[Results](http://sqlfiddle.com/#!4/a6746/1/0)**:
```
| V | V |
|---|---|
| 2 | * |
| * | 2 |
```
**Query 2**:
```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM B,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM B)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0
```
**[Results](http://sqlfiddle.com/#!4/a6746/1/1)**:
```
| V | V |
|---|---|
| + | / |
| / | + |
```
**Query 3**:
```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM C,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM C)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0
```
**[Results](http://sqlfiddle.com/#!4/a6746/1/2)**:
```
| V | V |
|---|---|
| 1 | - |
| - | 1 |
```
**Query 4**:
```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM D,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM D)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0
```
**[Results](http://sqlfiddle.com/#!4/a6746/1/3)**:
```
| V | V |
|---|---|
| 2 | 4 |
| 4 | 2 |
```
**Query 5**:
```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM E,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM E)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0
```
**[Results](http://sqlfiddle.com/#!4/a6746/1/4)**:
```
| V | V |
|---|---|
| 5 | 8 |
| 8 | 5 |
```
**Query 6**:
```
WITH r(v)AS(SELECT SUBSTR('1234567890-+*/',LEVEL,1)FROM DUAL CONNECT BY LEVEL<15)SELECT r.v,s.v FROM G,r,r s WHERE r.v<>s.v GROUP BY r.v,s.v HAVING SUM(f(TRANSLATE(x,r.v||s.v,s.v||r.v),y))=(SELECT COUNT(1)FROM G)AND SUM(INSTR(x,r.v)+INSTR(x,s.v))>0
```
**[Results](http://sqlfiddle.com/#!4/a6746/1/5)**:
```
| V | V |
|---|---|
| 1 | - |
| - | 1 |
```
[Answer]
# Powershell, ~~222~~ ~~209~~ 192 bytes
```
param($x)1..13|%{0..(($i=$_)-1)|%{$a,$b='+-*/0123456789'[$i,$_]
$a+$b|?{!($x|%{$e,$r=$_-split'='
try{$r-(-join$(switch($e|% t*y){$a{$b}$b{$a}default{$_}})-replace'-',' -'|iex)}catch{1}}|gu)}}}
```
Test script and explanation:
```
$f={
param($x) # array of strings with equations
1..13|%{ #
0..(($i=$_)-1)|%{ # $i and $_ contains unique couples of different indecies
$a,$b='+-*/0123456789'[$i,$_] # $a and $b contains buttons to swap
$g=$x|%{ # for each equation from array
$e,$r=$_-split'=' # split incorrect expression and correct result
$e=-join$(switch($e|% t*y){ # swap buttons for each symbol in the expression
$a{$b}
$b{$a}
default{$_}
})
$e=$e-replace'-',' -' # insert a space before each '-'.
# It need to work with negative numbers.
# For example, '4--1' throws an exception, '4 - -1' returns '5'
try{$r-($e|iex)}catch{1} # Try to calc $e as powershell expression
# return 0 if the expression result equal to the result of the calculation
# return non zero integer otherwise
}|gu # Get-unique of calculation for each equation
if(!$g){ # if $g is 0 or $null
# then all calculations returns true
$a+$b # Ok, return the couple of buttons
}
}
}
}
@(
,('2*','123=3','8423=252','4+4=8','4*7-10=417','9/3=3','42-9=-36')
,('/+','4/2=6','3/0=3','0/8+2=4','95-5=90','4+2=2')
,('1-','7+4=11','5-15=46','212-23=-2121')
,('42','4+8/2-9*1=-5','99/3-13=20','1+2+3+4=10','4-3-2-1=-6')
,('1-','9119=18','5-3=513','8*-9=152','13116/3=-1')
) | % {
$e,$x=$_
$r=&$f $x
"$($e-eq$r): $r : $x"
}
```
Output:
```
True: 2* : 123=3 8423=252 4+4=8 4*7-10=417 9/3=3 42-9=-36
True: /+ : 4/2=6 3/0=3 0/8+2=4 95-5=90 4+2=2
True: 1- : 7+4=11 5-15=46 212-23=-2121
True: 42 : 4+8/2-9*1=-5 99/3-13=20 1+2+3+4=10 4-3-2-1=-6
True: 1- : 9119=18 5-3=513 8*-9=152 13116/3=-1
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 21 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
SÙãʒË_}ʒ¹s‡„--'+:.EQ
```
Input as two lists, first being the equations and second being the results. Output as a filtered list of pairs with both rotations (i.e. `[["2","*"],["*","2"]]`).
[Try it online](https://tio.run/##MzBNTDJM/f8/@PDMw4tPTTrcHV97atKhncWHmx41LHzUME9XV13bSs/18PrA//@jlQwt9A0tlHSULC10QZSpqZYFiNY11dU1NFWK5Yo21LE00DGxMDHQMTSIBQA) or [verify all test cases](https://tio.run/##JVAxTkMxDN05RZUF6ccmsZP8n7B0AaSOCIGoqgoVwcrCXKliYGFBf2NBQhyAQ2TrMXqRj50usf30nt9zfNo80vPUXy3q5@3czDYvTzMzX1zcSX94H6WfbupX/d2P9eNhux/vX@vbYfdz2H0jntrzs8v6t7yetjCtDHEwYHJsJdqobzcgeWmKayBjMeuTVQBODBkiDRAAQy@YiY6FEpzSvctWp5IwtWWssl7IEYoHVv7QHBKSMpgYxVdwIog9oADUttrsxLUj3SYpkDQIWbbhmBADMpIqMQF7IA/Y8lB2lFWVUUtKXdaKCdVSnTRKzFE1KihEpSVq39ChDhSIencMliFRAJLLkdb/). (NOTE: Uses the legacy version of 05AB1E in the TIO, because `.E` is disabled in the newer version on TIO. Because of that, an additional `ï` (cast to integer) is added, because in the legacy version of 05AB1E `1.0` and `1` inside lists were not equal.)
**Explanation:**
```
S # Convert the (implicit) input-list of equations to a list of characters
# (which implicitly flattens)
# i.e. ["18/18","98-8","55*88","-5--15"]
# → ["1","8","/","1","8","9","8","-","8","5","5","*","8","8","-","5","-","-","1","5"]
Ù # Only leave all unique characters
# → ["1","8","/","9","-","5","*"]
ã # Cartesian product with itself; creating each possible pair of characters
# → [["1","1"],["1","8"],["1","/"],["1","9"],["1","-"],["1","5"],["1","*"],["8","1"],["8","8"],["8","/"],["8","9"],["8","-"],["8","5"],["8","*"],["/","1"],["/","8"],["/","/"],["/","9"],["/","-"],["/","5"],["/","*"],["9","1"],["9","8"],["9","/"],["9","9"],["9","-"],["9","5"],["9","*"],["-","1"],["-","8"],["-","/"],["-","9"],["-","-"],["-","5"],["-","*"],["5","1"],["5","8"],["5","/"],["5","9"],["5","-"],["5","5"],["5","*"],["*","1"],["*","8"],["*","/"],["*","9"],["*","-"],["*","5"],["*","*"]]
ʒ } # Filter it by:
Ë_ # Where both characters are unique
# i.e. → [["1","8"],["1","/"],["1","9"],["1","-"],["1","5"],["1","*"],["8","1"],["8","/"],["8","9"],["8","-"],["8","5"],["8","*"],["/","1"],["/","8"],["/","9"],["/","-"],["/","5"],["/","*"],["9","1"],["9","8"],["9","/"],["9","-"],["9","5"],["9","*"],["-","1"],["-","8"],["-","/"],["-","9"],["-","5"],["-","*"],["5","1"],["5","8"],["5","/"],["5","9"],["5","-"],["5","*"],["*","1"],["*","8"],["*","/"],["*","9"],["*","-"],["*","5"]]
ʒ # Then filter the pairs again by:
¹ # Push the first input-list with equations
s # Swap to take the pair we're filtering
 # Bifurcate it (short for Duplicate and Reverse)
‡ # Transliterate; replacing the characters at the same indices in the input-list
# i.e. ["18/18","98-8","55*88","-5--15"] and ["8","5"]
# → ["15/15","95-5","88*55","-8--18"]
# i.e. ["9119","5-3","8*-9","13116/3"] and ["1","-"]
# → ["9--9","513","8*19","-3--6/3"]
„--'+: '# Then replace all "--" with a "+"
# → ["15/15","95-5","88*55","-8+18"]
# → ["9+9","513","8*19","-3+6/3"]
.E # And evaluate the strings with Python eval
# → [1.0,90,4840,10]
# → [18,513,152,-1.0]
Q # And then check if this evaluated list is equal to the (implicit) second input
# i.e. [1.0,90,4840,10] and [1,90,4840,10] → 1 (truthy)
# i.e. [18,513,152,-1.0] and [18,513,152,-1] → 1 (truthy)
# (and output the result implicitly)
# i.e. [["8","5"],["5","8"]
# i.e. [["1","-"],["-","1"]
```
] |
[Question]
[
Your task is to write a piece of code that zeros the current cell in the Brainfuck variant that, each cell can contain a **signed** integer of arbitrarily large magnitude, instead of the normal 0 to 255.
You may assume there are *l* cells to the left and *r* cells to the right of the current cell that are initially zero. You program may only access these *l*+*r*+1 cells. After your code ends it should leave the *l*+*r* extra cells zero and the pointer to the current cell at the original position.
You may not use any input/output.
The code with smallest *l*+*r* wins. If there is a tie, the shortest code wins. It is recommended to also state the time complexity of your program for reference, where *n* is the absolute value of the original integer in the current cell.
### Useful tools
You can test a Brainfuck program in this variation using [this interpreter on TIO by mbomb007](https://tio.run/nexus/python2#fVG7boMwFJ3xV1h0sCkBOUNVicaR2kzZ2RADGFdY5WEZR2k/vHN6sSktHTrZ93Au5@EwDNHzxbajyXBfj33N2CMKATxxQwi57Yp0V97gVuyzZF8i1evRWDx9TCjnBSvvHxhDZ96pyVIA08k2akiNrBoaRUhwzRm6tqqTWBw6OdBTlKGg5qdClChQr7jmnBwJYIGO@R4OwPSRz9Q8yvJ41Qhkt9APnp6s9APLYBlIT6ulOP@1EJMsL3Tp/r@CiQeTDZiSbAkxXmx6NcpKKlpDZybE@SEWzgMM8xfO2TwFnXMU@Ljd0YOB8LkcW/hkUIJ8V5aSF1OJN2lxr6a@sqIl0TdzLsjrdN/7TnzBS8C31kvnyFvYOhC@KacPVf2nvBVe9v7qej9iK7/zdfIzroYGj6ah51SPmrIoggnD@7ke0J02arCutvV@q2rxOYyJqEQrvwA).
You can also use the interpreter in [this answer by boothby](https://codegolf.stackexchange.com/a/3085/25180) (other Python answers probably also work, but I didn't test).
[Answer]
# l+r = 0+2 = 2, ~~55~~ ~~53~~ 51 bytes
```
[>+[-<+>>+<]<[>]>[+[-<+<->>]<[->+<]]>[-<+>]<<]>[-]<
```
# l+r = 1+2 = 3, ~~46~~ 44 bytes
```
[[>+[-<+<+>>]<[<+[->->+<<]]>]>[>]<[-]<<[-]>]
```
My own algorithm. The pointer should begin at the number that needs to be zeroed. The time complexity is O(n^2).
### How it works:
* We start with the number `n`.
* We increment one, so the number becomes `n+1`.
* We decrement two, so the number becomes `n+1-2 = n-1`
* We increment three, so the number becomes `n-1+3 = n+2`.
* We decrement four, so the number becomes `n+2-4 = n-2`.
We repeat the process, increasing the in-/decrement each step, until we get zero.
[Answer]
# l + r = 0 + 2 = 2; 58 bytes
```
>+<[>[<->>+<-]>+<<[>]>[<<+>+>-]<[->+<]>[<]>+[-<+>]<<]>[-]<
```
The complexity is O(n^2).
The following is my testing program generator, so you can see that I actually tried to test it in case it doesn't work...
```
p='''
>+<
[
>
[<->>+<-]
>+<
<[>]>
[<<+>+>-]
<
[->+<]
>[<]>
+ [-<+>]
<<
]
> [-] <
'''
p = ''.join(p.split())
cpp = '''
#include <bits/stdc++.h>
using namespace std;
void test(int q) {
long long t[3] = {q, 0, 0};
int i = 0;
ZZZ
printf("q=%d %lld %lld %lld\\n", q, t[0], t[1], t[2]);
}
int main() {
while(true) {
int q; cin >> q; test(q);
}
}
'''
d = {
'>': '++i; assert(i<3);',
'<': '--i; assert(i>=0);',
'+': '++t[i];',
'-': '--t[i];',
'[': 'while(t[i]){',
']': '}',
}
print cpp.replace('ZZZ', ''.join(d[c] for c in p))
```
] |
[Question]
[
## Introduction
In the strategy game Starcraft 2, there are three "races" to choose from: Terran, Zerg, and Protoss. In this challenge we will be focusing on the Protoss and the iconic phrase "You must construct additional pylons!" This message is stated when you run out of supply to build your army. So, to help out the Starcraft community, you must write a program or function that tells players exactly how many pylons they need.
## The Challenge
You will be given an input of a string consisting of a single integer `N` and space-separated list of units. `N` will always be zero or positive, and the list of units will always have one or more valid units. `N` represents the amount of pylons the player currently has. Your job is to calculate if the amount of pylons that the player has is enough to build the units. Your program or function must output/return a truthy value if there is enough supply, or if there is not enough supply you must output `You must construct ZZZ additional pylons` where `ZZZ` is the amount of pylons needed to build the units. Note that `pylon(s)` must be plural when needed and unplural when not (`...1 additional pylon!`, `...2 additional pylons!`).
## Protoss Units and Supply Cost
Here is a list of all units and their corresponding supply cost. Pylons provide an additional 8 supply.
```
Unit Supply Cost
Probe 1
Zealot 2
Sentry 2
Stalker 2
HighTemplar 2
DarkTemplar 2
Immortal 4
Colossus 6
Archon 4
Observer 1
WarpPrism 2
Phoenix 2
MothershipCore 2
VoidRay 4
Oracle 3
Tempest 4
Carrier 6
Mothership 8
```
## Examples WITHOUT Bonuses
```
Input:
2 Probe Probe Probe Probe Stalker Zealot Carrier Probe Zealot
Output:
You must construct 1 additional pylon!
Why?
Adding up the supply costs for all of the units gives 17. The current 2 pylons provide 16 supply, so one more is needed to provide enough for 17.
Input:
5 Mothership Carrier Probe Tempest HighTemplar
Output:
true
Why?
Adding up the units gets 21. The current 5 pylons provide 40 supply, which is plenty enough.
Input:
0 Mothership Colossus Zealot
Output:
You must construct 2 additional pylons!
Why?
Adding the units gets 16. There is no pylons so 2 need to be built to provide enough supply.
```
## Bonuses
1. Any experienced Starcraft 2 player would know that you need a mothership core before to transform it into a mothership. Also, you can only have one mothership at a time (whether it is an actual mothership or a mothership core). If neither of these conditions are true, output any falsy value. If your program can check to see that only one mothership is active at a time, and that a mothership core is built *before* the actual mothership, take **20%** off your byte count.
2. Little may you know, but nexuses (protoss command centers) actually provide supply too! If your program can add 11 to the maximum supply every time it encounters a nexus in the unit list, take **10%** off your byte count. Note that it does not matter where the Nexus is in the build order, so `0 Probe Nexus` would still return `true`.
## Examples WITH Bonuses
```
Input (Bonus 1):
3 Mothership Zealot
Output:
false
Why?
According to the first bonus, a mothership core has to be built before a mothership.
Input (Bonus 1):
3 MothershipCore Mothership MothershipCore
Output:
false
Why?
According to the first bonus, only one mothership can be built and here there is two (MothershipCore -> Mothership and a second MothershipCore).
Input (Bonus 2):
0 Probe Nexus Probe
Output:
true
Why?
According to the second bonus, nexuses add 11 to the maximum supply, allowing both probes to be built.
Input (Both Bonuses):
0 Nexus MothershipCore Mothership Carrier
Output:
You must construct 1 additional pylon.
Why?
There are no pylons, but the nexus provides 11 supply. The motherships take up 2 and 8, respectively and the carrier takes up 6. You need one more pylon to have enough to provide for all 16 supply.
```
## TL;DR
Input a string consisting of an integer and space-separated unit names (from the table above). Output a truthy value if you can build all of the units with the supply provided by the `N` pylons (the integer in input). Output `You must construct ZZZ additional pylon(s)` if more pylons are needed, where `ZZZ` is the amount of pylons needed. Make sure to make pylons plural if necessary.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in bytes (or your language's counting method) wins!
## Leaderboard
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
---
```
var QUESTION_ID=69011,OVERRIDE_USER=36670;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={},r=1,a=null,n=1;e.forEach(function(e){e.size!=a&&(n=r),a=e.size,++r;var t=jQuery("#answer-template").html();t=t.replace("{{PLACE}}",n+".").replace("{{NAME}}",e.user).replace("{{LANGUAGE}}",e.language).replace("{{SIZE}}",e.size).replace("{{LINK}}",e.link),t=jQuery(t),jQuery("#answers").append(t);var o=e.language;/<a/.test(o)&&(o=jQuery(o).text()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.lang>s.lang?1:e.lang<s.lang?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?([\d\.]+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#answer-list,#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=83c949450c8b"> <div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td>{{SIZE}}</td><td><a href="{{LINK}}">Link</a></td></tr></tbody> </table>
```
[Answer]
# Python 3, 207\*.9 == 186.3 bytes.
Implements the nexus bonus.
Saved 26 bytes thanks to DSM.
Saved 2 bytes thanks to Tim Pederick
```
x,*l=input().split()
d=-((int(x)*8-sum((('vexuobcl'+2*'clsuie'+4*'Ratahoiesuhihi').count(q[-3:-1])*(1-12*(q[0]>'w'))or 2)for q in l))//8)
print((1,"You must construct %s additional pylon"%d+'s!'[d<2:])[d>0])
```
[Answer]
# Ruby, 263 - 30% = 184 bytes
```
v=c=k=0
l,a={PeOr:1,ZtSySrHrDrWmPxMe:2,Oe:3,VyIlAnTt:4,CsCr:6,Mp:8,Ns:-11},ARGV.shift
ARGV.map{|u|k+=l[l.keys.grep(/#{q=u[0]+u[-1]}/)[0]];c+=1if q=="Me";v=!0if c!=1&&q=~/M/}
n=k/8.0-a.to_i
p v ?n<0||"You must construct #{n.ceil} additional pylon#{'s'if n>1}!":nil
```
### Usage
`ruby sc.rb 0 Probe Nexus`
[Answer]
## JavaScript, ~~274~~ ~~265 bytes (no bonuses)~~ 281 - 10% = 252.9 bytes
```
s=>(c=eval(s[a="replace"](" ","-(")[a](/ /g,"+")[a](/\w+/g,m=>m[b="match"](/^(Pr|Ob)/g)?1:m[b](/^([ZSHDWP]|M\w+C)/g)?2:m[b](/^O/g)?3:m[b](/^[IAVT]/g)?4:m[b](/^N/g)?-11:m[b](/^C/g)?6:+m!=m?8:m*8)+")"))>0?true:`You must construct ${Math.ceil(-c/8)} additional pylon${c/8<-1?"s":""}!`
```
This appears to be pretty lengthy...
Demo + explanation:
```
p = s => (c = eval(
s[a = "replace"](" ", "-(") //replace the first space (after the number of pylons) with "-" and open the bracket
[a](/ /g, "+") //replace all the remaining spaces with "+"
[a](/\w+/g, m => //replace any sequence of characters with...
m[b = "match"](/^(Pr|Ob)/g) ? 1 : //with 1, if matches "Probe" or "Observer"
m[b](/^([ZSHDWP]|M\w+C)/g) ? 2 : //with 2, if it matches bunch of the units with cost 2. "Probe" didn't match already, so it's safe to catch "Phoenix" by only the first letter.
m[b](/^O/g) ? 3 : //with 3, if match is "Oracle"
m[b](/^[IAVT]/g) ? 4 : //with 4, if matches "Immortal", "Archon", "VoidRay" or "Tempest"
m[b](/^C/g) ? 6 : //with 6, if it's "Carrier" or "Colossus"
m[b](/^N/g) ? -11 : //don't forget nexuses!
+m != m ? 8 : m * 8 //and if's not a number, then it's "Mothership", so with 8. If it's number, it can only be the number of pylons, replace it with itself multiplied by 8.
) + ")" //close the opened bracket
)) > 0 ? true : `You must construct ${Math.ceil(-c/8)} additional pylon${c/8<-1?"s":""}!`
document.write(
p("2 Probe Probe Probe Probe Stalker Zealot Carrier Probe Zealot") + "<br>" +
p("5 Mothership Carrier Probe Tempest HighTemplar") + "<br>" +
p("0 Mothership Colossus Zealot") + "<br>" +
p("0 Probe Nexus Probe")
)
```
[Answer]
## Python 3, 293 − 30% = 205.1 bytes
Implements **both** bonuses. Prints 1 as its truthy value, and either 0 or an empty string as its falsey value.
```
s='5N 8O5P bDbHeM7P6S7S9W6Z 6O 6A8I7T7V . 7C8C . aM'.split()
m=M=n=o=0
p,*u=input().split()
for v in u:
S=0
while'%x'%len(v)+v[0]not in s[S]:S+=1
n+=S or-11;M+=S>7;m+='pC'in v;o+=m>1or M>1or m<1<=M
q=int(p)+n//-8
print([1,'You must construct %d additional pylon'%-q+'s!'[q>-2:]][q<0]*(o<1))
```
Credit to [Dom Hastings' solution](https://codegolf.stackexchange.com/a/69224/13959) for helping me shave off a good few bytes with a "poor man's `ceil`" of my own, and [Morgan Thrapp's](https://codegolf.stackexchange.com/a/69257/13959) for the idea underlying `'s!'[q>-2:]`, which saved me six bytes—not to mention pointing out, in the comments, how to save another byte on that bit.
---
### Explanations
The string in line 1 encodes all of the units and their supply requirements. Each unit is represented as two characters: a hexadecimal digit giving the length of the unit's name, and the first character of the name (e.g. `8O` is the Observer; `aM` is the Mothership). The supply requirement is the index of the encoded unit within the sequence `s`, formed by splitting the string on the spaces. Full stops mark unused amounts of supply (no unit needs 5 or 7 supply), and as a special case, the Nexus (`5N`) is at index 0.
Line 2 initialises values: `m` is the number of mothership cores, `M` is the number of motherships, `n` is the total supply cost, and `o` indicates whether or not the mothership build conditions have been violated. Line 3 takes the input, putting the number of pylons into `p` and the list of units into `u`.
Within the loop that starts at line 4, `S` is an index into `s` and, thus, also the amount of supply needed for the current unit, `v`. In line 6, the `while` statement steps through `s` until the unit is found. (`'%x'%len(v)` turns the length of the unit's name into a hex digit.)
Line 7 updates the total supply cost `n` (note the special case, `-11`, if `S` is zero). It then increments the counts of motherships `M` (identified by the supply cost being over 7) and mothership cores `m` (identified by the substring `pC` in the unit's name). Then, if either of these is greater than 1, or if `M` is at least one while `m` is still zero, the flag `o` is set. (Actually, it's incremented, but later on we only care if it's zero or non-zero.)
The pylon deficit `q` is calculated, a little oddly, in line 8. Naively, it should be `n // 8 - int(p)` (i.e. one eighth of the supply cost, minus any pylons we already have). But that would round down, when we need to round up. Integer division (`//`) rounds towards negative infinity, though, so we just work everything in negatives: `int(p) - -(n // -8)`, which simplifies to the form actually used.
Lastly, the output. If we're just one pylon short, `q` will be -1, hence the test `q>-2` (which slices the `s` out of the string `s!` if true, and keeps it otherwise). If there's no pylon deficit, `q` will be zero or positive, hence `q<0` to select between the truthy value 1 or the output string. Lastly, if the flag `o` isn't zero, multiplying either result (1 or a string) by Boolean `False` (handled as numeric 0) will give a falsey value (0 or the empty string).
[Answer]
# C++11, 732-30% = 512.4 bytes
Uses Dom Hastings's poor man's `ceil` and Martin Büttner suggestions of shorting the dictionary.
```
#include <iostream>
#include <map>
#include <string>
#include <cctype>
using namespace std;
map<int,int>a ={{536,1},{655,2},{677,2},{758,2},{1173,2},{1175,2},{869,4},{891,6},{635,4},{872,1},{997,2},{763,2},{1516,2},{766,4},{630,3},{770,4},{744,6},{1091,8},{563,-11}};
int main(){string b,c;int d,e,l,j,k=0,m=0,n=0,v=0;cin>>d;getline(cin,b);
while(b.size()){e=0;auto z=b.find(" ");c=b.substr(0,z);b.erase(0,((z==string::npos)?z:z+1));
for(int i=0;i<c.size();i++){e+=tolower(c[i]);}
if(e==1516){m++;}else if(e==1091){((m>1)?v=1:v=0);}
if((l=k-(d*8)>0)&&(m==n==1)){j=(int)(((float)l/8)+0.99);cout<<"You must construct "<<j<<" additional pylon"<<((j==1)?"!":"s!")<<endl;}
else{cout<<((m==n==1&&!v)?"True":"False")<<endl;}}
```
[Answer]
# Python 2, ~~442~~ ~~359~~ ~~464~~ ~~332~~ ~~314~~ 306 - 10% = 275.4
```
a,*l=input().split(' ');p=int(a)*8;for i in l:p-={"Ne":-11,"Pr":1,"Ze":2,"Se":2,"St":2,"Hi":2,"Da":2,"Im":4,"Co":6,"Ar":4,"Ob":1,"Wa":2,"Ph":2,"MoC":2,"Vo":4,"Or":3,"Te":4,"Ca":6,"Mo":8}[i[:2]+("C"if i[-4:]=="Core")]
e=int(.9+p/8)+1;print[1,"You must construct "+`e`+" additional pylon"+"s!"[e>1:]][p>=0]
```
[Answer]
# Lua, 418 - 10% = 376,2 bytes
```
function p(i)i=i:gsub("(%w+)",function(w)q=tonumber(w)*8;return""end,1);n=0;i:gsub("(%w+)",function(w)m=w.match;n=n+(m(w,"^Pr.*")and 1 or m(w,"^Ob.*")and 1 or m(w,"^[ZSHDWP]")and 2 or m(w,"^M.*C")and 2 or m(w,"^O")and 3 or m(w,"^[IAVT]")and 4 or m(w,"^C")and 6 or m(w,"^N")and -11 or 8)end)if n>q then a=math.ceil((n-q)/8);print("You must construct "..a.." additional pylon"..(a>1 and"s"or"")..".")else print(1)end end
```
Implements the Nexus bonus.
First time I've posted something here. Was writing Lua scripts for a game, stumbled across this and felt like contributing, hah.
Note: This Lua function assumes that the base library has been loaded, and that the host application defines an appropriate `print` function that accepts any non-nil value.
I'm exploiting Lua's `string.gsub` to the best of my ability, as well as its `and` and `or` operators.
Here's the pretty version:
```
function pylons(i)
-- Replace the first word, the number, with a space, while also storing it as a number * 8
i = i:gsub("(%w+)", function(w)
q = tonumber(w) * 8
return ""
end, 1)
n = 0
-- the function passed to gsub gets every word in the string, and then I misuse Lua's and/or
-- operator order to assign supply values to string.match calls that do not return nil
i:gsub("(%w+)", function(w)
m = w.match
n = n + (m(w,"^Pr.*") and 1 or
m(w,"^Ob.*") and 1 or
m(w,"^[ZSHDWP]") and 2 or
m(w,"^M.*C") and 2 or
m(w,"^O") and 3 or
m(w,"^[IAVT]") and 4 or
m(w,"^C") and 6 or
m(w,"^N") and -11 or 8)
end)
if n>q then
a = math.ceil((n-q)/8)
print("You must construct "..a.." additional pylon"..(a>1 and"s"or"")..".")
else
print(1)
end
end
pylons("5 Nexus Probe Observer Zealot Sentry Stalker HighTemplar DarkTemplar WarpPrism Phoenix MothershipCore Oracle Immortal Archon VoidRay Tempest Colossus Carrier Mothership")
pylons("2 Probe Probe Probe Probe Stalker Zealot Carrier Probe Zealot")
pylons("5 Mothership Carrier Probe Tempest HighTemplar")
pylons("0 Mothership Colossus Zealot")
```
[Answer]
# JavaScript (ES6), 228-10% = 206
```
s=>(s.replace(/\w+/g,x=>t+=~~{Ns:-11,Pe:1,Zt:2,Sy:2,Sr:2,Hr:2,Dr:2,Il:4,Cs:6,An:4,Or:1,Wm:2,Px:2,Me:2,Vy:4,Oe:3,Tt:4,Cr:6,Mp:8}[x[0]+x.slice(-1)]-8*~~x,t=7),t=t/8|0,t<=0||`You must construct ${t} additional pylon${t>1?'s':''}!`)
```
**Test**
```
F=s=>(
t=7,
s.replace(/\w+/g,
x=>t+=~~{Ns:-11,Pe:1,Zt:2,Sy:2,Sr:2,Hr:2,Dr:2,Il:4,Cs:6,An:4,Or:1,Wm:2,Px:2,Me:2,Vy:4,Oe:3,Tt:4,Cr:6,Mp:8}[x[0]+x.slice(-1)]-8*~~x),
t=t/8|0,
t<=0||`You must construct ${t} additional pylon${t>1?'s':''}!`
)
console.log=x=>O.textContent+=x+'\n';
;['2 Probe Probe Probe Probe Stalker Zealot Carrier Probe Zealot',
'5 Mothership Carrier Probe Tempest HighTemplar',
'0 Mothership Colossus Zealot','0 Probe Nexus Probe'
].forEach(t=>console.log(t+'\n'+F(t)))
```
```
<pre id=O></pre>
```
[Answer]
## Perl, 212 bytes code + 3 for `-p` - 10% = 193.5 bytes
I'm sure I can reduce this some more, not happy about the full `for$s(...){...}` block but I'm done for now!
```
$x=$_*8;s/^\d+ //;map{for$s(Pr,Ob,Or,C,V,I,A,T,Z,S,H,D,W,Ph,'.+C',N,'.+p$'){$x-=(1,1,3,6,(4)x4,(2)x7,-11,8)[$i++%17]*/^$s/}}/\w+/g;$x=int$x/-8+.9;$s=1<$x&&'s';$_=$x>0?"You must construct $x additional pylon$s!":1
```
### Interesting snippets
* Poor mans `ceil`: `int$n+.9` - I tried to use `0|` but got what looks like overflow!
* List duplication: `(9)x9` yields `(9,9,9,9,9,9,9,9,9,9)`
### Usage:
```
perl -p pylons.pl <<< '3 Mothership Zealot'
1
```
Thanks to [Tim Pederick](https://codegolf.stackexchange.com/users/13959/tim-pederick) for helping to save an extra byte!
] |
[Question]
[
# Golf Me An OOP!
Two important components of object-oriented programming are inheritance and composition. Together, they allow for creating simple yet powerful class hierarchies to solve problems. Your task is to parse a series of statements about a class hierarchy, and answer questions about the hierarchy.
## Input
A series of statements and questions about a class hierarchy, read from a file or standard input, whichever is best for your language. If you use the file option, the filename will be passed as the first argument to your code (function argument or command line argument, whichever you choose). The format is as follows:
```
<statement> : <name> is a <name>. | <name> has a <name>.
<question> : Is <name> a <name>? | Does <name> have a <name>?
<name> : a-z | A-Z | sequence of alphanumerics or underscores, starting with a letter
```
The input will always be statements, then questions. All class names will begin with an uppercase English letter (`A-Z`), and all member names will begin with a lowercase English letter (`a-z`). All names are case-sensitive - `ABC123` is not the same class as `Abc123`.
There will not be any cyclical inheritance - if `B` inherits from `A`, `A` will not inherit from `B` or any of `B`'s children.
Only class names will be a part of a hierarchy - statements such as `foo is a bar.` or `document has a name.` will not occur.
## Output
A series of truthy or falsey values, as answers to the queries, written to standard output or as the return value of your function. If you do not have enough information to answer a question (e.g. questions that involve names you have not seen in the statements), answer with a falsey value.
## Test Cases
Case 1:
Input:
```
B is a A.
C is a B.
A has a foo.
Does B have a foo?
Is C a A?
Is D a A?
```
Output:
```
True
True
False
```
Case 2:
Input:
```
Cop is a Person.
Criminal is a Person.
Sheriff is a Cop.
Crooked_Cop is a Cop.
Crooked_Cop is a Criminal.
BankRobber is a Criminal.
Cop has a badge.
Criminal has a criminal_record.
Person has a name.
Is Crooked_Cop a Person?
Does Criminal have a name?
Is Crooked_Cop a BankRobber?
Does Person have a potato?
Is Cop a Cop?
```
Output:
```
True
True
False
False
True
```
## Rules
* You may answer with a function or a program
* Standard loopholes are forbidden
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest correct answer in bytes wins
* The winning answer will be chosen in one week
Good luck, and may the OOP be with you!
# Leaderboard
The Stack Snippet at the bottom of this post generates the leaderboard from the answers a) as a list of shortest solution per language and b) as an overall leaderboard.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
## Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
## Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
## Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the snippet:
```
## [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
<style>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; }</style><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><script>var QUESTION_ID = 61097; var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe"; var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk"; var OVERRIDE_USER = 45941; var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page; function answersUrl(index) { return "https://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 "https://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.toLowerCase(), 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 > b.lang_raw) return 1; if (a.lang_raw < b.lang_raw) 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); } }</script>
```
[Answer]
# CJam, 59 bytes
```
q_'.e=\N/{)'?=\S/>_,(%}%/(__,*{(2$z~@f=.*\m*|}/ff{1$e=>:=N}
```
This finishes instantly for both test cases.
It either prints the second name name of the question or `1` (both truthy), or `0` (falsy).
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=q_'.e%3D%5CN%2F%7B)'%3F%3D%5CS%2F%3E_%2C(%25%7D%25%2F(__%2C*%7B(2%24z~%40f%3D.*%5Cm*%7C%7D%2Fff%7B1%24e%3D%3E%3A%3DN%7D&input=Cop%20is%20a%20Person.%0ACriminal%20is%20a%20Person.%0ASheriff%20is%20a%20Cop.%0ACrooked_Cop%20is%20a%20Cop.%0ACrooked_Cop%20is%20a%20Criminal.%0ABankRobber%20is%20a%20Criminal.%0ACop%20has%20a%20badge.%0ACriminal%20has%20a%20criminal_record.%0APerson%20has%20a%20name.%0AIs%20Crooked_Cop%20a%20Person%3F%0ADoes%20Criminal%20have%20a%20name%3F%0AIs%20Crooked_Cop%20a%20BankRobber%3F%0ADoes%20Person%20have%20a%20potato%3F%0AIs%20Cop%20a%20Cop%3F).
### Idea
Because of the distinction between classes and members, the challenge boils down to creating a [preorder](https://en.wikipedia.org/wiki/Preorder) for which the input provides a partial definition.
We define that *x* ≺ *y* iff *x* is a *y* or *x* has a *y*.
For the first test case, the input states that *B* ≺ *A*, *C* ≺ *B* and *A* ≺ *foo*. Because of transitivity, we also have *B* ≺ *foo*, *C* ≺ *A* and *A* ≺ *foo*. Also, because of reflexivity, *x* ≺ *x* is always true.
For a given input, we thus can extract the partial definition of ≺ from the statements, apply transitivity a sufficient amount of times to complete the definition of ≺ and finally answer the questions.
### Code
```
q_ e# Push all input from STDIN and a copy.
'.e= e# Count the number of dots/statements (C).
\N/ e# Split the original input at linefeeds.
{ e# For each line:
)'?= e# Pop the last character and check if it is a question mark.
e# Pushes 1 for '?', 0 for '.'.
\S/ e# Split the modified line at spaces.
> e# Remove the first chunk ("Does" or "Is") for questions.
_,(% e# Keep the first and last element of the resulting array.
}%/ e# Split the line array into chunks of length C.
(_ e# Extract the first chunk (statements) and push a copy.
e# The original becomes an accumulator for ≺.
_,* e# Repeat the statements C times.
{ e# For each of the repeated statements:
( e# Shift out the first name.
e# ["w" "x"] -> ["x"] "w"
2$z~ e# Copy the accumulator, zip it and dump.
e# [["x" "y"] ["z" "w"]] -> ["x" "z"] ["y" "w"]
@f= e# Rotate the shifted out name on top and check for equality.
e# ["y" "w"] "w" -> [0 1]
.* e# Vectorized string repetition.
e# ["x" "z"] [0 1] -> ["" "z"]
\m* e# Swap the result with the shifted array and apply Cartesian product.
e# ["" "z"] ["x"] -> [["" "x"] ["z" "x"]]
e# This accounts for transitivity; we had ["w" "x"] and ["z" "w"],
e# so now we have ["z" "x"].
| e# Perform set union with the accumulator to add the new pairs.
}/ e#
ff{ e# For each of the questions on the bottom of the stack.
1$e= e# Count the occurrences of the question pair in the accumulator.
> e# Remove 0 or 1 elements from the question pair.
:= e# Check for equality.
e# If the question pair occurs in the accumulator, this pushes the
e# second name of the question pair. Otherwise, it pushes 1 if the
e# names are equal (to account for reflexivity) and 0 otherwise.
N e# Push a linefeed.
} e#
```
[Answer]
# Python 3, ~~431~~ ~~331~~ 308 bytes
```
o={}
f={}
def h(z,f):
if z not in o:f[z]=[z];o[z]=[]
while 1:
g=input().split(' ');r=2;l=g[-1][:-1]
if'.'in g[3]:
if'i'in g[1]:h(g[0],f);h(l,f);f[g[0]]+=f[l]
if'h'in g[1]:o[g[0]]+=l,
else:
if'I'in g[0]:r=any(l in z for z in f[g[1]])
if'D'in g[0]:r=any(l in o[z] for z in f[g[1]])
if r<2:print(r)
```
---
This is the full version with comments
```
objects = {}
synonyms = {}
def createObject(name):
"""
Create a object with `name` if is does not yet exist and start a synonym tree.
"""
if name not in objects:
synonyms[name] = [name]
objects[name] = []
# use this to read from a file
# with open("questions.txt") as file:
# for l in file:
# print(">>> " + l, end='')
# inArg = l.replace("\n","").split(" ")
while True: # to read from a file comment this
inArg = input(">>> ").split(" ") # and this out
out = -1
if '.' in inArg[3]: # statement
last = inArg[3].replace('.','')
if 'i' in inArg[1]: # is a
createObject(inArg[0])
createObject(last)
synonyms[inArg[0]] += synonyms[last]
if 'h' in inArg[1]: # has a
objects[inArg[0]] += [last]
else:# question
last = inArg[-1].replace('?','')
createObject(inArg[1])
if 'I'in inArg[0]: # Is a
out = any([last in syn for syn in synonyms[inArg[1]]])
if 'D'in inArg[0]: # Does have a
out = any(last in objects[syn] for syn in synonyms[inArg[1]])
if out != -1:
print(out)
```
---
Output for test case #1:
```
True
True
False
```
Case #2:
```
True
True
False
False
True
```
I removed the debug commands for clarity in the main program, but if you would like to see them just look in the history
[Answer]
# Haskell, 157 bytes
```
o s=v(x 0#k)#(x 1#q)where(k,q)=break((=='?').l.l)(words#lines s)
x n w=(w!!n,init$l w)
v k(a,c)=a==c||or[v k(b,c)|b<-snd#(filter((==a).fst)k)]
(#)=map
l=last
```
Give the string to `o`. Not sure if making `x` and `v` ('extract' and 'verify') infixes cuts more than making `map` an infix, or if both is possible.
## EDIT: Explanation
So, `(#)` is how you define an infix operator, I use it just as a shorthand for `map`, applying a function to each element of a list. Resolving this and the other alias `l`, avoiding the 'direct-function-application'-operator `$` and adding even more parentheses and spacing things out, and with real function names we arrive at:
```
oop string = map (verify (map (extract 0) knowledge)) (map (extract 1) questions)
where (knowledge,questions) = break ((=='?').last.last) (map words (lines string))
extract n wordlist = (wordlist!!n,init (last wordlist))
verify knowledge (a,c) = (a==c)
|| or [verify knowledge (b,c) | b <- map snd (filter ((==a).fst) knowledge)]
```
`map words (lines string)` is a list of word lists of each lines in the input string.
`(=='?').last.last` is a predicate indicating whether the last letter in the last word of a line is a question mark, i.e. whether the line is a question.
`break` breaks the list in a tuple of the first part without questions (all statements) and the part from the first question on (all questions).
`map`ping `extract n` on these takes out of each word list the elements we really want, the `n`th one (which in statements is the first word - so `n == 0`, and in questions is the second word - so `n == 1`) using the `!!` operator and the last one, from which we have to cut the last letter (either `'.'` or `'?'`) using `init`.
(Note that I completetely ignore capitalization, that's because I completely ignore the distinction between classes and members, members are just leafs of a tree constructed by the knowledge base (but not all leafs represent members, they may also be classes with neither subclasses nor members), in which every child node represents a subclass or member of what its parent node represents. I JUST REALIZED THIS IS A WRONG THING TO DO in cases not covered by OP. Will edit solution soon.)
Now, `map (extract 0) knowledge` and `map (extract 1) questions` are lists of tuples of names representing a subclass- or member-relationship of the first to the second.
The tuples in `map (extract 0) knowledge` are all true relationships, those in `map (extract 1) questions` are now mapped the `verify` function over, with the first argument set to `map (extract 0) knowledge`.
(From now on, inside `verify`, `knowledge` is a parameter name and refers to the already `extract`ed tuple list.)
(Also, when reading `verify`, note that while the `||` (after the inelegant linebreak to avoid horizontal-scroll on SE) is a normal boolean disjunction between the 'reflexive' and the 'recursive' case, `or` folds that over a list, i.e. checks if any list element is true.)
Now, a relations is obviously correct if it is reflexive. Strictly speaking, no, a `potato` does not *have* a `potato` (and it isn't even one in the sense 'is' is used here, as in 'A Cop is a Cop'), but that's just the termination condition that covers all relationships after walking down the tree (which unlike in the case of real *trees* means 'towards the leafs').
In all other cases, we try to take a tuple from `knowledge` (after we `filter`ed to make sure we 'see' only pairs with the same first element as that we want to check), and go on from where it points to. The list comprehension deals with all possible tuple to continue with and calls `verify` again in each case. A dead end will just have an empty list here and return `false` overall, and so not influence the instance of `verify` it was called by.
[Answer]
# JavaScript, ~~265~~ 263 bytes
```
for(o={};i=prompt().split(/\W/);)a=i[0],b=i[1],d=i[2],b=="is"?((o[a]=o[a]||{p:[],k:{}}).p.push(d),o[d]=o[d]||{p:[],k:{}}):b=="has"?o[a].k[d]=1:alert(o[b]&&(a>"E"?b==d|(c=n=>~(p=o[n].p).indexOf(d)|p.some(c))(b):(c=n=>o[n].k.hasOwnProperty(i[4])|o[n].p.some(c))(b)))
```
Enter a blank string to quit.
## Explanation
```
for(
o={}; // o = all objects
i=prompt().split(/\W/); // i = command as an array of words
)
a=i[0], // a = first word
b=i[1], // b = second word
//c=i[2], // c = third word
d=i[3], // b = fourth word
//e=i[4], // e = fifth word
// Case: <name> is a <name>.
b=="is"?(
(o[a]=o[a]||{p:[],k:{}}) // create the object if it does not exist
.p.push(d), // add the parent to the object's list of parents
o[d]=o[d]||{p:[],k:{}} // create the parent if it does not exist
):
// Case: <name> has a <name>.
b=="has"?
o[a].k[d]=1 // set the specified property
:
alert( // display the responses to the questions
o[b] // false if the queried object does not exist
&&(
// Case: Is <name> a <name>?
a>"E"? // "Is" > "E" and "Does" < "E"
b==d // check if it is itself
|(c=n=>
~(p=o[n].p) // p = direct parents of current object
.indexOf(d) // check direct parents for the object
|p.some(c) // check the grandparents
)(b)
// Case: Does <name> have a <name>?
:
(c=n=>
o[n].k.hasOwnProperty(i[4]) // check if this object has the property
|o[n].p.some(c) // check it's parents for the property also
)(b)
)
)
```
] |
[Question]
[
# Challenge Description
Cycle all letters from the first part of the alphabet in one direction, and letters from the second half of the alphabet in the other. Other characters stay in place.
# Examples
1: Hello world
```
Hello_world //Input
Hell ld //Letters from first half of alphabet
o wor //Letters from second half of alphabet
_ //Other characters
dHel ll //Cycle first letters
w oro //Cycle second letters
_ //Other characters stay
dHelw_oroll //Solution
```
2: codegolf
```
codegolf
c deg lf
o o
f cde gl
o o
focdeogl
```
3.: empty string
```
(empty string) //Input
(empty string) //Output
```
# Input
String you need to rotate. May be empty. Does not contain newlines.
# Output
Rotated input string, trailing newline allowed
May be written to the screen or returned by a function.
# Rules
* No loopholes allowed
* This is code-golf, so shortest code in bytes solving the problem wins
* Program must return the correct solution
[Answer]
# [Retina](http://github.com/mbuettner/retina), 55 bytes
```
O$i`[a-m](?=.*([a-m]))?
$1
O$i`((?<![n-z].*))?[n-z]
$#1
```
[Try it online!](http://retina.tryitonline.net/#code=TyRpYFthLW1dKD89LiooW2EtbV0pKT8KJDEKTyRpYCgoPzwhW24tel0uKikpP1tuLXpdCiQjMQ&input=SGVsbG9fd29ybGQ)
Uses two sorting stages to rotate the first- and second-half letters separately.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~44~~ ~~43~~ 42 [bytes](http://www.cp1252.com/)
```
Оn2äø€J2ä©`ŠÃÁUÃÀVv®`yåiY¬?¦VëyåiX¬?¦Uëy?
```
**Explanation**
Generate a list of the letters of the alphabet of both cases. `['Aa','Bb', ..., 'Zz']`
```
Оn2äø€J
```
Split into 2 parts and store a copy in the register.
```
2ä©
```
Extract the letters from the input that are a part of the 1st half of the alphabet, rotate it and store in **X**.
```
`ŠÃÁU
```
Extract the letters from the input that are a part of the 2nd half of the alphabet, rotate it and store in **Y**.
```
ÃÀV
```
Main loop
```
v # for each char in input
®` # push the lists of first and second half of the alphabet
yåi # if current char is part of the 2nd half of the alphabet
Y¬? # push the first char of the rotated letters in Y
¦V # and remove that char from Y
ëyåi # else if current char is part of the 1st half of the alphabet
X¬? # push the first char of the rotated letters in X
¦U # and remove that char from X
ëy? # else print the current char
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w5DFvm4yw6TDuOKCrEoyw6TCqWDFoMODw4FVw4PDgFZ2wq5gecOlaVnCrD_CplbDq3nDpWlYwqw_wqZVw6t5Pw&input=SGVsbG9fd29ybGQ)
**Note:** The leading `Ð` can be omitted in [2sable](https://github.com/Adriandmen/2sable) for a **41** byte solution.
[Answer]
# Javascript (ES6), ~~155~~ ~~142~~ 138 bytes
```
s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)
```
*Edit: saved ~~3~~ 4 bytes by using `unshift()` (inspired by edc65's answer)*
### How it works
The `R` function takes an array method as its parameter `m`:
```
R = m => s = s.replace(/[a-z]/gi, c => (c < 'N' | c < 'n' & c > 'Z' ? a : b)[m](c))
```
It is first used with the `push` method to store extracted characters in `a[]` (first half of alphabet) and `b[]` (second half of alphabet). Once these arrays have been rotated, `R()` is called a second time with the `shift` method to inject the new characters in the final string.
Hence the slightly unusual syntax: `R`push`` and `R`shift`` .
### Demo
```
let f =
s=>(a=[],b=[],S=s,R=m=>s=s.replace(/[a-z]/gi,c=>(c<'N'|c<'n'&c>'Z'?a:b)[m](c)),R`push`,a.unshift(a.pop(b.push(b.shift()))),s=S,R`shift`,s)
console.log("Hello_world", "=>", f("Hello_world"));
console.log("codegolf", "=>", f("codegolf"));
console.log("HELLO_WORLD", "=>", f("HELLO_WORLD"));
```
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), 41 bytes
```
lee_{'N,_el^:A&},_1m>er_{ADf+&},_1m<erWf=
```
[Try it online!](http://cjam.tryitonline.net/#code=bGVlX3snTixfZWxeOkEmfSxfMW0-ZXJfe0FEZismfSxfMW08ZXJXZj0&input=SGVsbG9fd29ybGQ)
Uses a similar approach to my [vowel shuffling answer](https://codegolf.stackexchange.com/a/91766/8478).
[Answer]
# Python, 211 Bytes
```
x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
u=filter(y,x)
d=filter(z,x)
r=l=""
for i in x:
if y(i):r+=u[-1];u=[i]
else:r+=i
for i in r[::-1]:
if z(i):l=d[0]+l;d=[i]
else:l=i+l
print l
```
Best i could do. Takes the string from STDIN and prints the result to STDOUT.
### alternative with 204 Bytes, but unfortunatly prints a newline after each char:
```
x=input()
y=lambda i:'`'<i.lower()<'n'
z=lambda i:'m'<i.lower()<'{'
f=filter
u=f(y,x)
d=f(z,x)
r=l=""
for i in x[::-1]:
if z(i):l=d[0]+l;d=[i]
else:l=i+l
for i in l:
a=i
if y(i):a=u[-1];u=[i]
print a
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 29 bytes
```
FT"ttk2Y213:lM@*+)m)1_@^YS9M(
```
[Try it online!](http://matl.tryitonline.net/#code=RlQidHRrMlkyMTM6bE1AKispbSkxX0BeWVM5TSg&input=J0hlbGxvX3dvcmxkJw)
### Explanation
```
FT % Push arrray [0 1]
" % For each
t % Duplicate. Takes input string implicitly in the first iteration
tk % Duplicate and convert to lower case
2Y2 % Predefined string: 'ab...yz'
13: % Generate vector [1 2 ... 13]
lM % Push 13 again
@* % Multiply by 0 (first iteration) or 1 (second): gives 0 or 13
+ % Add: this leaves [1 2 ... 13] as is in the first iteration and
% transforms it into [14 15 ... 26] in the second
) % Index: get those letters from the string 'ab...yz'
m % Ismember: logical index of elements of the input that are in
% that half of the alphabet
) % Apply index to obtain those elements from the input
1_@^ % -1 raised to 0 (first iteration) or 1 (second), i.e. 1 or -1
YS % Circular shift by 1 or -1 respectively
9M % Push the logical index of affected input elements again
( % Assign: put the shifted chars in their original positions
% End for each. Implicitly display
```
[Answer]
# Python 2, 149 bytes
```
s=input();g=lambda(a,b):lambda c:a<c.lower()<b
for f in g('`n'),g('m{'):
t='';u=filter(f,s)[-1:]
for c in s:
if f(c):c,u=u,c
t=c+t
s=t
print s
```
[Answer]
# JavaScript (ES6), 144
Using `parseInt` base 36 to separate first half, second half and other. For any character `c`, I evaluate `y=parseInt(c,36)` so that
* `c '0'..'9' -> y 0..9`
* `c 'a'..'m' or 'A'..'M' -> y 10..22`
* `c 'n'..'z' or 'N'..'Z' -> y 23..35`
* `c any other -> y NaN`
So `y=parseInt(c,36), x=(y>22)+(y>9)` gives `x==1` for first half, `x==2` for second half and `x==0` for any other (as `NaN` > any number is false)
First step: the input string is mapped to an array of 0,1 or 2. Meanwhile all the string characters ar added to 3 arrays. At the end of this first step the array 1 and 2 are rotated in opposite directions.
Second step: the mapped array is scanned, rebuilding an output string taking each character from the 3 temporary arrays.
```
s=>[...s].map(c=>a[y=parseInt(c,36),x=(y>22)+(y>9)].push(c)&&x,a=[[],p=[],q=[]]).map(x=>a[x].shift(),p.unshift(p.pop(q.push(q.shift())))).join``
```
*Less golfed*
```
s=>[...s].map(
c => a[ y = parseInt(c, 36), x=(y > 22) + (y > 9)].push(c)
&& x,
a = [ [], p=[], q=[] ]
).map(
x => a[x].shift(), // get the output char from the right temp array
p.unshift(p.pop()), // rotate p
q.push(q.shift()) // rotate q opposite direction
).join``
```
**Test**
```
f=
s=>[...s].map(c=>a[y=parseInt(c,36),x=(y>22)+(y>9)].push(c)&&x,a=[[],p=[],q=[]]).map(x=>a[x].shift(),p.unshift(p.pop()),q.push(q.shift())).join``
function update() {
O.textContent=f(I.value);
}
update()
```
```
<input id=I oninput='update()' value='Hello, world'>
<pre id=O></pre>
```
[Answer]
# Perl. 53 bytes
Includes +1 for `-p`
Run with the input on STDIN:
```
drotate.pl <<< "Hello_world"
```
`drotate.pl`:
```
#!/usr/bin/perl -p
s%[n-z]%(//g,//g)[1]%ieg;@F=/[a-m]/gi;s//$F[-$.--]/g
```
[Answer]
# Python, ~~142~~ 133 bytes
A better variation on the theme:
```
import re
def u(s,p):x=re.split('(?i)([%s])'%p,s);x[1::2]=x[3::2]+x[1:2];return ''.join(x)
v=lambda s:u(u(s[::-1],'A-M')[::-1],'N-Z')
```
## ungolfed:
```
import re
def u(s,p):
x = re.split('(?i)([%s])'%p,s) # split returns a list with matches at the odd indices
x[1::2] = x[3::2]+x[1:2]
return ''.join(x)
def v(s):
w = u(s[::-1],'A-M')
return u(w[::-1],'N-Z')
```
## prior solution:
```
import re
def h(s,p):t=re.findall(p,s);t=t[1:]+t[:1];return re.sub(p,lambda _:t.pop(0),s)
f=lambda s:h(h(s[::-1],'[A-Ma-m]')[::-1],'[N-Zn-z]')
```
### ungolfed:
```
import re
def h(s,p): # moves matched letters toward front
t=re.findall(p,s) # find all letters in s that match p
t=t[1:]+t[:1] # shift the matched letters
return re.sub(p,lambda _:t.pop(0),s) # replace with shifted letter
def f(s):
t = h(s[::-1],'[A-Ma-m]') # move first half letters toward end
u = h(t[::-1],'[N-Zn-z]') # move 2nd half letters toward front
return u
```
[Answer]
## Ruby, 89 bytes
```
f=->n,q,s{b=s.scan(q).rotate n;s.gsub(q){b.shift}}
puts f[1,/[n-z]/i,f[-1,/[a-m]/i,gets]]
```
[Answer]
# PHP, 189 bytes
Quite hard to golf... Here is my proposal:
```
for($p=preg_replace,$b=$p('#[^a-m]#i','',$a=$argv[1]),$i=strlen($b)-1,$b.=$b,$c=$p('#[^n-z]#i','',$a),$c.=$c;($d=$a[$k++])!=='';)echo strpos(z.$b,$d)?$b[$i++]:(strpos(a.$c,$d)?$c[++$j]:$d);
```
] |
[Question]
[
## Challenge:
### Input:
You take two inputs:
- A string only containing printable ASCII (excluding spaces, tabs or new-lines)
- A printable ASCII character
### Output:
The first line will contain the string-input. Every `i`-modulo-3 first occurrence of this character will move in a South-East direction; every `i`-modulo-3 second occurrence will move in a South direction; and every `i`-modulo-3 third occurrence will move in a South-West direction. You'll continue until the characters are about to be at their initial starting position again (which means it will wrap around from one side to the other if necessary), and then you'll print the last line with the string-input again to finish it. (Note that all test cases will end up at their initial input after at most `length(input)` rows, including the row containing the trailing input. It can be sooner though, as seen in this first test case below, with a length of 14, but ending after 9.)
This may all be pretty vague, so here an example:
### Test case 1:
String-input: `"This_is_a_test"`
Character-input: `'s'`
Output:
```
This_is_a_test
s s s
ss s
s s
sss
sss
s s
ss s
s s s
This_is_a_test
```
Here is the same test case with the colored paths of the three `s`:
[](https://i.stack.imgur.com/6a0Qs.png)
where the first `'s'` follows the green path in a South-East direction; the second `'s'` follows the yellow path in a South direction; and the third `'s'` follows the light blue path in a South-West direction. (If there would be a fourth `'s'` it would go in a South-East direction again, which can be seen in some of the other test cases below.)
## Challenge rules:
* The inputs will only contain printable ASCII (excluding spaces, tabs and new-lines)
* I/O formats are flexible. Can be a new-line delimited string, character matrix, etc. Your call.
* It is possible that the given character isn't present in the string, in which case you are allowed to either output the input-string once or twice (i.e. `"test", 'a'` can have either of these as possible output: `"test\ntest"`/`"test"`).
* Leading spaces are mandatory; trailing spaces are optional. One or multiple leading/trailing new-lines are allowed.
## General rules:
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes wins.
Don't let code-golf languages discourage you from posting answers with non-codegolfing languages. Try to come up with an as short as possible answer for 'any' programming language.
* [Standard rules apply](https://codegolf.meta.stackexchange.com/questions/2419/default-for-code-golf-program-function-or-snippet/2422#2422) for your answer, so you are allowed to use STDIN/STDOUT, functions/method with the proper parameters and return-type, full programs. Your call.
* [Default Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are forbidden.
* If possible, please add a link with a test for your code.
* Also, please add an explanation if necessary.
## Test cases / more examples:
### Test case 2:
String-input: `"abcabcabcabcabc"`
Character-input: `'b'`
Output:
```
abcabcabcabcabc
b b b b b
bbb bb
b b
bbb bb
b b b b b
b b b b
b b b b b
bb b bb
b b b
bb bbb
b b bbb
b b b b
b bb bb
b b bb b
abcabcabcabcabc
```
Here is the same test case with the colored paths of the five `a`:
[](https://i.stack.imgur.com/aZg8n.png)
### Test case 3:
String-input: `"only_two_paths?"`
Character-input: `'o'`
Output:
```
only_two_paths?
o o
o o
o o
o o
o o
oo
o
oo
o o
o o
o o
o o
o o
o o
only_two_paths?
```
Here is the same test case with the colored paths of the two `o`:
[](https://i.stack.imgur.com/6h7rz.png)
### Test case 4:
String-input: `"lollollollollol"`
Character input: `'l'`
Output:
```
lollollollollol
lll ll ll
ll ll ll
l ll ll ll ll
lll l ll l ll
llllll ll ll
l l ll ll
ll lll ll
l l l lll ll l
ll l ll l l
l l l l llll l
ll lll lll
l l l ll
ll lll lllll
l l l ll l ll
lollollollollol
```
Here is the same test case with the colored paths of the ten `l`:
[](https://i.stack.imgur.com/Fq2QV.png)
### Test case 5:
String-input: `"AbCdEeDcBaAbCdEeDcBa_CCCCC"`
Character input: `'C'`
Output:
```
AbCdEeDcBaAbCdEeDcBa_CCCCC
C C C C C
C C C C CCC
C C C C C C C
C C C C C C C
C C C C C C C
C C C C C C C
C C C C C C C
C C C CC C C
C C CC C C
C C CC C C
C C CC C
CC CC C C
CC CC C C
C C CC C C
C C CC C C C
C C C C C C
C C CC C C C
C C C C C C C
C C C C C C C
C C C C C CC
C C C C C C
C C C C CCC
C C C CCCC
C C C C
C C CCCCC
AbCdEeDcBaAbCdEeDcBa_CCCCC
```
Here is the same test case with the colored paths of the seven `C`:
[](https://i.stack.imgur.com/FJBWl.png)
### Test case 6:
String-input: `"XyX"`
Character input: `'X'`
Output:
```
XyX
XX
X
XyX
```
Here is the same test case with the colored paths of the two `X`:
[](https://i.stack.imgur.com/Hna6q.png)
### Test case 7:
String-input: `"aaaa"`
Character input: `'a'`
Output:
```
aaaa
aa
aaa
aaa
aaaa
```
Here is the same test case with the colored paths of the four `a`:
[](https://i.stack.imgur.com/aCIxL.png)
[Answer]
# [Perl 5](https://www.perl.org/), `-plF` ~~101~~ ~~100~~ ~~99~~ ~~98~~ ~~97~~ 96 bytes
Replace the `\0` by a literal 0 byte to get 96. Notice that the Try It Online link has 97 bytes because it doesn't seem possible to input a literal 0 character there.
```
#!/usr/bin/perl -plF
say;say$$l=~y/\0/ /runtil--$l,(s:\Q${\<>}:$$l|=v0 x((++$#$l%3*$l-$l+"@-")%@F).$&;v0:oreg^$$l)eq$_
```
The code golf perl highlighter thinks `#` start a comment. How naive üòà
[Try it online!](https://tio.run/##DcpPC4IwGIDxe59C7DW0NV2El5nhyVuHoONoeBglvLjlliT9@eitwfPcfkaNWHpvu7kKA2D9nQvBiqgYH4PrkVLATWq5OMFL7A8fHsi7nlj0TFNCYAmY7NaAQZG4oXGWNG2Ww6qaGNejul4Cz9QdpPfnW29lqJNOWbewP21crwfrqcHW02OZb1nO/g "Perl 5 – Try It Online")
# How it works
`$l` is a counter for which line after the first we are on (it counts down though, so e.g. -3 for 3 lines below the top string).After printing the initial string once it repeatedly does the following.
Search the first string for occurrences of the target character and calculate at which offset it should appear: `(++$#$l%3*$l-$l+"@-")%@F` which is the current position plus the line number (negative) times `-1, 0, 1` (cyclic). Construct a string with that many times `\0` followed by the target character and `or` that into an accumulator `$$l` (that is a different accumulator for each `$l` and the reason `$l` counts down instead of up because `$1`, `$2` etc are read-only). Simularly `$#$l` refers to a different array each time through the loop. The result is the `$l`th line but with `\0` instead of spaces.
The target charcters in the first string are replaced by `\0` so you end up with the original string with "holes" (with `\0`) at the original positions of the target character. If you `xor` that with the accumulator the holes get filled if and only if the accumulator has the target characters in the original positions, so the result will be the original string. That is used to terminate the loop. If the loop is not finished yet print the accumulator with `\0` replaced by space.
When the loop ends the `-p` option once more prints the first string and the program is done.
The target character is picked up in a rather tricky way. The `${\<>}` converts a line read from STDIN to a reference which is then immediately dereferenced and substituted in the regex. The `\Q` prefix escapes all characters that are special in a regex (like `.` and `*`). The `\E` is implicit. The `o` modifier causes the search part to never be evaluated again but just repeated in all subsequent matches (which is good since there is nothing on STDIN anymore).
[Answer]
# [Python 2](https://docs.python.org/2/), ~~199~~ ~~193~~ 191 bytes
```
s,c=input()
print s;l=len(s);r=range;I=j=[i for i in r(l)if s[i]==c]
while 1:
j=[(j[i]-i%3+1)%l for i in r(len(I))]
if sorted(j)==I:print s;break
print''.join((' '+c)[i in j]for i in r(l))
```
[Try it online!](https://tio.run/##VY9Na8MwDIbv/hUiUGyv3aDbYdBgxpb2kNMuOwRKCI7rLs6MHWyPLr8@U8o@WqGD9PDqlTSMqfPufipetzuRZdkUV0oYN3wmxskQjEsQcyusdizyPIgg3bvOS9GLvYGjD2DAOAjMcnOEuDe1EKomp85YDesNAdSxHvGtWTws13xhr4bQteS8JjAP@5D0gfVciHLzu7kNWn4QOLeU3vXeOMYo0KXi@7NJX18dwSf8gZA/htKbRzxDf2kF848/XlP21pnYYMom6ZiyFY2UZLJVl4m0ReqdHZt08s0gUxefkHqk1tvLRGqRPrfFYae36kX@V00xBwoKFFRjhVU1L8PAUtJv "Python 2 – Try It Online")
---
If the loop can exit via exception:
# [Python 2](https://docs.python.org/2/), 187 bytes
```
s,c=input()
print s;l=len(s);r=range;I=j=[i for i in r(l)if s[i]==c]
while 1:
j=[(j[i]-i%3+1)%l for i in r(len(I))]
if sorted(j)==I:print s;q
print''.join((' '+c)[i in j]for i in r(l))
```
[Try it online!](https://tio.run/##VY9Pa8MwDMXv/hQiUGyv3Vi3wyDBjC3tIadddgiUEBLXXRyMndkebT59ppT9aYUOjx9P0tMwxs7Zhyl/22xFkiRTWEmh7fAVGSeD1zZCyIwwyrLAMy98Yz9UVohe7DQcnAcN2oJnhusDhJ2uhJAVOXbaKFinBNDHesS3evG4XPOFuRrCrQXnFYF52Pmo9qznQhTp7@VPAmdJ6V3vtGWMAl1Kvjsv6KurAHzC/IT8MbTePGGE6MdUnZSE@UcC6iTVENP7n81T8t7pUGM3dVQhJisaKEmaVl420haps2as49HVQxO78IzUITXOXDZSg/SlzfdbtZGvzb@q87nQkKOhHEtU5XwMC2VDvwE "Python 2 – Try It Online")
---
* -4 bytes thanks to Jonathan Frech
* -2 bytes thanks to Lynn
[Answer]
# [C (gcc)](https://gcc.gnu.org), 261 bytes
```
i,j,l,k;g(L,t,r,c)char**L;{L[r++][c]=k;c-=t?t-1?:0:-1;l<r||g(L,t,r,c<0?l-1:c%l);}f(S,K){char*s=S,*L[i=1+(l=strlen(s))];for(k=K;i--;)for(L[i]=calloc(j=l,1);j--;)L[i][j]=32;for(puts(s);s[++i];)s[i]-k||g(L,++j%3,0,i);for(i=1;strcmp(*L,L[i]);)puts(L[i++]);puts(s);}
```
[Try it online!](https://tio.run/##bY/NbsIwEITvPAWKhLBjWyLlxmJFLe2J3OgBKYoi4/LjxCQodlUh4NlTOy0th6z2YHu@mfVKtpeybRUtqKYl7FFCLW2oxPIgmjBM4JKkDSFZKjNegmTcxpZF8WwyYxHoeXO9/lnmk1izaCZHGsNth1Z0iS9diuErGiap4hFBmhvb6G2FDMYZ7OoGlXwJijHA/uKojEuhdS1RwTWNMBRe8@9pkfHpU@c5fVrjEsCkhKgMsHEyK3/@QkgxmtIJVbhD3VRwI@XxhMKE@hwMuPO7s1sMwz3s1qrKDo9CVQgPLoOhqx0K3g/K5K5FbrfGBnQ4NuNfTxBguGNiIx/bc5s@rq70ObdfdX4S9mBiz9V9nK71Y3tO93HPm8XH2/ZVvoj/U77w5S2LPsv6vPbauncNV14UThzc2m8)
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~197~~ 194 bytes
```
s=>c=>{(C=console.log)(s);w=0;g=[];while(~(w=s.indexOf(c,w)))g.push(w++);h=(H=_=>g.map(x=>A[x]=c,A=Array(l=s.length).fill` `)&&A.join``)();while(h!=(y=H(g=g.map((x,i)=>(l-~x-i%3)%l))))C(y);C(s)}
```
[Try it online!](https://tio.run/##LY5BasMwEEWv0hoSZogtCl2KERhvsusBQrCNIksKimQstZIpzdVdQwt/@9779/FrjHKxc2p8uKltoi2SkCS@oSMZfAxOMRc0QkSe6Y1rulx5NtYpeEKmyKy/qfIxgawzImo2f0YD@XRCbgjO1JPQ7DHOUEi0l3IlWbfULsu4gttpp7xOBtlknRteBjweW3YP1g8DAv53zCvBSmfQ9GeCUlskAa55lsYe3vHg9jJ2sCLv9p8/G5@gSsbGft/YJxVThVDFCrdf "JavaScript (Node.js) – Try It Online")
Takes inputs in currying syntax, i.e. `f(s)(c)`.
Not a perfect one at all, but I need JS. A lot of functions in function.
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~189 176 171 156 150 146 144~~ 137 bytes
```
->s,c,r=0..k=s.size,b=[p,s]{d=0;g=s.tr c,n=' '*k;l=r=r.map{|i|l||c==s[i]?(n[z=(i+1-d%3)%k]=g[z]=c;d+=1;z):p}-b;g==s||b<<n&&redo;puts b,s}
```
[Try it online!](https://tio.run/##VY/RboIwFIbv9xTERNFZiGZ3q0ezsb3BLkgIIW1BJVQgPTULWJ@dtReb3cl/cfJ9f05adeXDdIQp2iMRRMEmjhvAGOuxIhyynmB@K2FDTxZqFQjSQhiEzw2VoEDFF9bfTG2kMQIAszo/LNtshGW93kbl/GU1b3I4ZWMOgpZr2NJx9drfI27PARrDd7t2sVBV2dH@qjHgBO/TMZt9nWssbFihK9QzEoQY5jRwnSerGRd@nOe@71o5FPq7K3qmz3hwvvO97KQf56Xv33hSflYf4p09tiJx46qJX02H1LH03/PsOMh8@PuRPzj9AA "Ruby – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 24 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
»v↕*δó‼Γ█|q┬YM╨|·£↕fßßZo
```
[Run and debug it online](https://staxlang.xyz/#p=af76122aeba213e2db7c71c2594dd07cfa9c1266e1e15a6f&i=%22This_is_a_test%22+%22s%22%0A%22abcabcabcabcabc%22+%22b%22%0A%22only_two_paths%3F%22+%22o%22%0A%22lollollollollol%22+%22l%22%0A%22AbCdEeDcBaAbCdEeDcBa_CCCCC%22+%22C%22%0A%22XyX%22+%22X%22%0A%22aaaa%22+%22a%22&a=1&m=2)
This is the ascii representation of the same program.
```
YxP|Ic{{i3%v-x%%mb-!Czny&PWxP
```
It gets the indices of all the character, and then mutates them until they are set-wise equal to the original indices. For every change, output a string with the character at those indices.
```
Y Store character in y. Now the inputs are x and y.
xP Print x.
|Ic Get all indices of y in x. Make a copy.
{ W Loop until cancelled.
{ m Map index array using block.
i3%v- Subtract i%3-1 from each element. i is the loop index.
x%% Modulo len(x)
b-! Is the mutated array set-equal to the original?
C If so, cancel W loop
zny&P Print a string with y at all specified indices
xP Finally, print x again
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 33 bytes
```
3ḶNṁ+%⁹L¤‘
Ṅẹ©¥@ÇÇṢ⁻®ƊпṬị;⁶¥ṖY,Y
```
[Try it online!](https://tio.run/##AWgAl/9qZWxsef//M@G4tk7huYErJeKBuUzCpOKAmArhuYThurnCqcKlQMOHw4fhuaLigbvCrsaKw5DCv@G5rOG7izvigbbCpeG5llksWf/igJ1zIMOnIOKAnFRoaXNfaXNfYV90ZXN04oCd/w "Jelly – Try It Online")
---
Call as a function. (dyadic link)
I found [some](https://chat.stackexchange.com/transcript/message/43286603#43286603) [33-byte](https://chat.stackexchange.com/transcript/message/43286383#43286383) [alternatives](https://chat.stackexchange.com/transcript/message/43286524#43286524), but no actual improvement.
] |
[Question]
[
# Decipher Neurotic Frogs
Now that Puzzling.SE has finally cracked [my amphibian-obsessed cipher](https://puzzling.stackexchange.com/q/31212/21402), let's write a program or function to decrypt it!
**(If you want to look at the puzzle before having it spoiled for you, click the above link now.)**
---
### How the cipher works
In Neurotic Frogs *O*ught To Rel*a*x In *M*ud Baths ("Neurotic Frogs" for short), every letter is encrypted as one or two words:
* The length of a non-italicized word represents a letter.
+ `neurotic` => 8 letters => `H`
+ `frogs` => 5 letters => `E`
+ `perpendicular` => 13 letters = `M`
* A word that contains italics modifies the following word, adding 10 if the italicized word was odd in length or 20 if the italicized word was even in length. Any or all of the word may be italicized. An italicized word is always followed by a non-italicized word.
+ `*o*ught to` => odd, 2 => 12 => `L`
+ `lo*u*nging calms` => even, 5 => 25 => `Y`
Every word of plaintext corresponds to a sentence of ciphertext, and every sentence of plaintext corresponds to a paragraph of ciphertext.
### Input format
Your program or function shall input a message in Neurotic Frogs, formatted in Markdown. The input will consist only of printable ASCII and newlines.
* *Words* are runs of characters that match the regex `[A-Za-z0-9']`.
+ Numbers and letters both count toward the length of a word. `QB64` represents `D`.
+ NOTE: Apostrophes *do not count* toward the length of a word. `Isn't` represents `D`, not `E`.
* *Italicized letters* are wrapped in a pair of asterisks (`*letters*`).
+ One or more consecutive letters may be italicized, up to an entire word (`masseus*es*`, `*all*`); multiple non-consecutive letters in a word may also be italicized (`g*e*n*e*rates`).
+ Italics never span multiple words, never include punctuation, and never include apostrophes.
+ Unpaired asterisks and multiple adjacent asterisks will never occur.
* *Punctuation* is any of the following characters: `.,?!:;-()"`.
+ Words within a sentence are separated by one or more punctuation characters *and/or* a single space. Examples: `*all* welcomed`, `toad*s*, newts`, `Ever*y*one--frogs`, `cap... bliss`, `they're (I`
+ Sentences end with one or more punctuation characters and are separated by a double space: `Th*e* Montgomery A*m*phibian Salon! Come luxuriate today!`
+ Paragraphs are separated by a single newline. (The last sentence of a paragraph still has one or more punctuation characters at the end.)
Other characters will not appear in input and do not need to be handled.
Your code may, at your discretion, expect input to have a single trailing newline.
### Output format
The result of decrypting the input will be one or more sentences. Letters of plaintext may be any combination of upper- and lowercase. Words within a sentence must be separated by single spaces. Sentences must end with a period (`.`) and be separated by a single space. You may output a trailing space after the last sentence. Your output will all be on one line, but you may output a trailing newline.
### Miscellaneous details
Your code may use any of the standard input and output methods. It must receive input as a multiline string, not a list or other data structure, and it must output a string.
The shortest code in bytes wins!
### Test cases
```
-->
Neurotic Frogs *O*ught To Rel*a*x In *M*ud Baths!
<--
HELLO.
-->
Business standards all*o*w only *adult* amphibians.
<--
HINT.
-->
Rejoice, *a*ll frogs an*d* toads also! Montgomery Sal*o*n opens up! Ha*pp*y throng fill*s* street ecstatically!
<--
GOOD JOB PPL.
-->
I like 3.1415926535897.
IM*O*, it's a *b*la*st*, yeah!
<--
ADAM. MAN.
-->
*I*, happily, *th*anks 2 u *e*ditin*g* specific wor*ding*--clarifying a *bit*--betterment :D!
<--
QUARTATA.
-->
Perpendicular l*ou*nging calms. *A* frog, a m*u*d cap... bliss! Wallowing g*e*n*e*rates happiness. Amphibian sp*a* isn't expensive--seventy d*o*llars--cheap! That'*s* not *a* large e*x*pens*e* from an*y* discerning fr*o*g's money, unlik*e* Super 8.
Ever*y*one--frogs, toad*s*, newts, *a*nd salamanders! G*e*t a wonderful shiat*s*u, or recei*v*e an other kind. Masseus*es* are her*e* today! Invite a fianc*e*e, supervisor, roommate, niece: *all* welcomed!
Y*o*u simply ne*v*er believed these p*o*ssibilitie*s*; they're (I *swear*) absolute truth! Th*e* Montgomery A*m*phibian Salon! Come luxuriate today!
<--
MY NAME IS INIGO MONTOYA. YOU KILLED MY FATHER. PREPARE TO DIE.
```
[Answer]
# Perl, 72 bytes
```
#!perl -n
$x=/\*/?2-y/'//c%2:!print/ /?$':chr$x.0+y/'//c+64for/[\w*']+| /g,' . '
```
Counting the shebang as one, input is taken from stdin.
**Sample Usage**
```
$ more in.dat
Neurotic Frogs *O*ught To Rel*a*x In *M*ud Baths!
Perpendicular l*ou*nging calms. *A* frog, a m*u*d cap... bliss! Wallowing g*e*n*e*rates happiness. Amphibian sp*a* isn't expensive--seventy d*o*llars--cheap! That'*s* not *a* large e*x*pens*e* from an*y* discerning fr*o*g's money, unlik*e* Super 8.
Ever*y*one--frogs, toad*s*, newts, *a*nd salamanders! G*e*t a wonderful shiat*s*u, or recei*v*e an other kind. Masseus*es* are her*e* today! Invite a fianc*e*e, supervisor, roommate, niece: *all* welcomed!
Y*o*u simply ne*v*er believed these p*o*ssibilitie*s*; they're (I *swear*) absolute truth! Th*e* Montgomery A*m*phibian Salon! Come luxuriate today!
$ perl neurotic-frogs.pl < in.dat
HELLO. MY NAME IS INIGO MONTOYA. YOU KILLED MY FATHER. PREPARE TO DIE.
```
[Answer]
# JavaScript (ES6), ~~172~~ ~~169~~ ~~157~~ 150 bytes
*Saved 10 bytes thanks to @Neil*
```
x=>x.match(/[\w'*]+|\s+/g).map(y=>y[0]==" "?y[1]:y==`
`?". ":/\*/.test(y,l+=y.match(/\w/g).length)?(l=l%2*10+19,""):l.toString(36,l=9),l=9).join``+"."
```
Can probably be further improved. Outputs in all lowercase.
[Answer]
# [Pip](http://github.com/dloscutoff/pip), ~~65~~ 64 bytes
The score is 62 bytes of code + 2 for the `-rs` flags.
```
Flg{O{{(zy*t+#a-1)X!Y'*Na&2-#a%2}MJa@`[\w*]+`}MlRM''^sX2O". "}
```
[Try it online!](https://tio.run/##FY5NT8JAEIbv/ooBotWBNpGTR/FAoknBIIkYP8LSDtuN293NzhaohN9et4c5vfM@7@OU67q5lufl@Xz712IYj0R6f7cZfCS4EDfTdCSup5f8RTxuP7@O@D3eXnK9ypPkhzfT5TCD4aXrFtR4G1QBc28lAy6xkVWAtYUVaRR4gmcDmGNTwpMIFQ@uXsk7MqUqGi08aLQNGqmMhELomjMAnCHsI20CAmpssIyJy7IMdloxDwDehdb22FckEpp4XgRiqIRzyhD3kFntKrVTwgC7qAGKTRKATnGa1YHSlOlAJrRQokUdTThNi4qEi/x1JUKCjGBsgL4cY0lAeMK@Hvd6vxqEwRahVFyQN73O3keYTBhqa6idQGO0@u3f3xpHHh6yLvX8Dw)
### Explanation
The `-r` flag reads all lines of stdin and stores a list of them in `g`. The `-s` flag sets the output format of lists to space-separated.
The easiest way to read this code is from the outside in:
```
Flg{...} For each line l in g, do:
O{...}MlRM''^sX2O". " Translate a paragraph into a sentence of plaintext:
lRM'' Remove apostrophe characters
^sX2 Split on " " into sentences
{...}M Map the below function to each sentence
O Output the result list, space-separated, without newline
O". " Output that string, without newline
{...}MJa@`[\w*]+` Translate a sentence into a word of plaintext:
a@`[\w*]+` Find all matches of regex (runs of alphanumeric and *)
{...}MJ Map the below function to each word and join into string
(zy*t+#a-1)X!Y'*Na&2-#a%2 Translate a word into a letter of plaintext:
#a-1 Length of word minus 1
y*t+ Add 10 or 20 if y is set (see below)
(z ) Use that number to index into lowercase alphabet
'*Na& Count * characters in word, logical AND with...
2-#a%2 2 if word is even length, 1 if odd
Y Yank that value into y, to modify the following word
X! String multiply the character by not(y)
If y is truthy, the word had italics, and we get ""
If y is falsy, the word had no italics, and we get a letter
```
[Answer]
# Python 2, ~~238~~ ~~221~~ ~~218~~ ~~214~~ ~~207~~ 205 bytes
```
from re import*
def f(x):
d='';m=0
for w in split(r"[^\w\d*'~\n]+",sub(' ','~',x))[:-1]:l=len(sub("[*'~\n]",'',w));q='*'in w;d+='. '[w[0]>'}':]*(w[0]in'~\n')+chr(64+l+m)[q:];m=(2-l%2)*10*q
print d+'.'
```
Uses lots of regex to do the processing. We transform the double-space into `~` and use that to process it. `~` and `\n` are handled specially.
The biggest character gain comes from the preprocessing of the input in the `for` line; this can definitely be golfed further.
[Ideone it!](http://ideone.com/o1Fni1) (all test cases)
*Saved 7 bytes thanks to DLosc!*
[Answer]
# Python 2.7, ~~390~~ ~~342~~ ~~341~~ ~~339~~ 335 bytes:
```
from re import*
def F(i):
W=X="";S,s=split,sub;D='[^\w\s*]';Q=lambda c,t:len(s(D,X,c.group()).split()[t])
for m in S('\W\n',s(D+"*\w*\*\w+\*.*?(?=\s) \w+",lambda v:"a"*([20,10][Q(v,0)%2]+Q(v,1)),s("'",X,s("--"," ",i)))):
for g in S('\W ',m):
for q in S('\W',g):
W+=chr(64+len(q))
W+=" "
W=W[:-1]+". "
print s("@",X,W)
```
Takes input in the format:
`F('''Multi or Single-lined String''')`
Can be golfed down a lot more, which I will do whenever I get the chance.
[Repl.it with All Test Cases!](https://repl.it/D4Cp/46)
## Explanation:
Uses the immense power of Python's regular expression built-ins to decipher the input. This is the fundamental process the function goes through for each input:
1. Firstly, all `--` are replaced with a single space, and every apostrophe is removed. Then, all words containing italicized components and the word proceeding it are both matched in one string and replaced with `10 + len(second word)` number of consecutive `a`s if the length of the first word is `odd`, and `20 + len(second word)` consecutive `a`s otherwise. This makes use of the following regular expression:
`[^\w\s*]*\w*\*\w+\*.*?(?=\s) \w+`
For example, if we have the sentence `Perpendicular l*ou*nging calms.`, `l*ou*nging calms` will be replaced with `aaaaaaaaaaaaaaaaaaaaaaaaa`, or 25 `a`s, since `l*ou*nging` has an even number of characters and `calms` has 5. `20+5=25`.
2. Now, the newly modified input is split at each punctuation mark followed by a newline (`\n`) to get the paragraphs, then each paragraph is split at each punctuation followed by 2 spaces to get the sentences, and finally, each sentence is split into words along any punctuation including a space. Then, for each word (including the runs of consecutive `a`s), we add on to a string `W` the letter corresponding to the unicode code point `64` (the unicode code point of the character before `A`, which is `@`) plus `len(word)`. We then add a single space to `W` once all the words of a sentence have been exhausted, and when all the sentences in a paragraph are exhausted, we add a `.` followed by a single space.
3. Finally, after the entire input has been gone through, `W` is output to `stdout` as the deciphered message.
[Answer]
# PHP, 196 Bytes
```
<?preg_match_all("#[\w*']+| |$#m",$_GET[s],$m);foreach($m[0]as$s){if(!$s||$s==" ")echo!$s?". ":" ";else{$l=$p+64+strlen(str_replace("'","",$s));if(!$p=strstr($s,"*")?20-$l%2*10:0)echo chr($l);}}
```
If I could assume that there is only one Apostrophe in the middle of a word 194 Bytes
```
<?preg_match_all("#[\w*]+(<?=')[\w*]+|[\w*]+| |$#m",$_GET[s],$m);foreach($m[0]as$s){if(!$s||$s==" ")echo!$s?". ":" ";else{$l=$p+64+strlen($s);if(!$p=strstr($s,"*")?20-$l%2*10:0)echo chr($l);}}
```
[Answer]
# PHP, ~~231~~ ~~226~~ 228 bytes
for a start
```
<?preg_match_all("#([\w\*']+)([^\w\*']*)#",$argv[1],$m,2);foreach($m as list(,$a,$b)){$e=strlen(strtr($a,["'"=>""]))+$d;if(!$d=strstr($a,'*')?$e%2*10:0)echo chr($e+64),strpos(".$b","
")?". ":(strpos(".$b"," ")?" ":"");}echo".";
```
Save to file, rund `php <scriptpath> <text>`. Escape newlines in the text to make it work in shell.
] |
[Question]
[
**Objective**
Given a grid of numbers, fill in the inequalities.
**Assumptions**
The number of columns and rows in the grid are equal.
The maximum size of the grid is 12x12.
The grid only consists of integers 0-9.
The output may contain a trailing newline.
The input is exactly as written below, including spaces and newlines.
**Example Input**
```
4 2 3 1
6 2 3 1
6 9 2 1
0 2 1 6
```
**Example Output**
```
4>2<3>1
^ " " "
6>2<3>1
" ^ v "
6<9>2>1
v v v ^
0<2>1<6
```
**Example Input (2)**
```
1 2 3 4 5
5 4 3 2 1
0 0 0 3 2
3 2 0 0 0
2 1 3 1 5
```
**Example Output (2)**
```
1<2<3<4<5
^ ^ " v v
5>4>3>2>1
v v v ^ ^
0=0=0<3>2
^ ^ " v v
3>2>0=0=0
v v ^ ^ ^
2>1<3>1<5
```
**Example Input (3)**
```
8
```
**Example Output (3)**
```
8
```
**Example Input (4)**
```
0 0 0 0 0 0 0 0 0 0 0 0
0 1 1 1 1 1 1 1 1 1 1 0
0 1 2 3 4 5 6 7 8 9 1 0
0 1 3 9 8 7 6 5 4 8 1 0
0 1 4 8 9 8 7 6 5 7 1 0
0 1 5 7 8 9 9 7 6 6 1 0
0 1 6 6 7 9 9 8 7 5 1 0
0 1 7 5 6 7 8 9 8 4 1 0
0 1 8 4 5 6 7 8 9 3 1 0
0 1 9 8 7 6 5 4 3 2 1 0
0 1 1 1 1 1 1 1 1 1 1 0
0 0 0 0 0 0 0 0 0 0 0 0
```
**Example Output (4)**
```
0=0=0=0=0=0=0=0=0=0=0=0
" ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ "
0<1=1=1=1=1=1=1=1=1=1>0
" " ^ ^ ^ ^ ^ ^ ^ ^ " "
0<1<2<3<4<5<6<7<8<9>1>0
" " ^ ^ ^ ^ " v v v " "
0<1<3<9>8>7>6>5>4<8>1>0
" " ^ v ^ ^ ^ ^ ^ v " "
0<1<4<8<9>8>7>6>5<7>1>0
" " ^ v v ^ ^ ^ ^ v " "
0<1<5<7<8<9=9>7>6=6>1>0
" " ^ v v " " ^ ^ v " "
0<1<6=6<7<9=9>8>7>5>1>0
" " ^ v v v v ^ ^ v " "
0<1<7>5<6<7<8<9>8>4>1>0
" " ^ v v v v v ^ v " "
0<1<8>4<5<6<7<8<9>3>1>0
" " ^ ^ ^ " v v v v " "
0<1<9>8>7>6>5>4>3>2>1>0
" " v v v v v v v v " "
0<1=1=1=1=1=1=1=1=1=1>0
" v v v v v v v v v v "
0=0=0=0=0=0=0=0=0=0=0=0
```
[Answer]
# CJam, 52 bytes
```
qN%::~_z_2{{_1>.-W<:g}%\z}*@@..{'=+}.{N@"\"v^"f=S*N}
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=qN%25%3A%3A~_z_2%7B%7B_1%3E.-W%3C%3Ag%7D%25%5Cz%7D*%40%40..%7B'%3D%2B%7D.%7BN%40%22%5C%22v%5E%22f%3DS*N%7D&input=0%200%200%200%200%200%200%200%200%200%200%200%0A%0A0%201%201%201%201%201%201%201%201%201%201%200%0A%0A0%201%202%203%204%205%206%207%208%209%201%200%0A%0A0%201%203%209%208%207%206%205%204%208%201%200%0A%0A0%201%204%208%209%208%207%206%205%207%201%200%0A%0A0%201%205%207%208%209%209%207%206%206%201%200%0A%0A0%201%206%206%207%209%209%208%207%205%201%200%0A%0A0%201%207%205%206%207%208%209%208%204%201%200%0A%0A0%201%208%204%205%206%207%208%209%203%201%200%0A%0A0%201%209%208%207%206%205%204%203%202%201%200%0A%0A0%201%201%201%201%201%201%201%201%201%201%200%0A%0A0%200%200%200%200%200%200%200%200%200%200%200).
*Thanks to @CroCo for pointing out a bug in revision 3.*
*Thanks to @Pyrrha for pointing out a bug in revision 6.*
### How it works
```
qN% e# Read all input and split it at runs of linefeeds.
::~ e# Evaluate each character separately.
e# This turns non-empty lines into arrays of integers.
_z_ e# Copy, transpose rows and columns, and copy again.
2{ e# Do the following twice:
{ e# For each row:
_1> e# Copy the row and remove the copy's first element.
.- e# Perform vectorized subtraction.
W< e# Remove the last element.
e# This pushes the array of increments of the row.
:g e# Replace each difference with its sign (-1, 0 or 1).
}% e#
\ e# Swap the two topmost arrays on the stack.
z e# Transpose rows and columns of the topmost array.
}* e#
e# The topmost result has been transposed before and after computing
e# the increments of its rows. It holds the increments of it columns.
e# The result below it has been transposed twice (therefore not at
e# all) before computing the increments of its rows.
@@ e# Rotate the number array and the row increment array on top.
..{ e# For each number and the corresponding increment, push both; then:
'=+ e# Add the increment to the character '='.
} e#
.{ e# For each row of the column increment array and corresponding row
e# of the last result, push both rows; then:
N@ e# Push a linefeed and rotate the column increments on top.
"\"v^"f= e# For each, select the appropriate comparison character.
S* e# Join those characters, separated by spaces.
N e# Push another linefeed.
} e#
```
[Answer]
# Python 2, ~~207~~ 197 bytes
```
f=lambda a:''.join(['=><'[cmp(a[i-1],a[i+1])]if c==' 'else'\n'+' '.join('"v^'[cmp(a[j-a.index('\n')],a[j+2])]for j in range(i,i+a.index('\n'),2))if a[i:i+2]=='\n\n'else c for i,c in enumerate(a)])
```
This one creates a function **f** which takes the grid of numbers as a string and returns the corresponding string with filled inequalities.
The function iterates over each character in the string. If the character is a space, it is replaced with the inequality for the numbers on either side. If the character and the next character are newlines, the whole line is replaced with the inequalities for all the numbers above and below.
Here is the output of the function for each of the examples in the question, except the really long one:
```
>>> print f("""\
... 4 2 3 1
...
... 6 2 3 1
...
... 6 9 2 1""")
4>2<3>1
^ " " "
6>2<3>1
" ^ v "
6<9>2>1
>>> print f("""\
... 1 2 3 4 5
...
... 5 4 3 2 1
...
... 0 0 0 3 2
...
... 3 2 0 0 0
...
... 2 1 3 1 5""")
1<2<3<4<5
^ ^ " v v
5>4>3>2>1
v v v ^ ^
0=0=0<3>2
^ ^ " v v
3>2>0=0=0
v v ^ ^ ^
2>1<3>1<5
>>> print f("8")
8
```
[Answer]
# Pyth, 46 bytes
```
juCms.iJ-d\ m.x@H._-FsMk\ .:J2Gc2"=><\"v^"%2.z
```
Try it online: [Demonstration](http://pyth.herokuapp.com/?code=juCms.iJ-d%5C%20m.x%40H._-FsMk%5C%20.%3AJ2Gc2%22%3D%3E%3C%5C%22v%5E%22%252.z&input=4%202%203%201%0A%0A6%202%203%201%0A%0A6%209%202%201%0A%0A0%202%201%206)
[Answer]
## C, ~~552~~ 408 bytes
This is a mess, but it does work with the test cases (for the solo `8`, the input has to be followed by a newline to work properly)
```
#define P putchar
main(n,z)char**z;{char*t=*++z;n=0;while(*(*z)++!=10)if(**z!=32)n++;char a[n][n];int r=-1,c=0;n--;do*t>32?c?:r++,a[c][r]=*t:*t==10?c=0:c++;while(*++t);r=c=0;do{int j=a[c][r],s=61,k=a[c+1][r];P(j);if (c==n){if(r==n)break;c=0;r++;P(10);for(int t=a[c][r-1],b=a[c][r];c<n+1;t=a[c][r-1],b=a[c][r])s=t>b?118:t<b?94:34,printf("%c ",s),c++;c=0;P(10);continue;}s=j>k?62:j<k?60:s;P(s);c++;}while(1);}
```
Here's the expanded version; I'd love to here ways on how I could golf this more effectively. I know that there is much to be improved on here.
```
#define P putchar
main(n,z)char**z; {
char *t = *++z;
n = 0;
while (*(*z)++!=10)
if (**z!=32)
n++;
char a[n][n];
int c,r=c=0;
r = -1,n--;
do
*t>32?c?:r++, a[c][r] = *t:*t==10?c=0:c++; //32 is ASCII for space
while (*++t);
r=c=0;
do {
int j = a[c][r],s=61,k = a[c+1][r];P(j);
if (c==n)
{
if (r==n)break;
c=0;r++;P(10);
for (int t=a[c][r-1],b=a[c][r];c<n+1; t = a[c][r-1],b = a[c][r])
s=t>b?118:t<b?94:34,printf("%c ",s),c++;
c = 0;
P(10);
continue;
}
s=j>k?62:j<k?60:s;
P(s);
c++;
} while (1);
}
```
[Answer]
# JavaScript (ES6) 162
```
f=s=>(s=s.split`
`).map((r,i)=>r?(w=r).replace(/ /g,(c,j)=>x('<=>',r[j-1]-r[j+1])):w.replace(/\d/g,(c,j)=>x('^"v', c-s[i+1][j])) ,x=(y,v)=>y[-~(v>0)-(v<0)]).join`
`
// more readeable
u=s=>(
x=(y,v)=>y[-~(v>0)-(v<0)],
s=s.split`\n`,
s.map((r,i)=>r
?(w=r).replace(/ /g,(c,j)=>x('<=>',r[j-1]-r[j+1]))
:w.replace(/\d/g,(c,j)=>x('^"v', c-s[i+1][j]))
).join`\n`
)
//TEST
console.log=x=>O.innerHTML+=x+'\n'
;[
'4 2 3 1\n\n6 2 3 1\n\n6 9 2 1\n\n0 2 1 6'
,'1 2 3 4 5\n\n5 4 3 2 1\n\n0 0 0 3 2\n\n3 2 0 0 0\n\n2 1 3 1 5'
,'8',
,'0 0 0 0 0 0 0 0 0 0 0 0\n\n0 1 1 1 1 1 1 1 1 1 1 0\n\n0 1 2 3 4 5 6 7 8 9 1 0\n\n0 1 3 9 8 7 6 5 4 8 1 0\n\n0 1 4 8 9 8 7 6 5 7 1 0\n\n0 1 5 7 8 9 9 7 6 6 1 0\n\n0 1 6 6 7 9 9 8 7 5 1 0\n\n0 1 7 5 6 7 8 9 8 4 1 0\n\n0 1 8 4 5 6 7 8 9 3 1 0\n\n0 1 9 8 7 6 5 4 3 2 1 0\n\n0 1 1 1 1 1 1 1 1 1 1 0\n\n0 0 0 0 0 0 0 0 0 0 0 0'
].forEach(t=>console.log(t+'\n\n'+f(t)+'\n\n'))
```
```
<pre id=O></pre>
```
[Answer]
# Haskell, 201 bytes
```
import Data.List
t=transpose
g=mapM_ putStrLn.t.map(h 1).t.map(h 0).lines
h n s@(a:_:b:r)|'/'<a&&a<':'=a:(o n a b):h n(b:r)
|0<1=s
h n r=r
f=fromEnum
o n a b=l!!n!!(1+signum(f a-f b))
l=["<=>","^\"v"]
```
`g` expects a string.
] |
[Question]
[
You must generate an text stereogram according to an input string containing a paragraph of text, an empty line then the hidden message.
The result will be displayed as a pair of paragraphs, one with different spacing causing the effect of it being raised up when viewed stereographically (An explanation can be found [here](http://en.wikipedia.org/wiki/ASCII_stereogram#Text_emphasis)).
### Example
Input:
```
I invented vegetarianism. It is a diet involving no meat, just vegetables. It is also common in cows - they are awesome.
vegetarianism. is awesome.
```
Output:
```
I invented I invented
vegetarianism. vegetarianism.
It is a diet It is a diet
involving no involving no
meat, just meat, just
vegetables. It vegetables. It
is also common is also common
in cows - they in cows - they
are awesome. are awesome.
```
### Bonuses
* Add option to choose between parallel and cross-eyed as user input (-20)
* Adjustable column width as user input (-50)
This is code golf, so shortest code after bonuses wins.
[Answer]
# TeX 212
I am using a typesetting system, not ASCII. The column width can be changed by changing `90pt` in the fourth line, but I don't know if that's enough to qualify for the 50 bytes discount. The distance between the two copies of the text can be changed by changing the `9pt`, also in the fourth line. The code can probably be made shorter. One can replace each newline by a single space, but not remove them completely.
```
\let\e\expandafter\read5to\t\read5to\.\def\a#1
{\def\~##1#1##2\a{\def\t{##1\hbox{\
#1\~{}}##2}\a}\e\~\t\a}\e\a\.{}\shipout\hbox
spread9pt{\hsize90pt\fontdimen3\font\hsize\vbox{\t}\
\let\~\ \def\ {}\vbox{\t}}\end.
```
After calling `tex filename.tex` in the terminal, the user is prompted to give the main text, then prompted again for a list of words to shift. No empty line in between. The (space-separated) list of words given in the second line should appear exactly as it is in the main text (punctuation is treated just like a letter would be, only spaces delimit words).
[Answer]
# Javascript 391 (441 - 50)
(My first code golf)
```
k=' ';Q='length';A=prompt().split(k);S=prompt().split(k);i=-1;M=25;L=[[]];j=0;R='';while(i++<A[Q]-1){if((j+A[i][Q])<M){if(S.indexOf(A[i])>-1){A[i]=(j?k+k:k)+A[i]}L[L[Q]-1].push(A[i]);j+=A[i][Q]+1}else{j=0;i--;L.push([])}}for(i=0;i<L[Q]-1;P(L[i++].join(C))){C=k;while(L[i].join(C+k)[Q]<M){C+=k}}P(L[i].join(k)+k);function P(a){while(a[Q]<M){a=a.replace(k,k+k)}R+=a;for(c in S){a=a.split(k+k+S[c]).join(k+S[c]+k)}R+=k+k+a+'\n'}console.log(R);
```
## Result
```
In a little district In a little district
west of Washington west of Washington
Square the streets have Square the streets have
run crazy and broken run crazy and broken
themselves into small themselves into small
strips called 'places'. strips called 'places'.
These 'places' make These 'places' make
strange angles and strange angles and
curves. One Street curves. One Street
crosses itself a time or crosses itself a time or
two. An artist once two. An artist once
discovered a valuable discovered a valuable
possibility in this possibility in this
street. Suppose a street. Suppose a
collector with a bill collector with a bill
for paints, paper and for paints , paper and
canvas should, in canvas should, in
traversing this route, traversing this route,
suddenly meet himself suddenly meet himself
coming back, without a coming back, without a
cent having been paid on cent having been paid on
account! account!
```
## Long code:
```
var arr = "In a little district west of Washington Square the streets have run crazy and broken themselves into small strips called 'places'. These 'places' make strange angles and curves. One Street crosses itself a time or two. An artist once discovered a valuable possibility in this street. Suppose a collector with a bill for paints, paper and canvas should, in traversing this route, suddenly meet himself coming back, without a cent having been paid on account!".split(' ');
var secret = "Washington paints himself".split(' ');
var i = -1;
var MAX_WIDTH = 25;
var lines = [[]];
var _l = 0;
var result = '';
while (i++ < arr.length - 1) {
if ((_l + arr[i].length) < MAX_WIDTH) {
if (secret.indexOf(arr[i]) > -1) {arr[i] = (_l?' ':' ') + arr[i]}
lines[lines.length - 1].push(arr[i]);
_l += arr[i].length + 1;
} else {
_l = 0;
i--;
lines.push([]);
}
}
for (var i = 0; i < lines.length - 1; putText(lines[i++].join(chars))) {
// Align text
var chars = ' ';
while (lines[i].join(chars + ' ').length < MAX_WIDTH) {
chars += ' ';
}
}
putText(lines[i].join(' ') + ' ');
function putText(line) {
while (line.length < MAX_WIDTH) {
line = line.replace(' ', ' ');
}
// Make the illusion
result += line;
for (var val in secret) {
line = line.split(' '+secret[val]).join(' ' + secret[val] + ' ');
}
result += (' ' + line) + '\n';
}
console.log(result);
```
[Answer]
# Javascript 493 (minimum expectations)
```
g=" ";l=prompt().split(g);r=l.slice();m=prompt().split(g);f=[];s=f.slice();w=0;n=0;a="";for(i=0;i<l.length;i++){if(l[i]==m[0]){m.shift();l[i]=g+r[i];r[i]+=g;}if(l[i].length+1>w)w=l[i].length+1;}while(l.length){f[f.length]="";s[s.length]="";while(l.length&&f[f.length-1].length+l[0].length<w){f[f.length-1]+=l[0]+g;s[s.length-1]+=r[0]+g;l.shift();r.shift();}f[f.length-1]+=g.repeat(w-f[f.length-1].length);}console.log(f,s);while(f.length){a+=f[0]+s[0]+"\n";f.shift();s.shift();}console.log(a);
```
This code sets up two arrays of lines (left and right), arranges them in a string and prints to `f12` console.
This is just a minimum answer, not intended to win.
[Answer]
# GolfScript 209 (279 -50 -20)
This is my first big GolfScript program. I wouldn't be surprised if there are optimizations to be had. Both the bonuses are supported; they are expected to be found after the message inputs, like:
```
"I invented vegetarianism. It is a diet involving no meat, just vegetables. It is also common in cows - they are awesome."
"vegetarianism. is awesome."
16 # column width
0 # view type, 1 for cross eyed (?)
```
If you've saved that file to `input` (and downloaded [GolfScript](http://www.golfscript.com/golfscript/tutorial.html)) you can invoke the script with:
```
> cat input | ruby golfscript.rb
```
### Golfed
```
~{{\}}{{}}if:v;:w;n%~' '%\' '%[.]zip 0:c;{' '*}:s;{[.;]}:r;\{:x;{.c=0=x=}{1c+:c;}until.c<\1c+>[[x' 'v+' 'x v+]]\++}/zip{0:c;[[]]\{.,.c+w<{1c++:c;\)@r+r+}{:c;[r]+}if}/{.{,}%{+}*w\- 1$,1-.{1$1$/@@%@0:g;{3$3$g>+s\++1g+:g;}*\;\;}{[;.2/\2%1$s@@+s@)\;\]{+}*}if}%}%zip{{4s\++}*}%n*puts
```
### Ungolfed
```
~
#The program:
# Parameters, in reverse natural order
{{\}}{{}}if:v; # view - truthy for parallel, falsey for cross-eyed
:w; # col width
n%~ # split input on newlines
' '%\ # split secret message tokens
' '% # split public message
[.]zip # left and right
0:c; # word count
{' '*}:s; # spaces
{[.;]}:r; # array of top
# for each secret word
\{
:x; # word
{.c=0=x=}
{1c+:c;} until
# next public word is this private word
# splice edits
.c< \1c+> [[x' 'v+ ' 'x v+]]\ ++
}/
zip
# layout both messages
{
0:c; # char count
[[]]\ # line accumulator
# split lines
{
.,.c+w<
# if enough room on line
#append to current line
{1c++:c;
\)@r+r+
}
#append as new line
{:c;
[r]+
}if
}/
# set lines
{
.{,}%{+}* # line chars
w\- # space chars
1$,1- # gaps between words
# if multi word
.{
1$1$ # duplicate params
/@@ # chars per space
% # extra space gaps
@ # load line
0:g; # current gap
# join row
{
3$3$ # params
g>+ # extra space
s # space chars
\++ # append
1g+:g; # update gap
}*
\;\; # drop params
}
# else one word
{
[
; # drop gap count
. # num spaces needed
2/\ # spaces per side
2% # extra space
1$s # left space
@@+s # right space
@)\;\ # word
]{+}* # join
}if
}% # end line layout
}% # end message layout
zip
{{4s\++}*}%
n*
puts
```
[Answer]
## Bash, sed: ~~228~~ ~~223~~ ~~197~~ (242 - 70) = 172
```
c=${5:-=};R=$c;L=;for f in r l;do
e="sed -e ";$e"$ d;s/$\| */ \n/g" $1>m
o=1;for w in `$e"$ p;d" $1`;do
$e"$o,/^$w /s/^$w /$L$w$R /" m>n;o="/$c/"
cp n m;done;tr -d \\n<n|fold -sw${2:-35}|$e"s/$c/ /g">$f
L=$c;R=;done;pr -tmw${3:-80} ${4:-l r}
```
If the script is in an executable file called "stereo", then type
```
stereo file.in [column_width [page_width ["r l"]]]
```
column\_width is a number; 25-45 will work, default is 35.
page\_width is a number, should be about twice the column\_width, default is 80
For cross-eyed viewing, use "r l" as the 4th argument. Default is "l r" which
sets up for parallel viewing.
EDIT: Rewrote to split the file into one word per line, then reassemble at the end. Note: reserves the "=" sign for its own use. Any "=" signs in the input file will become blanks.
EDIT: If your message has "=" signs in it, you can choose another symbol for the script to use, by supplying it as the 5th parameter.
**Example**
Input: vegetarianism.txt:
```
I invented vegetarianism. It is a diet involving no meat, just
vegetables. It is also common in cows - they are awesome.
vegetarianism. is awesome.
```
**Result**
./stereo vegetarianism.txt 32 72 "l r" : | expand
(using the colon for its internal working symbol)
```
I invented vegetarianism. It I invented vegetarianism. It
is a diet involving no meat, is a diet involving no meat,
just vegetables. It is also just vegetables. It is also
common in cows - they are common in cows - they are
awesome. awesome.
```
./stereo washington.txt 35 75 "l r" |expand
```
In a little district west of In a little district west of
Washington Square the streets Washington Square the streets
have run crazy and broken have run crazy and broken
themselves into small strips themselves into small strips
called 'places'. These 'places' called 'places'. These 'places'
make strange angles and curves. make strange angles and curves.
One Street crosses itself a time One Street crosses itself a time
or two. An artist once discovered or two. An artist once discovered
a valuable possibility in this a valuable possibility in this
street. Suppose a collector with a street. Suppose a collector with a
bill for paints, paper and canvas bill for paints, paper and canvas
should, in traversing this route, should, in traversing this route,
suddenly meet himself coming suddenly meet himself coming
back, without a cent having been back, without a cent having been
paid on account! paid on account!
```
The "|expand" isn't necessary but when shifting the output by 4 places the TABs get handled incorrectly. It could be put into the script at a cost of 7 bytes.
## ImageMagick variation
Replacing the last line with a text-to-image ImageMagick command:
```
c=${6:-=};R=$c;L=;for f in r l;do
e="sed -e ";$e"$ d;s/$\| */ \n/g" $1>m
o=1;for w in `$e"$ p;d" $1`;do
$e"$o,/^$w /s/^$w /$L$w$R /" m>n;o="/$c/"
cp n m;done;tr -d \\n<n|fold -sw${2:-35}|$e"s/$c/ /g">$f
L=$c;R=;done;
convert -border 10x30 label:@${4:-l} label:@${5:-r} +append show:
```
In this one, the "r" and "l" for cross-eyed versus parallel viewing
are separate arguments:
./im\_stereo vegetarianism.txt 40 80 l r =
[](https://i.stack.imgur.com/iczCJ.png)
(source: [simplesystems.org](http://www.simplesystems.org/users/glennrp/StackOverflow/stereo_text.png))
EDIT 3: Added ImageMagick variation.
[Answer]
# JavaScript 391
```
_='L=b=>b.length;c=console.log;p=prompt;r=(l*=" ")3m*),s=(f=[]3n=w=a52i=0;i<67i++)l/==m@&&(m!,l/=g+r/,r/8g),?>w&&(w=?72;67){9$]52:]56)&&%#)+64)<w;)#8l4+g,:-1]8r@+g,l!,r!;#8g.repeat(w-%#))}2c(f,s7%f7)a8$f4+s4+"\\n",f!,s!;c(a)!.shift()#9-1]$??%L(*=p().split(g/[i]2for(3).slice(),4[0]5="";6%l7);8+=9f[%f):s[%s)?6/)+1@[$0]';for(Y in $='@?:98765432/*%$#!')with(_.split($[Y]))_=join(pop());eval(_)
```
] |
[Question]
[
**Introduction**
Knowledgeable code golfers [prepared us for the doomsday flood](https://codegolf.stackexchange.com/q/23259/18487). Areas at risk were evacuated, and the population moved to high ground.
We underestimated the flood (or perhaps there was a bug in @user12345's code). Some high-ground areas are rapidly approaching sea level. Walls must be erected in order to ensure the survival of the now densely populated encampments. Sadly, the government has a limited supply of walls.
**Problem**
Our doomsday scenario is described by two numbers on a single line, `n` and `m`. Following that line are `n` lines with `m` values per line, separated only by a single space. Each value will be one of four characters.
* `x` Impassable. Water cannot flow here. Walls cannot be erected here.
* `-` Unstable. Water can flow through this here. Walls cannot be erected here.
* `.` Stable. Water can flow through here. Walls can be erected here.
* `o` Encampment. Water can flow through here. If it does, everyone dies. Walls cannot be built here.
Water will flow from all edges of the map, unless the edge is impassable or a wall is constructed on the tile. Write a program that can output the minimum number of walls required to protect an encampment.
**Example Input**
```
6 7
x . . x x x x
x . . x - - x
x . x x - - x
x . o o o - .
x . o o o - .
x x x x x x x
```
**Example Output**
```
3
```
**Assumptions**
* Water only flows orthogonally
* Encampments only exist as one orthonagonally contiguous block per scenario
* A solution will always exist (although it may require copious amounts of walls)
* Encampments cannot be located on an edge, as the scenario would then have no solution
* 2 < `n` < 16
* 2 < `m` < 16
* Input may be provided from stdin, read from "city.txt", or accepted as a single argument
Shortest code wins!
[Answer]
# Mathematica, ~~257~~ 253 chars
```
d="city.txt"~Import~"Table";g=EdgeAdd[#,∞<->Tr@#&/@Position[VertexDegree@#,2|3]]&@GridGraph@d[[1,{2,1}]];{o,x,s}=Tr/@Position[Join@@d[[2;;]],#]&/@{"o","x","."};Catch@Do[If[Min[GraphDistance[VertexDelete[g,x⋃w],∞,#]&/@o]==∞,Throw@Length@w],{w,Subsets@s}]
```
Input is read from `"city.txt"`.
### Explanation:
Mathematica has many functions to deal with graphs.
First, I read the data from `"city.txt"`.
```
d="city.txt"~Import~"Table";
```
Then I construct a [grid graph](http://reference.wolfram.com/mathematica/ref/GridGraph.html) with 'm'\*'n' vertices (`GridGraph@d[[1,{2,1}]]`), and add to it a "vertex at infinity" which is connected to every vertex on the "edges" of the graph. This vertex is where the water flow from.
```
g=EdgeAdd[#,∞<->Tr@#&/@Position[VertexDegree@#,2|3]]&@GridGraph@d[[1,{2,1}]];
```
And `o`, `x` and `s` denote the positions of "o", "x" and "." respectively.
```
{o,x,s}=Tr/@Position[Join@@d[[2;;]],#]&/@{"o","x","."};
```
Then for any subset `w` of `s` (the subsets are sorted by length), I delete the vertices in `x` and `w` from `g` (`VertexDelete[g,x⋃w]`), and find the length of the shortest path from the "vertex at infinity" to the encampment `o`. If the length is infinity, then the encampment will be safe. So the length of the first such `w` is the minimum number of walls required to protect an encampment.
```
Catch@Do[If[Min[GraphDistance[VertexDelete[g,x⋃w],∞,#]&/@o]==∞,Throw@Length@w],{w,Subsets@s}]
```
[Answer]
## C, ~~827 799~~ 522
**Golfed:**
```
#define N for(
#define F(W,X,Y,Z) N i= W;i X Y;i Z)
#define C(A,B,C) if(c[A][B]==C)
#define S(W,X,Y,Z,A,B) p=1;F(W,X,Y,Z)C(A,B,120)p=0;if(p){F(W,X,Y,Z){C(A,B,46){c[A][B]='x';z++;Q();break;}}}else{F(W,X,Y,Z){C(A,B,120)break;else c[A][B]='o';}}
p,m,z,w,h,o,i,u,l,x,y;char c[16][16];Q(){N u=0;u<h;u++)N l=0;l<w;l++)if(c[u][l]=='o'){x=u;y=l;S(x,>,m,--,i,y)S(y,>,m,--,x,i)S(y,<,w,++,x,i)S(x,<,h,++,i,y)}}main(int a, char **v){h=atoi(v[1]);w=atoi(v[2]);N m=-1;o<h;o++)N i=0;i<w;i++)scanf("%c",&c[o][i]);Q();printf("%d",z);}
```
Input is given with the height and with as command line arguments, and then the grid is read as a single string on stdin like so: `./a.out 6 7 < input` where input is in this form (left to right, top to bottom):
>
> x..xxxxx..x--xx.xx--xx.ooo-.x.ooo-.xxxxxxx
>
>
>
**"Readable":**
```
#define F(W,X,Y,Z) for(i= W;i X Y;i Z)
#define C(A,B,C) if(c[A][B]==C)
#define S(W,X,Y,Z,A,B) p=1;F(W,X,Y,Z)C(A,B,120)p=0;if(p){F(W,X,Y,Z){C(A,B,46){c[A][B]='x';z++;Q();break;}}}else{F(W,X,Y,Z){C(A,B,120)break;else c[A][B]='o';}}
/*Example of an expanded "S" macro:
p=1;
for(i=x;i>m;i--) if(c[i][y]==120) p=0;
if(p)
{
for(i=x;i>m;i--)
{
if(c[i][y]==46)
{
c[i][y]='x';
z++;
Q();
break;
}
}
}
else
{
for(i= x;i > m;i --)
{
if(c[i][y]==120) break;
else c[i][y]='o';
}
}
*/
p,m,z,w,h,o,i,u,l,x,y;
char c[16][16];
Q(){
for(u=0;u<h;u++)
for(l=0;l<w;l++)
if(c[u][l]=='o')
{
x=u;y=l;
S(x,>,m,--,i,y)
S(y,>,m,--,x,i)
S(y,<,w,++,x,i)
S(x,<,h,++,i,y)
}
}
main(int a, char **v)
{
h=atoi(v[1]);
w=atoi(v[2]);
for(m=-1;o<h;o++)
for(i=0;i<w;i++)
scanf("%c",&c[o][i]);
P();
Q();
printf("%d\n",z);
P();
}
//Omitted in golfed version, prints the map.
P()
{
for(o=0;o<h;o++)
{
for (i=0;i<w;i++) printf("%c",c[o][i]);
printf("\n");
}
}
```
Nowhere near as short as the solution by @Claudiu, but it runs blazingly fast. Instead of flood filling from the edges, it finds the encampment and works outward from the 'o' tokens.
* If it encounters any unstable ground next to the encampment, it expands the encampment onto it.
* If any encampment on the grid doesn't have at least one wall in each direction, it moves in that direction until it can build a wall.
* After each new wall section is placed, it recurses to find the next wall section to place.
Sample wall placements:
```
x..xxxx x..xxxx
x..x--x x..xoox
x.xx--x x3xxoox
x.ooo-. <-- results in this --> xooooo1
x.ooo-. xooooo2
xxxxxxx xxxxxxx
```
[Answer]
# Python, ~~553~~ ~~525~~ ~~512~~ ~~449~~ ~~414~~ ~~404~~ ~~387~~ 368 characters (+4? for invocation)
I had way too much fun golfing this. It's 82 bytes bigger if you try to compress it! Now that's a measure of compactness and lack of repetition.
```
R=range;import itertools as I
f=map(str.split,open('city.txt'))[1:]
S=[]
def D(q):
q=set(q)
def C(*a):
r,c=a
try:p=(f[r][c],'x')[a in q]
except:p='x'
q.add(a)
if'.'==p:S[:0]=[a]
return p<'/'and C(r+1,c)|C(r-1,c)|C(r,c+1)|C(r,c-1)or'o'==p
if sum(C(j,0)|C(j,-1)|C(0,j)|C(-1,j)for j in R(16))<1:print n;B
D(S);Z=S[:]
for n in R(len(Z)):map(D,I.combinations(Z,n))
```
Indentation levels are space, tab.
**Usage**:
Reads from `city.txt`:
```
6 7
x . . x x x x
x . . x - - x
x . x x - - x
x . o o o - .
x . o o o - .
x x x x x x x
```
Invoke as follows:
```
$ python floodfill_golf.py 2>X
3
```
The `2>X` is to hide stderr since program exits by raising an exception. If this is considered unfair feel free to add 4 characters for the invocation.
**Explanation**:
Simple brute force. `C` does a flood-fill and returns true if it hit an encampment. No extra padding since it took too much space to set the padding up properly. `D`, given a set of walls to fill in, calls `C` from every point on the edge such that `C` accounts for those walls, and prints length and exits if none of them reached the encampment. The list of walls is also used to keep track of the flood-fill, so no copying of the board is required! Trickily, `C` also appends any empty spots it finds to a list, `S`, so the function `D` is *also* used to first construct the list of empty spots. For this reason, I use `sum` instead of `any`, to ensure all the `.`s are collected on the first run-through.
I invoke `D` once, then copy the list of empty spots into `Z` since `S` will keep being appended to (inefficient, but cheaper on character count). Then I use `itertools.combinations` to select each combo of empty spots, from 0 spots up. I run each combo through `D` and it prints the length of the first one that works, raising an exception to exit the program. If no answer is found then nothing is printed.
Note that currently, the program doesn't work if no walls are needed. It'd be +3 characters to take care of this case; not sure if it's necessary.
Also note that this is an `O(2^n)` algorithm, where `n` is the number of empty spots. So, for a 15x15 completely empty board with one encampment in the middle, this will take `2^(15*15-1)` = `2.6959947e+67` iterations to complete, which is going to be a very long time indeed!
[Answer]
## Groovy : 841 805 754
```
i=new File("city.txt").getText()
x=i[2] as int
y=i[0] as int
m=i[4..i.length()-1].replaceAll('\n','').toList()
print r(m,0)
def r(m,n){if(f(m))return n;c=2e9;g(m).each{p=r(it,n+1);if(p<c)c=p;};return c;}
def f(m){u=[];u.addAll(m);for(i in 0..(x*y)){for(l in 0..m.size()-1){n(l,u);s(l,u);e(l,u);w(l,u);}};m.count('o')==u.count('o')}
def n(i,m){q=i-x;if((((q>=0)&(m[q]=='!'))|(q<0))&m[i]!='x'&m[i]!='W'){m[i]='!'}}
def s(i,m){q=i+x;if((((q>=0)&(m[q]=='!'))|(q<0))&m[i]!='x'&m[i]!='W'){m[i]='!'}}
def e(i,m){q=i+1;if((((q%x!=0)&(m[q]=='!'))|(q%x==0))&m[i]!='x'&m[i]!='W'){m[i]='!'}}
def w(i,m){q=i-1;if((((i%x!=0)&(m[q]=='!'))|(i%x==0))&m[i]!='x'&m[i]!='W'){m[i]='!'}}
def g(m){v=[];m.eachWithIndex{t,i->if(t=='.'){n=[];n.addAll(m);n[i]='W';v<<n}};return v}
```
Ungolfed:
```
def i = new File("city.txt").getText()
x=i[2].toInteger()
y=i[0].toInteger()
def m=i[4..i.length()-1].replaceAll('\n','').toList()
println r(m, 0)
def r(m, n){
if(f(m)) return n
def c = Integer.MAX_VALUE
getAllMoves(m).each{ it ->
def r = r(it, n+1)
if(r < c) c = r
}
return c;
}
def f(m){
def t = []
t.addAll(m)
for(i in 0..(x*y)){
for(l in 0..m.size()-1){
n(l,t);s(l,t);e(l,t);w(l,t);
}
}
m.count('o')==t.count('o')
}
def n(i,m){
def t = i-x;
if( ( ( (t >= 0) && (m[t]=='!') ) || (t < 0)) && m[i]!='x' && m[i]!='W'){
m[i]='!'
}
}
def s(i,m){
def t = i+x;
if( ( ( (t >= 0) && (m[t]=='!') ) || (t < 0)) && m[i]!='x' && m[i]!='W'){
m[i]='!'
}
}
def e(i,m){
def t = i+1;
if( ( ( (t%x!=0) && (m[t]=='!') ) || (t%x==0)) && m[i]!='x' && m[i]!='W'){
m[i]='!'
}
}
def w(i,m){
def t = i-1;
if( ( ( (i%x!=0) && (m[t]=='!') ) || (i%x==0)) && m[i]!='x' && m[i]!='W'){
m[i]='!'
}
}
def getAllMoves(m){
def moves = []
m.eachWithIndex { t, i ->
if(t=='.'){
def newList = []
newList.addAll(m)
newList[i]='W'
moves << newList
}
}
return moves
}
```
Much more golfing to come...
Returns 2E9 if no solution.
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM), 91 [bytes](https://codegolf.meta.stackexchange.com/a/9429/43319)
`⊃∊{1∊a[⍸×{(×d)∧s 3∨/3∨⌿⍵}⍣≡4=d←0@⍵⊢a]:⍬⋄≢⍵}¨c[⍋≢¨c←(,⍳2⊣¨b)/¨⊂b←⍸2=a←(s←(4,4,⍨⍉)⍣2)'xo.'⍳⎕]`
assumes `⎕IO=0`, uses features from v16.0 (`@` and `⍸`), running time is exponential in the number of `.`-s
`⎕` is evaluated input, must be a matrix of characters
`'xo.'⍳` replace `x` with 0, `o` with 1, `.` with 2, and all others with 3
`s←(4,4,⍨⍉)⍣2` a function that surrounds a matrix with 4s
`a←` assign the numeric matrix surrounded with 4s to a variable `a`
`b←⍸2=` `b` is the list of coord pairs where the 2s (i.e. the `.`-s) are
`(,⍳2⊣¨b)/¨⊂b` generate all combinations of elements of `b`
`c[⍋≢¨c←...]` sort them by size
`{... :⍬⋄≢⍵}¨` for each combination, check something and return either its length or an empty list
`⊃∊` the first non-empty result
`d←0@⍵⊢a` `d` is `a` with some elements replaced with 0
`4=` create boolean matrix - where are the 4s? i.e. the border we added
`{...}⍣≡` keep on applying the function in `{}` until the result stabilizes
`3∨/3∨⌿⍵` "boolean or" each element with its neighbours
`s` the result will be smaller, so let's re-create the border
`(×d)∧` apply the non-zero elements of `d` (the non-walls) as a boolean mask
`a[⍸× ...]` what in `a` corresponds to the 1s in our boolean matrix?
`1∊` are there any 1s, i.e. `o`, encampments?
] |
[Question]
[
[](https://i.stack.imgur.com/PFi6b.png)
The above image displays a hexagonal grid of hexagons. Each cell in the grid is assigned an index, starting from the center and spiraling counterclockwise around as shown. **Note that the grid will continue indefinitely - the above picture is simply the first section. The next hexagon would be adjacent to 60 and 37.**
Your task is to determine if two given cells on this grid are adjacent.
Write a program or function that, given two cell indices, prints/returns a truthy value if the two cells are adjacent, and a falsey value if not.
If not limited by practical reasons, your code should theoretically work for any size inputs.
Truthy test cases:
```
0, 1
7, 18
8, 22
24, 45
40, 64
64, 65
```
Falsey test cases:
```
6, 57
29, 90
21, 38
38, 60
40, 63
41, 39
40, 40
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so the shortest answer in bytes wins. Explanations, even for non-esoteric languages, are encouraged.
[Answer]
# [Elixir](https://elixir-lang.org/), ~~263~~ ~~257~~ ~~264~~ ~~223~~ ~~214~~ ~~218~~ 214 bytes
```
a=fn x,y->i=&(&1*(&1-1)*3+1)
[x,y]=Enum.sort [x,y]
if x<1,do: y in 1..6,else: (y-x==1||fn->a=y-trunc i.((r=(:math.sqrt(12*x-3)+3)/6)+1)
t=trunc r
a in [0,1,rem(b=x-i.(t)+1, t)<1&&b-t*6!=0&&2]||b<2&&a==-1 end.())end
```
[Try it online!](https://tio.run/##ZVLLjpswFF3DV9xOJGRnrikmGfJQHKmLSjOrfkCUhQGnoQrQ8pBAhG9PL4lGituFbZ1zj8/145hL1mXVLTWnvEzbi4F30@mfZaEv39JfOjFF0kNaug4JINdZwTjBm1anAjrsxT5THvPknIaQfL54ldw9UOGovhdt7tdl1cAdu9kJup3EtNxCD1kB0vcjNJfabIH1olNKXq@nQuy16kVTtUUCmc9Ypdg2183Zr/9UDZPhvBML/rrgXyM@tWrUQ1q5evI8BCixMjmLVSdoe0MihIbvpOfFoplHX1TgeeHxeo13oedppYQEU6Q@45yWm@s4ia5NrQ7OMFmRuRmRWGdYoVw/4zWG4TMOl7h8eyaWAUbLZ4JQZCkifFvhSdMTfHpscBPYjMTF2mIIRrZmarSwGdq1sZgVhoF9G3K2Bfb1VhjZR5Wbf5su7WMEGCA8iOPnO8J1D/ccGJ2cGUVmoChgPILYw8cP/3fb1PDyUdBKIaASV2w2dCPOhn7kkNUwG7R/L4xQn8v2kkJMeZkN8fgy/Rt3HZrdabj/59Z/5PX2Fw "Elixir – Try It Online")
## ungolfed version
```
def get_ring(x) do
1/6*(:math.sqrt(12*x-3)+3)
end
def inv_get_ring(x), do: x*(x-1)*3+1
def ring_base(x), do: inv_get_ring(trunc(x))
def is_corner(x) do
ring = trunc(get_ring(x))
inv_ring = ring_base(ring)
stuff = (x-inv_ring+1)
rem(stuff, ring) == 0
end
def is_last(x),do: ring_base(get_ring(x)+1)-1 == x
def is_first(x),do: ring_base(get_ring(x)) == x
def hex_adj(x, y) do
{x, y} = {min(x,y), max(x,y)}
cond do
x == 0 ->y in 1..6
y-x==1 -> true
true ->
adj = trunc(inv_get_ring(get_ring(x)+1))
number = if is_corner(x)&&!is_last(x), do: 2, else: 1
if y-adj in 0..number do
true
else
is_first(x) && y == adj-1
end
end
end
```
* `trunc(number)` Returns the integer part of number
* `rem(a,b)` Returns the remainder of a/b
* `cond do end` This is equivalent to else if or switch case clauses in many imperative languages
## Explanation
### get\_ring(index)
Calculates the "ring" of the index.
Example: 1 for 1-6, 2 for 7-18, etc.
This only applies if the result is `floor`ed.
**Trailing digits represent how far that tile is around the ring.**
### inv\_get\_ring(ring)
Calculates the inverse of `get_ring(index)`.
### ring\_base(ring)
Calculates the index of the first tile in the ring.
### is\_corner(index)
Corners are tiles that have three adajcent tiles in the outer ring.
The innermost ring consists entirely of corners.
Examples: 21,24,27,30,33,36
### is\_last(index)
Is true if this index is the highest in its ring.
### is\_first(index)
Is true if this is the base-tile of the ring.
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~47~~ ~~45~~ ~~44~~ ~~43~~ 41 bytes
```
s:"JH3/^6:^t5)w5:&)@qY"w@Y"]vYs0hG)d|Yo1=
```
[**Try it online!**](https://tio.run/##y00syfn/v9hKycvDWD/OzCquxFSz3NRKTdOhMFKp3CFSKbYsstggw10zpSYy39D2//9oMxMdBTPTWAA) Or [**verify all test cases**](https://tio.run/##y00syfmfEOH9v9hKycvDWD/OzCquxFSz3NRKTdOhMFKp3CFSKbYsstggw1szpSYy39D2v0vI/2gDHQXDWK5ocyBlAaQtdBSMjIC0kYmOgokpkGECVGBmAmSYAUXMQCJmOgqm5iAlljoKlgYghqGOgjFIszFQt5kBTJMxiAGSsoSKmBjEAgA).
As a bonus, the code generates a hexagonal spiral that traces the positions of the cell centers, which can be seen graphically at [**MATL Online**](https://matl.suever.net/?code=s%3A%22JH3%2F%5E6%3A%5Et5%29w5%3A%26%29%40qY%22w%40Y%22%5DvYs0h1YSXG&inputs=8&version=20.2.2) by modifying the last part of the code.
### Explanation
**General idea**
The code first builds a sufficiently large hexagonal spiral with unit step. The spiral is defined as a vector of complex numbers representing positions of the cell centers. Indexing into that vector with the input numbers and computing the absolute difference gives the distance between the two indicated cells. Cells are adjacent if and only if the result is 1. However, due to floating point inaccuracies, rounding is necessary before comparing with 1.
**Building the spiral**
The spiral will have a number of "layers" equal to the sum of the two inputs. This is (much) larger than necessary, and ensures that the input cells will be present in the spiral.
To build the spiral, the complex number *j* 2/3 (where *j* is the imaginary unit) is first computed. Raising this to exponents 1 through 6 gives a basic set of displacements, such that following those displacements in order would trace a hexagon. This hexagon would form the innermost layer of the spiral, except that it would be "closed". Actually, we want that hexagon to "grow" at the last step and then we trace a larger hexagon, with twice as many points (aligned in groups of two), to form the next layer of the spiral; see illustration [here](https://matl.suever.net/?code=s%3A%22JH3%2F%5E6%3A%5Et5%29w5%3A%26%29%40qY%22w%40Y%22%5DvYs0h1YS%27.-%27%26XG&inputs=2&version=20.2.2). The next layer will have thrice as many points as the first (in groups of three); see [here](https://matl.suever.net/?code=s%3A%22JH3%2F%5E6%3A%5Et5%29w5%3A%26%29%40qY%22w%40Y%22%5DvYs0h1YS%27.-%27%26XG&inputs=3&version=20.2.2).
To do this, the fifth displacement from the basic set (which points in the south-east direction) is chosen as the "growing" step. Layer *k* begins with that step, followed by the first five basic steps repeated *k* times, followed by the sixth step (east direction) repeated *k*−1 times. This hopefully becomes clearer by looking at the two figures linked above.
The resulting vector, including all layers, represents the complex displacements that would trace the spiral. Cumulative sum gives the actual coordinates of the cell centers.
Lastly, the initial cell, located at 0, is attached *to the end* of this vector. This is because MATL uses modular 1-based indexing, and index 0 refers to that *last* entry of an array.
**Testing for adjacency**
The two cells given by the input numbers are selected, their coordinates are subtracted, and the absolute value is rounded and compared with 1.
**Commented code**
```
s % Implicitly input array of two numbers. Push their sum, say S
: % Range [1 2 ... S]
" % For each k in [1 2 ... S]
J % Push 1j
H3/ % Push 2, then 3, then divide: gives 2/3
^ % Power
6: % Push [1 2 ... 6]
^ % Element-wise power. This is the array of 6 basic displacements
t5) % Duplicate. Get 5th entry
w5:&) % Swap. Push subarray with entries 1st to 5th, then push 6th
@qY" % Repeat the 6th displacement k-1 times
w@Y" % Swap. Repeat 1st to 5th displacements k times
] % End
v % Concatenate everything into a column vector
Ys % Cumulative sum. This gives the cell center coordinates
0h % Append a 0
G) % Index by the input vector
d| % Absolute difference
Yo % Round to nearest integer
1= % Does it equal 1? Implicitly display
```
[Answer]
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), ~~30~~ ~~29~~ 27 bytes
```
α2‹i1q}1ݹ+v12y*3-tîÌy+}Ÿ²å
```
[Try it online!](https://tio.run/##ATQAy/8wNWFiMWX//86xMuKAuWkxcX0xw53CuSt2MTJ5KjMtdMOuw4x5K33FuMKyw6X//zQwCjY0)
## Explanation of code:
```
α2‹i1q} : if the absolute diff of the two number is 1 or 0 return 1
²å: return that the second number is in
Ÿ : range of {
1Ý : create [0, 1]
¹+ : add the first number to the elements
v } : map that list
12y*3-tîÌy+ : calculate the corresponding value where it's an adjacency
}
```
## Explanation of math:
I "wasted" around 5 hours making this golf.
In short I started making a 2d graph of the inputs, and draw `X` where they were adjacency to each other. Then I found a pattern. I searched for it on [OEIS](https://oeis.org) and bingo! I found [that sequence](https://oeis.org/A182618) and I used the formula given on the website.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~175~~ 173 bytes
Thanks to [Peter Taylor](https://codegolf.stackexchange.com/users/194/peter-taylor) for catching a bug.
Thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) for -2 bytes. That ~ operator continues to be my main blindspot.
```
c,r,C,L;y(a){a=a<L*2?L-a:a<L*3?-L:a<5*L?a-L*4:L;}z(a){L=ceil(sqrt(a/3.+.25)-.5);C=y(a-=3*L*~-L);L?L=y((L+a)%(L*6)):0;}f(a,b){z(a);c=C,r=L;z(b);a=a-b&&(abs(c-C)|abs(r-L))<2;}
```
[Try it online!](https://tio.run/##VY5Nb4JAFEXX8ismJJoZnLHKl8pIWJB09ZZduhlGpSRIW8AmaulPL30TaNpu4OTmvHtHi1zrvte85ikHeaWK3VWsduC4CQgVGfISAQiBA4kS4PgRyO5mRIj1sShp81a3VD14i/nCDZhYBEymMTaJ2HPA@RTAJCSACYW5YlMKTshYtJTdiSqesbvpkjpOeR2DvNGMSXyByGYzqrKGapGyDwM1FrGdK7v@/aU4kJwWVUsUJ@aXMetuTV5r5BO1p@6BE/yQiEwP@8rmRss4MXuoMml1lmXOzqqo6HB6aRtqP9WX9vka7SshhI3aJKdLTlYDrZE2A244cd0BXZ8TPxjYRzn0Bw4xD8c8xNxbG/4Z2lePqmyO/6dCToL12LrlZLsceYXX47CHy@Hyz5o3snG2v7lvnK7/0qdS5U0vyvM3 "C (gcc) – Try It Online")
This approach is focused on finding the row and the column of the two cells and compare them; any neighbours cannot have their corresponding coordinates differ by more than 1. Moving from the center outwards, we observe that each layer has 6 more cells than the previous. This means that the highest "index" in each layer L is on the form 6 \* (L \* (L - 1) \* (L - 2) ...), or C = 6 \* (L2 + L) / 2, where C is the "global" cell number. Shuffling things around, we get L2 + L - C / 3 = 0, which gives high-school math flashbacks. From that, we get the formula ceil (sqrt (1 / 4 + C / 3) + 0.5). Plugging a global cell index into it, we receive which layer the cell is in.
Since the first cell in each layer is naturally one higher than the highest of the previous layer, we find Lstart = (6 \* (L - 1)2 + (L - 1)) / 2, which simplifies to 3 \* (L2 - L). From that we get the layer index Lindex = C - Lstart.
Next up, we see that each layer is comprised of six sections, each of length L. Starting at north-east and going counter-clockwise, we see that for the first two sections (1 <= Lindex <= 2 \* L), we get the column from L - Lindex. The next section L \* 2 < Lindex <= L \* 3 have all cells sharing a single column -L. The two next sections are L \* 3 < Lindex <= L \* 5 with their columns according to Lindex - L \* 4. And lastly the sixth section all have its cells on column L. We can shift the upper bounds one step along to save some bytes in the code.
So then what about the rows? To reuse code, we turn the grid so that cell 44 is straight up. Then we run the same logic as for columns but call the results "rows" this time around. Of course, instead of actually turning a grid, we just walk 1 / 6 of a lap around it.
[Answer]
# Python 3, 150 bytes
```
def h(a,b):
L=[];i=1
while len(L)<a+b:r=sum((i*[1j**(k/3)]for k in range(4,16,2)),[]);r[0]+=1;L+=r;i+=1
return.9<abs(sum(L[min(a,b):max(a,b)]))<1.1
```
My solution basically follows the same line of thought as Luis Mendo's above. If written more readable, the code is pretty self-explanatory:
```
def h(a,b):
L=[]
i=1
while len(L)<a+b:
l=sum((i*[1j**(k/3)]for k in range(4,16,2)),[])
l[0]+=1
L+=l
i+=1
return .9<abs(sum(L[min(a,b):max(a,b)]))<1.1
```
1. function `h` does the following:
2. List L will contain the (complex) positions of each number.
3. `i` is the ring number.
4. In the while-loop, a new ring is added every iteration. Instead of figuring out how many rings we need, we just continue to build the list until it is long enough to contain a+b, then it is certainly long enough to contain either of them.
5. the 'ring-list' `l` is a concatenation of 6 lists of len(i) times the step-vector, where the step-vector is 1j\*\*(2/3) to some power. The range does not start at 0 but at 4, which causes a rotation of the whole grid. This allows me to do:
6. `l[0]+=1` in line 6, which is the step from one ring to the next.
7. `L+=l` concatenates the complete list and the ring-list.
8. List L contains only step vectors, which still must be summed (integrated) to get a position. A neat feature here is that we can just sum the slice *from the lowest number to the highest* to get their distance! Because of roundoff errors, the result won't be exactly 1, hence the .9<...<1.1. Interestingly, the zero case `h(0,0)` or h(0,1) is taken care of implicitly, because the sum of an empty list is zero.
If I could be sure that `a<b`, ie the arguments would come in increasing order, I could shave off another 14 bytes by replacing `L[min(a,b):max(a,b)]` with `L[a:b]`, but alas!
PS: I didn't know this was such an old challenge, it showed up on top a few days ago, and kept nagging on me since:)
[Answer]
# Mathematica, ~~111~~ ~~105~~ 104 bytes
```
r=Floor[(1+Sqrt[(4#-1)/3])/2]&;t=Limit[Pi(#/(3x)+1-x),x->r@#]&;p=r@#*Exp[I*t@#]&;Round@Abs[p@#-p@#2]==1&
```
## Explanation:
`r=Floor[(1+Sqrt[(4#-1)/3])/2]&` defines a function `r` which takes input `#` and calculates the distance (in number of cells) to cell 0. It does this by exploiting the pattern in the last cells of each distance/ring: 0=3(0^2+0), 6=3(1^2+1), 18=3(2^2+2), 36=3(3^2+3),... and inverting the formula for that pattern. Note that for cell 0, it actually takes the floor of (1/2)+*i* \*(sqrt(3)/6), which it calculates component-wise to get 0+0 \* *i* = 0.
With `r` defined, `r@#` is the ring for cell `#` (inside the definition of another function). `#+3r@#-3(r@#)^2&` does not appear in the code exactly, but it takes the number of a cell and subtracts the highest number of a cell in the next inner ring, so that it gives the answer to the question "which cell of the current ring is this?" For example, cell 9 is the 3rd cell of ring 2, so `r[9]` would output 2 and `#+3r@#-3(r@#)^2&[9]` would output 3.
What we can do with the function above is use it to find the [polar angle](https://en.wikipedia.org/wiki/Polar_coordinate_system#Conventions), the counter-clockwise angle from the "cell 0, cell 17, cell 58" ray to the cell in question. The last cell of every ring is always at an angle Pi/6, and we go around a ring in increments of Pi/(3\*ring\_number). So, in theory, we need to calculate something like Pi/6+(which\_cell\_of\_the\_current\_ring)\*Pi/(3\*ring\_number). However, the rotation of the picture doesn't affect anything, so we can discard the Pi/6 part (to save 6 bytes). Combining this with the previous formula and simplifying, we get `Pi(#/(3r@#)+1-r@#)&`
Unfortunately, this is undefined for cell 0 since its ring number is 0, so we need to get around this. A natural solution would be something like `t=If[#==0,0,Pi(#/(3r@#)+1-r@#)]&`. But since we don't care about the angle for cell 0 and because `r@#` is repeated, we can actually save a byte here with `t=Limit[Pi(#/(3x)+1-x),x->r@#]&`
Now that we have the ring number and the angle, we can to find the position of a cell (center) so we can test for adjacency. Finding the actual position is annoying because the rings are hexagonal, but we can simply pretend the rings are perfect circles so that we treat ring number as the distance to the center of cell 0. This won't be a problem since the approximation is pretty close. Using the [polar form of a complex number](https://en.wikipedia.org/wiki/Polar_coordinate_system#Complex_numbers), we can represent this approximate position in [the complex plane](https://en.wikipedia.org/wiki/Complex_plane) with a simple function: `p = r@#*Exp[I*t@#] &;`
The distance between two complex numbers on the complex plane is given by the [absolute value](https://en.wikipedia.org/wiki/Absolute_value#Complex_numbers) of their difference, and then we can round the result to take care of any errors from the approximation, and check if this is equal to 1. The function that finally does this work doesn't have a name, but is `Round@Abs[p@#-p@#2]==1&`.
---
You can **try it online** in the [Wolfram Cloud sandbox](https://sandbox.open.wolframcloud.com/) by pasting code like the following and clicking Gear->"Evaluate cell" or hitting Shift+Enter or the numpad Enter:
```
r=Floor[(1+Sqrt[(4#-1)/3])/2]&;t=Limit[Pi(#/(3x)+1-x),x->r@#]&;p=r@#*Exp[I*t@#]&;Round@Abs[p@#-p@#2]==1&[24,45]
```
Or for all test cases:
```
r=Floor[(1+Sqrt[(4#-1)/3])/2]&;t=Limit[Pi(#/(3x)+1-x),x->r@#]&;p=r@#*Exp[I*t@#]&;Round@Abs[p@#-p@#2]==1&//MapThread[#,Transpose[{{0,1},{7,18},{8,22},{24,45},{40,64},{64,65},{6,57},{29,90},{21,38},{38,60},{40,63},{41,39},{40,40}}]]&
```
] |
[Question]
[
You will be given a list of radii, you must output the area of the smallest rectangle which they will all fit in.
For example, given the list `[5,3,1.5]` you would output `157.460`.
This is the image:
[](https://i.stack.imgur.com/gWPlw.png)
The width is 15.7460 and the height is 10, so the area is 157.460
Rules:
* You get the list via stdin or function argument, output the answer via stdout or function return.
* The radii will have at most 2 decimal places.
* The list will have a length between 2 and 6.
* The output should be accurate to 3 decimal places or more.
* If you need, π = 3.1416.
Test cases:
* `[5,3,1.5] = 157.460`
* `[9,4,8,2] = 733.431` - [working here](https://i.stack.imgur.com/j9IwO.jpg).
* `[18,3,1] = 1296.000`
Shortest code in bytes wins.
[Answer]
# Python 2 + [PySCIPOpt](https://github.com/SCIP-Interfaces/PySCIPOpt), 267 bytes
```
from pyscipopt import*
R=input()
m=Model()
V,C=m.addVar,m.addCons
a,b,c=V(),V(),V()
m.setObjective(c)
C(a*b<=c)
P=[]
for r in R:
x,y=V(),V();C(r<=x);C(x<=a-r);C(r<=y);C(y<=b-r)
for u,v,s in P:C((x-u)**2+(y-v)**2>=(r+s)**2)
P+=(x,y,r),
m.optimize()
m.printBestSol()
```
### How it works
We write the problem as follows: minimize *c* over variables *a*, *b*, *c*, *x*1, *y*1, …, *x**n*, *y**n*, where
* *ab* ≤ *c*;
* *r**i* ≤ *x**i* ≤ *a* − *r**i* and *r**i* ≤ *y**i* ≤ *b* − *y**i*, for 1 ≤ *i* ≤ *n*;
* (*x**i* − *x**j*)2 + (*y**i* − *y**j*)2 ≥ (*r**i* + *r**j*)2, for 1 ≤ *j* < *i* ≤ *n*.
Obviously, we’re using an external optimization library on these constraints, but you can’t just feed them to any old optimizer—even Mathematica’s `NMinimize` gets stuck at local minima for these tiny test cases. If you stare closely at the constraints, you’ll see that they constitute a [quadratically-constrained quadratic program](https://en.wikipedia.org/wiki/Quadratically_constrained_quadratic_program), and finding the global optimum for a non-convex QCQP is NP-hard. So we need some incredibly high-powered magic. I chose the industrial-strength solver [SCIP](http://scip.zib.de/), which is the only global QCQP solver I could find with so much as a free license for academic use. Happily, it has some very nice Python bindings.
### Input and output
Pass the radius list on stdin, like `[5,3,1.5]`. The output shows `objective value:` rectangle area, `x1`, `x2` rectangle dimensions, `x3` rectangle area again, `x4`, `x5` first circle center coordinates, `x6`, `x7` second circle center coordinates, etc.
### Test cases
### `[5,3,1.5]` ↦ `157.459666673757`
[](https://i.stack.imgur.com/FiSxZ.png)
```
SCIP Status : problem is solved [optimal solution found]
Solving Time (sec) : 0.04
Solving Nodes : 187
Primal Bound : +1.57459666673757e+02 (9 solutions)
Dual Bound : +1.57459666673757e+02
Gap : 0.00 %
objective value: 157.459666673757
x1 10 (obj:0)
x2 15.7459666673757 (obj:0)
x3 157.459666673757 (obj:1)
x4 5 (obj:0)
x5 5 (obj:0)
x6 7 (obj:0)
x7 12.7459666673757 (obj:0)
x8 1.5 (obj:0)
x9 10.4972522849871 (obj:0)
```
### `[9,4,8,2]` ↦ `709.061485909243`
This is better than the OP’s solution. The exact dimensions are 18 by 29 + 6√3.
[](https://i.stack.imgur.com/GwoCy.png)
```
SCIP Status : problem is solved [optimal solution found]
Solving Time (sec) : 1.07
Solving Nodes : 4650
Primal Bound : +7.09061485909243e+02 (6 solutions)
Dual Bound : +7.09061485909243e+02
Gap : 0.00 %
objective value: 709.061485909243
x1 18 (obj:0)
x2 39.3923047727357 (obj:0)
x3 709.061485909243 (obj:1)
x4 9 (obj:0)
x5 30.3923047727357 (obj:0)
x6 14 (obj:0)
x7 18.3923048064677 (obj:0)
x8 8 (obj:0)
x9 8 (obj:0)
x10 2 (obj:0)
x11 19.6154311552252 (obj:0)
```
### `[18,3,1]` ↦ `1295.999999999`
[](https://i.stack.imgur.com/FkgO2.png)
```
SCIP Status : problem is solved [optimal solution found]
Solving Time (sec) : 0.00
Solving Nodes : 13
Primal Bound : +1.29599999999900e+03 (4 solutions)
Dual Bound : +1.29599999999900e+03
Gap : 0.00 %
objective value: 1295.999999999
x1 35.9999999999722 (obj:0)
x2 36 (obj:0)
x3 1295.999999999 (obj:1)
x4 17.9999999999722 (obj:0)
x5 18 (obj:0)
x6 32.8552571627738 (obj:0)
x7 3 (obj:0)
x8 1 (obj:0)
x9 1 (obj:0)
```
### Bonus cases
### `[1,2,3,4,5]` ↦ `230.244214912998`
[](https://i.stack.imgur.com/hoetL.png)
```
SCIP Status : problem is solved [optimal solution found]
Solving Time (sec) : 401.31
Solving Nodes : 1400341
Primal Bound : +2.30244214912998e+02 (16 solutions)
Dual Bound : +2.30244214912998e+02
Gap : 0.00 %
objective value: 230.244214912998
x1 13.9282031800476 (obj:0)
x2 16.530790960676 (obj:0)
x3 230.244214912998 (obj:1)
x4 1 (obj:0)
x5 9.60188492354373 (obj:0)
x6 11.757778088743 (obj:0)
x7 3.17450418828415 (obj:0)
x8 3 (obj:0)
x9 13.530790960676 (obj:0)
x10 9.92820318004764 (obj:0)
x11 12.530790960676 (obj:0)
x12 5 (obj:0)
x13 5 (obj:0)
```
### `[3,4,5,6,7]` ↦ `553.918025310597`
[](https://i.stack.imgur.com/9J9uB.png)
```
SCIP Status : problem is solved [optimal solution found]
Solving Time (sec) : 90.28
Solving Nodes : 248281
Primal Bound : +5.53918025310597e+02 (18 solutions)
Dual Bound : +5.53918025310597e+02
Gap : 0.00 %
objective value: 553.918025310597
x1 21.9544511351279 (obj:0)
x2 25.2303290086403 (obj:0)
x3 553.918025310597 (obj:1)
x4 3 (obj:0)
x5 14.4852813557912 (obj:0)
x6 4.87198593295855 (obj:0)
x7 21.2303290086403 (obj:0)
x8 16.9544511351279 (obj:0)
x9 5 (obj:0)
x10 6 (obj:0)
x11 6 (obj:0)
x12 14.9544511351279 (obj:0)
x13 16.8321595389753 (obj:0)
```
### `[3,4,5,6,7,8]` ↦ `777.87455544487`
[](https://i.stack.imgur.com/gEQpR.png)
```
SCIP Status : problem is solved [optimal solution found]
Solving Time (sec) : 218.29
Solving Nodes : 551316
Primal Bound : +7.77874555444870e+02 (29 solutions)
Dual Bound : +7.77874555444870e+02
Gap : 0.00 %
objective value: 777.87455544487
x1 29.9626413867546 (obj:0)
x2 25.9614813640722 (obj:0)
x3 777.87455544487 (obj:1)
x4 13.7325948669477 (obj:0)
x5 15.3563780595534 (obj:0)
x6 16.0504838821134 (obj:0)
x7 21.9614813640722 (obj:0)
x8 24.9626413867546 (obj:0)
x9 20.7071098175984 (obj:0)
x10 6 (obj:0)
x11 19.9614813640722 (obj:0)
x12 7 (obj:0)
x13 7 (obj:0)
x14 21.9626413867546 (obj:0)
x15 8.05799919177801 (obj:0)
```
] |
[Question]
[
Suppose one day you are digging through your big box of unused computer cords and adapters (USB to USB mini, VGA to DVI, etc.). There are tangled cords everywhere making quite a mess, and you wonder if you could simplify things by attaching all the cords together in one long strand, and then just rolling it up.
The question is, is it possible to connect all of your cords and adapters in one long line like this? It's obviously not always possible, e.g. if you only had two cords with completely different plugs, they could not be connected together. But if you had a third cord that can connect to both of them, then you could string all your cords together.
You don't care about what type of plugs are on the ends of the all-cord strand. They don't need to plug into one another to form a loop. You only want to know if making the all-cord strand is possible, and if it is, how to do it.
# Challenge
Write a program or function that takes in a multiline string where every line depicts one of the cords you own. A cord is made up of one or more dashes (`-`), with a plug on either end. A plug is always one of the 8 characters `()[]{}<>`.
So these are some valid cords:
```
>->
(--[
}-{
<-----]
(---)
```
But these are not:
```
-->
(--
)--
[{
---
```
When connecting cords, only plugs with the exact same bracket type can be connected together.
So these are some valid cord connections:
```
...---((---...
...---))---...
...---]]---...
...---{{---...
...---<<---...
```
And these are invalid:
```
...---()---...
...---)(---...
...---{]---...
...---{[---...
...---><---...
...--->)---...
```
If all the cords in the input can be rearranged and attached together in one long strand, then output that strand to stdout on one line (with an optional trailing newline). When there are multiple solutions you can choose any one of them to output. If making a single strand is not possible, then output nothing (or output an empty string with an optional trailing newline).
---
For example, if the input is
```
[-->
{---]
>----{
```
the output could be
```
[-->>----{{---]
```
where all the cords are strung together.
However if the input were
```
[-->
{---]
```
the cords cannot be connected so there would be no output.
---
Note that cords can be flipped around as much necessary to make connections. e.g. `[-->` and `<--]` are effectively the same cord because they can make the same type of connections. Some outputs may depend on flipping the input cords.
---
For example
```
(-[
}--]
```
could have output
```
(-[[--{
```
where the second cord is flipped, or
```
}--]]-)
```
where the first cord is flipped.
(Note that in general flipping the entire output is valid because it's the same as initially flipping every cord individually.)
---
The lengths of the cords in the output should of course match the lengths of the corresponding input cords. But the cords may be reordered and flipped around as much as you want in order to make the all-cord strand. The input will always contain at least one cord.
**The shortest code in bytes wins.**
# Test Cases
Cases with output:
```
[-->
{---]
>----{
gives
[-->>----{{---]
or
[---}}----<<--]
(-[
}--]
gives
(-[[--{
or
}--]]-)
(-)
gives
(-)
[--{
gives
[--{
or
}--]
[-]
]-[
gives
[-]]-[
or
]-[[-]
[----->
)------------[
{--<
}---)
could give
[----->>--}}---))------------[
or
>--}}---))------------[[----->
or
}---))------------[[----->>--}
or
{--<<-----]]------------((---{
etc.
>-->
>->
>--->
could give
>-->>->>--->
or
>--->>-->>->
or
>->>-->>--->
or
<--<<---<<-<
etc.
(-]
]->
>-}
}-)
)-[
[-<
<-{
{-(
could give
(-]]->>-}}-))-[[-<<-{{-(
or
{-((-]]->>-}}-))-[[-<<-{
or
<-{{-((-]]->>-}}-))-[[->
etc.
```
Cases without output:
```
[-->
{---]
[-]
[-]
(-]
]->
}-)
>->
>-->
]---]
[-------------------]
]-------------------[
[-----------------]
[-----------------]
{--[
]--}
```
[Answer]
# [Unreadable](https://esolangs.org/wiki/Unreadable), 3924 bytes
This is the first time I implemented somewhat of a call-stack-like structure in Unreadable.
(The first version of this was over 5300 bytes, just to give an idea of how much I golfed this.)
>
> '"""""'""'""""""'""""""'"""'""'""'""'""'""'""'"""""""'"""'""""""'""'"""'""""""""""'""""'""""'""""'""""""'""'""'""'""'""'""'"""""""'"""'"""""'"""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""'""'""'"""""""'"""'""""""""""'""""""""'"""'"""'""""'""""""'""'""'""'""'"""'"""""""'""'""'"""""""'"""'""""""'""'"""""""'"""'""'"""""""'""'"""""""'"""'"""""'""""""'""'"""'"""""""'"""""""'"""'""""'""""""'""'""'""'"""""""'"""'"""""""""'""""""'""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'""'"""'"""""""""'""""""'""'"""'""""""""'"""""""'""'"""'"""""""""'""""""'""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'""'"""'"""""""""'""""""'""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'""'"""'"""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'""'"""'""""""""'""""""""'"""""""'"""""""'"""'""'""'"""""""'"""""""'"""'""'""'"""""""'"""""""'"""'""'""'"""""""'"""""""'"""'""""""""'"""""""'"""""""'"""'""'"""""""'"""""""'"""'""""""'"""'""'""'"""""""'"""'""""""'""'""'""'"""""""'"""'"""""""'""""""""'"""""""'"""'""""""""""'""""""'"""""""'"""'""""""""'""""""'""'""'""'"""'""""""'""""""'""'"""'""'"""""""'"""'"""'"""""'"""""""'""'""'""'"""'""""'""""'""""""'""'""'"""'""""""'"""'"""'"""""'"""""""'""""""'"""'""'""'""'""'""'"""""""'"""'"""""""""'"""""""'""'""'""'""'"""""""'"""'"""'""""""'""'""'"""'""""""""'"""'"""""""""'"""""""'""'""'"""'""""""'""'""'""'"""'""""""""'"""'""""'""""'""""""'"""'"""""""'"""""""'""'"""'"""""'"""""""'""""""'"""'""'""'""'""'""'"""""""'"""'"""""""""'"""""""'""'""'""'""'"""""""'"""'"""'"""""""""'"""""""""'"""""""'""""""""'"""""""'""'"""'""""'""""'""""""'""""""""'"""'"""""""'""'""'"""""""'""""""""'"""""""'""'"""'""""""'""'""'"""'""'"""""""'"""""""'"""'"""""""""'"""""'""""""'""'""'"""'""""""""'"""""""'""'""'"""'""""""'""""""""'"""'""""""""'"""""""'""""""""'"""'""""""""'"""'"""'"""'""""""'"""'""""""""'""""""'""'""'"""'""""""'"""""""'""'"""'"""""""'"""'"""'"""""""""'"""""""'""'""'"""'""""""'""""""'""'"""'""'"""""""'""'"""'""""""'"""""""'"""'""""""'"""""""""'"""""""'""""""""'"""""""'"""'""'""'""'""'""'"""""""'"""'""""""""'""""""""'""""""""'""""""""'""""""""'"""""""'"""'"""'"""""""""'""""""'"""'"""""""'""""""'""'"""'""""""""'"""""""'""'"""'""""""'""'""'""'""'"""""""'"""'""""""'"""""""""'"""""""'""'""'""'"""""""'"""'""'""'""'""'""'""'""'""'""'"""""""'"""'""""""""'"""""""'"""'""""""""'"""'""""""'""'""'""'"""'""""""""'"""'"""""""""'"""""""'"""'"""""'""""""""'"""""""'""""""'"""'""'"""""""'"""'""""'""""'"'"""""""'"""""""'"""""""'"""'"""""'""'""""""'""'"""""""'"""""""'"""'""""""""'"""""""'""'"""""""'"""""""'"""'"'"""""""'""'""'""'""'"""'"'"""""""'""'""'"""""""'"""""""'"""'"""
>
>
>
## Explanation
Consider this example input:
```
>--{
[---}
```
Throughout most of the execution, the tape is laid out as follows:
* Cells 0 to 5 are locations for various variables.
* Cell 6 onwards contain all information about the set of cables in your box:
[](https://i.stack.imgur.com/jNkmm.png)
* The remaining cells after the “zero terminator” contain the stack. Each “stackframe” is a single cell that points to the first cell of a cable (the “start plug” cell). In the above example, when the program decides it has found a solution, the stack will contain 6 (referring to `>--{`, the first cable) and 21 (referring to `{---]`, the mirror of the second cable).
The program proceeds in three main stages:
1. Read the entire input and generate the above structure, including all the mirrored cables.
2. Try out all combinations (but stop if a solution is found).
3. If a solution was found, output it.
The first stage (read input and generate cables structure) only uses cells #1 (which I’ll call `p`) and #2 (which I’ll call `ch`) and operates in a while loop as follows:
* While condition: increment `p` by 6, read the next character (start plug) into cell `*p`, and check that it isn’t `-1` (EOF).
* Read subsequent characters into `*(p+2)`, and count them in `*(p+1)`, until we encounter anything other than `-` (hyphen). At that point, `*(p+1)` will contain the number of hyphens (cable length) and `*(p+2)` the last non-hyphen character (the end plug). (We also copy the hyphen characters to cell #5 so we can access this ASCII code later in the output stage.)
* In a while loop, find the mirror plug and store it at `*(p+3)`, then increment `p` by 2, until `*p` is zero. The loop looks like this in pseudocode:
```
while (ch = *p) {
*(p+3) = (ch -= 40) ? (ch -= 1) ? (ch -= 19) ? (ch -= 31) ? ch-32 ? *p-2 : *p+2 : *p+2 : *p+2 : *p-1 : *p+1
p += 2
}
```
* This loop will always perform two iterations (the start plug and end plug) and store the results in the fourth and sixth cell of this cable. Now, if you paid attention, you realize that the sixth cell is indeed the correct location for the mirrored end plug, but the mirrored start plug is in the cell labeled “boolean indicating original cable”. This is OK because we only need this cell to be a non-zero value.
* Since `p` has just been incremented a total of 4, it’s now pointing at the cell labeled “boolean indicating cable is in use”. Set `*(p+3)` to the value of `*(p-1)`. This puts the mirrored start plug in the right place.
* Read (and discard) one more character (which we expect to be a newline, but the program doesn’t check for that).
`p` initially starts out at 0 but is incremented by 6 inside the while condition, thus the cable data starts at cell #6. `p` is incremented by 4 inside the loop body, and thus a total of 10 for each cable, which is exactly what we need.
During the second stage, cells #0–4 are occupied by variables that I’ll call `a`, `p`, `q`, `m`, and `notdone`. (Cell #5 still remembers the ASCII code of the hyphen.)
To get ready for stage 2, we need to set `*p` back to 0 (the cell labeled “zero terminator”) so that it can act as the terminator for the list of cables; we also set `q` (which is our stack pointer) to `p+1` (i.e. the cell after the “zero terminator”; this is where the stack starts); `*q` to 1 (the first item on the stack; why 1 will become apparent later); and `notdone` to 1. All this is done in a single statement:
```
*p = (notdone = *(q = p+1) = 1)-1
```
The second stage is also a while loop. Its condition is simply `notdone`. In each iteration of that while loop, any one of the following four things could happen:
1. We find that all cables are marked “in use”. This means we’ve found a solution (which is represented by the current stack contents).
2. We can advance `*q` to another eligible cable (which we promptly mark as “in use” along with its twin) and then recurse (i.e. create a new stackframe).
3. We cannot advance `*q` because no further eligible cable exists, so we need to backtrack (remove a stackframe and mark the previous cable and its twin as no longer “in use”).
4. We cannot advance `*q` because no further eligible cable exists and we cannot backtrack because we have reached the bottom of the stack. This means there is no solution.
The loop body checks for each of these four conditions in this order. Here are the details:
1. Set `m` and `p` to 1 and in a while loop, increment `p` by 5 (thus iterating through the cables) and check if `*(p+4)` (“in use”) is set. If it isn’t, set `m` to 0. At the end of that loop, `m` tells us if all the cables are in use. If so, set `notdone` to 0 to terminate the main loop. Otherwise, continue at step 2 below.
2. Set `p` to `*q` (the cable at the top of the stack) and in a while loop similar to the above, increment `p` by 5 to iterate through the cables. Starting at `*q` ensures we only consider those that we haven’t already considered before; however, remember that the initial value for a new stackframe is 1, so the first cable looked at is the one at cell 6, which is indeed the first cable.
For each cable, we need to check `*(p+4)` to ensure that it’s not already in use, and also that *either* `*(q-1)` is zero (meaning we’re at the bottom of the stack, so there’s no constraint on the start plug), *or* `*p` (the cable’s start plug) is equal to `*(*(q-1)+2)` (the end plug of the cable just below on the stack). We check for equality by setting `a` to `*(*(q-1)+2)` and `m` to `*p+1` and then decrementing both in a while loop. The `+1` is because `m` is decremented inside the while condition, so it is decremented once more than `a`. If `a` is zero at the end of this, the two plugs are equal.
Thus, if either `*(q-1)` was zero or the equality comparison succeeded, the cable is eligible. Set `*q` to `p` to replace the cable at the top of the stack with the new one; set `m` to the same to indicate that we found a matching cable; and then decrement `p`. That decrement is a little trick to cause the while loop (iterating through the cables) to terminate early; it will increment `p` by 5 again, thus taking it to the cell containing this cable’s “in use” flag, and we know that’s zero because we just checked that.
Finally, after the cable-iterating while loop, we check if `m` is non-zero. If so, we found a matching cable and `p` is pointing at the “in-use” flag for that matching cable. Set it to 1 to mark it as in use. Also set `*(*(p-1) ? p+5 : p-5)` to 1 to mark its twin as in use. Finally, increment `q` and set the new `*q` to 1 to create a new stackframe.
3. If, after the cable-iterating while loop, we find `m` to be zero, there are no more matching cables, so we need to backtrack. Decrement `q` to move down the stack and check if it’s still pointing at a cable (a non-zero value). If so, mark that cable and its twin as no longer in use. (We store the value of `*q` in `p` to make this expression shorter in code.)
4. If, after decrementing `q`, we find that it points at a zero value, then that is the “zero terminator”, which means we’ve underrun the stack. We conclude that there is no solution. We set `notdone` to 0 to terminate the main loop.
The third stage is the output stage. There are two things that can happen:
* the main loop found a solution that we need to output, or
* the main loop concluded there is no solution and we output nothing.
Conveniently, if there was *no* solution, `p` is zero because we set it to the value of `*q` before checking that for zero; and if there *was* a solution, `p` is pointing at the “zero terminator” because it just iterated through the cables, so we can now use `p` to iterate through the stack. So just iterate through the stack, outputting for each cable the start plug (`*(*p)`), the hyphens (by decrementing `*(*p+1)` in a while loop; and using the hyphen ASCII code stored in cell #5), and the end plug (`*(*p+2)`). Never mind that this destroys the cable-length information; we don’t need that anymore.
[Answer]
# CJam, 67
```
qN%e!{_,2,m*\f{.{_{"()[]{}<>--"_@#1^=}%W%?}_2ew{~\W=#}%0-{;}&}~}%1<
```
[Try it online](http://cjam.tryitonline.net/#code=cU4lZSF7XywyLG0qXGZ7LntfeyIoKVtde308Pi0tIl9AIzFePX0lVyU_fV8yZXd7flxXPSN9JTAtezt9Jn1-fSUxPA&input=PC0tXQp7LS0tXQo-LS0tLXs)
Note: the link is using the latest code from the repository (pushed but not yet released), as it contains a bug fix.
**Explanation:**
The program simply tries all permutations and all orientations of the cords.
```
qN% read the input and split into lines
e! generate all permutations
{…}% map each permutation of cords
_, get the number of cords (n)
2,m* generate all patterns of n bits (cartesian power of [0 1])
\f{…} for each bit pattern and the cord permutation
.{…} apply the block to each bit and cord (flipping cords for bit 0)
_ duplicate the cord
{…}% map each character of the cord
"…"_ push the string of all the plugs (and 2 dashes) and duplicate it
@# get the index of the character in the string
1^ XOR with 1
= get the character at this new index (plugs get toggled)
W% reverse the cord
the stack now has the bit, the original cord and the flipped cord
? if the bit is 1, use the original cord, else use the flipped one
_ duplicate the array of cords
2ew get all pairs of adjacent cords
{…}% map each pair of cords
~\ dump the 2 cords on the stack and swap them
W= get the right plug of the first cord
# find its position in the second cord (if 0, we have a match)
0- remove all the zeros
{…}& if the array is not empty (i.e. we have a mismatch)
; pop the array of cords
~ dump all the results for this permutation on the stack
(to avoid nested arrays)
1< get the first result (if any) from the array of all results
```
[Answer]
# JavaScript (ES6), 206
Recursive function
```
f=(l,a=l.pop(),x=x=>(z='<>[]{}()')[z.indexOf(x)^1])=>l[0]?l.some((b,i)=>r=[b,x([...b].pop())+b.slice(1,-1)+x(b[0])] .some(b=>r=a[0]==[...b].pop()?b+a:b[0]==[...a].pop()?a+b:0)&&(l=[...l],l[i]=r,f(l)))?r:'':a
```
*More readable*
```
f=(l,a=l.pop(),x=x=>(z='<>[]{}()')[z.indexOf(x)^1])=>
l[0]?
l.some((b,i)=>
r=[b,x([...b].pop())+b.slice(1,-1)+x(b[0])]
.some(b=>r=a[0]==[...b].pop()?b+a:b[0]==[...a].pop()?a+b:0)
&&(l=[...l],l[i]=r,f(l))
)?r:''
:a
```
**Test**
```
f=(l,a=l.pop(),x=x=>(z='<>[]{}()')[z.indexOf(x)^1])=>l[0]?l.some((b,i)=>r=[b,x([...b].pop())+b.slice(1,-1)+x(b[0])] .some(b=>r=a[0]==[...b].pop()?b+a:b[0]==[...a].pop()?a+b:0)&&(l=[...l],l[i]=r,f(l)))?r:'':a
console.log=(...x)=>O.textContent+=x+'\n'
;[
//OK
['[-->','{---]','>----{']
,['(-[','}--]']
,['(-)']
,['[--{']
,['[-]',']-[']
,['[----->',')------------[','{--<','}---)']
,['>-->','>->','>--->']
,['(-]',']->','>-}','}-)',')-[','[-<','<-{','{-(']
//KO
,['[-->','{---]']
,['[-]','[-]']
,['(-]',']->','}-)']
,['>->','>-->',']---]']
,['[-------]',']-------[','[-------]','[---------]'] // shortened a little,
,['{--[',']--}']
].forEach(t=>{
console.log(t+' : "'+f(t)+'"\n')
})
```
```
<pre id=O></pre>
```
[Answer]
# Javascript, 800 Bytes
Far from an optimized solution, but here's a quick hack together in javascript (no fancy ecma5 or anything, because I don't know it).
```
function a(r){function t(r,t){var n=r.slice();return n.splice(t,1),n}function n(r){var t,n={"[":"]","]":"[",">":"<","<":">","(":")",")":"(","{":"}","}":"{"},e=r.split("").reverse();for(t=0;t<e.length;t++)n.hasOwnProperty(e[t])&&(e[t]=n[e[t]]);return e.join("")}function e(r,t){return r.unshift(t),r}var h,u,f=[];if(1==r.length)return r[0];for(h=0;h<r.length;h++){var l=r[h],i=t(r,h),c=l.charAt(0),g=l.charAt(l.length-1);for(u=0;u<i.length;u++){var o=i[u],s=o.charAt(0),p=o.charAt(o.length-1);c==p&&f.push(e(t(i,u),o+l)),g==s&&f.push(e(t(i,u),l+o)),o=n(o),s=o.charAt(0),p=o.charAt(o.length-1),c==p&&f.push(e(t(i,u),o+l)),g==s&&f.push(e(t(i,u),l+o))}}if(f.length<1)return!1;for(h=0;h<f.length;h++){if(1===f[h].length)return f[h][0];f[h]=a(f[h])}for(h=0;h<f.length;h++)if(f[h]!==!1)return f[h];return!1}
```
Ungolfed, here it is... I'm sure at least 2 for loops are unnecessary here and that checking for a single element input at the top and a single element match at the bottom is stanky... but it seems to work and processes the test inputs.
```
function a(inputs)
{
var i, ii, matches = [];
if (inputs.length == 1) {
return inputs[0];
}
// For each of the elements in inputs (e1)
for (i = 0; i < inputs.length; i++) {
var e1 = inputs[i],
others = except(inputs,i),
e1s = e1.charAt(0),
e1e = e1.charAt(e1.length-1);
// Compare to each of the other elements in inputs (e2)
for (ii = 0; ii < others.length; ii++) {
// get the start and end of the elements to compare (e1s,e1e,e2s,e2e)
var e2 = others[ii],
e2s = e2.charAt(0),
e2e = e2.charAt(e2.length-1);
// if any of them match up (e1s == e2e || e1s == e2s || e1e == e2s || e1e = e2e)
// Make a new array of inputs containing the joined elements (as a single element) and all other elements which might join with them
if (e1s == e2e) {
matches.push(addTo(except(others,ii),e2+e1));
}
if (e1e == e2s) {
matches.push(addTo(except(others,ii),e1+e2));
}
e2 = flip(e2);
e2s = e2.charAt(0);
e2e = e2.charAt(e2.length-1);
if (e1s == e2e) {
matches.push(addTo(except(others,ii),e2+e1));
}
if (e1e == e2s) {
matches.push(addTo(except(others,ii),e1+e2));
}
}
}
if (matches.length < 1) {
return false;
}
for (i = 0; i < matches.length; i++) {
if (matches[i].length === 1) {
return matches[i][0];
} else {
matches[i] = a(matches[i]);
}
};
for (i = 0; i < matches.length; i++) {
if (matches[i] !== false) {
return matches[i];
}
};
return false;
function except(list,idx)
{
var newList = list.slice();
newList.splice(idx,1);
return newList;
}
function flip(s) {
var replacements = {
'[':']',
']':'[',
'>':'<',
'<':'>',
'(':')',
')':'(',
'{':'}',
'}':'{'
}, i, a = s.split('').reverse();
for (i = 0; i < a.length; i++) {
if (replacements.hasOwnProperty(a[i])) {
a[i] = replacements[a[i]];
}
}
return a.join('');
}
function addTo(arr,newEl)
{
arr.unshift(newEl);
return arr;
}
}
```
[Answer]
# Python 3, 217 bytes
```
from itertools import*
a='()[]{}<>'
all(any(c[-1]!=d[0]for c,d in zip(q,q[1:]))or print(''.join(q))for p in permutations(open(0))for q in product(*[(c[:-1],a[a.find(c[-2])^1]+c[-3:0:-1]+a[a.find(c[0])^1])for c in p]))
```
([Demo on Ideone](http://ideone.com/d8s8Uy))
[Answer]
# Lua, 477 bytes
```
function r(s)return s:reverse():gsub("[()%[%]{}<>]",{["("]=")",[")"]="(",["["]="]",["]"]="[",["{"]="}",["}"]="{",["<"]=">",[">"]="<"})end
function a(c,b)for i, v in next,b do
m=c:sub(-1,-1)n=v:sub(1,1)o=r(c):sub(-1,-1)p=r(v):sub(1,1)l=table.remove(b,i)if m==n then
return a(c..v,b)elseif o==n then
return a(r(c)..v,b)elseif m==p then
return a(c..r(v),b)elseif o==p then
return a(r(c)..r(v),b)end
table.insert(b,i,l)end
return#b>0 and""or c
end
print(a(table.remove(arg,1),arg))
```
Accepts cords as command line arguments
[Answer]
# Python 3.5, 448 432 427 424 286 311 bytes:
(*+25 since there was a bug where the output may be longer than it should be for some inputs*)
```
def g3(z):
B=z.split();M='i[::-1].translate({41:40,40:41,125:123,123:125,62:60,60:62,93:91,91:93})';f=B+[eval(M)for i in B if eval(M)not in B];d=[f.pop(0)]
for h in d:
try:[d.append([f.pop(f.index(c))for c in f if h[-1]==c[0]][0])if len(d)<len(B)else E]
except:break
return''.join(d)if len(d)>=len(B)else''
```
Works perfectly! *except* for inputs with 7 or more values. It takes a **long** time for those, most likely because it must go through all those permutations of the input plus the input *reversed*. I will try to fix this if and when I can, but for now, this seems to be good enough. All is good now! If *only* I could somehow use that `try-except` block in list comprehension, it could be a little shorter, and look **much** nicer. Nonetheless, it now works for **all** the test cases, and, best of all, it uses *no* imports! :)
[Try it online! (Ideone)](http://ideone.com/cOCee4) (284 bytes here)
(Tip: To try it, just select "fork", and then input your choices, *space-separated*, and select "run")
# Explanation
Basically, what's happening is...
1. A list, `B`, is created from the input by splitting it at the whitespace into its component "cords".
2. `M` is a string I created which, when evaluated, returns a list based on `B` which contains all the cords, but this time *backwards*.
3. The list created from `M` is ultimately concatenated with `B` itself to create a list, `f`, with all possible orientations of the "cords".
4. Another list, `d` is created, which will be initialized with the first value (value `f[0]`) of `f`.
5. Finally, all the values in `d` are iterated through, and each value's last character is compared with the first character of each element in `f`, and when a match is found, that character is popped (or removed) and returned from list `f`. This happens until a `IndexError` is raised, or the length of list `d` exceeds `B` and a `NameError` is raised after the call to `E`,both of which are handled, and then list `d`'s contents are joined into a string and returned as long as the length of list `d` is more than or equal to the length of list `B`. Otherwise, an empty string is returned (`''`), since `d` not being the same length as `B` signifies that all the "cords" in list `B` cannot be joined into one long "cord".
] |
[Question]
[
Let's define a simple 2D language, which we'll give the incredibly original name *befinge*. Befinge has 5 instructions:
* `<>^v`, as in most 2D esolangs, redirect the instruction pointer in their respective directions.
* `.` is a no-op.
The instruction pointer starts out at the top-left corner going right. If the instruction pointer gets to an edge, the program halts. Every Befinge program will obviously either halt or go into an infinite loop which does nothing. Here are two examples:
Halting:
```
>.v
..<
```
Non-Halting:
```
>....v
..v..<
..>v..
^..<..
```
The halting problem is not solvable for a Turing-complete language, but it is for this one. Your task is to write a program (or function) that takes as input a string representing the *befinge* program and returns a truthy or falsey value depending on whether it halts or not.
* You can assume that the input will consist only of these characters and will be padded with spaces to form a rectangle.
* You can use any set of five characters for the instructions (e.g. `adws` ).
## Test Cases
### Halting:
```
.
```
```
v>
>^
```
```
....v....
....>...v
.^..<....
.......v<
.......v.
....^..<.
```
```
v<>v>v^
>v^>^>v
<>>^v<v
v^<>v^<
```
### Non-Halting:
```
>..v
^..<
```
```
>v<
v<.
>v.
v<.
>.^
```
```
>.>.>.v
.><.<.<
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest program (in bytes) wins.
[Answer]
# ES6 (JavaScript), ~~111~~,101 bytes
*EDIT:* changed output values to *true* and *false*, instead of *Y* and *N*, to shave off 10 bytes more
**Golfed**
```
F=(I,M=[...I],c=0,i)=>(i={j:v=I.search`\n`+1,k:-v,h:-1,l:1,q:i,0:0}[M[c]])?F(I,M,c+i+(M[c]=0),i):i!=0
```
**Test**
```
F=(I,M=[...I],c=0,i)=>(i={j:v=I.search`\n`+1,k:-v,h:-1,l:1,q:i,0:0}[M[c]])?F(I,M,c+i+(M[c]=0),i):i!=0
//Alphabet Map
tr={
'<':'h',
'>':'l',
'^':'k',
'v':'j',
'.':'q',
'\n':'\n'
};
//Test
T=(I,A)=>{
console.log({"Y":"#Halting","N":"#Non-Halting"}[A]);
console.log("I=\n",I,"\nF(I)=",O=F([...I].map(s=>tr[s]).join('')));
console.log('NY'[O*1] == A ? "OK !" : "NOT OK !");
}
//Halting
T(
`>.v
..<`
,'Y');
//Non-Halting
T(
`>....v
..v..<
..>v..
^..<..`
,'N');
//Halting
T(
`.`
,'Y')
//Halting
T(
`v>
>^`
,'Y');
//Halting
T(
`....v....
....>...v
.^..<....
.......v<
.......v.
....^..<.`
,'Y');
//Halting
T(
`v<>v>v^
>v^>^>v
<>>^v<v
v^<>v^<`
,'Y');
//Non-Halting
T(
`>..v
^..<`
,'N');
//Non-Halting
T(
`>v<
v<.
>v.
v<.
>.^`
,'N');
//Non-Halting
T(
`>.>.>.v
.><.<.<`
,'N');
```
**Sample Output**
```
#Halting
I=
>.v
..<
F(I)= true
OK !
#Non-Halting
I=
>....v
..v..<
..>v..
^..<..
F(I)= false
OK !
#Halting
I=
.
F(I)= true
OK !
#Halting
I=
v>
>^
F(I)= true
OK !
#Halting
I=
....v....
....>...v
.^..<....
.......v<
.......v.
....^..<.
F(I)= true
OK !
#Halting
I=
v<>v>v^
>v^>^>v
<>>^v<v
v^<>v^<
F(I)= true
OK !
#Non-Halting
I=
>..v
^..<
F(I)= false
OK !
#Non-Halting
I=
>v<
v<.
>v.
v<.
>.^
F(I)= false
OK !
#Non-Halting
I=
>.>.>.v
.><.<.<
F(I)= false
OK !
```
[Answer]
# [Befunge-98 (PyFunge)](https://pythonhosted.org/PyFunge/), ~~217~~ ~~209~~ 200 bytes
```
#v10dpf1dp12dp3dpk
>#v~:a-#v_$10dp1dg1+1dp >
v >10dp;>0dg1dgp0dg1+0dp^;f1dp
>0dg1dgg:'^-#v_n1-v
^<v01_v#!->':<
< >:'<-#v_01-0> v
v^pd1+gd3gd1[:'v-#v_01>3dp2dpndg1dgp
>0dg2dg+0dp ^ @.!;>:'.-#;_
```
[Try it online!](https://tio.run/##PY7BCsIwDIbvfYpIhR1GS6MX7UrxPYQOJdqDMHox4MVXn8km6yFNvvz5k/vj@Z7qw51Prn2WdJ4tY6D2RGp4oHak9jKQLX/jzVke99pEqtiLALJhgKxoyEEg1aZfL6AMamH@uMau6PiEjk1JHHBku3O5i8kAJBCX2CVVBHQhS82GSyPsKx0r4TV2vHazXCR3Teu2xf9AVTdCgYvfDWLknR3GefbyWIPRkLUyvnifNqYobdnKFsEP "Befunge-98 (PyFunge) – Try It Online")
A befinge halting problem needs a befunge solution.
Returns 0 for truthy and 1 for falsey.
Puts the input on the grid starting from 1,15 and then moves on top, replacing the arrows with zeros. As soon as we hit a zero, we know it loops. Anything besides ><^v. and zero is considerd to halt the program, which includes the border of spaces we get around the program by placing it on the grid slightly offset.
One easy way to shave off a few bites would be to use numbers instead of ><^v. but I don't feel like that's worth it.
[Answer]
# [Python 2](https://docs.python.org/2/), ~~116~~ 105 bytes
```
x=1
X=Y=y=0
H=[]
G=input()
while(X,Y,x,y)not in H:H+=[(X,Y,x,y)];C=ord(G[Y][X]);x=C%3-1;y=C%5-1;X+=x;Y+=y
```
[Try it online!](https://tio.run/##PcqxCsMgFIXh3afIUkzQQtPSpXIXL3jzCIq4tRChmBBSqk9vbYdO38/hrGWfl3SuNcPILDgocGIT@MAIYlpfez@w9xyfj95KJ7MsQ1r2LqZuuk0C/H8NCmHZ7j15F7wNg8qAh8txVKV5bVoBWTkBpVbPURMSGi473iBD@E1NZFD/Ek17GM3DBw "Python 2 – Try It Online")
The challenge is old, but I figured since this is the shortest Python, I will post it. Input is a list of strings, but the characters used are unusual.
```
> G
< B
v C
^ F
. L
```
For example, the third halting example turns into `['LLLLCLLLL', 'LLLLGLLLC', 'LFLLBLLLL', 'LLLLLLLCB', 'LLLLLLLCL', 'LLLLFLLBL']`.
Output is via exit code, 0 (success) for non-halting, and 1 (error) for halting. Any tips or tricks appreciated.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 80 bytes
```
f=(a,v=1,x=0,[t,...u]=a,n=1+a.search`
`,c=a[x])=>t?f(a,v=+c?c-2||v:c+n,x-v,u):!c
```
[Try it online!](https://tio.run/##Pc7BboMwDAbge55iO4UI45buxur0QSoqLC@FVggqoBHS2LNTl8MiJd8vxY5z58ijDLfHlHX9T1jXKyUMkXKYaQ/nCRDxWRJDR3nKOAYepKlMBUJ8nktHfjpdt45UTpIdliUWknYwZxGerviUtSYmryU4tjcJSe5wCI@WNe5wV@sYn/zaoy3slwXr1Vy9qKka1UxF9WD/3Huk@zbN@03pu7FvA7Z9rR/40GO7Sirj0VT/UVc0uhGPilfNRTNuNesL "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 86 bytes
```
f=(a,v=1,x=0,[t,...u]=a,n=1+a.search`
`,c=a[x])=>t?c>' '<=f(a,v=+c?c-2||v:c+n,x-v,u):0
```
[Try it online!](https://tio.run/##Pc3BzoIwDAfw@57C21goVfTGR@eDGA1NnegXAgZwIVGfHYsHd9iv67r9/znyIP3tPmZtdw7zfKGEIVIOE23gMAIiPo7E0FKeMg6Be7lWpgIhPkxHR37ci7crW9Ll@zCVvWTb1ysWkrYwZREertjMNTF5ncChuUlIcod9uDes5RrXtYb55GlLW9idBevVXD2pqRrVTEV1a99uCXZ/5rr8KV07dE3Apqs1f6Xb9yqpjMdoEEtT/c66llZcuoheNSetFZ2ZPw "JavaScript (Node.js) – Try It Online")
[Answer]
# [Turtlèd](http://github.com/Destructible-Watermelon/Turtl-d), 146 bytes
```
!u[*.[ r+.]l[ l]dr_+]#*#[ u]d[ (.r)(>.r{.r}@>)(v.d{.d}@v)(<.l{.l}@<)(^.u{.u}@^)(*@0' )],@1(0@0)(v' d)(<' r)(>' l)(^' d)[ u]d[ l]r[ [ r]l[ ' l]dr],
```
This program takes I/O differently: please terminate each line with a space, including the last one. Turtlèd doesn't like newlines, as it uses a grid for it's second dimension of characters.
### [Try it online!](http://turtled.tryitonline.net/#code=IXVbKi5bIHIrLl1sWyBsXWRyXytdIyojWyB1XWRbICgucikoPi5yey5yfUA-KSh2LmR7LmR9QHYpKDwubHsubH1APCkoXi51ey51fUBeKSgqQDAnICldLEAxKDBAMCkodicgZCkoPCcgcikoPicgbCkoXicgZClbIHVdZFsgbF1yWyBbIHJdbFsgJyBsXWRyXSw&input=Pi48IA)
0 for loops forever, 1 for halts.
## General explanation:
It writes the input on the grid, then it actually follows the path the arrows make around the grid, replacing each arrow with a \* as it goes, also saving the direction in the char var. If it encounters an \*, an arrow it hit before, the program would not halt, so it sets the char var to `0`, exit the loop. Otherwise, it will hit the end of the grid and exit the loop. It will write the char var. If it hit the end of grid, it uses the direction stored in the char var to get back to the grid, and sets the char var to `1`, for halts. If the char var was actually 0, not a direction, it does not need to get back, as it is still there, and it sets it back to `0`. It clears the grid off, then writes the char var, `1` for halts, else `0`.
[Answer]
## JavaScript (ES6), ~~158~~ 127 bytes
```
f=(a,x=0,y=0,d=1,e=0,c=a[y]&&a[y][x])=>c<'~'?(c>'.'&&(a[y][x]='~',d=(c=='>')-(c=='<'),e=(c=='v')-(c=='^')),f(a,x+d,y+e,d,e)):!c
```
Takes input as a two-dimensional character array and returns `true` for halting and `false` for an infinite loop. Works by setting visited direction characters to `~`s as it recursively traverses them. Edit: Saved 31 bytes by updating my direction vector before recursing.
Abusing the instruction characters (`1=^ 4=< 5=. 6=> 9=v`) takes me down to 101 bytes:
```
f=(a,x=0,y=0,d=1,e=0,c=a[y]&&a[y][x])=>+c?(c-5&&(a[y][x]='0',d=~-c%4,e=~-(c>>2)),f(a,x+d,y+e,d,e)):!c
```
[Answer]
# SmileBASIC, ~~158~~ 145 bytes
If the same arrow is encountered more than once, the program will never halt.
When the instruction pointer passes an arrow, it's replaced with a different symbol, which will cause the function to return 0 if it's reached again.
If the IP goes out of bounds, it returns 1.
```
DEF H P@L
C=VAL(P[Y][X])IF C>8THEN?0RETURN
IF C THEN D=C-1P[Y][X]="9
X=X+!D-(D==1)Y=Y+(D==2)-(D>2)IF X+1&&Y+1&&Y-LEN(P)&&X-LEN(P[0])GOTO@L
?1
END
```
Takes input as an array of strings. `<any non-digit chracter>`,`1`,`2`,`3`,`4` = `.`,`>`,`<`,`v`,`^`
[Answer]
## Python 2, 182 bytes
```
m,v,d,x,y=input(),[],'>',0,0
try:
while 1:
if[x,y]in v:print 0;break
c=m[y][x]
if c!='.':d=c;v+=[[x,y]]
if d in'><':x+=[-1,1][d=='>']
else:y+=[-1,1][d=='v']
except:print 1
```
Takes a string array as input. I have to golf this more but for now it's time to stress over the election.
Ungolfed:
```
input = input()
visited = [ ]
dir = ">"
x=0
y=0
try:
while True:
if[x,y]in visited:print False;break
char=input[y][x]
if char!=".":
dir=char
visited+=[[x,y]]
if dir==">":
x+=1
if dir=="<":
x-=1
if dir=="v":
y+=1
if dir=="^":
x-=1
except:
print True
```
[Answer]
## Clojure, 143 bytes
```
#((fn[p v i s](if-let[v({\> 1\< -1\^(- s)\. v\v s}(get % p))](if(neg? i)1(recur(+ p v)v(dec i)s))))0 1 1e9(+(count(take-while(set"<>v^.")%))1))
```
A function with 4 state arguments: position `p`, velocity `v`, step index `i` and size of one line `s`. Returns `1` if we didn't go out of bounds in 10^9 steps and `nil` otherwise. Actually how many steps do we need to check to be sure, `(count %)`? I think it is more than that as same NOP can be traversed horizontally and vertically.
Can be called like this (takes normal strings as arguments, `get` returns `nil` when out of bounds):
```
(def f #( ... ))
(f ">....v\n..v..<\n..>v..\n^..<..")
(f "v>\n>^")
(f "....v....\n....>...v\n.^..<....\n.......v<\n.......v.\n....^..<.")
```
State transitions (+1, -1, +s, -s) are encoded in the dictionary `{\> 1\< -1\^(- s)\. v\v s}`.
[Answer]
# Python 2/3, ~~201~~ 192 bytes
```
def f(x):
X=Y=b=0;a=1;D={}
while len(x)>Y>-1<X<len(x[Y]):
try:
a,b={'>':(1,0),'^':(0,-1),'<':(-1,0),'v':(0,1)}[x[Y][X]]
if(X,Y)in D:return 0
except:0
D[X,Y]=0;X+=a;Y+=b
return 1
```
[Try it online!](https://tio.run/##hZHBaoQwEIbvPkVuUVaDoTdN5uRDKNaAtpEVFlfEprss@@x2ooXSxNJ4cPz55p8/43RfztfxZV3fdU/68BZlASllJTuZ5q3keSEfz4B8noeLJhc9IgAVJFyUYvuqq8Z2kGW@2xdp404@KNAs5HEaxVRhlcYJx1Jgmeyq2VQePWtrUJdNY3uHPizjKhpGUmSzXj7mkaSo69ubnpbMlkWNQIPJypNs8@oku4B8k3yd5mFcwj6sqQDaRFEQ/CjADI3Jq52yH8qY8CE8Pmcs6oqAqiMq5FD8beqMcEe6ODXguILyetiWyZtvJTi6wR7skLe4@EM/4jcrL7MAA0a5wY0CBW4YAaCMcFWj0EId/RBzsGQP865gBPPSsP8ZpvwE9vE2CgLXsOdYvwA "Python 3 – Try It Online")
Gives correct answer for `["<>"]`
[Answer]
## Java, 477
I know that this is not winning, n=and can probably be golfed more, but it implments a similar method as to what the other answers use, but this one uses hashmap to perform lookups. The input is using the symbols ><^v and anything other than that for the no op. Input comes through args.
**GOLFED**
```
import java.util.*;interface B{static void main(String[]a){HashMap<String,Byte>h=new HashMap<>();int x,y=0;for(String s:a){x=0;for(char c:s.toCharArray()){if("><^v".indexOf(c)>-1)h.put(x+","+y,(byte)c);x++;}y++;}x=0;y=0;int d=0;int D=0;while(x>-1&&x<a[0].length()&&y<a.length&&y>-1){Byte v=h.get(x+","+y);if(v!=null){if(v==0){System.out.print(0);return;}d=(v<85)?"<>".indexOf(v)*2-1:0;D=(v>84)?"^v".indexOf(v)*2-1:0;}h.replace(x+","+y,(byte)0);x+=d;y+=D;}System.out.print(1);}}
```
**UNGOLFED**
import java.util.\*;
```
interface B{
static void main(String a[]) {
HashMap<String, Byte> h = new HashMap<>();
int x, y = 0;
for(String s : a) {
x = 0;
for(char c : s.toCharArray()) {
if ("><^v".indexOf(c) > -1) h.put(x + "," + y, (byte) c);
x++;
}
y++;
}
x = 0;
y = 0;
int d = 0;
int D = 0;
while(x > -1 && x < a[0].length() && y < a.length && y > -1) {
Byte v = h.get(x + "," + y);
if(v != null) {
if(v == 0) {System.out.print(0); return;}
d = (v < 85) ? "<>".indexOf(v)*2-1 : 0;
D = (v > 84) ? "^v".indexOf(v)*2-1 : 0;
}
h.replace(x + "," + y, (byte) 0);
x += d;
y += D;
}
System.out.print(1);
}
}
```
Explanation coming soon!
] |
[Question]
[
Consider some binary sequence, using `1` and `2`, e.g.:
```
1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 2, 1 ...
```
Let's write down the run lengths of that:
```
1, 2, 1, 1, 2, 2, 1, 2, 1, 2, 2, 1 ...
_ _ ____ ____ _ _ _ ____
1, 1, 2, 2, 1, 1, 1, 2, ...
```
In this case we happen to get another binary sequence. Of course, that's not guaranteed (e.g. if we repeated the process, the third run would be `3`), but let's assume we do.
Now the question is, can we find a sequence such that applying this type of run-length encoding multiple times gives us back the original sequence? For a cycle-length of 1 (i.e. a fixed point of this transformation), we find the Oldenburger-Kolakoski sequence (OEIS entry [A0000002](https://oeis.org/A000002)):
```
1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, ...
```
(There is actually another solution: we can also omit the leading `1`.)
What about a cycle of length-2? That's also possible! The following two sequences are each others' list of run lengths:
```
1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, ...
2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, ...
```
(These are OEIS entries [A025142](https://oeis.org/A025142) and [A025143](http://oeis.org/A025143). This is the only solution.)
Can we find a cycle of length 3? Sure, here each sequence is the run-length encoding of the next (and the third one is the run-length encoding of the first):
```
1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, ...
1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, ...
2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, ...
```
In this case there is one other solution. It turns out that we can find such a cycle for every cycle length. In fact, the number of distinct cycles of length n is given by OEIS entry [A001037](https://oeis.org/A001037) (this is not counting the arbitrary choice of which sequence in a cycle is considered the first).
**Fun fact:** As unlikely as it seems, this challenge was inspired by studying the complex map `f(z) = z - 1/z`. Whoever figures out what that map has to do with this challenge gets a cookie.
## The Challenge
Given a cycle length `k > 0` and a sequence length `n > 0`, output the first `n` terms of `k` distinct (infinite) binary sequences that form a cycle under the above run-length transformation. If multiple cycles exist, you may output any one of them. It's up to you which sequence in the cycle to start with, and which direction the cycle goes (so you can either output them such that each sequence describes the next, or such that each sequence describes the previous one, cyclically).
You may write a program or function, taking input via STDIN (or closest alternative), command-line argument or function argument and outputting the result via STDOUT (or closest alternative), function return value or function (out) parameter.
Output may be in any convenient, unambiguous, nested list format, such that the the outer dimension is `k` and the inner dimension is `n`.
Standard [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules apply.
## Additional examples
Here are some examples. But as I said, the solutions are not unique, so your own solutions might differ and still be correct. Maybe these will help you come up with a solution though. Each example is `k n` followed by the sequences, such that each line describes the next (cyclically):
```
4 20
1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2
2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1
2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1
1, 1, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1
5 6
2, 2, 1, 2, 2, 1
1, 1, 2, 2, 1, 2
2, 1, 2, 2, 1, 1
1, 1, 2, 1, 1, 2
2, 1, 2, 2, 1, 2
8 20
2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2
1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1
2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2
2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2
1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1
2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2
1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1
2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1
13 50
1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1
1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1
1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2
1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2
1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2
1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2
2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1
1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1
1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1
1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1
1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 2
1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1
1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 1, 2, 2, 1, 2, 1, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 2, 2, 1, 2, 2, 1, 1, 2, 1, 1, 2, 2, 1, 2, 1, 1
```
Note that not all of the lines in the last two outputs differ, although they would eventually if `n` was large enough.
### Related Questions
* [Generate a Kolakoski sequence](https://codegolf.stackexchange.com/q/8369/8478)
[Answer]
## CJam (41 bytes)
```
{Ma*{1:Bm<{1+ee{(1&B^)+}%e~A<0:B;}%}@:A*}
```
This is an anonymous function which takes input on the stack in the order `n k` and leaves output on the stack. [Online demo](http://cjam.aditsu.net/#code=80%203%7BMa*%7B1%3ABm%3C%7B1%2Bee%7B(1%26B%5E)%2B%7D%25e~A%3C0%3AB%3B%7D%25%7D%40%3AA*%7D~%60)
The basic idea is to start with a Lyndon word column `[2 1 1 1 ...]` and iteratively extend right on the basis that knowing the initial element of each row and the alternation we can run-length decode and get more elements.
[Answer]
# Haskell, 72 bytes
```
~(a:b)?c=c:[c|a>1]++b?(3-c)
k!n=take k$take n<$>last(k!n)?2:map(?1)(k!n)
```
Demo:
```
*Main> 4!20
[[2,1,1,2,2,1,2,2,1,2,1,1,2,1,1,2,2,1,2,1],[1,1,2,1,2,2,1,1,2,1,1,2,2,1,2,2,1,2,1,1],[1,2,1,1,2,1,1,2,2,1,2,1,1,2,1,2,2,1,1,2],[1,2,2,1,2,1,1,2,1,2,2,1,1,2,1,1,2,1,2,2]]
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 35 bytes
```
{(⍺↑¨⊣{⍵/(≢⍵)⍴⍺,3-⍺}¨¯1⌽⊢)⍣≡⍨1+⍵↑1}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1rjUe@uR20TD6141LW4@lHvVn2NR52LgLTmo94tQCkdY10gWXtoxaH1ho969j7qWgSUWPyoc@Gj3hWG2kB1QL2Gtf/THrVNeNTb96hvqqf/o67mQ@uNgeJAXnCQM5AM8fAM/g9SaKCQpmDMpa6rq6vOBeQbgfgmAA "APL (Dyalog Unicode) – Try It Online")
An anonymous dfn whose left argument is `n` and right is `k`.
Almost direct translation of [Anders Kaseorg's Haskell answer](https://codegolf.stackexchange.com/a/81110/78410) (adapted to the finite and strict nature of APL arrays), with a bit of hint from [Peter Taylor's idea](https://codegolf.stackexchange.com/a/83024/78410):
>
> The basic idea is to start with a Lyndon word column `[2 1 1 1 ...]` and iteratively extend right on the basis that knowing the initial element of each row and the alternation we can run-length decode and get more elements.
>
>
>
### How it works
```
{(⍺↑¨⊣{⍵/(≢⍵)⍴⍺,3-⍺}¨¯1⌽⊢)⍣≡⍨1+⍵↑1} ⍝ left argument(⍺)←n, right(⍵)←k
1+⍵↑1 ⍝ u←[2, 1, ..., 1] of length k
⍨ ⍝ Run the following with both sides being u:
( )⍣≡ ⍝ Repeat until fixpoint:
⍝ (left: u, right: intermediate result v)
¯1⌽⊢ ⍝ Rotate v down once
⊣{ }¨ ⍝ Zip with left side u: (left elem u_i, right elem v_i)
⍺,3-⍺ ⍝ Make a 2-elem array [u_i, 3-u_i] which is [1 2] or [2 1]
(≢⍵)⍴ ⍝ Cycle the above to the length of v_i
⍵/ ⍝ Duplicate each element of above v_i times e.g. 1 1 2/2 1 2 → 2 1 2 2
⍵/(≢⍵)⍴⍺,3-⍺ ⍝ Run-length decode v_i with alternating 1 and 2's, starting with u_i
⍺↑¨ ⍝ Extend or truncate each row to length n
```
### Comparison with Anders' Haskell version
Anders' Haskell code (parenthesized for clarity) works like this:
```
~(a:b)?c=(c:[c|a>1])++(b?(3-c))
(c:[c|a>1]) -- Two copies of c if head of x > 1, one copy otherwise
++(b?(3-c)) -- Run-length decode the rest with alternating 1 and 2
k!n=take k$take n<$>((last(k!n))?2):(map(?1)(k!n))
take k$ -- take first k rows
take n<$> -- take first n elements from each row
((last(k!n))?2) -- run-length decode the last row with starting value 2
:(map(?1)(k!n)) -- run-length decode the other rows with starting value 1
```
In one iteration, this is equivalent to "prepend the k-th row, run-length decode each row, and then discard the last row". We can simplify it to "rotate once and run-length decode", which I implemented as `¯1⌽`.
For the run-length decoding function, I simply used the APL primitive `/`, while the Haskell version uses infinite lists to implement it.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 22 bytes
```
YΔ´12¹иćRšvyÞsÅΓI∍Dˆ]¯
```
[Try it online!](https://tio.run/##ATMAzP9vc2FiaWX//1nOlMK0MTLCudC4xIdSxaF2ecOec8OFzpNJ4oiNRMuGXcKv/8K7/zMKMjA "05AB1E – Try It Online")
] |
[Question]
[
Write a program or function that draws a tree of trees, thus constructing a forest.
The trees are drawn like stacking a pyramid. The first (top) row contains `1` tree, the next row down contains `2` (for a total of `3`), the next contains `3` (for a total of `6`), and so on. If there aren't enough trees to complete a full row, fill it to the left and leave the spots on the right empty. Additionally, lower-level trees slightly overlap upper-level trees due to their placement.
This is a forest of size `1`
```
/\
//\\
///\\\
||
||
```
This is a forest of size `2`
```
/\
//\\
/\///\\\
//\\ ||
///\\\||
||
||
```
This is a forest of size `3`
```
/\
//\\
/\///\\\/\
//\\ || //\\
///\\\||///\\\
|| ||
|| ||
```
This is a forest of size `4`
```
/\
//\\
/\///\\\/\
//\\ || //\\
/\///\\\||///\\\
//\\ || ||
///\\\|| ||
||
||
```
This is a forest of size `5` (note the top of the fifth tree is covering the trunk of the first tree)
```
/\
//\\
/\///\\\/\
//\\ || //\\
/\///\\\/\///\\\
//\\ || //\\ ||
///\\\||///\\\||
|| ||
|| ||
```
(skip a few)
This is a forest of size `8` (extending the pattern)
```
/\
//\\
/\///\\\/\
//\\ || //\\
/\///\\\/\///\\\/\
//\\ || //\\ || //\\
/\///\\\/\///\\\||///\\\
//\\ || //\\ || ||
///\\\||///\\\|| ||
|| ||
|| ||
```
and so on.
### Input
A single positive integer [in any convenient format](http://meta.codegolf.stackexchange.com/q/2447/42963), `n > 0`.
### Output
An ASCII-art representation of the forest, following the above rules. Leading/trailing newlines or other whitespace are optional, provided that the trees all line up appropriately.
### Rules
* Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
* [Standard loopholes](http://meta.codegolf.stackexchange.com/q/1061/42963) are forbidden.
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so all usual golfing rules apply, and the shortest code (in bytes) wins.
[Answer]
## Haskell 310 bytes
```
w i=putStr$unlines$reverse$b i 0 0[][]
b 0 _ _ w r=e w r
b c l 0 w r=b c(l+1)l(e w r)[]
b c l p w r=b(c-1)l(p-1)w(n(++)[" || "," || ","///\\\\\\ "," //\\\\ "," /\\ "]r)
e w r=t++n(n d)(map(\t->" "++t)w)c where(t,c)=splitAt 2 r
n f(a:c)(b:d)=f a b:n f c d
n _ a[]=a
n _ _ a=a
d d ' '=d
d _ d=d
```
Call it with `w 5`, for example.
Here the uncompressed code:
```
-- TreeTree
-- by Gerhard
-- 12 February 2017
module TreeTree (wood,test) where
type Tree = [String]
-- Test cases
test = do
wood 0
wood 1
wood 2
wood 3
wood 4
wood 5
-- build wood
wood :: Int -> IO ()
wood i = printTree $ buildWood i 0 0 [] []
-- Prints the trees
printTree :: Tree -> IO ()
printTree = putStr . unlines . reverse
-- build wood
buildWood :: Int -> Int -> Int -> Tree -> Tree -> Tree
buildWood 0 _ _ w r = concatTree w r
buildWood c l 0 w r = buildWood c (l+1) l (concatTree w r) []
buildWood c l p w r = buildWood (c-1) l (p-1) w (addTree r)
-- indent definition
space :: String
space = " "
-- tree definition
tree :: Tree
tree = reverse [
" /\\ ",
" //\\\\ ",
"///\\\\\\ ",
" || ",
" || "]
-- Add a Tree on the left side
addTree :: Tree -> Tree
addTree = match (++) tree
-- add tree row at the bottom of the wood
concatTree :: Tree -> Tree -> Tree
concatTree w r = trunk ++ matched
where
wood = grow w
(trunk, crown) = splitAt 2 r
matched = matchTree wood crown
-- elnarge forrest on the left side to match next tree line
grow :: Tree -> Tree
grow = map (\t -> space ++ t)
-- match
match :: (a -> a -> a) -> [a] -> [a] -> [a]
match f (a:az) (b:bz) = f a b : match f az bz
match _ a [] = a
match _ _ a = a
-- match trees
matchTree :: Tree -> Tree -> Tree
matchTree = match matchLine
-- match lines
matchLine :: String -> String -> String
matchLine = match matchChar
-- match chars
matchChar :: Char -> Char -> Char
matchChar c ' ' = c
matchChar _ c = c
-- End
```
[Answer]
## JavaScript (ES6), ~~357~~ ~~297~~ 276 bytes
```
f=
n=>{a=` /\\`;d=`///\\\\\\`;b=d+`/\\`;c=` //\\\\ ||`;d+=`||`;e=`
`;r=`repeat`;s=``;for(i=1;n>i;n-=i++)s=(s+a+b[r](i-1)+e+c[r](i)).replace(/^/gm,` `)+e;return(s+a+b[r](n-1)+d[r](i-=n)+e+c[r](n)+(s=` ||`[r](i))+e+d[r](n)+s+(s=e+` || `[r](n))+s).replace(/\|.$/gm,``)}
```
```
<input type=number min=1 oninput=o.textContent=f(this.value)><pre id=o>
```
Edit: Saved 21 bytes thanks to @KritixiLithos.
[Answer]
# C++ (on Windows), ~~330~~ ~~312~~ ~~308~~ ~~304~~ 303 bytes
```
#import<cstdio>
#import<windows.h>
#define P(x,y,s)SetConsoleCursorPosition(GetStdHandle(-11),{X+x,Y+y});puts(s);
int X,Y,R,r,c;t(){P(2,-2,"/\\")P(1,-1,"//\\\\")P(0,0,"///\\\\\\")P(2,1,"||")P(2,2,"||")}f(int n){for(c=R=r=1;c<n;c+=++R);for(;r;r++)for(c=0;++c<r+1;){X=(R-r-2)*4+c*8;Y=r*2;t();r=--n?r:-1;}}
```
Call with:
```
int main()
{
f(8);
}
```
[Answer]
## Javascript ~~418~~ 377 bytes
Thanks to @Kritixi Lithos for helping golf off 39 bytes
```
x=>{s='';for(t=0;++t<x;x-=t);q='//\\\\';z="///\\\\\\";h="/\\";t--;for(i=0;i<t;i++){a=4*(t-i)+1;s+=" "[w="repeat"](a+1)+h+(z+h)[w](i)+`
`+" "[w](a)+q+(" || "+q)[w](i)+`
`}c=t-x+1>0?t-x+1:0;return x?s+" "+(h+z)[w](--x)+h+(c?(z+"||")[w](c-1)+z:'')+`
`+q+(" || "+q)[w](x)+" || "[w](c)+`
`+(z+"||")[w](x)+z+(c?"||"+" ||"[w](c-1):'')+`
`+(" || "[w](x+1)+`
`)[w](2):''}
```
[Try it Online](https://tio.run/#lgkpp)
[Answer]
# C (on Windows), ~~297~~ ~~295~~ 294 bytes
```
#import<windows.h>
#define P(x,y,s)C.X=X+x;C.Y=Y+y;SetConsoleCursorPosition(GetStdHandle(-11),C);puts(s);
COORD C;X,Y,R,r,c;t(){P(2,-2,"/\\")P(1,-1,"//\\\\")P(0,0,"///\\\\\\")P(2,1,"||")P(2,2,"||")}f(n){for(c=R=r=1;c<n;c+=++R);for(;r;r++)for(c=0;++c<r+1;){X=(R-r-2)*4+c*8;Y=r*2;t(r=--n?r:-1);}}
```
Similar to my C++ answer, but I posted this because it's somewhat shorter in C.
] |
[Question]
[
I like the [Hilbert Curve](https://en.wikipedia.org/wiki/Hilbert_curve).
---
Your task for this challenge is to take an image (strictly a square image where all the sides are a power of two pixels wide) and unravel it line by line in a zig-zagging fashion and ravel it back up in a pseudo-Hilbert curve.
## Unraveling
To unravel you will start with the pixel in the upper left hand corner and travel right until you arrive at the edge of the image. Once you have hit the edge of the image you will move down to the next row and begin traveling left until you hit the edge again. You will continue unraveling row by row switching the direction each time so you get one continuous curve. This should look like a well played game of snake
The result of unraveling should be an order of pixels that includes every pixel exactly once
## Reraveling
Once you have an order for the pixels you will rearrange them on a new equally sized canvas following the path of a pseudo-Hilbert curve. For a `2**n` sized square image you should use the nth iteration of the pseudo-hilbert curve. Each pixel will be placed in exactly one spot on the new canvas. You should reravel the image so that the point originally in the top left (the start of our snake curve) will remain there and point in the bottom right (the end of our snake curve) will be placed in the top right.
## I/O
Your program or function should take in an image of specified constraints via standard methods and output another image via standard methods.
## Scoring
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") program with the fewest bytes wins.
## Examples
### Input
[](https://i.stack.imgur.com/Upo06.jpg)
### Output
[](https://i.stack.imgur.com/otvMc.png)
---
### Input
[](https://i.stack.imgur.com/NONLQ.jpg)
### Output
[](https://i.stack.imgur.com/XzJV1.png)
---
### Input
[](https://i.stack.imgur.com/UtkBc.png)
### Output
[](https://i.stack.imgur.com/rMCVe.jpg)
---
I also recommend testing on a blank white or solid color image to make sure you are not missing any pixels.
Feel free to include your own results in your answers!
[Answer]
# Mathematica, ~~286~~ 273 bytes
```
Image[Array[1,{l=Length@#,l}]~ReplacePart~Thread[#&@@@Split[#&@@@FoldList[Switch[#2,"-",#{1,I},"+",#/{1,I},"F",#+{ReIm@Last@#,0},_,#]&,{{1,1},I},Characters@Nest[StringReplace@{"L"->"+RF-LFL-FR+","R"->"-LF+RFR+FL-"},"L",Log2@l]]]->Join@@MapAt[Reverse,#,2;;;;2]]]&@*ImageData
```
Phew! Challenging but fun!
# Explanation
```
ImageData
```
Convert an `Image` into an array of RGB values.
```
Array[1,{l=Length@#,l}]
```
Generate an `l` by `l` array with head `1`, where the `l` is the length of the input (i.e. the width of the image).
This yields `{{1[1, 1], 1[1, 2], ..., 1[1, L]}, {1[2, 1], ..., 1[2, L]}, ..., {1[L, 1], ..., 1[L, L]}}` (`l` written in caps to reduce confusion)
```
StringReplace@{"L"->"+RF-LFL-FR+","R"->"-LF+RFR+FL-"}
```
A `StringReplace` function that replaces every `"L"` with `"+RF-LFL-FR+"` and `"R"` with `"-LF+RFR+FL-"`
```
Nest[ ... ,"L",Log2@l]
```
Apply the `StringReplace` function to the `String` `"L"`, `Log2[l]` times.
```
Characters
```
Convert the resulting `String` into a `List` of characters.
```
Switch[#2,"-",#{1,I},"+",#/{1,I},"F",#+{ReIm@Last@#,0},_,#]&
```
An unnamed function that:
* If the second input is `"-"`, multiply the second element of the first input by `I`.
* If the second input is `"+"`, divide the second element of the first input by `I`.
* If the second input is `"F"`, increase the first input by the `ReIm` (separates the real and imaginary part of the input) of the second input.
```
FoldList[ ... ,{{1,1},I}, ... ]
```
Starting with `{{1,1},I}`, cumulatively apply the above unnamed function, using each element of the `List` of characters as the second input. This code yields the outputs of all iterations.
```
#&@@@Split[#&@@@ ... ]
```
Get rid of the second elements of each `List` and delete duplicates. (The steps up to this point generate a `List` of coordinates of the Hilbert curve)
```
Join@@MapAt[Reverse,#,2;;;;2]
```
Unravel the input RGB array (reverses every other row and flattens).
```
Thread[ ... -> ... ]
```
Create `Rule` objects, such that the first element in the first input (the coordinates of the Hilbert curve) is paired with the the first element of the second input (the unraveled image), the second element with the second input, and so on.
```
... ~ReplacePart~ ...
```
Apply those replacement `Rule`s to the `Array` from the second step.
```
Image
```
Convert to the array of RGB values into an `Image`.
# Sample in/out
Input:
[](https://i.stack.imgur.com/Upo06.jpg)
Output:
[](https://i.stack.imgur.com/xoQTl.png)
---
Input:
[](https://i.stack.imgur.com/8pQyE.jpg)
Output:
[](https://i.stack.imgur.com/SMfRP.jpg)
# Inverse function (~~266~~ 253 bytes)
```
Image[MapAt[Reverse,Extract[#,#&@@@Split[#&@@@FoldList[Switch[#2,"-",#{1,I},"+",#/{1,I},"F",#+{ReIm@Last@b,0},_,#]&,{{1,1},I},Characters@Nest[StringReplace@{"L"->"+RF-LFL-FR+","R"->"-LF+RFR+FL-"},"L",Log2[l=Length@#]]]]]~Partition~l,2;;;;2]]&@*ImageData
```
[Answer]
# Octave 234 Bytes
```
I=imread(input(''));w=rows(I);X=[0,3;1,2];for k=2:log2(w);n=numel(X);X=[X',rot90(X',2)+3*n;X+n,X+2*n];end;for k = 1:3;I(2:2:end,:,k)=fliplr(I(2:2:end,:,k));end[~,S]=sort(X(:));I(S+(0:w^2:2*w^2))=permute(I,[2 1 3]);imwrite(I,input(''))
```
File names of input and output images should be provided form standard input.
size of code without input/output is **194 bytes**.
Explanation:
The base pattern of indices is:
```
X =
0 3
1 2
```
In each iteration 4 copies from result of the previous iteration made and some transformation applied to each copy then all blocks concatenated to form the current result.
```
X =[0,3;1,2];
for k = 2:log2(s)
n=numel(X);
X = [X',rot90(X',2)+3*n;X+n,X+2*n];
end
```
so we have:
```
block(1,1): X'
block(1,2): rot90(X',2)+3*n
block(2,1): X+n
block(2,2): X+2*n
0 1 | 14 15
3 2 | 13 12
--------|--------
4 7 | 8 11
5 6 | 9 10
```
Hilbert indices sorted and indexes of sorted elements returned:
```
[~,S]=sort(X(:));
```
Unraveling applied flipping all even rows:
```
for k = 1:3
I(2:2:end,:,k) = fliplr(I(2:2:end,:,k));
end
```
Reraveling applied :
-S repeted for each channel
-permutation applied since in Octave data arranged column wise
```
I(S+(0:w^2:2*w^2))=permute(I,[2 1 3]);
```
Example images:
[](https://i.stack.imgur.com/golLo.jpg)
[](https://i.stack.imgur.com/moIWX.jpg)
[](https://i.stack.imgur.com/fl18W.jpg)
[](https://i.stack.imgur.com/TbM7G.jpg)
] |
[Question]
[
Your task is to determine whether a graph is planar.
A graph is planar if it can embedded in the plane, or in other words if it can be drawn without any crossing edges.
**Input:** You will be given an undirected graph in your choice of the following formats:
* Edge list, e.g. `[(0, 1), (0, 2), (0, 3)]`
* Adjacency map, e.g. `{0: [1, 2, 3], 1:[0], 2:[0], 3:[0]}`
* Adjacent matrix, e.g. `[[0, 1, 1, 1], [1, 0, 0, 0], [1, 0, 0, 0], [1, 0, 0, 0]]`
Node names may be numbers, strings or similar, but your chosen format must be able to support an an arbitrary graph. No putting code in the node names. There will be no self loops.
Standard choice of input, including STDIN, command line arguments and function arguments.
**Output:** You should return a specific output for all planar graphs, and a different specific output for all nonplanar graphs.
Standard choice of output, including STDOUT, function return value.
**Examples:**
Planar:
```
[]
[(0,1), (0,2), (0,3), (0,4), (0,5), (0,6)]
[(0,1), (0,2), (0,3), (1,2), (1,3), (2,3)]
[(0,2), (0,3), (0,4), (0,5), (1,2), (1,3), (1,4), (1,5), (2,3),
(2,5), (3,4), (4,5)]
```
Nonplanar:
```
[(0,1), (0,2), (0,3), (0,4), (1,2), (1,3), (1,4), (2,3), (2,4), (3,4)]
[(0,3), (0,4), (0,5), (1,3), (1,4), (1,5), (2,3), (2,4), (2,5)]
[(0,3), (0,4), (0,6), (1,3), (1,4), (1,5), (2,3), (2,4), (2,5), (5,6),
(7,8), (8,9), (7,9)]
```
Any function which explicitly performs planarity testing or otherwise specifically references planar embeddings is disallowed.
This is code golf. May the shortest code win.
[Answer]
# Mathematica, 201 bytes
```
f@g_:=EdgeCount@g<9||!(h=g~IsomorphicGraphQ~CompleteGraph@#&)@5&&!h@{3,3}&&And@@(f@EdgeDelete[g,#]&&f@EdgeContract[g,#]&/@EdgeList@g);And@@(f@Subgraph[g,#]&/@ConnectedComponents[g=Graph[#<->#2&@@@#]])&
```
This evaluates to an unnamed function, which takes an edge list like
```
{{0, 3}, {0, 4}, {0, 5}, {1, 3}, {1, 4}, {1, 5}, {2, 3}, {2, 4}, {2, 5}}
```
This is a horribly inefficient recursive approach based on [Wagner's theorem](https://en.wikipedia.org/wiki/Wagner%27s_theorem):
>
> A finite graph is planar if and only if it does not have *K5* or *K3,3* as a minor.
>
>
>
Here, *K5* is the complete graph with 5 vertices, and *K3,3* is the complete bipartite graph with 3 vertices in each group. A graph *A* is a [minor](https://en.wikipedia.org/wiki/Graph_minor) of graph *B* if it can be obtained from *B* by a sequence of edge deletions and edge contractions.
So this code just checks if the graph is isomorphic to *K5* or *K3,3* and if not then it recursively calls itself once for every possible edge deletion or contraction.
The catch is that deleting or contracting edges in one component of an unconnected graph will never get rid of all the vertices there, so we'll never find the desired isomorphisms. Hence, we apply this search to each connected component of the input graph separately.
This works very fast for the given inputs, but if you add a few more edges it will quickly take catastrophically long (and take a lot of memory as well).
Here is an indented version of `f` (the unnamed function after it just generates a graph object from the input:
```
f@g_ :=
EdgeCount@g < 9 ||
! (h = g~IsomorphicGraphQ~CompleteGraph@# &)@5 &&
! h@{3, 3} &&
And @@ (f@EdgeDelete[g, #] && f@EdgeContract[g, #] & /@ EdgeList@g)
```
And this is the unnamed function which converts the input to a graph and calls `f` for each connected component:
```
And @@ (
f @ Subgraph[g, #] & /@ ConnectedComponents[
g=Graph[# <-> #2 & @@@ #]
]
)&
```
I can save a couple of bytes by changing the termination condition from `EdgeCount@g<9` to `g==Graph@{}`, but that will blow up the runtime significantly. The second test case then takes 30 seconds, and the last one hasn't completed yet.
] |
[Question]
[
On the advice of Ms. Pac-Man who's worried about him getting overweight, Pac-Man has decided to keep track of his daily Pac-Dot intake. Help him count the number of Pac-Dots on a given path in the maze!
## The maze
[](https://i.stack.imgur.com/h1mJK.png)
To help you build your own encoding of the maze, you can **[get some raw data here](https://pastebin.com/3KkwaGyN)**.
## Pac-Man's journey
In the context of this challenge, the following rules apply:
* First, the good news: the ghosts aren't there.
* Pac-Man always starts his race at the position indicated on the above picture, heading to the East. There is no Pac-Dot at the starting position.
* As long as he's following a straight path, he keeps advancing to the next squares.
* When he encounters a *90° turn* without any other available path (orange squares on the map), he automatically and systematically takes the turn.
* When he encounters a *junction* where several paths are available (green squares on the map), he may either continue on the same direction -- if applicable -- or choose another direction (including doing a U-turn).
* When Pac-Man passes through one of the exits on the middle left or middle right side of the maze, he immediately reappears on the opposite side.
* Pac-Man eats all the Pac-Dots on the path he's following. Once a Pac-Dot has been eaten, it is removed from the maze.
## The challenge
### Input
You'll be given a string describing Pac-Man's behavior on the junctions that he's going to reach. This string will be made of the following characters:
* `L`: do a 90° turn to the left
* `R`: do a 90° turn to the right
* `F`: go forwards (no direction change)
* `B`: go backwards (do a U-turn)
When all characters have been processed, Pac-Man stops at the next junction he encounters.
### Output
You have to print or output the number of Pac-Dots eaten along the input path.
### Rules
* You can write a full program or a function.
* You can take input in either uppercase or lowercase, as either a string or an array of characters. You may also use other characters (but only one character per direction) or integers in `[0 .. 9]`. If you do so, please specify it clearly in your answer.
* You can assume that the input is always valid. (The jsFiddle below will detect errors, but you're not supposed to.)
* This is code-golf, so the shortest code in bytes wins.
* Standard loopholes are forbidden.
### Hint
It may not be required nor optimal to store the exact shape of the maze.
## Test cases and demo
The following test cases -- or any other input -- **[can be tested in this jsFiddle](https://jsfiddle.net/Arnauld/ww6b4n3v/1)**.
```
1. Input : ""
Output : 1
Comment: Pac-Man just advances to the first junction, eats the Pac-Dot on it and stops.
2. Input : "L"
Output : 7
3. Input : "FFR"
Output : 13
4. Input : "LFLR"
Output : 17
Comment: Pac-Man will exit on the middle right side and re-appear on the left side.
5. Input : "BBBB"
Output : 2
6. Input : "BRRFFFL"
Output : 15
7. Input : "LFFRLFFFFRF"
Output : 50
8. Input : "BRFRLRFRLFR"
Output : 54
Comment: Pac-Man will exit on the middle left side and re-appear on the right side.
9. Input : "FFLRLFFLLLLFFBFLFLRRRLRRFRFLRLFFFLFLLLLFRRFBRLLLFBLFFLBFRLLR"
Output : 244
Comment: All cleared!
```
[Answer]
# Pyth, ~~356~~ 345 + 1 = 346 bytes
The code contains some unprintables, so here is the reversible `xxd` hexdump.
```
0000000: 4a4b 304c 2c3d 2b4b 4062 4a58 624a 3041 JK0L,=+K@bJXbJ0A
0000010: 2c63 6a43 2201 e120 49b4 efbc e267 27f4 ,cjC".. I....g'.
0000020: a11b f5d5 7f79 d1a0 ab8a 7689 449f 0c50 .....y....v.D..P
0000030: b2d4 7c30 99c3 368e aa67 4213 ab9b d276 ..|0..6..gB....v
0000040: d75f 6e99 5757 04a6 08cc 99d0 7141 3d2f ._n.WW......qA=/
0000050: d854 7cf7 4a70 954e 6e35 f9b9 e0c5 1d53 .T|.Jp.Nn5.....S
0000060: 36d5 63f9 cf13 0f66 c113 4dec 956e 5225 6.c....f..M..nR%
0000070: b14a 1659 dcb5 6822 3534 2034 6a43 2203 .J.Y..h"54 4jC".
0000080: ffe3 8fff 2232 3d59 636a 4322 0b8a 4624 ...."2=YcjC"..F$
0000090: 7815 4a94 192c 79f6 d6e5 e098 5e97 76bc x.J..,y.....^.v.
00000a0: 23cf 027c 35c5 5098 2a83 68f1 823a 83f6 #..|5.P.*.h..:..
00000b0: dfa4 7e12 443f 0257 7adb ab2d 8e6f 1199 ..~.D?.Wz..-.o..
00000c0: 9a3e 3f9d a524 d331 c5ff 94ae e5a2 3507 .>?..$.1......5.
00000d0: bd22 3334 2032 3d6b 2b30 6a43 2202 25f2 ."34 2=k+0jC".%.
00000e0: f55c 2252 c250 0002 c250 0000 065c 225c .\"R.P...P...\"\
00000f0: 2247 5289 3698 4227 5350 8822 3136 3d64 "GR.6.B'SP."16=d
0000100: 636a 4322 8223 a80e 5c22 981d d272 729d cjC".#..\"...rr.
0000110: d88d 981d 5c22 5c22 2bd7 91dd 9428 73d7 ....\"\"+....(s.
0000120: 1dd7 2234 2032 5651 2079 483d 547e 4a40 .."4 2VQ yH=T~J@
0000130: 4047 4a2b 5a78 2246 5242 4c22 4e20 796b @GJ+Zx"FRBL"N yk
0000140: 3d5a 4040 647e 4a40 4059 4a3d 5421 7840 =Z@@d~J@@YJ=T!x@
0000150: 594a 5454 2968 7948 0a YJTT)hyH.
```
Requires the `-M` flag to disable memoization. Unfortunately, this can't be done in any online executor I know of.
Here is a ~~readable~~ printable ASCII version:
```
JK0L,=+K@bJXbJ0A,cj746957013238413906925468440008893181365431681519974815772691846219267045007717553452313017550830370829477591340658010575885616582299429376501117428763541235628345630376341520044712982918668584832091126800263024965443560007480163218792 54 4j17178005503 2=Ycj664551201217474826979459068682259492333017695780569003557724234375880492114440213266014621594427584622393511454741615093293082181365458295035985321888753898774398909 34 2=k+0j883734055588186287049718559289059922762611092840989558085734536 16=dcj53536195844172273707047543644202986760006840011986146398708374999 4 2VQ yH=T~J@@GJ+Zx"FRBL"N yk=Z@@d~J@@YJ=T!x@YJTT)hyH
```
## Explanation
This is very much work in progress, so I won't post a complete explanation yet.
Basically, the program represents the board as a (somewhat weird) graph using five lookup tables: 2 for connectivity, 1 for junction directions, and 2 for dot counts. This was built by a 200-line Python script I spent way too many hours on. Then the program just walks through the input and counts the dots, updating the dot tables to zero as the dots are collected.
### TODO:
* Write Python routine for reordering the nodes until the lookup table contains as few escape-requiring characters as possible
* Try to remove section handling altogether (should remove one lookup table)
+ **UPDATE:** tried this, seems to not remove the table and lengthen code
* Rewrite Pyth-side logic (the current one isn't very golfed)
+ **UPDATE:** somewhat done, code's still imperfect
[Answer]
# k, 264 bytes
```
b:,/16 16\'108_a:-135#0+1:"p.k"
(#(?27,r 1)^(12+!8)^14 17)+/b@?*|r:+1 27 0{i:a?64/(4!2+y+*x;x 1);(4 64\a i+1-2*2!i),_i%2}\0:""
\
...binary data...
```
Hex dump:
```
$ xxd p.k
00000000: 623a 2c2f 3136 2031 365c 2731 3038 5f61 b:,/16 16\'108_a
00000010: 3a2d 3133 3523 302b 313a 2270 2e6b 220a :-135#0+1:"p.k".
00000020: 2823 283f 3237 2c72 2031 295e 2831 322b (#(?27,r 1)^(12+
00000030: 2138 295e 3134 2031 3729 2b2f 6240 3f2a !8)^14 17)+/b@?*
00000040: 7c72 3a2b 3120 3237 2030 7b69 3a61 3f36 |r:+1 27 0{i:a?6
00000050: 342f 2834 2132 2b79 2b2a 783b 7820 3129 4/(4!2+y+*x;x 1)
00000060: 3b28 3420 3634 5c61 2069 2b31 2d32 2a32 ;(4 64\a i+1-2*2
00000070: 2169 292c 5f69 2532 7d5c 303a 2222 0a5c !i),_i%2}\0:"".\
00000080: 0a02 4005 c006 4109 c103 8008 8143 c244 [[email protected]](/cdn-cgi/l/email-protection)
00000090: c345 c446 c547 c648 c749 c84a 820a 830c .E.F.G.H.I.J....
000000a0: 840d 870b 8889 cb0e 8a11 8b0f 4c4d cc10 ............LM..
000000b0: cd4e d14f ce51 d014 8e12 8f13 9017 9153 .N.O.Q.........S
000000c0: d215 9216 931e 5455 d41a d51b 5657 d61f ......TU....VW..
000000d0: d718 941d 9759 d85a d95b da5c db5d dc98 .....Y.Z.[.\.]..
000000e0: de20 9921 9c5f 9d5e 60df e161 e089 9833 . .!._.^`..a...3
000000f0: 4222 2247 2662 7550 0000 0500 5000 c255 B""G&buP....P..U
00000100: 2c22 2202 2588 5ff2 ,"".%._.
```
The binary data at the end encodes two arrays:
* `a` consists of pairs of bytes, each representing (64\*direction)+junctionId
* `b` is the number of Pacman dots between each pair of junctions in `a`
The program reads its own source file (`p.k`) and decodes the data.
The input comes from stdin and uses 0x00,0x01,0x02,0x03 (a.k.a. NUL,SOH,STX,ETX - the first four ASCII codes) instead of FLBR.
I use [my own implementation of k](https://github.com/ngn/k) which is limited, bloated, crashy, and slow compared to [the real thing](https://en.wikipedia.org/wiki/K_%28programming_language%29). I test with the following program:
```
t:{e:($y),"\n"; a:`sys[("/path/to/k";"./p.k");`c$"FLBR"?x]
1@$[a~e;"ok\n";"failed ",x,"\n expected: ",e," actual: ",a,"\n"];}
t["";1]
t[,"L";7]
t["FFR";13]
t["LFLR";17]
t["BBBB";2]
t["BRRFFFL";15]
t["LFFRLFFFFRF";50]
t["BRFRLRFRLFR";54]
t["FFLRLFFLLLLFFBFLFLRRRLRRFRFLRLFFFLFLLLLFRRFBRLLLFBLFFLBFRLLR";244]
\
```
] |
[Question]
[
I have a pile of clean socks that I want to sort into pairs. Unfortunately, I can only take socks from either end of the pile, not the middle. Further, I can only remove socks from the pile a matching pair at a time. My strategy is to first split the pile into one or more smaller piles. I think some examples will make this clear. I'll represent each sock as a positive integer (matching integers indicate equal socks).
If the initial pile of socks is
```
1 2 3 3 2 1
```
then I don't have to do any splitting. I can remove both `1` socks, then both `2` socks, then both `3` socks.
If instead the initial pile is
```
1 2 3 2 3 1
```
then I have to split it first because I won't be able to pair all the socks by just removing them from the end. One possibility is to split it into the two piles
```
1 2 3 and 2 3 1
```
Now I can remove the `1` socks, leaving `2 3 and 2 3`, followed by the `3` socks, leaving `2 and 2`, and finally the `2` socks.
## Your Job
Given the initial pile of socks, write a program that will split it into smaller piles that will allow me to sort the socks. Your program should split the pile into the fewest number of piles possible (if there are multiple best solutions, you need only find one).
The input will be given as a list, delimited string, or other convenient form. It will contain only integers between `1` and some maximum value `n`, with each integer occurring exactly twice.
The output should consist of the input list split into smaller lists, given in any convenient form.
## Examples
```
Input Sample Output
1 1 1 1
1 2 1 2 1; 2 1 2
1 3 2 4 3 2 1 4 1 3 2; 4 3 2 1 4
1 2 3 4 3 4 1 2 1; 2 3; 4 3 4 1 2
1 1 2 2 3 3 1 1 2; 2 3 3
4 3 4 2 2 1 1 3 4 3 4 2; 2 1 1 3
```
Note that this isn't the only allowed output for most of these inputs. For the second case, for example, the outputs `1 2; 1 2` or `1 2 1; 2` would also be accepted.
Thanks to Sp3000 for some test suggestions!
I hate spending a long time sorting my clothes, so make your code as short as possible. Shortest answer in bytes wins!
## Notes
* I don't want to have to look behind a sock to see if its matching pair is there, so taking both socks in a pair from the same end is not allowed. E.g. if the pile is `1 1 2 2` then you wouldn't be able to leave it as one pile and take both `1` socks from the left end.
[Answer]
# Pyth, 25 bytes
```
hf!u #-R.-F{BhMs_BMGGT)./
```
[Test suite](https://pyth.herokuapp.com/?code=hf%21u+%23-R.-F%7BBhMs_BMGGT%29.%2F&test_suite=1&test_suite_input=%5B1%2C1%5D%0A%5B1%2C2%2C1%2C2%5D%0A%5B1%2C3%2C2%2C4%2C3%2C2%2C1%2C4%5D%0A%5B1%2C2%2C3%2C4%2C3%2C4%2C1%2C2%5D%0A%5B1%2C1%2C2%2C2%2C3%2C3%5D%0A%5B4%2C3%2C4%2C2%2C2%2C1%2C1%2C3%5D&debug=0)
Explanation:
```
hf!u #-R.-F{BhMs_BMGGT)./
./ Form all partitions (implicitly) of the input.
f Filter the permutations on
u T) Run the following function on the partition
until it reaches a fixed point:
_BMG Bifurcate the lists on reversal
s Concatenate
hM Take the first element of each list.
These elements are all the ones on the ends of lists.
{B Bifurcate on deduplication
.-F Bagwise subtraction.
Only elements repeated in ends of lists remain.
-R G Remove these elements from each list.
' #' Filter out empty lists.
! Negate. Only an empty list as fixed point succeeds.
h Output the first successful partition.
```
[Answer]
# JavaScript (ES6), 329
Not an easy task for a language that has no combinatorics builtins.
Probably sligthly more golfable.
Note: all partition are at least of size 2, as a partition with a single element is always less useful.
```
Example: [1] [2 3 4] // can take 1 or 2 or 4
Better: [1 2] [3 4] // can take 3 too
```
```
a=>{G=(v,i,u=v)=>{if(i--){for(;r[i]=--u;)if(G(u,i))return 1;}else for(w=[...r,n=l].map((x,i)=>a.slice(z,z=x-~i),z=0),y=w.join`;`;w.map(b=>[0,1].map(q=>(x=b[q*=~-b.length])&&(t[x]?([c,p]=t[x],n-=2,p?c.pop():c.shift(),q?b.pop():b.shift()):t[x]=[b,q])),c=0,t=[]),c;)if(!n)return 1};for(l=a.length,r=[],k=0;!G(l-k-1,k);k++);return y}
```
**Explanation in parts**
(it's overly verbose, but I found it tough to explain - eventually skip to "put it all together")
A recursive function to enumerate all possible splits of an array
```
// v: array length
// i number of splits
// fill the global array r that must exists
G=(v,i,u=v)=>
{
if(i--)
{
for(;r[i]=--u;)
G(u,i)
}
else
{
// the current split position are in r, ready to use
// for instance...
parts = [...r,a.length].map(x=>a.slice(z,z=x),z=0)
console.log(r, parts)
}
};
r=[]
a=['A','B','C','D']
G(4, 2)
// output in console (firebug)
[2, 3] [["A", "B"], ["C"], ["D"]]
[1, 3] [["A"], ["B", "C"], ["D"]]
[1, 2] [["A"], ["B"], ["C", "D"]]
```
Now, I need partitions of size 2 or more, so I must use this function with sligtly different parameters. The parameter v is "array size - number of desired partitions - 1". Then I must build the partitions in a slightly different way.
```
// Same call (4,2), same r, but the array b is of size 7
part = [...r,b.length].map((x,i)=>
b.slice(z,z=x+i+1) // add 1 more element to each partition
,z=0))
// output in console (firebug)
[2, 3] [["A", "B", "C"], ["D", "E"], ["F", "G"]]
[1, 3] [["A", "B"], ["C", "D", "E"], ["F", "G"]]
[1, 2] [["A", "B"], ["C", "D"], ["E", "F", "G"]]
```
So, I can enumerate the list of partitions for no split, 1 split, 2 splits and so on. When I find a working partition I will stop and output the result found.
To check, scan the partition list, note the values at start and end of each, if found a repated value then remove it. Repeat until nothing can be removed, at last: if all pairs were removed then this partition is good.
```
t = []; // array to note the repeated values
// t[x] == [
// subarray holding value x,
// position of value x (I care zero or nonzero)
// ]
n = a.length // counter start, must reach 0
// remember part just in case, because this check will destroy it
result = part.join(';') // a string representation for return value
do
{
// in the golfed code there is a forr loop
// all this body is inside the for condition
c = 0; // init c to a falsy, if a pair is found c becomes truthy
part.forEach(b=> // b: array, current partition
[0,1].forEach(q=> ( // exec for 0 (start), 1 (end)
q *= b.length-1, // now q is the correct index
x = b[q]) // x is the value at start or end
x && ( // b could be empty, check that x is not 'undefined'
t[x] ? // is there a value in t at position x?
( // yes, remove the pair
n-=2, // pair found, decrement counter
[c, p] = t[x], // get stored array and position
p ? c.pop() : c.shift(), // remove from c at start or end
q ? b.pop() : b.shift() // remove twin value from b
)
: // no, remember the value in t
t[x] = [b, q]
)) // end [0,1].forEach
) // end part.forEach
}
while (c) // repeat until nothing can be removed
if(!n) return 1 // wow, result found (in 'result' variable)
```
Then, the missing part is just a loop caling the G function increasing the partition count. The loop exit when a result is found.
*Put it all together*
```
F=a=>{
G=(v,i,u=v)=>{
if (i--)
{
for(; r[i]=--u; )
if (G(u,i))
return 1;
}
else
{
w = [...r,n=l].map((x,i)=>a.slice(z, z = x-~i), z = 0);
y = w.join`;`;
for(; // almost all the for body is inside the condition
w.map(b=>
[0,1].map(q=>
(x=b[q*=~-b.length])
&&(t[x]
?([c,p]=t[x],n-=2,
p?c.pop():c.shift(),
q?b.pop():b.shift())
:t[x]=[b,q])) // end [0,1].map
,c=0,t=[] // init variables for w.map
),c; // the loop condition is on c
)
if(!n)return 1 // this is the for body
}
};
for(l = a.length, r = [], k = 0; !G(l-k-1, k); k++);
return y
}
```
**Test**
```
F=a=>{G=(v,i,u=v)=>{if(i--){for(;r[i]=--u;)if(G(u,i))return 1;}else for(w=[...r,n=l].map((x,i)=>a.slice(z,z=x-~i),z=0),y=w.join`;`;w.map(b=>[0,1].map(q=>(x=b[q*=~-b.length])&&(t[x]?([c,p]=t[x],n-=2,p?c.pop():c.shift(),q?b.pop():b.shift()):t[x]=[b,q])),c=0,t=[]),c;)if(!n)return 1};for(l=a.length,r=[],k=0;!G(l-k-1,k);k++);return y}
console.log=x=>O.textContent+=x+'\n'
TestData=[[1,1],[1,2,1,2],[1,3,2,4,3,2,1,4],[1,2,3,4,3,4,1,2],[1,1,2,2,3,3],[4,3,4,2,2,1,1,3]]
TestData.forEach(t=>console.log(t+' -> '+F(t)))
function RandomTest() {
var l=I.value*2
var a=[...Array(l)].map((_,i)=>1+i/2|0)
a.map((v,i)=>a[a[i]=a[j=0|i+Math.random()*(a.length-i)],j]=v) // shuffle
Q.textContent=a+''+'\n\n'+F(a).replace(/;/g, ';\n') // better readability
}
```
```
Base test
<pre id=O></pre>
Random test. Number of pairs: <input id=I value=15><button onclick="RandomTest()">-></button>
<pre id=Q></pre>
```
] |
[Question]
[
Given a list of integer coordinates, find the area of the biggest [convex polygon](https://en.wikipedia.org/wiki/Convex_polygon) you can construct from the list such that -
* every vertex is in the list
* no element of the list is contained within the polygon.
Example:
>
> (0, 0) (8, 0) (0, 1) (3, 1) (7, 1) (1, 2) (5, 2) (9, 2) (2, 3) (5, 3) (7, 3) (3, 4) (5, 5) (11, 5)
>
>
>
Visualized:
```
o o
o o o
o o o
o o o
o
o o
```
The biggest convex polygon you can make from this is this:
```
o
o o
o o
o o
o
o
```
With an area of 12.
---
You may take the list of coordinates in any reasonable format, and should output (in an appropriate way for your language of choice) the area of the largest convex polygon, rounded to no less than 2 digits after the decimal point.
Additionally, you must employ some sort of algorithm, and not simply brute force all subsets of the points. To enforce this, your program must solve a list of 50 vertices in under a minute on a modern PC.
**Shortest code in bytes wins.**
[Answer]
# Javascript ES6, 738 bytes
```
((V,C,L,r,k,n,A,G,F,e,i,j,q)=>p=>{p=p.map((p,i)=>({i:i,x:p[0],y:p[1]}));A=(f,p,a,b,v,i)=>{for(i=p[n],v=V(a,b);i--;)if(f(v,V(a,p[i])))return 1};G=(p,i,a)=>{for(i=p[n]-1,a=C(p[i],p[0]);i--;)a+=C(p[i],p[i+1]);if((a/=2)>r)r=a};F=(p,s,l,f,a,b,v)=>(l=s[n],f=s[0],a=s[l-2],b=s[l-1],e[a.i][b.i]||A((a,b)=>C(a,b)?0:a.x<0==b.x<0&&a.y<0==b.y<0&&L(a)>L(b),p,a,b)?0:(p=(v=V(a,b),p[k](x=>C(v,V(a,x))>=0)),A((a,b)=>C(a,b)>0,p,b,f)?0:(p.map(q=>F(p[k](r=>q!==r),[...s,q])),s[2]&&!p[n]&&!e[b.i][f.i]?G(s):0)));e=p.map(x=>p.map(y=>x===y));for(i=p[n];i--;){for(j=i;j--;){q=p[k]((p,x)=>x-i&&x-j);F(q,[p[i],p[j]]);F(q,[p[j],p[i]]);e[i][j]=e[j][i]=1}}console.log(r)})((a,b)=>({x:b.x-a.x,y:b.y-a.y}),(a,b)=>a.x*b.y-a.y*b.x,v=>v.x*v.x+v.y*v.y,0,'filter','length')
```
Here's an ES5 or less version that should work in most browsers and node without tweaking: **827 bytes**
```
eval("(%V,C,L,r,k,n,A,G,F,e,i,j,q){@%p){p=p.map(%p,i){@{i:i,x:p[0],y:p[1]}});A=%f,p,a,b,v,i){for(i=p[n],v=V(a,b);i--;)if(f(v,V(a,p[i])))@1};G=%p,i,a){for(i=p[n]-1,a=C(p[i],p[0]);i--;)a+=C(p[i],p[i+1]);if((a/=2)>r)r=a};F=%p,s,l,f,a,b,v){@(l=s[n],f=s[0],a=s[l-2],b=s[l-1],e[a.i][b.i]||A(%a,b){@C(a,b)!=0?0:a.x<0==b.x<0&&a.y<0==b.y<0&&L(a)>L(b)},p,a,b)?0:(p=(v=V(a,b),p[k](%x){@C(v,V(a,x))>=0})),A(%a,b){@C(a,b)>0},p,b,f)?0:(p.forEach(%q){@F(p[k](%r){@q!==r}),s.concat([q]))}),s[2]&&p[n]==0&&!e[b.i][f.i]?G(s):0)))};e=p.map(%x,i){@p.map(%y,j){@i==j})});for(i=p[n];i--;){for(j=i;j--;){q=p[k](%p,x){@x!=i&&x!=j});F(q,[p[i],p[j]]);F(q,[p[j],p[i]]);e[i][j]=e[j][i]=1}}console.log(r)}})(%a,b){@{x:b.x-a.x,y:b.y-a.y}},%a,b){@a.x*b.y-a.y*b.x},%v){@v.x*v.x+v.y*v.y},0,'filter','length')".replace(/%/g,'function(').replace(/@/g,'return '))
```
Code returns an anonymous function. As a parameter, it takes an array of points, like `[[0,1],[2,3],[4,5]]`. To use it you can place `var f=` before it, or if you want to use it from the command line, add `(process.argv[2].replace(/ /g,'').slice(1,-1).split(')(').map((x)=>x.split(',')))` to the end, and call it like `node convpol.js '(1,2)(3,4)(5,6)'`
Thanks for the challenge! As there is no reference implementation, I can't prove this is correct, but it is consistent at least for permutations of the point list. I almost didn't think this was going to work, as versions with debugging code, even disabled, were way too slow with exponential time increase. I decided to golf it anyway, and was pleased to see that it dropped down to under 2 seconds for 50 points on my machine. It can calculate approximately 130 points in 1 minute.
The algorithm is similar to the [Graham scan](https://en.wikipedia.org/wiki/Graham_scan), except that it has to search for empty convex hulls everywhere.
### Explanation
Here's a high-level overview of how the algorithm works. The meat of this algorithm is just searching for counter-clockwise convex loops that don't enclose a point. The procedure is something like this:
1. Start with a pair of points, and a list of all other points.
2. If the current pair of points goes exactly through any point in the list, stop.
3. Filter out all points clockwise of the current pair, since they would make the polygon concave.
4. For all points left, do the following:
1. If a line from this point to the first point of the chain goes through or encloses any points counter-clockwise, skip this point, since any polygons would enclose the point.
2. Add this point to the chain, recurse from step 1 with the current chain and list of points.
5. If there were no points left, and the chain has at least 3 points, this is a valid convex polygon. Remember the largest area of these polygons.
Also, as an optimization, we record the initial pair of the chain as checked, so any searches afterwards upon seeing this pair anywhere in the chain can immediately stop searching, since the largest polygon with this pair has already been found.
This algorithm should never find a polygon twice, and I've experimentally verified this.
] |
[Question]
[
## Challenge
Given a (floating-point/decimal) number, return its reciprocal, i.e. 1 divided by the number. The output must be a floating-point/decimal number, not just an integer.
### Detailed specification
* You must receive input in the form of a floating-point/decimal number...
+ ...which has at least 4 significant digits of precision (if needed).
+ More is better, but does not count in the score.
* You must output, with any acceptable output method...
+ ...the reciprocal of the number.
+ This can be defined as 1/x, x⁻¹.
+ You must output with at least 4 significant digits of precision (if needed).
Input will be positive or negative, with absolute value in the range [0.0001, 9999] inclusive. You will never be given more than 4 digits past the decimal point, nor more than 4 starting from the first non-zero digit. Output needs to be accurate up to the 4th digit from the first non-zero one.
(Thanks @MartinEnder)
Here are some sample inputs:
```
0.5134
0.5
2
2.0
0.2
51.2
113.7
1.337
-2.533
-244.1
-0.1
-5
```
Note that you will never be given inputs which have above 4 digits of precision.
Here is a sample function in Ruby:
```
def reciprocal(i)
return 1.0 / i
end
```
## Rules
* All accepted forms of output are allowed
* Standard loopholes banned
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer in bytes wins, but will not be selected.
### Clarifications
* You will never receive the input `0`.
## Bounties
This challenge is obviously trivial in most languages, but it can offer a fun challenge in more esoteric and unusual languages, so some users are willing to award points for doing this in unusually difficult languages.
* ~~[@DJMcMayhem](https://codegolf.stackexchange.com/users/31716/djmcmayhem) will award a **+150 points** bounty to the shortest brain-flak answer, since brain-flak is notoriously difficult for floating-point numbers~~
* [@L3viathan](https://codegolf.stackexchange.com/users/21173/l3viathan) will award a **+150 points** bounty to the shortest [OIL](https://github.com/L3viathan/OIL) answer. OIL has no native floating point type, nor does it have division.
* [@Riley](https://codegolf.stackexchange.com/users/57100/riley) will award a **+100 points** bounty to the shortest sed answer.
* [@EriktheOutgolfer](https://codegolf.stackexchange.com/users/41024/erik-the-outgolfer) will award a **+100 points** bounty to the shortest Sesos answer. Division in brainfuck derivatives such as Sesos is very difficult, let alone floating-point division.
* ~~I ([@Mendeleev](https://codegolf.stackexchange.com/users/53551/Mendeleev)) will award a bounty of **+100 points** to the shortest Retina answer.~~
If there's a language you think would be fun to see an answer in, and you're willing to pay the rep, feel free to add your name into this list (sorted by bounty amount)
## Leaderboard
Here is a Stack Snippet to generate an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=114544,OVERRIDE_USER=62393;function answersUrl(e){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(e,s){return"https://api.stackexchange.com/2.2/answers/"+s.join(";")+"/comments?page="+e+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){answers.push.apply(answers,e.items),answers_hash=[],answer_ids=[],e.items.forEach(function(e){e.comments=[];var s=+e.share_link.match(/\d+/);answer_ids.push(s),answers_hash[s]=e}),e.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(e){e.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),e.has_more?getComments():more_answers?getAnswers():process()}})}function getAuthorName(e){return e.owner.display_name}function process(){var e=[];answers.forEach(function(s){var r=s.body;s.comments.forEach(function(e){OVERRIDE_REG.test(e.body)&&(r="<h1>"+e.body.replace(OVERRIDE_REG,"")+"</h1>")});var a=r.match(SCORE_REG);a&&e.push({user:getAuthorName(s),size:+a[2],language:a[1],link:s.share_link})}),e.sort(function(e,s){var r=e.size,a=s.size;return r-a});var s={};e.forEach(function(e){var o=e.language;/<a/.test(o)&&(o=jQuery(o).text().toLowerCase()),s[o]=s[o]||{lang:e.language,user:e.user,size:e.size,link:e.link,uniq:o}});var t=[];for(var o in s)s.hasOwnProperty(o)&&t.push(s[o]);t.sort(function(e,s){return e.uniq>s.uniq?1:e.uniq<s.uniq?-1:0});for(var c=0;c<t.length;++c){var i=jQuery("#language-template").html(),o=t[c];i=i.replace("{{LANGUAGE}}",o.lang).replace("{{NAME}}",o.user).replace("{{SIZE}}",o.size).replace("{{LINK}}",o.link),i=jQuery(i),jQuery("#languages").append(i)}}var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;getAnswers();var SCORE_REG=/<h\d>\s*([^\n,]*[^\s,]),.*?(\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/,OVERRIDE_REG=/^Override\s*header:\s*/i;
```
```
body{text-align:left!important}#language-list{padding:10px;width:290px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/codegolf/all.css?v=617d0685f6f3"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~772~~ ~~536~~ ~~530~~ ~~482~~ 480 + 1 = 481 bytes
Since Brain-Flak does not support floating point numbers I had to use the `-c` flag in order input and output with strings, hence the +1.
```
(({})[((((()()()()())){}{})){}{}]){((<{}>))}{}({}<{({}[((((()()()){}())()){}{}){}]<>)<>}<>{({}<>[()()])<>}{}([]<{({}<>[()()])<>}>)<>([[]](())){({}()<((((((({}<(((({})({})){}{}){}{})>)({})){}{}){})({})){}{}){})>)}{}({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>){({}<((()()()()()){})>(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><([{}()]{})>)}{}<>({}()<<>([]){{}({}<>)<>([])}{}<>>){({}[()]<({}<>((((()()()){}){}){}){})<>>)}{}([()()])([]){{}({}<>((((()()()){}){}){}){})<>([])}<>>)
```
[Try it online!](https://tio.run/nexus/brain-flak#lVBBDsMwCPuOOXTqbRfERyJO2y@ivL0z0GzNpB2WtlQB23F8AH1IQyyZj0gf7GZ16YD2YSLcEayd5UIgigUnhwQ1URtqgVNrgfHoENdcv7sBRmvuyHMRaopaRNZPMO1UsaWxbuz0CfpIbR7UUzNRaX4aik9Ng2o50iWGUPtDBi3M@/RAUl4myEyxwqvres3traM5W0L9vAHM9Cq0q9pPRp4RxOPY7rd9P7bn4wU "Brain-Flak – TIO Nexus")
# Explanation
The first thing we need to take care of is the negative case. Since the reciprocal of a negative number is always negative we can simply hold on to the negative sign until the end. We start by making a copy of the top of the stack and subtracting 45 (the ASCII value of `-`) from it. If this is one we put a zero on the top of the stack, if not we do nothing. Then the we pick up the top of the stack to be put down at the end of the program. If the input started with a `-` this is still a `-` however if it is *not* we end up picking up that zero we placed.
```
(({})[((((()()()()())){}{})){}{}]){((<{}>))}{}
({}<
```
Now that that is out of the way we need to convert the ASCII realizations of each digit into there actual values (0-9). We also are going to remove the decimal point `.` to make computations easier. Since we need to know where the decimal point started when we reinsert it later we store a number to keep track of how many digits were in front of the `.` on the offstack.
Here is how the code does that:
We start by subtracting 46 (the ASCII value of `.`) from each element on the stack (simultaneously moving them all onto the offstack). This will make each digit two more than should be but will make the `.` exactly zero.
```
{({}[((((()()()){}())()){}{}){}]<>)<>}<>
```
Now we move everything onto the left stack until we hit a zero (subtracting two from each digit while we go):
```
{({}<>[()()])<>}{}
```
We record the stack height
```
([]<
```
Move everything else onto the left stack (once again subtracting the last two from every digit as we move them)
```
{({}<>[()()])<>}
```
And put the stack height we recorded down
```
>)
```
Now we want to combine the digits into a single base 10 number. We also want to make a power of 10 with twice the digits as that number for use in the calculation.
We start by setting up a 1 on top of the stack to make the power of 10 and pushing the stack height minus one to the on stack for the use of looping.
```
<>([][(())])
```
Now we loop the stack height minus 1 times,
```
{
({}[()]<
```
Each time we multiply the top element by 100 and underneath it multiply the next element by 10 and add that to the number below.
```
((((((({}<(((({})({})){}{}){}{})>)({})){}{}){})({})){}{}){})
```
We end our loop
```
>)
}{}
```
Now we are finally done with the set up and can begin the actual calculation.
```
({}(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><{}{}>)
```
That was it...
We divide the power of 10 by the modified version of the input using [0 '](https://codegolf.stackexchange.com/users/20059/millet-mage)'s integer division algorithm as found on [the wiki](https://github.com/DJMcMayhem/Brain-Flak/wiki/Basic-Arithmetic-Operations). This simulates the division of 1 by the input the only way Brain-Flak knows how.
Lastly we have to format our output into the appropriate ASCII.
Now that we have found `ne` we need to take out the `e`. The first step to this is converting it to a list of digits. This code is a modified version of [0 '](https://codegolf.stackexchange.com/users/20059/)'s [divmod algorithm](https://codegolf.stackexchange.com/a/114321/56656).
```
{({}<((()()()()()){})>(<>))<>([()]{()<(({})){({}[()])<>}{}>}{}<><([{}()]{})>)}{}
```
Now we take the number and add the decimal point back where it belongs. Just thinking about this part of the code brings back headaches so for now I will leave it as an exercise for the reader to figure out how and why it works.
```
<>({}()<<>([]){{}({}<>)<>([])}{}<>>){({}[()]<({}<>((((()()()){}){}){}){})<>>)}{}([()()])([]){{}({}<>((((()()()){}){}){}){})<>([])}<>
```
Put the negative sign down or a null character if there is no negative sign.
```
>)
```
[Answer]
# [Python 2](https://docs.python.org/2/), 10 bytes
```
1..__div__
```
[Try it online!](https://tio.run/nexus/python2#S1OwVYj5b6inFx@fklkWH/@/oCgzr0QjTcNcU/M/AA "Python 2 – TIO Nexus")
[Answer]
## [Retina](https://github.com/m-ender/retina), ~~99~~ 91 bytes
```
1`\.|$
8$*;
+`;(;*)(\d)
$2$1
\d+
$*1,10000000$*
(1+),(\1)+1*
$#2
+`(\d)(;+);
$2$1
1`;
.
;
0
```
[Try it online!](https://tio.run/nexus/retina#JYu7DcMwEEN7rhEF0Mc@iCcrdnADZAkVKjJGdnfOMIv3WJDP@Jkn55BfwBGyoUyLllMc34SggRjfgpC5sN4JGZElLXEwFWaEh/rp2kcrye4Tp0FgqOdZpbNtcEGhUr0pOh1kkx2U1pzqm1Wlt@baNiHWeqFffh/76w8 "Retina – TIO Nexus")
Woohoo, sub-100! This is surprisingly efficient, considering that it creates (and then matches against) a string with more than 107 characters at one point. I'm sure it's not optimal yet, but I'm quite happy with the score at the moment.
Results with absolute value less than 1 will be printed without the leading zero, e.g. `.123` or `-.456`.
### Explanation
The basic idea is to using integer division (because that's fairly easy with regex and unary arithmetic). To ensure that we get a sufficient number of significant digits, we divide the input into **107**. That way, any input up to **9999** still results in a 4-digit number. Effectively, that means we're multiplying the result by **107** so we need to keep track of that when later reinsert the decimal point.
```
1`\.|$
8$*;
```
We start by replacing the decimal point, or the end of the string if there is no decimal point with 8 semicolons. The first one of them is essentially the decimal point itself (but I'm using semicolons because they don't need to be escaped), the other 7 indicate that value has been multiplied by **107** (this isn't the case yet, but we know we will do that later).
```
+`;(;*)(\d)
$2$1
```
We first turn the input into an integer. As long as there are still digits after the decimal point, we move one digit to the front and remove one of the semicolons. This is because moving the decimal point right multiplies the input by **10**, and therefore divides the result by **10**. Due to the input restrictions, we know this will happen at most four times, so there are always enough semicolons to be removed.
```
\d+
$*1,10000000$*
```
Now that the input is an integer, we convert it to unary and append **107** `1`s (separated by a `,`).
```
(1+),(\1)+1*
$#2
```
We divide the integer into **107** by counting how many backreferences to it fit (`$#2`). This is standard unary integer division `a,b` --> `b/a`. Now we just need to correct the position of the decimal point.
```
+`(\d)(;+);
$2$1
```
This is basically the inverse of the second stage. If we still have more than one semicolon, that means we still need to divide the result by **10**. We do this by moving the semicolons one position to the left and dropping one semicolon until we either reach the left end of the number, or we're left with only one semicolon (which is the decimal point itself).
```
1`;
.
```
Now is a good time to turn the first (and possibly only) `;` back into `.`.
```
;
0
```
If there are still semicolons left, we've reached the left end of the number, so dividing by 10 again will insert zeros behind the decimal point. This is easily done by replacing each remaining `;` with a `0`, since they're immediately after the decimal point anyway.
[Answer]
# [yup](https://github.com/ConorOBrien-Foxx/yup), 5 bytes
```
|0~-e
```
[Try it online!](https://tio.run/nexus/yup#0/pfY1Cnm/pf@f9/3bz/RgA "yup – TIO Nexus") This takes input from the top of the stack and leaves output on the top of the stack. The TIO link takes input from command line arguments, which is only capable of taking integer input.
## Explanation
yup only has a few operators. The ones used in this answer are **ln**(x) (represented by `|`), **0**() (constant, nilary function returning `0`), **−** (subtraction), and **exp**(x) (represented by `e`). `~` switches the top two members on the stack.
```
|0~-e top of the stack: n stack: [n]
| pop n, push ln(n) stack: [ln(n)]
0 push 0 stack: [ln(n), 0]
~ swap stack: [0, ln(n)]
- subtract stack: [-ln(n)]
e exp stack: [exp(-ln(n))]
```
This uses the identity
[](https://i.stack.imgur.com/KrP3L.gif)
which implies that
[](https://i.stack.imgur.com/w5l7r.gif)
[Answer]
# [LOLCODE](http://lolcode.org/), ~~63~~, 56 bytes
```
HOW DUZ I r YR n
VISIBLE QUOSHUNT OF 1 AN n
IF U SAY SO
```
7 bytes saved thanks to @devRicher!
This defines a function 'r', which can be called with:
```
r 5.0
```
or any other `NUMBAR`.
[Try it online!](https://repl.it/Gn1P/1)
[Answer]
# [sed](https://www.gnu.org/software/sed/), 575 + 1 (`-r` flag) = ~~723~~ ~~718~~ ~~594~~ ~~588~~ 576 bytes
```
s/$/\n0000000000/
tb
:b
s/^0+//
s/\.(.)(.*\n)/\1.\2/
tD
bF
:D
s/.*/&&&&&&&&&&/2m
tb
:F
s/\.//
h
s/\n.+//
s/-//
:
s/\b9/;8/
s/\b8/;7/
s/\b7/;6/
s/\b6/;5/
s/\b5/;4/
s/\b4/;3/
s/\b3/;2/
s/\b2/;1/
s/\b1/;0/
s/\b0//
/[^;]/s/;/&&&&&&&&&&/g
t
y/;/0/
x
G
s/[^-]+(\n0+)\n(0+)/\2\1/
s/\n0+/&&\n./
:a
s/^(-?)(0*)0\n0\2(.*)$/\10\2\n\30/
ta
s/.*/&&&&&&&&&&/2m
s/\n0(0*\n\..*)$/\n\1 x/
Td
s/x//
ta
:d
s/[^-]+\n//
s/-(.+)/\1-/
s/\n//
:x
s/^0{10}/0x/
s/(.)0{10}/0\1/
tx
s/00/2/g
s/22/4/g
y/0/1/
s/41/5/g
s/21/3/g
s/45/9/g
s/44/8/g
s/43/7/g
s/42/6/g
y/ /0/
s/([1-9])0/\1/g
y/x/0/
s/(.+)-/-\1/
```
[Try it online!](https://tio.run/nexus/sed#bVG7bhsxEOz3K1wExp2E5ZK8t1ikMZwfSCdKgM4OYhehgpyKM4J8dtooQ65jpDABknO7O3uzw@siHyQm@7aELjPtZlrkaLciuKOpTF2ZTUy1RGeiR8kdzfe0u0PWbOT2bYn/Vuj3hQb2UwbJaCPGucuBeZIwltbzKGFQNEjoFfUSOkWdhFZRK6FR1EjwirwEp8hJsIos/iH7YzjIIuF/ZV/pQi8IoW6lT6jdH/mwrTD6to6pwinRR@2HGKjQDb2n7ETFH@vKbmqLVPTwooZpDjCm2GTLTu85UTqBhiKjlBTdzSr0@RG5VQpv9/hPS0zqUmWyFscqJXu2ltf46ewvsWsO40FeP7PiS87j5TyGXMR7aQFeMGmZpnXSacJJU0DbyaSglVFBI4MCL30h30gxtNo7ng61hZ4SXl/DkMjCCF6v7ExD7PK2xBPxSDwQ98QdcUuMhEeO2OAy@bYdle0IIUeeGmqpo54GGmkitEE3dP1z/n55Pqflyj9@pzM/nB6evvwF "sed – TIO Nexus")
Note: floats for which the absolute value is less than 1 will have to be written without a leading 0 like `.5` instead of `0.5`. Also the number of decimal places is equal to [](https://i.stack.imgur.com/VgXZk.gif), where `n` is the number of decimal places in the number (so giving `13.0` as input will give more decimal places than giving `13` as input)
This is my first sed submission on PPCG. Ideas for the decimal-to-unary conversion were taken from [this amazing answer](https://codegolf.stackexchange.com/a/51329/41805). Thanks to @seshoumara for guiding me through sed!
This code performs repeated long division to get the result. The division only takes ~150 bytes. The unary-decimal conversions take the most bytes, and a few other bytes go to supporting negative numbers and floating-point inputs
### Explanation
[Explanation on TIO](https://tio.run/nexus/sed#hVRtb9s2EP5@v@IQD6ucRKIk23mxsA3r3BQG1nTYun2JEoCSGJuITAoindgr@teXHUnbSYABE2zpeOS9PXzungc/d51QDWYppu9Mgl@W0iD97FJgIx9lQ5unOKe1VA9g2HesVOnhYWArgIE3qnqu6iWu9KPYmYtarniLnZbKYoZWe3UvF0sL0woGvwt3GFvBG6kWLj5GZk0@uMH7Xq9QrVeV6A228kFgkk7whx8xTSZDyuMuPWEMBp@cg/8NZliZRMkwSo5LNWRllpQ52c7v/RFeOR9LitkLs26taFAq5EiZ1MKY@3VLYmWstGsrtTrFhXbed@XOwM5gIFoj3uqvoLoiZD6RQ9m12zd4YrUlvAvkrdH4IEQX8Fpp3VD@Rlr5KGA6o7STY/b94WH5ykEtlItU8frhVbjKX8T06gDqWzyMVLVAad3N8rb14Z749g1KqPSTR4pwXR78HK2VEg4H3m@PPAsWxp1SicPfsJjeMPhFq0fRW@dvregkTN2Z6pIVF8xLF6w4D9I5K86CdMaKSZAmrBgHacyKUZBGrMiDlLMiC1LGijRIKYVlN3fFLTOseI3RAixsSZW6tHbcdiX6tHaE2pfdcWtFr9B0vBawgY/k@uYuvj2JiOMnw1JF9GZlXmbO2WCAH65nOAvAxlbHf3qfta/dEDX8mfcfPs6vcUZX7VUw@E3097pfGfxVE8kPG4MrUnKLrdYPBo1eCQ9u4Lp1DRXVXL2zxMqVcFkPp55ARvel2jOpVLVeK1uqQF13EbR0KdletwaX@glXXG1f6NBSqYFuXJknwsIs9bptiP@PosCmcy2WpXcE1EwupDWRGu65YPbxQ3Me2MwDxNQzDS0wdfDu8/nsePeW@6KmWikFrdFQSu0p8nBNPFzEi7n33Acecvxb9DpE9jVTVlIZsTvTCe7bnO6N2EDsZDDlbkxE8U/DKD0eprRV5jQBhjTBMhJLVY7c/OL/1WbeE5nRoSSYqDLDDYMvDe1tmLd7ocT8r/kf88/Xr@7fU8NxZEeX1yyBabMnWqlCE0WJI1oWe3Ir31JHNe@JXVR7fxQTMQoagIcnDEKYbvwk/Jql31i6ccY05XZLR1q7edWbgtOc6LjsUd/v2iE1u1YgZXNIlMAVfcd76xqdZnxOTWVYnrMxCVvqLN@N44xNwkbGRl4YT9hlEMbsIggjdh6EnJ15Y2S@gaObLL68HaZUs1dvdmqCIWYxKZ@f4ywZQZylEF9CfAHxOcRnEE8gHkNMGzntQZzQJ3HfdAL@nwGpMshhBGOYwBmcwwVcArkhd//ozk1w8xz3/wI "sed – TIO Nexus")
```
#Append 10 0's. This is the dividend, I think
s/$/\n0000000000/
tb
#This branch moves the decimal point 1 to the right
:b
#Remove leading 0's (such as from numbers like .05 => 0.5)
s/^0+//
#Move the decimal point 1 to the right
s/\.(.)(.*\n)/\1.\2/
#If the above has resulted in a successful substitution, go to branch D
tD
#else go to branch F
bF
#Multiply the dividend by 10; also keeps the mood positive
:D
s/.*/&&&&&&&&&&/2m
#Then go back to branch b
tb
:F
#Remove decimal point since it is all the way to the right now
s/\.//
h
#Remove "unnecessary" things
s/\n.+//
s/-//
#Convert to unary
:
s/\b9/;8/
s/\b8/;7/
s/\b7/;6/
s/\b6/;5/
s/\b5/;4/
s/\b4/;3/
s/\b3/;2/
s/\b2/;1/
s/\b1/;0/
s/\b0//
/[^;]/s/;/&&&&&&&&&&/g
t
y/;/0/
#Append the unary number to the pattern space
x
G
s/[^-]+(\n0+)\n(0+)/\2\1/
### END Decimal-to-Unary conversion
### BEGIN Division
#Performs Long Division
#Format looks something like this (can't remember): divisor\ndividend\ncount\nresult
#Count controls how many decimal places the answer should have; dp => 10^numDigits(n)
#Removes divisor from dividend and then add a 0 to result
#Once the dividend becomes too small, append a space to result and remove a zero from count
#Rinse and repeat
s/\n0+/&&\n./
:a
s/^(-?)(0*)0\n0\2(.*)$/\10\2\n\30/
ta
s/.*/&&&&&&&&&&/2m
s/\n0(0*\n\..*)$/\n\1 x/
Td
s/x//
ta
### END DIVISION
### BEGIN Unary-to-Decimal conversion
:d
s/[^-]+\n//
s/-(.+)/\1-/
s/\n//
#"carry over"-ing; .0000000000 => 0.
:x
s/^0{10}/0x/
s/(.)0{10}/0\1/
tx
#Convert each pair of unary 0s to their decimal counterparts
s/00/2/g
s/22/4/g
y/0/1/
s/41/5/g
s/21/3/g
s/45/9/g
s/44/8/g
s/43/7/g
s/42/6/g
y/ /0/
s/([1-9])0/\1/g
y/x/0/
s/(.+)-/-\1/
```
### Edits
* `s:s/(.)/(.)/g:y/\1/\2/g:g` to save 1 byte at each substitution (5 in total)
* Saved a ton of bytes by looking at a nice decimal-to-unary converter on "Tips for golfing in sed"
* I changed around some substitutions revolved around taking care of the minus sign to save 6 bytes.
* Used `\n` instead of `;` as the separator, then I was able to shorten the "multiply by 10" substitutions to save 12 bytes (thanks to @Riley and @seshoumara for showing me this)
[Answer]
# [OIL](https://github.com/L3viathan/OIL), ~~1428~~ 1420 bytes
Oh well. I thought I might as well try it, and I did in the end succeed. There's just one downside: It takes almost as long to run as it took to write.
The program is separated into multiple files, which have all 1-byte-filenames (and count for one additional byte in my byte calculation). Some of the files are part of the example files of the OIL language, but there's no real way to consistently call them (there's no search path or anything like that in OIL yet, so I don't consider them a standard library), but that also means that (at the time of posting) some of the files are more verbose than neccessary, but usually only by a few bytes.
The computations are accurate to 4 digits of precision, but calculating even a simple reciprocal (such as the input `3`) takes a really long time (over 5 minutes) to complete. For testing purposes, I've also made a minor variant that's accurate to 2 digits, which takes only a few seconds to run, in order to prove that it does work.
I'm sorry for the huge answer, I wish I could use some kind of spoiler tag. I could also put the bulk of it on gist.github.com or something similar, if desired.
Here we go: `main`, 217 bytes (file name doesn't count for bytes):
```
5
1
1
4
-
14
a
5
Y
10
5
8
14
29
12
1
97
1
97
24
9
24
13
99
1
1
4
31
1
35
14
a
32
.
10
32
8
50
41
1
53
2
14
b
1
1
6
72
14
c
5
0000
14
d
6
6
10
74
5
63
68
1
6
1
6
72
14
b
1
5
1
77
0
14
e
1
0
14
f
1
1
1
31
0
14
b
0
0
4
```
`a` (checks if a given string is in a given other string), 74+1 = 75 bytes:
```
5
0
5
1
14
g
2
0
10
2
30
24
13
10
1
31
27
18
14
h
1
1
6
4
4
30
3
4
29
N
Y
```
`b` (joins two given strings), 20+1=21 bytes:
```
5
0
5
1
13
0
2
0
4
0
```
`c` (given a symbol, splits the given string at its first occurrence), 143+1=144 bytes (this one is obviously still golfable):
```
5
0
5
83
12
83
83
10
84
0
21
17
8
13
6
12
1
13
1
1
5
2
14
i
45
1
1
83
1
1
45
2
14
i
57
1
9
45
13
84
1
8
13
1
13
56
13
13
2
4
1
11
4
2
```
`d` (given a string, gets the first 4 characters), 22+1=23 bytes:
```
5
0
12
0
20
13
21
4
4
```
`e` (high-level division (but with zero division danger)), 138+1=139 bytes:
```
5
0
5
1
.
.
1
1
6
14
j
0
0
1
0
4
10
11
1
58
21
14
b
4
4
1
1
15
14
k
0
15
1
6
1
14
j
0
0
1
0
5
14
b
4
4
9
8
10
8
11
58
53
10
11
1
58
25
4
4
```
`f` (moves a dot 4 positions to the right; "divides" by 10000), 146+1=147 bytes:
```
5
.
12
0
100
10
101
1
14
10
8
6
6
5
1
6
34
1
6
33
8
33
1
6
37
8
37
10
55
3
48
32
1
102
101
1
1
102
9
55
8
34
8
33
8
37
6
27
1
100
53
13
101
4
4
```
`g` (checks if a string starts with a given character), 113+1=114 bytes:
```
5
0
5
1
12
0
100
12
1
200
1
6
2
1
9
3
8
2
8
3
9
100
9
200
1
2
31
1
3
32
10
39
35
4
38
3
N
10
100
5
44
16
4
46
Y
```
`h` (returns everything but the first character of a given string), 41+1=42 bytes:
```
5
0
12
0
100
9
100
1
100
12
13
102
0
4
0
```
`i` (subtracts two numbers), 34+1=35 bytes:
```
5
0
5
1
10
16
1
14
9
9
0
9
1
6
4
0
```
`j` (low-level division that doesn't work in all cases), 134+1=135 bytes:
```
5
0
5
2
10
2
19
52
9
1
2
3
10
23
2
28
17
10
23
0
35
22
9
0
9
2
6
12
8
1
1
3
2
6
17
10
23
2
46
40
9
2
9
3
6
35
4
1
11
4
3
3
4
19
11
4
0
```
`k` (multiplication), 158+1=159 bytes:
```
5
0
5
1
8
0
9
0
8
1
9
1
1
5
2
12
0
68
10
69
66
23
29
8
7
14
l
0
0
12
1
68
10
69
66
37
43
8
7
14
l
1
1
10
0
5
56
48
9
0
14
m
2
1
6
43
10
7
3
61
63
4
66
4
2
3
-
```
`l` (return absolute value), 58+1=59 bytes:
```
5
-
12
0
24
10
25
1
13
10
4
0
3
9
24
1
24
20
13
26
0
6
10
```
`m` (addition), 109+1=110 bytes:
```
5
0
5
1
8
0
9
0
8
1
9
1
12
1
46
10
47
45
31
20
10
1
43
42
25
9
1
8
0
6
20
10
1
43
42
36
8
1
9
0
6
31
4
0
3
-
```
[Answer]
# [JSFuck](http://www.jsfuck.com), 3320 bytes
JSFuck is an esoteric and educational programming style based on the atomic parts of JavaScript. It uses only six different characters `()[]+!` to write and execute code.
```
[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]][([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]])+[])[!+[]+!+[]]+[+!+[]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+(!![]+[])[+[]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+!+[]])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]+!+[]])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]]
```
### Try it online!
```
alert(
/* empty array */ []
/* ['fill'] */ [(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]]
/* ['constructor'] */ [([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]]
/* ('return+1/this') */ ((!![]+[])[+!+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+([][[]]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+!+[]]+(+(+!+[]+(!+[]+[])[!+[]+!+[]+!+[]]+[+!+[]]+[+[]]+[+[]])+[])[!+[]+!+[]]+[+!+[]]+(![]+[+![]])[([![]]+[][[]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[!+[]+!+[]+!+[]]]()[+!+[]+[+[]]]+(!![]+[])[+[]]+(+(+!+[]+[+[]]+[+!+[]]))[(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(+![]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(+![]+[![]]+([]+[])[([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+([][[]]+[])[+!+[]]+(![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[+!+[]]+([][[]]+[])[+[]]+([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]])[+!+[]+[+[]]]+(!![]+[])[+!+[]]])[!+[]+!+[]+[+[]]]](!+[]+!+[]+[+!+[]])[+!+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]+!+[]])
/* ['call'] */ [([][(![]+[])[+[]]+([![]]+[][[]])[+!+[]+[+[]]]+(![]+[])[!+[]+!+[]]+(!![]+[])[+[]]+(!![]+[])[!+[]+!+[]+!+[]]+(!![]+[])[+!+[]]]+[])[!+[]+!+[]+!+[]]+(![]+[])[+!+[]]+(![]+[])[!+[]+!+[]]+(![]+[])[!+[]+!+[]]]
(prompt())
)
```
[Answer]
## J, 1 byte
```
%
```
`%` is a function giving the reciprocal of its input. You can run it like this
```
% 2
0.5
```
[Answer]
# [Taxi](https://bigzaphod.github.io/Taxi/), 467 bytes
```
Go to Starchild Numerology:w 1 l 2 r 1 l 1 l 2 l.1 is waiting at Starchild Numerology.Pickup a passenger going to Divide and Conquer.Go to Post Office:w 1 r 2 r 1 r 1 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:s 1 l 1 r.Pickup a passenger going to Divide and Conquer.Go to Divide and Conquer:e 4 l.Pickup a passenger going to The Babelfishery.Go to The Babelfishery:e 1 r.Pickup a passenger going to Post Office.Go to Post Office:e 1 l 1 r.
```
[Try it online!](https://tio.run/nexus/taxi#rVDNCoJAEH6V7wkEq5PHCrqVUC@w6bgObbs1uyY@vZVKRElBdJphhu@3XTkEh21QkpVscqyrI4kzTjdJjRgGE0g3@91EMdijVhzYaqgwCo1Szg7VCQon5T1ZTQLt7oCb1pIvnBOUzbFw9lyRRL2J1PmATVFwRp22DNqd/kfKXUmYqz2Zgn1J0gyEr@fED0nkN4Pvj4Qw@5M3@urrqZ@RxuiRrW2nVw "Taxi – TIO Nexus")
Ungolfed:
```
Go to Starchild Numerology:west 1 left, 2 right, 1 left, 1 left, 2 left.
1 is waiting at Starchild Numerology.
Pickup a passenger going to Divide and Conquer.
Go to Post Office:west 1 right, 2 right, 1 right, 1 left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:south 1 left, 1 right.
Pickup a passenger going to Divide and Conquer.
Go to Divide and Conquer:east 4 left.
Pickup a passenger going to The Babelfishery.
Go to The Babelfishery:east 1 right.
Pickup a passenger going to Post Office.
Go to Post Office:east 1 left, 1 right.
```
[Answer]
# Vim, ~~10~~ 8 bytes/keystrokes
```
C<C-r>=1/<C-r>"
```
Since V is backwards compatible, you may [Try it online!](https://tio.run/nexus/v#@@9s46xbZGdrqA@mlbj@/zfVM/ivWwYA "V – TIO Nexus")
[Answer]
# x86\_64 Linux machine language, 5 bytes
```
0: f3 0f 53 c0 rcpss %xmm0,%xmm0
4: c3 retq
```
To test this, you can compile and run the following C program
```
#include<stdio.h>
#include<math.h>
const char f[]="\xf3\xf\x53\xc0\xc3";
int main(){
for( float i = .1; i < 2; i+= .1 ) {
printf( "%f %f\n", i, ((float(*)(float))f)(i) );
}
}
```
[Try it online!](https://tio.run/nexus/c-gcc#PYvBCsIwEETv@YohUshqKWrx1NYfsR5C6tJAm0gaoSD99poqeBjezrBv3Vlnhlf3qKfYWV/0V/FfRh37bTDeTRGm1wF8uzeynblMaedLgjmmlLIS1kWM2jpFbwGwDwo8eB1h0aA4VYk1zgmHrYKwvQHPkERWkBkj49bJHDaHUl9X7el3EDEpS6AqSYtY1vUD "C (gcc) – TIO Nexus")
[Answer]
# C, ~~15~~ 12 bytes
```
#define f 1/
```
[Try it online!](https://tio.run/nexus/c-gcc#@6@ckpqWmZeqkKZgqP8/M69EITcxM09Dk6uaSwEICoqAQmkaSqppSjoKaRrGegaamtZctf8B)
**~~16~~ 13 bytes, if it needs to handle integer input also:**
```
#define f 1./
```
So you can call it with `f(3)` instead of `f(3.0)`.
[Try it online!](https://tio.run/nexus/c-gcc#@6@ckpqWmZeqkKZgqKf/PzOvRCE3MTNPQ5OrmksBCAqKgEJpGkqqaUo6Cmkaxpqa1ly1/wE)
*Thanks to @hvd for golfing 3 bytes!*
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 1 byte
```
z
```
[Try it online!](https://tio.run/nexus/05ab1e#@1/1/78pAA "05AB1E – TIO Nexus")
```
z # pop a push 1 / a
```
[Answer]
# MATLAB / Octave, 4 bytes
```
@inv
```
Creates a function handle (named `ans`) to the built-in [`inv`](https://www.mathworks.com/help/matlab/ref/inv.html) function
[Online Demo](http://ideone.com/F9NFL4)
[Answer]
## [GNU sed](https://www.gnu.org/software/sed/), ~~377~~ 362 + 1(r flag) = 363 bytes
**Warning:** the program will eat all the system memory trying to run and require more time to finish than you'd be willing to wait! See below for an explanation and a fast, but less precise, version.
```
s:\.|$:,,,,,,,,:;:i;s:,(,+)(\w):\2\1:;ti
h;:;s:\w::2g;y:9876543210:87654321\t :;/ /!s:,:@,:;/\s/!t;x;s:-?.::;x;G;s:,.*::m;s:\s::g;/\w/{s:@+:&&&&&&&&&&:;t}
/@,-?@/!{s:^:10000000,:;h;t}
:l;s:(@+)(,-?\1):\2;:;tl;s:,::;s:@+;?@+::
s:-?:&0:;:c;s:\b9+:0&:;s:.9*;:/&:;h;s:.*/::;y:0123456789:1234567890:;x;s:/.*::;G;s:\n::;s:;::;/;/tc
:f;s:(\w)(,+),:\2\1:;tf;s:,:.:;y:,:0:
```
This is based on the [Retina answer](https://codegolf.stackexchange.com/a/114630/59010) by Martin Ender. I count `\t` from line 2 as a literal tab (1 byte).
My main contribution is to the conversion method from decimal to plain unary (line 2), and vice versa (line 5). I managed to significantly reduce the size of code needed to do this (by ~40 bytes combined), compared to the methods shown in a previous [tip](https://codegolf.stackexchange.com/a/51329/59010). I created a [separate tip answer](https://codegolf.stackexchange.com/a/115617/59010) with the details, where I provide ready to use snippets. Because 0 is not allowed as input, a few more bytes were saved.
**Explanation:** to better understand the division algorithm, read the Retina answer first
The program is theoretically correct, the reason why it consumes so much computational resources is that the division step is run hundred of thousands of times, more or less depending on the input, and the regex used gives rise to a backtracking nightmare. The fast version reduces the precision (hence the number of division steps), and changes the regex to reduce the backtracking.
Unfortunately, sed doesn't have a method to directly count how many times a backreference fits into a pattern, like in Retina.
```
s:\.|$:,,,,,,,,: # replace decimal point or end of string with 8 commas
:i # loop to generate integer (useful for unary division)
s:,(,+)(\w):\2\1: # move 1 digit in front of commas, and delete 1 comma
ti # repeat (':i')
h;: # backup pattern and start decimal to unary conversion
s:\w::2g # delete decimal digits, except the first (GNU magic)
y:9876543210:87654321\t :; # transliterate characters
/ /!s:,:@,: # if no space is present, append a unary digit ('@')
/\s/!t # if no whitespace is present, go back to ':'
x;s:-?.::;x # delete first digit and the negative sign from backup
G;s:,.*::m;s:\s::g # append backup, delete whitespace and duplicate stuff
/\w/{s:@+:&&&&&&&&&&: # if decimal digit left, multiply unary number by 10
t} # and repeat (':')
/@,-?@/!{ # if only one unary number found (the input)
s:^:10000000,: # prepend decimal 10^7 separated by a comma
h;t} # backup pattern and convert new number to unary also
:l # start unary division loop (tons of RAM and time!!!)
s:(@+)(,-?\1):\2;: # delete as many '@'s from 10^7, as found in unary
#input, and add one ';' (new unary digit)
tl # repeat (':l')
s:,::;s:@+;?@+:: # delete leftover stuff
s:-?:&0:;:c # prepend zero and start unary to decimal conversion
s:\b9+:0&: # if only 9s found, prepend zero to them
s:.9*;:/&: # separate the digit(s) that would change on increment
h;s:.*/:: # backup, delete all (non-changing) digits (till '/')
y:0123456789:1234567890: # increment changing digit(s)
x;s:/.*:: # delete changing digits from backup
G;s:\n:: # append backup, delete newline
s:;:: # delete one unary digit (';')
/;/tc # if unary portion left, repeat (':c')
:f # loop to generate floating-point number
s:(\w)(,+),:\2\1: # move 1 digit after the commas, and delete 1 comma
tf # repeat (':f')
s:,:.: # turn first comma into a decimal point
y:,:0: # turn the rest of commas into zeroes (final result)
# implicit printing
```
For a fast and safe version of the program, but less precise, you can [try this online](https://tio.run/nexus/sed#PVDLasMwELz7K2Ioxg9Zr8RJPDpEt/6EyKGBJoY2KZXADW1/ve6uwdmD2N3Rzs7sFBHkzxPEHHAYXIQoRVOVYawQbDBwacguDgSEEbBnd0e/3227zdoajSULaQWnViqneXiiUiGqPLkvmmsPEqDsmcllDbwzWQTO9GtU3xG@QfEI2vibKS/ag1c5gUcYzUGkF4YiSt9UoiS8EYtIvBHnkXqurmY4WATjgqWpxJindRlrQaHp@4klvPQNdMHWZF87qII3UFEr0nuHNna96ba7fY9HpjFbUmxjNhSuYAJHr3IqnTK8Usnn4zOK5YbcFJBMK6AxTZ2R9u/2kYbbNU7t5z8).
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes
The obvious solution would be
```
1/U
```
which is, quite literally, `1 / input`. However, we can do one better:
```
pJ
```
This is equivalent to `input ** J`, and `J` is set to -1 by default.
[Try it online!](https://tio.run/nexus/japt#@1/g9f@/KQA "Japt – TIO Nexus")
Fun fact: as `p` is the power function, so `q` is the root function (`p2` = `**2`, `q2` = `**(1/2)`); this means that `qJ` will work as well, since `-1 == 1/-1`, and therefore `x**(-1) == x**(1/-1)`.
[Answer]
# Javascript ES6, 6 bytes
```
x=>1/x
```
[Try it online!](https://tio.run/nexus/javascript-node#S7P9X2FrZ6hf8T85P684PydVLyc/XSNNw9BAU/M/AA "JavaScript (Node.js) – TIO Nexus")
Javascript defaults to floating point division.
[Answer]
# APL, 1 byte
```
÷
```
`÷` Computes reciprocal when used as monadic function. [Try it online!](http://tryapl.org/?a=%F73&run)
Uses the Dyalog Classic character set.
[Answer]
# [Cheddar](http://cheddar.vihan.org/), 5 bytes
```
1&(/)
```
[Try it online!](https://tio.run/nexus/cheddar#y0ktUUiz/W@opqGv@b@gKDOvRCNNw680Nym1yMoqOSM1JSWxSC@xKL0s2ihWU/P/fxMA "Cheddar – TIO Nexus")
This uses `&`, which bonds an argument to a function . In this case, `1` is bound to the left hand side of `/`, which gives us `1/x`, for an argument `x`. This is shorter than the canonical `x->1/x` by 1 byte.
---
Alternatively, in the newer versions:
```
(1:/)
```
[Answer]
# Python, 12 bytes
```
lambda x:1/x
```
One for 13 bytes:
```
(-1).__rpow__
```
One for 14 bytes:
```
1 .__truediv__
```
[Answer]
# TI-Basic (TI-84 Plus CE), ~~6~~ ~~5~~ 2 bytes
```
Ans⁻¹
```
-1 byte thanks to [Timtech](https://codegolf.stackexchange.com/questions/114544/reciprocal-of-a-number-1-x?page=2&tab=votes#comment279524_114610).
-3 bytes with `Ans` thanks to [Григорий Перельман](https://codegolf.stackexchange.com/questions/114544/reciprocal-of-a-number-1-x/114610?noredirect=1#comment279663_114610).
`Ans` and `⁻¹` are [one-byte tokens](http://tibasicdev.wikidot.com/one-byte-tokens).
TI-Basic implicitly returns the last value evaluated (`Ans⁻¹`).
[Answer]
## Java 8, 6 bytes
```
x->1/x
```
Almost the same as the [JavaScript answer](https://codegolf.stackexchange.com/a/114547/34543).
[Answer]
## Mathematica, 4 bytes
```
1/#&
```
Provides you with an exact rational if you give it an exact rational, and with a floating-point result if you give it a floating-point result.
[Answer]
## ZX Spectrum BASIC, 13 bytes
```
1 INPUT A: PRINT SGN PI/A
```
Notes:
* Each line costs 2 bytes for the line number, 2 bytes for the length of the line and 1 byte for the newline
* Numeric literals are converted into binary at parse time, costing an extra 6 bytes, thus the use of `SGN PI` instead of literal `1`.
* Keywords take 1 byte each.
ZX81 version for 17 bytes:
```
1 INPUT A
2 PRINT SGN PI/A
```
[Answer]
# [Haskell](https://www.haskell.org/), 4 bytes
```
(1/)
```
[Try it online!](https://tio.run/nexus/haskell#@59mq2Gor/k/NzEzT8FWoaC0JLikyCdPQUWhOCO/HEilKRj/BwA "Haskell – TIO Nexus")
[Answer]
## R, 8 bytes
```
1/scan()
```
Pretty straightforward. Directly outputs the inverse of the input.
Another, but 1 byte longer solution can be : `scan()^-1`, or even `scan()**-1` for an additional byte. Both `^` and `**` the power symbol.
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 3 bytes
```
l_^
```
Try it at [**MATL Online**](https://matl.io/?code=l_%5E&inputs=10&version=19.8.0)
**Explanation**
```
% Implictily grab input
l_ % Push -1 to the stack
^ % Raise the input to the -1 power
% Implicitly display the result
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
İ
```
[Try it online!](https://tio.run/nexus/jelly#@39kw////80B "Jelly – TIO Nexus")
[Answer]
## C, 30 bytes
```
float f(float x){return 1./x;}
```
] |
[Question]
[
**Locked**. This question and its answers are [locked](/help/locked-posts) because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
**This challenge has ended!** Congratulations **Flonk**!
I was sure I would get a good grade, but after turning in Flonk's my work, my professor did not believe it was mine and also could not understand why it was so complicated... I failed *and* my mom grounded me from Facebook and Minecraft for a month. I don't understand. :(
Thanks for all your submissions! Some great answers here. The official winner is **Flonk** with a score of **64**. The top 5 are:
1. [Flonk](https://codegolf.stackexchange.com/a/25219/16504), 64 (Haskell, with efficient maths!)
2. [DigitalTrauma](https://codegolf.stackexchange.com/a/25208/16504), 40 (The cloud, the future is now)
3. [primo](https://codegolf.stackexchange.com/a/25212/16504), 38 (Python, and my personal favorite - and very professional much!)
4. [Sylwester](https://codegolf.stackexchange.com/a/25221/16504), 20 (Racket, although Janember is stretching it!)
5. [ilmale](https://codegolf.stackexchange.com/a/25243/16504), 16 (A *highly* optimized algorithm in Lua)
Original challenge below.
---
Please help me, it's very urgent!!! :(
I need to convert shortened versions of month names to their longer representations (e.g "Dec" -> "December"), case-insensitive. Right now I'm using Java; the month's name is a String and I would rather not convert it to a Date object first. Any language will do, though.
Is there an easy way to do this?? Go easy please I am a newbie to programming!
---
This is a [**code trolling**](https://codegolf.stackexchange.com/tags/code-trolling/info) popularity contest (the best kind there is!). The answer with the most upvotes on Apr 8, 2014 wins.
[Answer]
It's really simple with a little polynomial interpolation!
First, I looked at the list of short month names
```
["jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"]
```
and checked the sum of their characters ASCII values
```
[313,301,320,323,327,333,331,317,328,326,339,300]
```
then subtracted 300 from those to get a grasp of what I'm dealing with here, and prepared an Array that contains all the longer versions of the months' names.
```
[13,1,20,23,27,33,31,17,28,26,39,0]
mons = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
```
I guess you can see what's going on now - all I need is a function getIndex that maps 13 to 0, 1 to 1, 20 to 2, and so on, so I can simply do
```
getMonthName shortname = mons !! (getIndex shortname)
```
Luckily, Wolfram|Alpha [can do this for me](http://www.wolframalpha.com/input/?i=interpolating+polynomial+%7C+%7B%7B13%2C+0%7D%2C+%7B1%2C+1%7D%2C+%7B20%2C+2%7D%2C+%7B23%2C+3%7D%2C+%7B27%2C+4%7D%2C+%7B33%2C+5%7D%2C+%7B31%2C+6%7D%2C+%7B17%2C+7%7D%2C+%7B28%2C+8%7D%2C+%7B26%2C+9%7D%2C+%7B39%2C+10%7D%2C+%7B0%2C+11%7D%7D)! The numbers get a bit large, but Haskell can handle that with grace. We just need to make sure to round the results, because floating-point-arithmetic is a little imprecise!
So there you go, fast, elegant, and idiomatic Haskell:
```
import Data.Char
getIndex x = round $ 11 -
(220797068189915461*x)/11644212222720 +
(184127469431441671621*x^2)/6982771136140800 -
(8800438195450444577647153*x^3)/1013060436431307264000 +
(2826703553741192361967823*x^4)/2026120872862614528000 -
(269098602165195540339443*x^5)/2026120872862614528000 +
(13744405529566098359*x^6)/1692665725031424000 -
(13060656886070844161*x^7)/39727860252208128000 +
(5939638907108115199*x^8)/675373624287538176000 -
(303426664924585177*x^9)/2026120872862614528000 +
(2983240583426137*x^10)/2026120872862614528000 -
(12901227927103*x^11)/2026120872862614528000
mons = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
getMonthName = (mons!!).getIndex.subtract 300.fromIntegral.sum.fmap (ord.toLower)
```
Run it simply like this:
```
λ> getMonthName "DeC"
"December"
λ> getMonthName "jan"
"January"
```
[Answer]
# Bash + GNU tools + "the cloud"
Google has the answer to everything, and *I'm feeling lucky*:
```
wget -qU Mozilla -O- "http://www.google.com/search?q=$1+month&btnI" | grep -Eo "<title>[[:alpha:]]+" | cut -d\> -f2
```
In use:
```
$ ./longmonth.sh jan
January
$ ./longmonth.sh feb
February
$
```
[Answer]
## Python
Because this function is very important, it will probably be used a lot, so you should try to make it as fast as possible. Other posters have recommended using a hashmap look-up... don't do this! Hashmaps are *really slow* compared to arrays. You just need to convert each abbreviation to a number. There's a standard hashing technique that can be used for this:
```
index = reduce(int.__mul__, (ord(c) for c in abbr))
```
This is almost guaranteed to be unique, and lots of professional tools use this.
Now you need to create a look-up function:
```
def month_abbr_to_name(abbr):
months = ["Unknown"] * 2000000
months[679932] = "December"
months[692860] = "Febuary"
months[783315] = "August"
months[789580] = "January"
months[829920] = "April"
months[851466] = "March"
months[903749] = "May"
months[907236] = "October"
months[935064] = "July"
months[938896] = "September"
months[952380] = "June"
months[1021644] = "November"
index = reduce(int.__mul__, (ord(c) for c in abbr))
month_name = months[index]
if month_name == "Unknown":
raise ValueError("Invalid month abbreviation!")
return month_name
```
And use it like this:
`print month_abbr_to_name("Dec")` → `December`
HTH!
---
**Trolling**
>
> - This code is horrendously slow. Although array access is indeed faster than hashmaps, this doesn't apply if the array is thousands of times larger than the necessary hashmap would be.
>
> - This incredibly large array is created again, and again, every time the function is called. To waste a little more space, each value is initialized with "Unknown".
>
> - The hashing function is meant to be obscure to someone unfamilar with Python. I add that it is "used in lots of professional tools" to discourage investigation.
>
> - The hashing function is unique enough to distiquish between the twelve months correctly, but will not catch many common typos, such as swapped characters.
>
> - Just about any string longer than 3 chars will crash on array index out of bounds.
>
> - "Febuary" is misspelled.
>
> - "This function is very important." Minor ego-rub for the OP.
>
>
>
[Answer]
# Racket
I go for a [KISS solution](http://en.wikipedia.org/wiki/KISS_principle). I've test it with OP's use case "Dec" with all caps to check if the correct result is returned. It passed with flying colors.
```
(define (long-month short-month)
(define end "ember")
(string-titlecase
(string-append short-month end)))
;; Test OP's use case
(long-month "DEC") ;;==> "December"
```
Obviously the trolling here is that it only works for a few cases so it's useless :-)
[Answer]
# LUA
My solution will work in your locale language, your professor will be happy
```
input = ...
found = false
input = string.lower(input)
i = 12
while i > 0 do
abb = os.date("%b")
if string.lower(abb) == input then
print(os.date("%B"))
return
end
os.execute('sleep 28d')
i = i - 1
end
print('not found')
```
Test
```
lua 25207.lua aPr
April
```
>
> Check the abbreviation of the current month, if correct return the long string otherwise try again.. ONE MONTH LATER
>
>
>
[Answer]
# Perl
```
use re 'eval';$_=lc<>;
s/b/br/;s/an|br/$&uary/;s/(?<!u)ar/arch/;s/r$/ril/;s/p$/pt/;s/t|v|c$/$&ember/;
s/ju(.)/$&.$1=~tr\/nl\/ey\/r/e;s/(?<=g)/ust/;s/ctem/cto/;
print ucfirst;
```
---
>
> - Regex hell. I hope regex doesn't count as "trolling by obscure language".
>
> - Extremely fragile. You'd have a hard time adding a support for Bugsember.
>
> - Unreadable. Pattern inside pattern makes it even more so.
>
> - Compression of June and July into a single statement doesn't actually compress anything.
>
> - random usage of lookbehind for `g`, while others repeat the pattern in the substitution.
>
> - `use re 'eval'` is actually not needed; it's only used when a variable pattern is wanted. Also, use of `eval` to "gain" a little "compression".
>
>
>
[Answer]
# Java
You said your current code's in Java, so I thought I'd make things easy for you.
```
// The standard library's there, so you should use it
import static java.util.Calendar.*;
public class MonthConverter {
private static int shortNameToNumber(String shortName) {
int i;
switch (shortName) {
case "jan": i = 1;
case "feb": i = 2;
case "mar": i = 3;
case "apr": i = 4;
case "may": i = 5;
case "jun": i = 6;
case "jul": i = 7;
case "aug": i = 8;
case "sep": i = 9;
case "oct": i = 10;
case "nov": i = 11;
case "dec": i = 12;
default: i = 0;
}
return i;
}
private static String numberToLongName(int month) {
switch (month) {
case JANUARY: return "January";
case FEBRUARY: return "February";
case MARCH: return "March";
case APRIL: return "April";
case MAY: return "May";
case JUNE: return "June";
case JULY: return "July";
case AUGUST: return "August";
case SEPTEMBER: return "September";
case OCTOBER: return "October";
case NOVEMBER: return "November";
case DECEMBER: return "December";
default: return "Unknown";
}
}
public static String fullName(String shortName) {
return numberToLongName(shortNameToNumber(shortName));
}
public static void main(String[] args) {
// Always test your code
System.out.println("jan is: " + fullName("jan"));
assert fullName("jan").equals("January");
}
}
```
>
> The Calendar class has a fun little gotcha where months are numbered starting at 0 - so `JANUARY == 0`. However, this clearly can't affect our code, as we test it, right? Notice that there's an unintended switch fallthrough in shortNameToNumber, which means every month ends up being 0. Handily, `JANUARY == 0`, so our test passes.
>
>
>
[Answer]
# Bash + coreutils + paq8hp12
The answer that is currently upvoted the most has to access the internet for every query. In addition to being very inefficient, this also means that your script will fail if there's no internet.
It's better to store the necessary information on your hard disk. Of course, you could store just the data needed for this very script, but that would require different data for different tasks. It is much better to store all data you could possibly need in a single multi-purpose file.
```
# This script is supposed to output only the wanted information, so we'll have to close
# STDERR and make sure accidental keyboard presses don't show any characters on the screen.
exec 2>&-
stty -echo
# Unfortunately, Bash doesn't have goto labels. Without them, it's impossible to use if
# statements, so we'll implement them.
goto()
{
exec bash <(egrep -A 1000 "^: $1" $0) $BASH_ARGV
}
# We'll need enwik8, a magic file containing all the important Wikipedia data. EVERYTHING
# can be found on Wikipedia, so this file contains all the information any script could
# possibly need.
ls | grep -q enwik8 && goto alreadydownloaded
# Too bad.
wget http://mattmahoney.net/dc/enwik8.zip
unzip enwik8.zip
# ZIP is a very wasteful format and hard disk space is expensive. It is best to compress
# the file using a more efficient algorithm.
wget http://mattmahoney.net/dc/paq8hp12any_src.zip
unzip paq8hp12any_src.zip
# Make the compression program executable and compress the magic Wikipedia file.
chmod +x paq8hp12_l64
./paq8hp12_l64 enwik8.paq8 enwik8
: alreadydownloaded
# Extract the enwik8 file from the paq archive.
./paq8hp12_l64 enwik8.paq8 enwik8
# Now we use a simple POSIX Basic Regular Expression to find the required information in
# the file.
cat enwik8 | egrep -io "[0-9].[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?[a-z]?.[0-9]" | sort | uniq -c | sort -n | tac | egrep -o "$1[a-z]*" | sort | uniq -c | sort -n | tac | head -n 1 | cut -d ' ' -f 7
# We're done.
```
# Trolling
* >
> Closes STDERR, so we won't be able to debug the script if it fails.
>
>
>
* >
> Disables input echoing, which persists after the script has finished. If executed from a terminal, you have to execute **stty echo** to get your terminal usable again. If not executed from a terminal, this could crash the script.
>
>
>
* >
> Requires implementing **goto** first. As if that wasn't bad enough on its own, the **goto** function won't work if the script's filename contains spaces.
>
>
>
* >
> We won't download the archive if a file containing the string *enwik8* exists in the current directory. This *might* work.
>
>
>
* >
> Downloading a 100 MB file (even if compressed to 36 MB) is obviously overkill for this task. Plus, *enwik8* contains the first 100 MB of a 4+ GB Wikipedia dump, so for a specific task, it's unlikely to contain any useful information.
>
>
>
* >
> Compressing the file with paq8hp12 shrinks it to 16 MB, but compression and decompression both take one hour. It actually will do both the first time this script is run.
>
>
>
* >
> The script doesn't delete the zipped or raw version of *enwik8*, so shrinking it to 16 MB consumed even more hard disk space.
>
>
>
* >
> The compression utility will only work on 64-bit processors.
>
>
>
* >
> It leaves all the files that have been downloaded or extracted in the current directory.
>
>
>
* >
> It doesn't explain the most tricky part of the script, which is the regex-pipe monster. It basically extracts all strings between 4 and 19 bytes that have a leading and trailing digit, sorts those strings by number of occurrences, filters the strings containing the short month name, sorts again by number of occurrences and displays the most frequent.
>
>
>
* >
> Even if the above *was* a good idea, **cat** is unneeded at the beginning, **egrep** is rather slow for this task, the regex will return *a lot* of false positives (everything could be done with one regex), the first **sort | uniq -c | sort -n | tac** accomplishes absolutely nothing, it uses **sort | tac** instead of **sort -r** and **cut** won't work reliably since the number of spaces at the beginning is variable.
>
>
>
* >
> The regex is an *Extended* POSIX Regular Expression, so googling the BRE syntax won't help at all.
>
>
>
* >
> Returns **Nov** instead of **November** and **6** instead of **August**.
>
>
>
[Answer]
# Python + SQLite
Many of the answers so far make the mistake of hard-coding the month names. But, you never know when some Pope or President is going to make us switch to another calendar, and then tons of date parsing/formatting code will instantly become worthless! (Or, more commonly, when you need to internationalize your program.)
What you need is a database.
```
CREATE TABLE tblShortMonthNames (
MonthAbbr CHAR(3) PRIMARY KEY NOT NULL COLLATE NOCASE,
MonthID INTEGER NOT NULL
);
CREATE TABLE tblFullMonthNames (
MonthID INTEGER PRIMARY KEY,
MonthName VARCHAR(9) NOT NULL
);
INSERT INTO tblFullMonthNames VALUES (1, 'January');
INSERT INTO tblFullMonthNames VALUES (2, 'February');
INSERT INTO tblFullMonthNames VALUES (3, 'March');
INSERT INTO tblFullMonthNames VALUES (4, 'April');
INSERT INTO tblFullMonthNames VALUES (5, 'May');
INSERT INTO tblFullMonthNames VALUES (6, 'June');
INSERT INTO tblFullMonthNames VALUES (7, 'July');
INSERT INTO tblFullMonthNames VALUES (8, 'August');
INSERT INTO tblFullMonthNames VALUES (9, 'September');
INSERT INTO tblFullMonthNames VALUES (10, 'October');
INSERT INTO tblFullMonthNames VALUES (11, 'November');
INSERT INTO tblFullMonthNames VALUES (12, 'December');
INSERT INTO tblShortMonthNames
SELECT SUBSTR(MonthName, 1, 3), MonthID FROM tblFullMonthNames;
```
Then, just write a simple program to query it.
```
import sqlite3
import sys
QUERY = """SELECT tblFullMonthNames.MonthName
FROM tblShortMonthNames INNER JOIN tblFullMonthNames USING (MonthID)
WHERE tblShortMonthNames.MonthAbbr = ?"""
with sqlite3.connect('months.db') as db:
for abbr in sys.argv[1:]:
row = db.execute(QUERY, [abbr]).fetchone()
if row:
print(row[0])
else:
print(abbr + ' is not a valid month name.')
```
[Answer]
# SH & a friend (date)
The function:
```
longmonth() {
date +%B -d"$1 1"
}
```
Testing it:
```
$ echo $LANG
de_DE.utf8
$ for i in jan feb mar apr may jun jul aug sep oct nov dec ; do longmonth $i ; done
Januar
Februar
März
April
Mai
Juni
Juli
August
September
Oktober
November
Dezember
$ LANG=C
$ for i in jan feb mar apr may jun jul aug sep oct nov dec ; do longmonth $i ; done
January
February
March
April
May
June
July
August
September
October
November
December
```
It is short... but calculate it's "evil per character" ratio... mwhuaaahahahaaa...
[Answer]
# perl
How about some good ol' brute force?
```
$|++;
use List::Util qw(reduce);
sub hash {
my $t=9;
(reduce { $a*$b*log(++$t+$a) } map { ord() } split//, shift)%54321098
}
my @m = (qw( january february march april may june
july august september october november december ) );
my %targets = map { hash($m[$_]) => 1 } (0..$#m);
chomp(my $in = lc <>);
print ucfirst $in;
my $r;
if(!$targets{hash($in)}) {
$r = "a";
++$r until $targets{hash($in.$r)};
}
print "$r\n";
```
Why this is awesome:
* brute force is always the manliest way to do it.
* for your convenience, prints the partial answer as soon as it knows it (I bet you didn't know that "Feb" is short for something starting with "Feb..."???)
* custom hashing function for maximal security.
* use of perl's built-in operator overloading (increment on strings) makes this code as fast as native C code. Look at all those zeroes, showing just how fast it runs!
```
ski@anito:/tmp$ for m in mar apr may jun jul ; do echo $m | time -f "%U user" perl brute.pl ; done
March
0.00 user
April
0.00 user
May
0.00 user
June
0.00 user
July
0.00 user
```
* The algorithm is intuitively obvious, and I leave a proof as an exercise to the reader, but just to make sure it works in all cases, let's check August, one of the -ber months, and one of the -uaries to make sure we didn't miss anything:
```
ski@anito:/tmp$ for m in aug jan oct ; do echo $m | perl brute.pl ; done
August
January
October
```
Trollage:
Leaving aside the coding practices that would make Damian Conway die on sight, this code is intermittently wrong, and intermittently extremely slow. "Feb" runs about 6 orders of magnitude - one million times - slower than "may", "jun", or "jul". Feboapic, Sepibnd, Novgpej, and Decabjuj are not months (although they are fun to try to pronounce).
```
ski@anito:/tmp$ for m in jan feb mar apr may jun jul aug sep oct nov dec ; do echo $m | time -f "%U user" perl brute.pl ; done
January
3.14 user
Feboapic
62.77 user
March
0.00 user
April
0.00 user
May
0.00 user
June
0.00 user
July
0.00 user
August
0.10 user
Sepibnd
1.33 user
October
2.22 user
Novgpej
1.11 user
Decabjuj
4.27 user
```
PS - I had some code that has an even greater spread of runtimes, but it boringly outputs the correct answer in all cases, which is much less fun.
[Answer]
# JavaScript - Optimized Node cluster with Branches, Leaves, and string barrels.
```
// fullMon - Converts month key names to full names using a highly optimized tree for fast traversal.
function fullMon(key) {
// Initialize the full month string
var fullMonth = "";
// Make sure the key is capitalized.
key = key.substr(0,1).toUpperCase() + key.substr(1).toLowerCase();
// Set the current node to the tree root.
var current = fullMon.tree;
// Traverse the characters in key until we can go no further.
for (var i = 0; i < key.length; i++) {
var c = key.charAt(i)
fullMonth += c
if (typeof current[c] === "undefined") return key // no full month for this key
current = current[c]
}
// The remaining leaves are the characters in the full month.
while (current !== null) {
for (c in current) fullMonth += c
current=current[c]
}
return fullMonth
}
// fullMon.treeBuilder - Builds a character node tree of full month names.
fullMon.treeBuilder = function() {
// Set a barrel of month keys.
var barrel = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
// Root node for letter tree.
var tree = {};
// Loop through all month keys.
for (var i = 0; i < barrel.length; i++) {
// Get the next month key and do a barrel roll by
// splitting into an array of single character strings.
var monKey = barrel[i].split("");
// Set the current branch to the tree root.
var branch = tree;
// Climb branches in the tree by looping through
// month key characters and doing leaf wipes.
for (var c = 0; c < monKey.length; c++) {
// The next character is the next leaf of the branch.
var leaf = monKey[c];
// Wipe this leaf on the branch if it doesn't already exist.
if (typeof branch[leaf] === "undefined") {
// If the leaf is the last character then it's not sticky should be set to null.
branch[leaf] = (c === (monKey.length-1)) ? null : {};
}
// Switch to the next branch.
branch = branch[leaf];
}
}
return tree;
}
fullMon.tree = fullMon.treeBuilder();
fullMon.demo = function () {
// Demonstrates keys that are not found "none" and found keys.
var short = ["none","jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"];
for (var i = 0; i < short.length; i++) {
console.log(fullMon(short[i]));
}
// Shows the optimized tree for fast lookups.
console.log(JSON.stringify(fullMon.tree));
}
fullMon.demo();
```
[Answer]
## Java, Google and Probability
I am disappointed that so many of the solutions here "reinvent the wheel" when the answer is easily available on the internet.
Here is my program's output:
```
The short version of jan is january
The short version of feb is february
The short version of mar is margin
The short version of apr is april
The short version of may is mayinhistory
The short version of jun is june
The short version of jul is july
The short version of aug is august
The short version of sep is september
The short version of oct is october
The short version of nov is november
The short version of dec is december
```
Not perfect, but good enough to send to QA. I was able to achieve these results by leveraging the power of crowdsourcing:
```
public static String expandMonthName(String shortMonthName) {
try {
// First, we ask Google for the answer
String query = "https://www.google.com/search?q="
+ "what+month+is+" + shortMonthName;
String response = curl(query);
// now sift through the results for likely answers.
// The best way to parse HTML is regex.
List<String> possibleMonths = new ArrayList<>();
Pattern pattern = Pattern.compile(shortMonthName + "[A-Za-z]+");
Matcher matcher = pattern.matcher(response);
while (matcher.find())
possibleMonths.add(matcher.group(0));
// And finally, choose the likeliest answer using
// the ineluctable laws of probability
return possibleMonths.get(new Random().nextInt(possibleMonths.size()));
} catch (Exception e) { return "August";} // well, we tried.
}
```
>
> If it's not clear, expandMonthName("jan") returns a randomly selected word beginning with "jan" from the Google result for "what month is jan". Unless you're behind a proxy, in which case it returns "August."
>
>
>
[Answer]
# Bash + binutils
I tried hard to do the obvious by converting the input to a date object, but failed miserably. Finally I resorted to brute-force approach.
```
while read -e line; do
[[ "${line,,}" == "${1,,}"* ]] && o=$line && break
done < <(strings /bin/date)
o=${o:=$1}
o=${o,,}
echo ${o^}
```
Test runs:
```
$ bash getmonth.sh jan
January
$ bash getmonth.sh may
May
$ bash getmonth.sh DEC
December
```
[Answer]
I understand that checking months' names is very hard, and it requires lots of computation and logic thinking. Here's an optimized version of the [Buzz-Strahlemann algorythm for checking months' names](http://www.google.com/ "Buzz-Strahlemann Algorythm for checking months' names").
# PHP
```
$month = "Jan"; //Change this to search for a different month, noob :)
$time = time(); //This loads an extended time library
$ivefoundthismonthnowexit = false;
while (!$ivefoundthismonthnowexit) {
$checkThis = date('F', $time); //"F" stands for "Find it"
if (substr($checkThis, 1, 4) == $month) $ivefondthismonthnowexit = true; //You can also replace it with ($checkThis, 0, 3)
//since PHP understands if you are counting from 0 or 1!
$time++;
}
```
**Trolls:**
* This answer;
* Doesn't handle timezones and will output a warning message;
* Doesn't accept month as an input, but you need to hardcode it;
* Even when you hardcode it, it's case-sensitive;
* What this code tries to do is to get the current month, get the first three letters, and check if it matches with `$month`. If it does not match, it increments the timestamp by 1 and then retries. This ends up to be **EXTREMELY SLOW**;
* This code outputs nothing (except the warning, of course);
* Comments are very misleading: `time()` does not load an extended time library, but gets the current timestamp; `substr($checkThis,1,4)` skips the first letter of the month and gets the following 4 (`arch` for `March`, e.g.); The correct form is the one in the comments;
* Even when a match is found, the code won't exit the loop: in fact, the variable that gets set to `true` is different.
[Answer]
# Batch
What you're asking for is non-trivial. However I have found the perfect solution for you!
How this works is by downloading a highly intricate list of the English language to your hard-disk. The input is then checked against the downloaded list and the final name of the month is given! Genius!
Now, this method has many pros over other methods, some being:
* You can have any abbreviation of the word! E.g. `Jan` or `Janu` for January!
* "You never know when some Pope or President is going to make us switch to another calendar, and then tons of date parsing/formatting code will instantly become worthless!" This is never a problem with our method!
* The user is sent confirmation prompts, better safe than sorry!
## The Code:
```
@ECHO OFF
setlocal EnableDelayedExpansion
REM Remove this at the end ^^^
REM First off, we have to get the user's input
set /p abbreviatedUserInput= Please input your abbreviated form of the month:
REM echo out confirmation message. Without this, the thing won't work
SET /P variableThatIsUsedForConfirmation= Are you sure you want to look for %abbreviatedUserInput% (Y/N)?
REM if the user said no, send him elsewhere
if /i {%variableThatIsUsedForConfirmation%}=={n} (goto :hell)
REM to keep things clean, we clear the screen!
cls
ECHO Prepare for launch!
REM make sure the user reads what we wrote, we spent time on this and the user must understand that...
REM BTW this pings an incorrect ip address and waits 3000 millisex for the output
ping 1.1.1.1 -n 1 -w 3000 > nul
REM to keep things clean, we clear the screen!
cls
REM We must inform the user that something is going on, otherwise they might get bored and quit the app
ECHO LOA-DING!
REM Now, how this works is by utilizing the dictionary.. I believe we all know what that is. First of all, let's get a dictionary!
powershell -Command "(New-Object Net.WebClient).DownloadFile('http://www.mieliestronk.com/corncob_caps.txt', 'dic.txt')"
REM to keep things clean, we clear the screen!
cls
REM The user probably already got bored, let's inform them that we're still working...
ECHO STILL WORKING...
REM wait what?!! The dictionary is all caps!! Lets fix that...
REM Lets loop through the file like so:
for /F "tokens=*" %%A in (dic.txt) do (
SET "line=%%A"
REM replace ALL the letters!!
SET "line=!line:A=a!"
SET "line=!line:B=b!"
SET "line=!line:C=c!"
SET "line=!line:D=d!"
SET "line=!line:E=e!"
SET "line=!line:F=f!"
SET "line=!line:G=g!"
SET "line=!line:H=h!"
SET "line=!line:I=i!"
SET "line=!line:J=j!"
SET "line=!line:K=k!"
SET "line=!line:L=l!"
SET "line=!line:M=m!"
SET "line=!line:N=n!"
SET "line=!line:O=o!"
SET "line=!line:P=p!"
SET "line=!line:Q=q!"
SET "line=!line:R=r!"
SET "line=!line:S=s!"
SET "line=!line:T=t!"
SET "line=!line:U=u!"
SET "line=!line:V=v!"
SET "line=!line:W=w!"
SET "line=!line:X=x!"
SET "line=!line:Y=y!"
SET "line=!line:Z=z!"
ECHO !line! >> dic-tmp.txt
)
REM to keep things clean, we clear the screen!
cls
REM The user probably already got bored, let's inform them that we're still working...
:lookup
ECHO WOW! THAT TOOK LONG! ALMOST THERE...
REM Alright, now we need to find the correct date in the dictionary, we might need the users help in this...
REM Lets loop through ALL the lines again
set match=seriously?
for /F "tokens=*" %%a in (dic-tmp.txt) do (
SET "line=%%a"
REM to keep things clean, we clear the screen!
cls
REM replace the user input with some other stuff...
SET "test=!line:%abbreviatedUserInput%=lol!"
REM if the original line does not equal the test variable, then we have a match!
IF NOT !line!==!test! (
REM ask the user if the match is correct..
set /P variableThatIsUsedForConfirmation= "Did you mean !line!? (Y/N): "
REM if the user entered "y"
IF /i {!variableThatIsUsedForConfirmation!}=={y} (
REM set the variable "match" to the current line and goto the matchFound section...
set match=!line!
goto :matchFound
)
)
)
:matchFound
REM to keep things clean, we clear the screen!
cls
REM give the user their match
Echo Here's your month's full name: %match%
PAUSE
:hell
ECHO screw you!
```
## Trollz
>
> - Batch...
>
> - Downloading a list of words, because we can't type out the months manually...
>
> - Not using [switch case hack](https://stackoverflow.com/questions/18423443/switch-statement-equivalent-in-windows-batch-file)
>
> - VERY SLOW
>
> - converting the text file to lowercase and saving it in another file
>
> - run it a second time without deleting the text files created and it will be even slower
>
> - Something ticks the script off while converting the dic.txt file to lowercase, this sets echo back on
>
> - This spoiler thing has messed up formatting by the way...
>
>
>
[Answer]
# ! #/bash
```
! #/bash
# Make the MONTH variable equal to the $1 variable
MONTH="$1"
# Run grep passing the $MONTH variable and the -i flag
# Then use the << operator followed by a list of months
grep -i "$MONTH" << January
March
May
July
August
0ctober
December
April
June
September
November
February
January
```
To make your program respond faster, I have put the months with 31 days earlier in the list. Statistically speaking, given an even distribution of dates, you are more likely to be in one of those months.
I documented each line to impress your boss.
Save this in a file called `lookup_month_script.bash` and copy-paste the following line to test it:
```
bash $PWD/lookup_month_script.bash "0ct"
```
Good luck with your project!
---
>
> - Doesn't work for January, despite it being listed *twice*. (We are actually using `January` as the delimiter for the start and end of the heredoc.)
>
>
>
> - Also doesn't work for October. Nobody can see why.
>
>
>
> - If the input happens to be empty, returns all 11 months.
>
>
>
> - If the script is copy-pasted, the June response will be 42 characters in length.
>
>
>
> Minor:
>
>
>
> - The shebang is somewhat incorrect, but no warning is given.
>
>
>
> - Comments that are comments which say what the line below them is saying.
>
>
>
> - Even if the program did respond sooner for the earlier entries, it still wouldn't complete any faster.
>
>
>
[Answer]
# JavaScript - 209
It does say not to convert to a Date, which is not what's happening here, I'm simply using Date to generate the extension of the short name.
```
function m(s){c=s.charAt(0).toUpperCase()+s.substr(1).toLowerCase();a="ember,ember,ober,tember,ust,y,e,,il,ch,uary,uary".split(",");b=[];for(i=12;i--;)b[(""+new Date(1,i,1)).slice(4,7)]=11-i;return c+a[b[c]];}
```
Tests Input/Output:
```
jan: January
feb: Febuary
mar: March
apr: April
may: May
Jun: June
JUL: July
AuG: August
sEp: September
OCT: October
nov: November
dec: December
```
[Answer]
**Java 696 including test input**
```
public class DateConverter {
String months[] =
{
"January", "February","March","April","May","June","July",
"August","September","October","November","December"
};
DateConverter(){}
String LongMonth(String shortMonth)
{
String m = "Invalid";
for(int i=0;i<months.length;i++)
{
if(months[i].toLowerCase().contains(shortMonth.toLowerCase()))
{
m=months[i];
break;
}
}
return m;
}
public static void main(String[] args) {
String input[] = {"jan","feb","mar","apr","may","jun","jul","aug","sep","oct","nov","dec"};
for(int i=0; i<input.length; i++)
{
System.out.println((new DateConverter()).LongMonth(input[i]));
}
}
}
```
[Answer]
The programming language "Brainf\*ck" is a perfect tool for this! It might not be exactly what you were looking for, sure, but it gets the job done flawlessly!
```
>+<+[>[>[-]+<-]>[<+>>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<->-]>>>>>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+
This is the debug part of the code used when looping more than once
>>+++++++++++++++[>+++++>+++++++>++>+++++++>+++<<
<<<-]>--.>+++++.++.+++++.-.>++.<.>>-.---.<.<.>>+++.<<--.>>---..>.<<<------.>>.
<<++++++++..>>.<<--.>.>----.+..<<.>>+++.<<++++.>>++++.--------
.<<--.>>++++++++.<<-----.-.>+.>>[-]<[-]<[-]<[-]<[-]<++++++++++.[-]
It takes a dummy argument due to the nature of my interpreter
If you're using some other intepreter I can rewrite the code for you
>>>>>>>>>>>>>>>>>>>>>>>,<+<<<<<<<<<<<<<<<<<<<<<<<<->-]>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+
This is the normal part of the code, used when starting the programme the first time
>>+++++++++++++++[>+++++>+++++++>++>+++++++>+++<<<<<-]>--.>
+++++.++.+++++.-.>++.<.>>-.---.<.<.>>+++.<<--.>>---..>.<<<------.>>.<<++++++++..>>.<<-
-.>.>----.+..<<.>>+++.<<++++.>>++++.--------.<<--.>>++
++++++.<<-----.-.>+.>>[-]<[-]<[-]<[-]<[-]<++++++++++.[-]<-]>>>>>>>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>>-]<<<<<<
<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+
Here we take three arguments and assign them to variables; This is the three-letter
abbreviation of the month
>>>>>>>>>>>>>>,<,<,
Now we check if the abbreviation is good; note that it will fail if it doesn't begin
with a capital letter and isn't followed by two lowercase letters
In general it will print an error message and wait for you to input a letter
(or just hit enter) before it exits
<<<[-]>>>>>[<<<<<+<<<<<<<+>>>>>>>>>>>>-]<<<<<<<<<<<<[>>>>>>>>>>>>+<<<<<<<
<<<<<-]>>>>>>>----------------------------------------------------------------->[-]
<[<<<+>>>-]->[<<<<<<<+>+<<+>>>>>>>>-]<<<<<<<<[>>>>>>>>+<<
<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>
[>>>+<<<[-]]<<<[-]<->>>>>>>[<<<<<<<->>>>>>>-]<<<<<<<[>
>>>>>>+<<<<<<<-]>>>>>>>[>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]
<[>[-]+<-]>[<+>>+++++++++++[>++++++>++++++++++>+++<<<-
]>+++.>++++..---.+++.>.[-]<[-]<[-]<++++++++++.[-]>>>>>>>>>>>>>>>,,<<<<<<<<<<<<<<<<<-<-
>>-]>>>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<+>>>
>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>>>>>>>>[-]>>>>[<<<<+
<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>
>>>>>-------------------------------->[-
]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<[<<<+>>>-]>
[<<<<<<<+>+<<+>>>>>>>>
-]<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]
<<<[>>[-]+<<-]>>-]<[>>>>>>-<<<<<<[-]]>>>[-]>>>>[-]>>
>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>>---------------
----------------->[-]+++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++<[<<<<+>>>>-]>[<<<<<<<<+>+
<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>[>>[<+<<
<+>>>>-]<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]>>[>>>>-<<<<[-]]<<<[-
]>>>>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>-<<<<<<<[-]]>
>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]<[>>>>>>>[-]-<<<<<<<[-]]->>>>>>>
[<<<<<<<->>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>
>>>>>>+<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[<+>>+++++++++++
[>++++++>++++++++++>+++<<<-]>+++.>++++..---.+++.>.[-]<[-]<[-]<+
+++++++++.[-]>>>>>>>>>>>>>>>,,<<<<<<<<<<<<<<<<<-<->>-]>>>>>>>>>>>>>>>>>>
[<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<[>[-]+<
-]>[<+>>>>>>>>>[-]>>>[<<<+<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>-
------------------------------->[-]+++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++++++++<[<<<+>>>-]>[<<<<<<<+>+<<+>>>>>>>>-]
<<<<<<<<[>>>>>>>>+<<<<<<<<-]>>[>>[<+<<<+>>>>-]<<<<[>>>>+
<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>-]<[>>>>>>-<<<<<<[-]]>>>[-]>>>>[-]>>[<<+
<<<<<<<<+>>>>>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-
]>>>>>>>>-------------------------------->[-
]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<[<<<
<+>>>>-]>[<<<<<<<<+>+<<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>>[>>[<+<<<+>>>>-]
<<<<[>>>>+<<<<-]+>>>[<<->>>-<<<<->>>[-]]<<<[>>[-]+<<-]>>
-]>>[>>>>-<<<<[-]]<<<[-]>>>>>>[<<<<<<<+>>>>>>>-]<<<<<<<[>>>>>>>-<<<<<<<[-]]>>>>>>>>
[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]<[>>>>>>>[-
]-<<<<<<<[-]]->>>>>>>[<<<<<<<->>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>>>>>>>>+
<<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[
<+>>+++++++++++[>++++++>++++++++++>+++<<<-]>+++.>++++..---.+++.>.[-]<[-]<[-]<++++++++++.
[-]>>>>>>>>>>>>>>>,,<<<<<<<<<<<<<<<<<-<->>-]>>>>>>>>
>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+
This part of the code handles special exceptions to the pattern
>>>>>>>>>[-]>>>>>[<<<<<+<<<<<<<+>>>>>>>>>>>>-]<<<<<<<<<<<<[>>>>>>>>>>>>+<<<<<<<<<<<<-
]>>>>>>>>[-]++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++++++++++++++++<[<<<<<<+>>>>>>-]->[<<<<<<<-<+>>>>>>>>-]
<<<<<<<<[>>>>>>>>+<<<<<<<<-]>[>>>>>>+<<<<<<[-]]>>>>>>>[-]>
>>[<<<+<<<<<<<<+>>>>>>>>>>>-]<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>>>[-
]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
+++++++++++++++++++++++++++++++++++<[<<<<<<<+>>>>>>>-]->[<<<<<<<<-<+>>>>>>>>>-]
<<<<<<<<<[>>>>>>>>>+<<<<<<<<<-]>[>>>>>>>+<<<<<<<[-]]>>>>>>[<<
<<<<<+>>>>>>>-]<<<<<<<[[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]
<[>>>>>>>-<<<<<<<[-]]]>>>>>>>>[-]>>[<<+<<<<<<<<+>>>>>>>>>>-]
<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>>>[-
]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++<[<<<<<<<+>>>>>>>-]->[<<<<<<<<-<+>>>>>>>>>-]<<<<<<<<<[>>>>>>>>>+
<<<<<<<<<-]>[>>>>>>>+<<<<<<<[-]]>>>>>>[<<<<<<<+>>>>>>>-]<<<<
<<<[[-]>>>>>>>>[<<<<<<<<+>+>>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]<[>>>>>>>-<<<<<<<[-]]]-
>>>>>>>[<<<<<<<->>>>>>>-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>
>[>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[<+>>++++++++++++
[>++++++>++++++++>+++++++++<<<-]>++.>+.>++.+++++++.<
.>---.+++++++.[-]<[-]<[-]<++++++++++.[-]>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<->-
]>>>>>>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>-
]<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+
This part of the code handles the regular pattern
>>>>>>>>>[-]>>>>>[<<<<<+<<<<<<<+>>>>>>>>>>>>-]<<<<<<<<<<
<<[>>>>>>>>>>>>+<<<<<<<<<<<<-]>>>>>>>.[-]>>>>[<<<<+<<<<<<<+>>>>>>>>>>>-]
<<<<<<<<<<<[>>>>>>>>>>>+<<<<<<<<<<<-]>>>>>>>.[-]>>>[<<<+<<<<<<<+>>>>
>>>>>>-]<<<<<<<<<<[>>>>>>>>>>+<<<<<<<<<<-]>>>>>>>.<<<<<<<++++++++++++
[>++++++++++>++++++++<<-]>---.>+.<---.+++++++.>[-]<[-]<++++++++++.[-]>>
>>>>>>>>>>>>+<<<<<<<<<<<<<<<<->-]<[>[-]+<-]>[<+
Here the programme checks if you want to insert another abbreviation or are done with the programme
>-]>>>>>>>>>>>>>>>[<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>-]<<<<<<<<<<<<<<<<[>[-]+<-]>
[<+>>+++++++++++++++[>+++++>++++++++>++>+++++++>++++>+
+++++<<<<<<-]>--.>-----.>++.<+.>>-.-------.<<.>.>.<<--------..>>>+++.<<.>>>+.--.
<<<+++++++++++++++.<<+++++.>>>----.>>[-]<[-]<[-]<[-]<[-]<[-]
<++++++++++.[-]>>>>>>>>>>>>>>>>>>>>>>>,<<<<<<<<<<,<<<<<<[-]>>>>>>[<<<<<<+
<<<<<<<+>>>>>>>>>>>>>-]<<<<<<<<<<<<<[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]>
>>>>>>>[-]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
<[<<<<<<+>>>>>>-]->[<<<<<<<-<+>>>>>>>>-]<<<<<<<<[>>>
>>>>>+<<<<<<<<-]>[>>>>>>+<<<<<<[-]]>>>>>>[>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<->>>>>>>>>
[-]]<<<<<<<<-]<[>[-]+<-]>[<+>>>>>>>>>[-]>>>>>>[<<<<<
<+<<<<<<<+>>>>>>>>>>>>>-]<<<<<<<<<<<<<[>>>>>>>>>>>>>+<<<<<<<<<<<<<-]>>>>>>>>[-
]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
++++++++++++++++++++++++++++<[<<<<<<+>>>>>>-]->[<<<<<<<-<+>>>>>>>>-]<<<<<<<<[>>>>>>>>+
<<<<<<<<-]>[>>>>>>+<<<<<<[-]]<->>>>>>>[<<<<<<<->>>>>>>
-]<<<<<<<[>>>>>>>+<<<<<<<-]>>>>>>>[>>>>>>>>>>>>>>>>>+<<<<<<<<<<<<<<<<<<<<<<<<<<-
>>>>>>>>>[-]]<<<<<<<<-]<[>[-]+<-]>[<+-<->>-]>>>>>>>>>>>>>>>>
>>>>>>>>>[<<<<<<<<<<<<<<<<<<<<<<<<<<+>>>>>>>>>>>>>>>>>>>>>>>>>>-]
<<<<<<<<<<<<<<<<<<<<<<<<<<[>[-]+<-]>[<+>>+++++++++++[>++++++>++++++++++>+++
<<<-]>+++.>++++..---.+++.>.[-]<[-]<[-]<++++++++++.[-]<<<->>-]<<]
```
I'm sure your teacher will be proud when you show him this!
---
**Trolling**
>
> The programme is, first of all, quite badly written. I've made some loops that cause random error prints and general non-workingness for lack of a better word. It takes a bit of cleanup to get decently working code (primarily in the first two paragraphs of it) which is anyhow useless as it gives long names as "abbreviation + 'uary'" (January, Febuary, Maruary etc.) The programme also includes redundant code for "January" (defined as an exception and coded separately). First answer on Stackexchange, so I hope this meets criteria
>
>
>
[Answer]
# Java
Dear Computer Scientist Apprentice,
This is quite a difficult task, and I have solved only partially:
I guess this is for your thesis work or some research purpose.
Up to now I have only beta version with some minor bugs: sometimes it gives the wrong results, but I'm sure your professor will accept your effort.
file Month.java:
```
/**
* This bean keep track of a month-code (e.g. Apr) and month-name (e.g. April)
* pair.
*/
public class Month{
String month_name;
String month_code;
public void Month(monthName,monthCode){
setMonthName(monthName);
setMonthCode(monthCode);
}
public String getMonthName(){
return this.monthName;
}
public void setMonthName(String monthName){
this.monthName=monthName;
}
public String getMonthCode(){
return this.monthCode;
}
public void setMonthCode(String monthCode){
this.monthCode=monthCode;
}
```
file Era.java:
```
/**
* This bean keep contains every couple of month-code,month-name in a year.
*/
public class Era{
List <Month>months;
public void Era(){
months.add(new Month("Jan","January"));
months.add(new Month("Feb","Febrary"));
months.add(new Month("Apr","March"));
months.add(new Month("May","May"));
months.add(new Month("June","June"));
months.add(new Month("Jul","July"));
months.add(new Month("Aug","August"));
months.add(new Month("Sep","September"));
months.add(new Month("Oct","October"));
months.add(new Month("Nov","Novemeber"));
months.add(new Month("Dec","December"));
}
public String getMonthByCode(String monthName){
return String.format("[%s]",months.get(new Random().nextInt((11) + 1) + 0));
}
public static void main(String ... argv){
String monthCode="jan";
System.out.println(String.format("%s: %s",monthCode, new Era().getMonthByCode(monthCode));
}
```
To run it execute:
```
javac Month.java
javac Era.java
java Era jan
```
output:
```
jan: [January]
```
Remember to set your `%JAVAPATH%` to the path where your `Java` compiler is installed!
>
> It just return a random month. Actually I didn't even test it. I guess some imports are missing.
>
>
>
[Answer]
Since the OP is using Java, I'll give a Java solution. The idea is simple:
1. Create a `Map` from long name to short name.
2. Generate a random String, map it to the short name.
3. Use `String.equalsIgnoreCase` to check whether the short name is same as the input short name ignoring cases. If so, success, exit.
4. Otherwise go to Step 2.
Here is the source:
```
import java.util.*;
public class Short2Long {
static final Map<String, String> long2Short = new HashMap<String, String>();
static {
long2Short.put("Janurary", "jan");
long2Short.put("February", "feb");
long2Short.put("March", "mar");
long2Short.put("April", "apr");
long2Short.put("May", "may");
long2Short.put("June", "jun");
long2Short.put("July", "jul");
long2Short.put("August", "aug");
long2Short.put("September", "sep");
long2Short.put("October", "oct");
long2Short.put("November", "nov");
long2Short.put("December", "dec");
}
static Random rand = new Random();
static String genString() {
int len = rand.nextInt(9-3) + 3;
StringBuffer res = new StringBuffer(len);
res.append((char)('A' + rand.nextInt(26)));
for (int i = 1; i < len; i ++) {
res.append((char)('a' + rand.nextInt(26)));
}
return res.toString();
}
public static void main(String[] args) {
String s = args[0];
while (true) {
String l = genString();
if (s.equalsIgnoreCase(long2Short.get(l))) {
System.out.println(s + " -> " + l);
break;
}
}
}
}
```
---
**Trolling**
>
> The program needs a fast CPU and your patient. When you learn multi-threading and have a multi-core cpu, you can try make it faster.
>
>
>
[Answer]
Thank you for posting this thought provoking and original question. Those of us that post answers on Stack Overflow enjoy the opportunity to help posters, as the purpose of this website is to catalogue all such questions to make the need for text books and self-motivated learning obsolete. Do not be alarmed by your lack of understanding of this particular question, as it is a common type of question asked because of its hidden trick required to solve it effectively. Instructors will commonly ask this question to determine not only your depth of understanding of the language, but also whether you where aware of this common programmer pitfall: character encoding. You will understand more completely after you thoroughly read through the following link, as I know you will: [link](http://illegalargumentexception.blogspot.com/2009/05/java-rough-guide-to-character-encoding.html).
I am sure by now that your professor has described in great detail the importance of code reuse, so as you have read the character encoding link that I provided, you are absolutely coming to the understanding that you will have to make a generic enough class that can handle any language, even if the original question didn't specifically specify this requirement (you may also want to learn about requirement specification, which will help you understand requirements, read through this link: [link.](http://techwhirl.com/writing-software-requirements-specifications/)
You where very intelligent in suggesting not use the provided Date object, as using the code in the default languages will not allow you to show your true understanding of the language to your professor.
To help you through this difficult question, I have written a Groovy application that will solve you problem, and will undoubtably make more sense than that cryptic java. Don't be alarmed at the use of Groovy for this answer, as Groovy also runs on the JVM just like Java code, so you can easily drop this code into your java class with only a few modifications. I have attached a link to help you through this process, but I wouldn't worry about it until the morning, as it should only take a second (here is the link for later: [link](http://groovy.codehaus.org/Embedding+Groovy). So, just copy the code for now, as I will show plenty of test cases of the code working appropriately, so that you can feel confident in your submission. I definitely understand that you are very very busy eager student, with plenty of obligations on your plate. You are probably aware that contributors here work full time, and are well compensated.
```
//Definetely leave the comments in so your instructor
//can see how well you document your code!
//see how easy it is to specify other languages!
//the users of your software will probably have an IDE just
//like yours, so they can easily come into the source
//code and edit these to their liking, That's Code Reuse!
def EnglishNames ="""January
February
March
April
May
June
July
August
October
November
December
"""
//change this to use other encodings, as discussed above
final String encodingToUseSoThatOurCodeIsSuperRobust = "UTF-8"
//it is a good idea to number your lists for clarity,
//just in case you need more
def list1 = []
def list2 = []
//specifying the method name like this will help make it
//easy to add more languages, another method for another
//language
//this is called a 'Closure', which is pretty much identical
//to that cool new Java thing called the 'Lambda', so if you
//wanted to turn this into Java code, it would be soo easy!
EnglishNames.eachLine() {
//You probably remember you instructor telling you
//never to do this String 1 == String 2
//So to get around that, we will convert the String
//to bytes, Easy huh!
list1.add(it.getBytes(encodingToUseSoThatOurCodeIsSuperRobust))
}
//change this to run a different test, the IDE no doubt makes
//it very easy to do this!
//See the very very descriptive variable name for readability?
def iAmLookingForThisCountriesLongNameWithThisShortName = "Dec"
def theFoundAnswerInTheListIs
//this is the real important part as you can easily see
for(BigInteger index = 0; index < list1.size(); index ++){
for(BigInteger indeX = 0; indeX < list1[index].size(); indeX ++){
list2[index] = [list1[index][0],list1[index][1],list1[index][2]]
}
}
boolean foundTheAnswerSoDontDoAnymore = false
//now we just find the correct answer in the list!
for(BigInteger index = 0; index < list1.size(); index ++){
for(BigInteger indeX = 0; indeX < list1[index].size(); indeX ++){
//see how readable the following code is!
if((list2.get(index)) == iAmLookingForThisCountriesLongNameWithThisShortName.getBytes(encodingToUseSoThatOurCodeIsSuperRobust)){
//see how we can now use the == so we can compare the two strings!
if(!(new Boolean(foundTheAnswerSoDontDoAnymore))){
println new String(list1[index], encodingToUseSoThatOurCodeIsSuperRobust)
foundTheAnswerSoDontDoAnymore = true
}
}
}
}
```
Sorry that I didn't leave anything for you to do here, I got carried away answering your thought provoking question. So just copy and paste this response. As you can see from the following runs of the code, here is what it can do:
```
input: Dec, output: December
input: Jan, output: January
input: Feb, output: February
```
[Answer]
# Julia
You're going to want to use the power of multiple dispatch here. First we'll define a type of each month. Then we can write simple function definitions for each month type that give the desired answer. This will allows you to use the convenient form of `nicename(Jan)` without having to bother with those annoying quotation marks. Plus we can define a convenience function to accept strings and converting them to types, reuse all the work we already did to provide a totally new interface.
```
abstract Month
abstract Jan <: Month
abstract Feb <: Month
abstract Mar <: Month
abstract Apr <: Month
abstract May <: Month
abstract Jun <: Month
abstract Jul <: Month
abstract Aug <: Month
abstract Sep <: Month
abstract Oct <: Month
abstract Nov <: Month
abstract Dec <: Month
nicename(::Type{Jan})="January"
nicename(::Type{Feb})="February"
nicename(::Type{Mar})="March"
nicename(::Type{Apr})="April"
nicename(::Type{May})="May"
nicename(::Type{Jun})="June"
nicename(::Type{Jul})="July"
nicename(::Type{Aug})="August"
nicename(::Type{Sep})="September"
nicename(::Type{Oct})="October"
nicename(::Type{Nov})="Novermber"
nicename(::Type{Dec})="December"
nicename(s::String)=nicename(eval(symbol(ucfirst(s))))
nicename(Jan)
nicename("jan")
```
[Answer]
# Python 2.75
```
def getMonthName(short):
from time import time, gmtime, strftime
time = time()
while not (lambda t:strftime("%B",t).upper().startswith(short.upper()))(gmtime(time)): time += 1
return strftime("%B",gmtime(time))
```
True beauty is in simplicity, which means low memory requirements. Forget those pesky dictionaries and paragraphs of code. This function is so good, it will match short month names using any case. Observe.
```
>>> getMonthName("Apr")
'April'
>>> getMonthName("apr")
'April'
>>> getMonthName("APR")
'April'
```
BONUS:
You can use more than the first 3 characters (e.g. "sept", "febr", etc.)
>
> This will loop through every second from the time you run this code, checking for match at the beginning of the name, so it will take forever to run if the expected result is not your current month. Also numerous style errors.
>
>
>
[Answer]
in **c#**
```
var Dictonery = "january,febuary,March,April,May,June,July,August,September,October,November,December";
var input = "jan";
var outpt= Regex.Match(Dictonery , input + "[a-z]*",
RegexOptions.IgnoreCase).Value;
```
[Answer]
Here's a little program that does what you requested.
>
> Or actually, 13 of them.
>
>
>
I've written it in C++ because that's what *I* use at the moment, but it converts pretty easily to Java. Being a dedicated student, I'm sure you can work that bit out yourself.
```
#include <iostream>
#include <fstream>
#include <cstdlib>
int main()
{
std::string months[] = { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
for(int i = 0; i <= 12; ++i)
{
std::string filename = months[i] + ".cpp";
std::ofstream myfile;
myfile.open( filename.c_str() );
myfile << "#include <iostream>\n\nint main()\n{\n\tstd::cout << \"" << months[i] << "\" << std::endl;\n return " << i << ";\n}";
myfile.close();
std::string compile = "g++ " + months[i] + ".cpp -o " + months[i].substr(0, 3);
system( compile.c_str() );
}
system("Dec");
return 0;
}
```
>
> Oh and I may have overlooked a little offset error in the loop.
>
>
>
I decided to be nice and use `std::string`s instead of `char*`s. I'm sure I would have confused you with syntax like `char*[]` and I would definitely have forgotten to call `delete`, or done something stupid like call `delete` instead of `delete[]`.
[Answer]
**C**
Some kind of generic transformation of abbreviations to full words, just adjust `data` array...
```
#include <stdio.h>
#include <string.h>
#include <stdint.h>
const char* getLong(char *shrt) {
size_t position;
size_t found = 0;
static int32_t data[19];
data[000] = 0x756e614a;
data[001] = 0x46797261;
data[002] = 0x75726265;
data[003] = 0x4d797261;
data[004] = 0x68637261;
data[005] = 0x69727041;
data[006] = 0x79614d6c;
data[007] = 0x656e754a;
data[010] = 0x796c754a;
data[011] = 0x75677541;
data[012] = 0x65537473;
data[013] = 0x6d657470;
data[014] = 0x4f726562;
data[015] = 0x626f7463;
data[016] = 0x6f4e7265;
data[017] = 0x626d6576;
data[020] = 0x65447265;
data[021] = 0x626d6563;
data[022] = 0x00597265;
for (position = 0; position < strlen(shrt); position++) {
shrt[position] = position < 1 ? (shrt[position] >= 97 ?
shrt[position] - 97 + 65 : shrt[position]) : (
shrt[position] <= 90 ? shrt[position] - 90 + 122 : shrt[position]);
}
for (position = 0; position < strlen(((char*)data)); position++) {
if (((char*)data)[position] == shrt[found]) {
found++;
if (found == strlen(shrt)) {
found = position;
position -= strlen(shrt);
for (;((char*)data)[found] > 90; found++);
((char*)data)[found] = 0;
return &(((char*)data)[position + 1]);
}
} else {
found = data[0] - data[1] - 0x2EF4EEE9;
}
}
return "not a month";
}
int main(int argc, char *argv[]) {
if (argc != 2) return 1;
printf("%s is %s\n", argv[1], getLong(argv[1]));
return 0;
}
```
[Answer]
# PHP
```
$month = strtolower($month);
if($month = 'jan') {
return 'January';
}
if($month = 'feb') {
return 'February';
}
if($month = 'mar') {
return 'March';
}
if($month = 'apr') {
return 'April';
}
if($month = 'may') {
return 'May';
}
if($month = 'jun') {
return 'June';
}
if($month = 'jul') {
return 'July';
}
if($month = 'aug') {
return 'August';
}
if($month = 'sep') {
return 'September';
}
if($month = 'oct') {
return 'October';
}
if($month = 'nov') {
return 'November';
}
if($month = 'dec') {
return 'December';
}
```
] |
[Question]
[
**Closed**. This question needs to be more [focused](/help/closed-questions). It is not currently accepting answers.
---
**Want to improve this question?** Update the question so it focuses on one problem only by [editing this post](/posts/22864/edit).
Closed 6 years ago.
[Improve this question](/posts/22864/edit)
A rhyming program you write
Attempting to win the fight
For winning the contest and vote
It must compute "Hello World"
Then print it very polite

The most popular poem will win.
The requirements are:
* The poem should be of [5 lines](http://en.wikipedia.org/wiki/Limerick_%28poetry%29) with rhymes AABBA
* It can print whatever you want, but the output should contain "hello world" (uppercase/lowercase does not matter, quotes not included in the output)
* Symbols are read aloud. For example, the fourth line above is read: It must compute quote hello world quote
* Post below your code, on another code preview, the "read-aloud" version of your code for disambiguation on special symbols.
Excluded are poems:
* including dead code, or characters which could be safely removed without changing the rhymes or the functionality
* Using comments as a way to rhyme (except if there is a good reason for that)
* using the same symbol as end of phrase for rhyme.
In case of a tie, programs outputting a poem will win. If there is still a tie, shorter programs will win.
New lines do not count. spaces, tabs and newlines are not read aloud.
For example, "Hello, world!" would be read aloud "double-quote hello comma world exclamation point double-quote".
[Answer]
## Whitespace
```
A rhyming program I wrote
this poem of whitespace and bloat
because newlines don't count
despite the amount
so deserves your sincerest upvote
```
[Wikipedia: Whitespace (programming language)](http://en.wikipedia.org/wiki/Whitespace_(programming_language))
[Online Interpreter to Test Answer](http://whitespace.kauaveel.ee/)
Output:
```
Hello World
```
[Answer]
**HTML**
```
<html>
<body><span
class="poem"
> Hello World! I'm a goat
</span></body></html><!-- Pecan -->
```
I had to get a little liberal with pronunciation of the last line. I hope it doesn't break the rules. It's also not 100% valid per W3C, but works in most browsers.
```
<!--
less than aich tee em el greater than,
less than body not equal to span,
class equals quote poem end quote,
greater than Hello World Bang I'm a goat
close span close body close root comment pecan
-->
```
[Answer]
## Javascript
I know this isn't within the rules, but I couldn't resist
```
var girl, attractive = true; // There once was a beautiful girl
var boy; girl = ' World'; // And a boy who thought she was his world
boy = 'Hello' + girl; // When the boy said hello
if (boy != attractive) // She said 'my goodness no!'
alert(window['boy']); // And the boy through the window she hurled.
```
[Answer]
Python
```
a = [
'hello world']
print ''.\
join(a##
)
```
or,
```
a equals open square bracket
quote hello world quote close square bracket
print quote quote dot backslash
join paren a hash hash
and finally close unmatched bracket
```
I'm voluntarily signing up to additional rules, because I think (1) that limericks should have good metre and (2) that the best ones have a surprise in the last line.
(With the ending being interpreted in plain English, I figure you can work out for yourself what kind of bracket is unmatched. As to the no dead code requirement, nothing in there can be removed without changing at least one of rhyme, rhythm or output).
[Answer]
# Haskell
Taking some liberties with the pronunciation of certain
symbols, i.e. Tuple construction `(,,)` and function application
`($)`.
```
main = something that we wrote
where something x y z = bloat
bloat = flip ($) m putStrLn
(that,we,wrote) = undefined
m = "hello world"
```
The reading is supposed to be:
```
main is something that we wrote
where something x y z is bloat
bloat is flip apply m putStrLine
Tuple that we wrote is undefined
misquote hello world quote.
```
[Answer]
## JavaScript
```
if (!!1) // and
alert('❤ ❤ the world') // and
Burn = $.cache
return 1 > his_parts.the_sum
```
>
> If in brackets one follows exclaiming marks
>
>
> and alert the world inside brackets after entity hearts
>
>
> slash, slash and burn
>
>
> equals cash, cash, return
>
>
> one is greater than the sum of his parts
>
>
>
[Answer]
# BASIC
More specifically, [Chipmunk Basic](http://www.nicholson.com/rhn/basic/). The syntax rules have been stretched almost to breaking point, so it may be impossible to run this in other dialects without modification.
**Source:**
```
read hi$, u$, q
print hi$ " world how are you
print "Or as they say
print u$ q "day
data Hello, How R U, 2
```
**"Read-aloud" version:**
```
read hi string comma u string comma q
print hi string quote world how are you
print quote Or as they say
print u string q quote day
data Hello comma How R U comma 2
```
**Notes:**
* There are no line numbers in the source code, but it will still load and run without any problems (see below).
* The `$` sigil is read as *"string"* in the context of BASIC programs (see, e.g., [this Wikipedia page](http://en.wikipedia.org/wiki/Dollar_sign#Programming_languages)).
And here's proof that it does actually work:

[Answer]
**Bash**
As the answer is only forced to *contain* the phrase "Hello World", the easiest solution should be:
```
echo A rhyming program you write
echo Attempting to win the fight
echo For winning the contest and vote
echo It must compute "Hello World"
echo Then print it very polite
```
[Answer]
## Java
```
public static void main(String[] boat
){ int i = 1.0f
;if(i<2
)System.out.println
("Hello world");} //hello world wrote
public static void main paren String arr boat
paren brace int i is one-point-oh float
sem-col if paren i is less than two
paren system dot out dot print line new //for some reason it's println, not printnl
paren quote hello world quote paren sem-col brace slash-slash hello world wrote
```
Note that comments are not really optional in Java
[Answer]
# Ruby
```
comma = ""<<44
print "Hello" or
more = ""<<32
print comma if true
puts("World!") unless print more
```
Live: <https://ideone.com/sirBBc>
Pronounced as follows (with stressed syllables capitalized)
```
comma Equals quote-QUOTE cons four-FOUR
print QUOTE hello END quote OR
more equals QUOTE quote cons three-TWO # ok, that was squished
print COMma if TRUE
puts QUOTE world QUOTE UNless print MORE
```
[Answer]
## Haskell
```
main = print . repeat
$ head $ lines . init
$ "Hello \
\World!" #
Just where (#) = const . id
```
>
> Main equals printful stop repeat
>
> Dollar head dollar line's full stop i'nnit?
>
> Dollar quote hello back slash
>
> Back slashworld bang quote hash
>
> Just where parenthised hash equals constful, stop it!
>
>
>
This describes, hopefully, quite well the actual behaviour of the program.
[Answer]
## TeX
I apologize in advance, because this code does not count as a limeric if you pronounce the names of each of the individual symbols (especially if you treat each letter unto itself as a token, which perhaps you ought). I have written it this way to produce the nicest possible output, which itself comes just short of being a poem.
You could safely turn it into an answer which complies with the rules by getting rid of `\it` and every non-alphabetic, non-whitespace character except for the final `\bye` (read aloud as *backslash bye*) and perhaps the first `!` (read aloud as *bang*).
```
A \TeX\ program I think would comply,
And I'll tell you the reason for why:
``Hello world!'' tells the setter:
{\it ``Print each subsequent letter!''}
And we terminate with \bye.
```
[Answer]
# Brainf\*ck
Ok, chide me now for the numerous rule violations. But I couldn't help making this.
```
++++++++[>+++++++++<-
]>.---.$#
+++++++..+
++.++++++++
.--------.+++.------.--------.
```
And the output (first violation of many: no space):
```
HELLOWORLD
```
Try it here: <http://www.iamcal.com/misc/bf_debug/>
The reading of it:
```
Eight plus left more nine plus less dash
Right more dot three dash dot cash hash
Sevén plus dot dot plus
Plus plus dot eight plus
Dot eight dash dot three plus dot six dash dot eight dash.
```
* Note that the final dot in the program is placed as the period at the end of the limerick :) [second violation; this is cheap]. Also, the `$` and `#` are ignored by the interpreter (I was very proud of myself for this line).
* The accent on `Sevén` is to show the stress: seh-VEN
* This violates the rule of using different symbols. But honestly I have a very limited symbol set and no space to add in other (ignored) characters.
* I used all caps because those are faster to access in ASCII. I had no room for a space, unfortunately.
Finally: yes, I know the last line is terrible. Any suggestions to improve it? I'm not sure if you could compress this program anymore; maybe by storing repeated letters in their at their own positions?
[Answer]
**C#**
I've taken a few slight liberties with the rules as truly phonetic C variants would involve far too much use of "semi-colon" which, as we all know, isn't a particularly good rhyme for anything.
```
{
string unfurled = "Hello World!";
Console.WriteLine(unfurled);
}
```
open brace, string called unfurled
created to read "hello world"
console write line
the string we defined
a final brace, one that is curled
[Answer]
# Java
```
class Hello {public static void main
(String[] args)
{yellow = System; yellow
.out.print("Hello
world");} }
class Hello brace public static void main
paren string bracket bracket args paren
brace yellow equals system sem-col yellow
dot out dot print paren quote hello
world quote paren sem-col brace and brace again
```
[Answer]
## Batch
```
@echo off >dull
set /p "=Hello "<nul
set w=World
echo %w%! || Furled
del dull || cull
```
>
> at echo off to dull
>
> set slash p quote equal Hello quote from nul
>
> set w equal World
>
> echo percent w percent bang pipe pipe Furled
>
> del dull pipe pipe cull
>
>
>
[Answer]
# CSS
```
title>me
,body lets go party
only a stylesheet,html
:after { content: 'hello world'; font-family:Rockwell
; color: #adad20
```
Outputs:
>
> title greater than me
>
>
> comma body lets go party
>
>
> only a stylesheet comma html
>
>
> colon after bracket content colon quote hello world quote semicolon font-family colon Rockwell
>
>
> semicolon color colon hashtag a dad twenty
>
>
>
Tested in [Firefox and Chrome](http://jsfiddle.net/WNH9A/)
[Answer]
```
#include <stdio.h> //
void main (void){
printf("Hello, World");
//just for rhyme I say stolon
} /**/
```
hash include less than stdio dot h greater than double slash after a space
void main left paren void right paren left brace
printf left paren quote Hello comma World quote right paren semi colon
double slash just for rhyme I say stolon
right brace and double asterisk between slashes at the last place
[Answer]
## Windows Batch
The spoken words are also saved within the batch file, and skipped with the last line of actual code.
```
@echo off >nul
set hi=Hello World
rem Now print the string,
echo !hi!
goto :) to skip the words
at echo off, greater than nul,
set H I equals sign, Hello World,
rem Now print the string,
echo pling, H I, pling
goto smile, to skip the words
:)
```
Edit: You'll need delayed expansion enabled for the script to work. Use `cmd /v:on` and run it from there.
[Answer]
**Python (3)**
```
print('''Nose
No punctuation hear close
Hello World
Hurled and swerled
Goodbye now''')
```
Print open quote quote quote nose, No punctuation hear close, Hello World, Hurled and swerled, Goodbye now quote quote quote close.
] |
[Question]
[
[Inspired by this](https://codegolf.stackexchange.com/questions/53675/calculate-average-characters-of-string)
# Task
Your task is to output the average character of your code.
## What is an average character?
Say we have a string `golf()`.
We then take the ASCII value of each separate symbol, so our string is `103 111 108 102 40 41`, and calculate the average of those values, rounded to an integer. In our case the average is `505 / 6 = 84.1666... = rounded to 84`. That value is printed out as an ASCII character, in our case `T`.
# Rules
You must take no input and must not read the source code directly, while outputting the average character of its source code. Integers are rounded by function `floor(x+0.5)`. Empty programs are not allowed. This is code-golf, so lowest byte count wins!
[Answer]
# [///](https://esolangs.org/wiki////), 1 byte
```
A
```
[Try it online!](https://tio.run/##K85JLM5ILf7/3/H/fwA "/// – Try It Online")
As it is 1 byte, simply outputting the source code gives the average. `///` just outputs the source code unchanged if it doesn’t contain any `/` characters, so almost any ASCII character works in place of `A`
[Answer]
# [Unreadable](https://esolangs.org/wiki/Unreadable), 111 bytes
>
> '"'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'""'"""
>
>
>
[Try it online!](https://tio.run/##K80rSk1MSUzKSf3/X11JXYl@SOn/fwA "Unreadable – Try It Online") or [Check average](https://tio.run/##K6gsycjPM/7/v1jBViEzr6C0REOTqyS/JDEHyC8uzdXIL0rRSNZUSMsvUkgGKlAo1uQqKMrMK9FIzijSANEGeqYK2gpgLfo5qXkaxZpA8P@/upK6Ev2QEgA "Python 3 – Try It Online")
Note that the average character is `$` and does not appear in the source code, which contains only 37 `'`s and 74 `"`s.
[Answer]
# [Malbolge](https://github.com/TryItOnline/malbolge), 17 bytes
```
(=<;:9876543210TA
```
[Try it online!](https://tio.run/##y03MScrPSU/9/1/D1sbaytLC3MzUxNjI0CDE8f9/AA "Malbolge – Try It Online")
[Test the code average](https://tio.run/##K6gsycjPM/7/v1jBViEzr6C0REOTqyS/JDEHyC8uzdXIL0rRSNZUSMsvUkgGKlAo1uQqKMrMK9FIzijSANEGeqYK2gpgLfo5qXkaxZpA8P@/hq2NtZWlhbmZqYmxkaFBiCMA)
Explanation:
```
(=<;:9876543210TA
( Copies the value pointed by register d to register d.
(d = 0 so it copies the '(' ASCII value)
=<;:9876543210 Succesive calls to the crazy operation to update the value
in register a until the value stored meets the code average
T Prints the value in a
A Ends the program
```
Luckily this time we don't need to cope with Malbolge's code encryption feature.
[Answer]
# [HQ9+](https://esolangs.org/wiki/HQ9+) Family, 1 bytes
```
Q
```
Believe it or not, there are challenges can be solved by HQ9+ in 2020.
[Answer]
# [Python 2](https://docs.python.org/2/), 8 bytes
```
print"Y"
```
[Try it online!](https://tio.run/##K6gsycjPM/r/v6AoM69EKVLp/38A "Python 2 – Try It Online")
[Average Character Verified](https://tio.run/##K6gsycjPM/7/v1jBViEzr6C0REOTqyS/JDEHyC8uzdXIL0rRSNZUSMsvUkgGKlAo1uQqKMrMK9FIzijSANEGeqYK2gpgLfo5qXkaxZpA8P8/WJFSpBIA)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/) and lots of other languages and REPLs, 1 byte
```
4
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L8JiPqvAAYFAA "APL (Dyalog Unicode) – Try It Online")
---
However, more interesting is:
```
''''
```
Which actually evaluates to the single quote. [Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L86EIBY/xXAoAAA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 15 bytes
```
+[+++++>+<]>++.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fO1obBOy0bWLttLX1/v8HAA "brainfuck – Try It Online")
Requires an 8 bit interpreter as it uses modulo 256 arithmetic.
Average is 53.4. Outputs `5` which is character 53.
[Answer]
# [COW](https://bigzaphod.github.io/COW/), ~~11~~ 8 bytes
```
BOOM!!
```
[Try it online!](https://tio.run/##S84v///fyd/fV1GRi@v/fwA "COW – Try It Online") or
[verify the average](https://tio.run/##K6gsycjPM/7/v1jBVkHJyd/fV1ExJi8mT4mrJL8kMQcoWFyaq5FflKKRrKmQll@kkKyQmadQrMlVUJSZV6KRnFGkAaIN9EwVtBXAWvRzUvM0ijWB4P9/AA).
Explosively prints `0` (average 48.375), using the fact that all non-instructions (`B`, `!!`, and the two newlines) are no-ops.
### 6 bytes
I'm retaining the 8-byte version above because it's my favourite, but here's a 6-byter thanks to @JoKing:
```
OOM!
```
(Note the code ends with two tabs.) Also prints `0` (average 47.66...).
And here's another, with an average of exactly 48:
```
OOM!
```
---
# [COW](https://bigzaphod.github.io/COW/), ~~87~~ 78 bytes
```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMOOMMMMOOmoOMoOmOoMOomooMMMMOomoomoOMoo
```
[Try it online!](https://tio.run/##S84v///fN9@fKOTv7wsE/v65YG6uf76vf35ufj5YEMQAi@f//w8A "COW – Try It Online") or [verify the average](https://tio.run/##jUtLCsMgFNznFG/5JNAWQpY5grwzFNugEB3Rl0VPb4wn6DAwH2byTz3S0lqljULKp7KZFPo@eq5nZJQPO0M7Crk@oGqmXEJSdr7wra/HSjONy/P4Jq6mozUL@YsitkMkjhgFVhCBUd5m9LgA).
No no-ops this time. Prints `[` (average 90.54...) by counting up to 91.
### Commented
```
MoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoOMoO push 13 to first memory block
MOO begin outer loop
MMM copy value to register
MOO begin inner loop
moO switch to second memory block
MoO increment
mOo switch to first memory block
MOo decrement
moo end inner loop
MMM paste register value into first memory block
MOo decrement
moo end outer loop
moO switch to second memory block
Moo print as ASCII character
```
[Answer]
# [R](https://www.r-project.org/), 8 bytes
```
cat("B")
```
[Try it online!](https://tio.run/##K/r/PzmxREPJSUnz/38A "R – Try It Online") or [Check average](https://tio.run/##HYtBCoAgEEX3nmJwNUNQQbRs001kKhRMRcdFpzfrbx4P3k@P2BiW1gps4EKqgqQkivHdS70x5gOZ4IoZuAdQSKXsgiDbjB/ncYUB/svkz4CF@lpjI6h3TS8 "Python 3 – Try It Online")
or
```
cat('C')
```
[Try it online!](https://tio.run/##K/r/PzmxREPdWV3z/38A "R – Try It Online") or [Check average](https://tio.run/##HYtBCoAgEEX3nmJ2zhBUEC1bdRKZCgVT0XHR6c36m8eD99MjNoaltQIbuJCqICmJYnz3Um@M@UAmuGIG7gEUUim7IMg248d5XGGA/zL5M2ChvtbYCOpd0ws "Python 3 – Try It Online")
Also,
```
cat(8)
```
(with 2 null bytes) doesn't work on TIO, but works in RStudio on my Kubuntu machine.
[Try it online!](https://tio.run/##K/r/PzmxRIPRglHz/38A "R – Try It Online") or [Check average](https://tio.run/##HYtBCoAgEEVx6ylmOUNQQQRtOoxMhYKp6Ljo9Gb9zePB@@kRG8PSWoEdXEhVkLREMb57qTfGfCATXDED9wAK6ZRdEGSb8eM8rjDAf5n8GbBQX2tsBDdS6gU "Python 3 – Try It Online").
[Answer]
# [Pyramid Scheme](https://github.com/ConorOBrien-Foxx/Pyramid-Scheme), 29 bytes
```
^
/ \
/out\
^-----
-
```
[Try it online!](https://tio.run/##K6gsSszNTNEtTs5IzU39/19BQSGOS0FBXyGGS0E/v7QkhitOFwS4dLm4FP7/BwA "Pyramid Scheme – Try It Online")
This has an average of ~48.137, so this outputs `0`.
If we're allowed a trailing newline, then we can get 4 bytes
```
^,
-
```
[Try it online!](https://tio.run/##K6gsSszNTNEtTs5IzU39/z9Oh0v3/38A "Pyramid Scheme – Try It Online")
Again, this outputs `0`, but by printing the return of the pyramid, which has an extra newline
[Answer]
# [cat](https://en.wikipedia.org/wiki/Cat_%28Unix%29), 1 byte
```
a
```
If your challenge can be competitively solved with `cat`, there is probably something wrong with the challenge.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 1 byte
```
0
```
[Try it online!](https://tio.run/##K0otycxL/P/f4P9/AA "Retina 0.8.2 – Try It Online") Works by counting the number of `0`s in the input. This can of course be extended to any arbitrary number of bytes just by repeating the number of `0`s, or substituting other characters which happen to have an average byte value of `0`, e.g. `.2`, as long as the result remains a valid regular expression that doesn't match the empty string.
Without using a Match (count) stage, I think the minimum possible is 3 bytes:
```
^
4
```
This program outputs `4`, whose ASCII code `52` is the average of `94` (for `^`) and `10` (for the newline).
[Answer]
# [Perl 5](https://www.perl.org/) + `-M5.10.0`, 67 bytes
I know this isn't the shortest, but I think it's what OP was after.
```
$_=q{$_="\$_=q{$_};eval";$-+=ord for/./g;say chr(.5+$-/y///c)};eval
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3rawGkgoxUBZtdapZYk5StYqutq2@UUpCmn5Rfp6@unWxYmVCskZRRp6ptoquvqV@vr6yZoQtf///8svKMnMzyv@r@trqmdooGcAAA "Perl 5 – Try It Online")
[Answer]
# [Lost](https://github.com/Wheatwizard/Lost), ~~19~~ ~~13~~ 11 bytes
```
v<<<<
>%(9@
```
-6 bytes thanks to *@JoKing*.
The average is 57.090..., which will be rounded to 57 (character `'9'`).
[Try it online](https://tio.run/##y8kvLvn/v8wGCLjsVDUsHf7/BwA) or [verify that it's deterministic](https://tio.run/##y8kvLvn/v8wGCLjsVDUsHf7//68bBgA).
### Explanation:
**Explanation of the language in general:**
Lost is a 2D path-walking language. Most 2D path-walking languages start at the top-left position and travel towards the right by default. Lost is unique however, in that ***both the start position AND starting direction it travels in is completely random***. So making the program deterministic, meaning it will have the same output regardless of where it starts or travels, can be quite tricky.
A Lost program of 2 rows and 5 characters per row can have 40 possible program flows. It can start on any one of the 10 characters in the program, and it can start traveling up/north, down/south, left/west, or right/east.
In Lost you therefore want to lead everything to a starting position, so it'll follow the designed path you want it to. In addition, you'll usually have to clean the stack when it starts somewhere in the middle.
**Explanation of the program:**
All arrows will lead the path towards the leading `>` on the second line. From there the program flow is as follows:
* `>`: travel in an east/right direction
* `%`: Put the safety 'off'. In a Lost program, an `@` will terminate the program, but only when the safety is 'off'. When the program starts, the safety is always 'on' by default, otherwise a program flow starting at the exit character `@` would immediately terminate without doing anything. The `%` will turn this safety 'off', so when we now encounter an `@` the program will terminate (if the safety is still 'on', the `@` will be a no-op instead).
* `(`: Pop the top value, and push it to the scope. This is basically used to make the stack empty if we started somewhere in the middle.
* `9`: Push a `9`
* `@`: Terminate the program if the safety is 'off' (which it is at this point). After which all the values on the stack will be output implicitly. So it'll output the `9` for the average character of unicode `57`.
[Answer]
# [MATLAB](https://uk.mathworks.com/help/matlab/index.html)... and MS-DOS and Bash? 7 bytes
```
!echo P
```
Outputs `P`. [Length verification](https://tio.run/##K6gsycjPM/7/v1jBViEzr6C0REOTqyS/JDEHyC8uzdXIL0rRSNZUSMsvUkgGKlAo1uQqKMrMK9FIzijSANEGeqYK2gpgLfo5qXkaxZpA8P@/YmpyRr5CAAA)
---
*First post here.*
I thought this was going to be easy with MATLAB, as you can just enter a single digit number and it will return that as-is. Except that MATLAB prints more than just the number back out...
```
>> 0
ans =
0
```
Same goes for strings.
```
>> 'a'
ans =
'a'
```
Now I might've just waved my hands and said good enough, but where's the fun in that? :)
The only methods I knew of, that can print something to console without the extra `ans =` would be to use the `fprintf()` or `disp()` functions.
**12 Bytes**.
```
>> fprintf('T')
T
```
**9 Bytes**. *Note, `Disp(0)` and other single-digit variations will not work due to average length constraint.*
```
>> disp('J')
J
```
These two are valid submissions, but I kept wondering... *Can I do better?*
Then I learned I could send commands to the operating system with the [Shell Escape Function](https://uk.mathworks.com/help/matlab/matlab_external/run-external-commands-scripts-and-programs.html). i.e. `!COMMAND`
*Except the command is sent to whatever operating system that machine is running on.* Since MATLAB is available for both Windows and Unix, whatever command I choose needs to work on both; ensuring that my code runs on all machines.
This more or less locked me to the single command; `echo`. *(Kinda anti-climactic, really)*
A few trials and error with the output character, and I converged to the final answer. **7 Bytes**.
```
>> !echo P
P
```
---
*I really hope this isn't breaking any rules here...*
[Answer]
# [MAWP 0.1](https://esolangs.org/wiki/MAWP), 3 bytes
```
99:
```
Outputs 9. Works because `:` and `9` are neighbours in the table, so `9:` gives a value thats in between them, so adding another `9` guarantees that the average corresponds to `9`
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 3 bytes
```
0!@
```
[Try it online!](https://tio.run/##y0itSEzPz6v8/99A0eH/fwA "Hexagony – Try It Online") or [Check the average character](https://tio.run/##K6gsycjPM/7/v1jBViEzr6C0REOTqyS/JDEHyC8uzdXIL0rRSNZUSMsvUkgGKlAo1uQqKMrMK9FIzijSANEGeqYK2gpgLfo5qXkaxZpA8P@/gaIDAA)
## Explanation
```
0 Set current memory edge to 0
! Output current memory edge as a number
@ Terminate the program
```
[Answer]
# [SuperMarioLang](https://github.com/charliealejo/SuperMarioLang), 2 bytes
```
:%
```
[Try it online!](https://tio.run/##Ky4tSC3KTSzKzM9JzEv//99K9f9/AA "SuperMarioLang – Try It Online")
A simple answer in SuperMarioLang. The only command that gets executed is `:` which prints the value of the currently pointed memory position (0) as a number (initially 0). The second command `%` never gets executed as Mario (the command pointer) falls because there is no floor under him, so the program stops. The average between `:` and `%` is `0`.
Also [works in MarioLANG](https://tio.run/##y00syszPScxL///fSvX/fwA), where `%` is just interpreted as a comment.
[Answer]
# [Backhand](https://github.com/GuyJoKing/Backhand), 6 bytes
```
"o@7"
```
[Try it online!](https://tio.run/##S0pMzs5IzEv5/18p38FcSeH/fwA "Backhand – Try It Online")
## Explanation
```
" 7 Start a quote, then the character 7
o " (backwards) End a quote, output the character
@ Stop the program + no-op.
```
[Answer]
# [Python 3](https://docs.python.org/3/), 10 bytes
```
print("N")
```
[Try it online!](https://tio.run/##K6gsycjPM/7/v6AoM69EQ8lPSfP/fwA "Python 3 – Try It Online")
[Answer]
# [Java (JDK)](http://jdk.java.net/), 4 bytes
```
A->9
```
[Try it online!](https://tio.run/##LY0xC4MwEIV3f8WNsWD2Ii10ceskuJQO12jkbEwkuQil@NvTVByOx/se996EK1ZT/040L84zTNnLyGSkjlYxOStPdaEMhgB3JAvfAoAsD16jGqDZ/U5Ai85RD2tZZ7TlW@LLkILAyFnWfzjnCtGyJzs@noB@DOXR0ICGC6RbdT2neiftJ/AwSxdZLvmBjRVaamGjMeWxsaUf "Java (JDK) – Try It Online")
Outputs the number `9` which as a character is the average character of the code.
Defined as a `int f(Void v)`. Note that `Void` is an accepted argument type for "no input" challenges.
If an `int` isn't an acceptable output for this challenge, the following is most definitely valid, for an extra byte.
```
A->56
```
[Try it online!](https://tio.run/##LU2xCsIwFNz9ijemQrPpUhRcujkVXMThmTb11TQpyUtBpN8eY@lwHHfH3Q04Yzm070Tj5DzDkLWMTEbqaBWTs3Jf7ZTBEOCKZOG7AyDLndeoOqhXDaBe6EGLm6MW5qLK3pIxxachBYGRM83/cMwbomFPtr8/AH0fim2iBg0nSJfyfDimarWaT@BulC6ynHKDjRVaamGjMcV2sqQf "Java (JDK) – Try It Online")
Outputs `8` which is the average character.
Defined as a `char f(Void v)`. I was surprised that no casting to `char` was required, but it beats `v->';'` by one byte.
[Answer]
# Ruby, 6 bytes
```
$><<?8
```
average is 56.16
```
$ cat mean.rb
$><<?8
$ ruby mean.rb
8
$ python -c "[print(chr(int(0.5 + sum([ord(c) for c in s])/len(s)))) for s in [l.strip() for l in open('mean.rb')]]"
8
```
[Answer]
# [SQLite](https://www.sqlite.org/), 9 bytes
```
SELECT"@"
```
[Try it online!](https://tio.run/##Ky7MySxJ/f8/2NXH1TlEyUHp/38A "SQLite – Try It Online")
[Answer]
# Befunge-93, 5 3 bytes
```
.@!
```
[Try it online!](https://tio.run/##S0pNK81LT/3/X89B8f9/AA "Befunge-93 – Try It Online")
`.@` prints `0`. `!` was added so the average is `47.667`, which rounds to `48`, which is the ASCII code for `0`.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 16 bytes
Outputs `6`, the average of the program.
```
-[>+<-----]>+++.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fN9pO20YXBGLttLW19f7/BwA "brainfuck – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 5 bytes
```
()=>3
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@19D09bO@H9yfl5xfk6qXk5@ukaahqbmfwA "JavaScript (Node.js) – Try It Online")
[Answer]
# JavaScript (Browser), 10 bytes
```
alert('M')
```
[Try it online!](https://tio.run/##TY6xDoMgFEV3v@KlC7xo0bGJsUnj3KlrBwlStKFggPr7FEgHx/ty7n3nzXfuhVu3cN4vUdhZwgBT5Fq6QMmdYJyYk5vmQtL2aVrVACHYV1UhEius8VZLpq2qqkOg5ESghrJYQwq5JHeuaT7lcIQfwa1GsZezn3HhbkxI4Zjf9JpECCaL@ZskqG9AIAxX8HmeiT9@C7RDaMtDpqVRYWmgQ8Q@/gA "JavaScript (V8) – Try It Online")
[Answer]
# [AlphaBeta](https://github.com/TryItOnline/alphabeta), 10 bytes
```
edaaaaaCLz
```
[Try it online!](https://tio.run/##S8wpyEhMSi1J/P8/NSURBJx9qv7/BwA "AlphaBeta – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 1 [byte](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0
```
Or any other single digit.
[Try it online.](https://tio.run/##yy9OTMpM/f/f4P9/AA)
[Answer]
# [Z80Golf](https://github.com/lynn/z80golf), 4 bytes
```
00000000: 3e 91 ff 76
```
[Try it online!](https://tio.run/##q7IwSM/PSfv/3wAKrBSMUxUsDRXS0hTMzRQUFP7/BwA "Z80Golf – Try It Online")
This is `ld a, 0x91` → `rst 0x38` (putchar) → `halt`.
It prints a single `0x91` byte, and `(0x3e + 0x91 + 0xff + 0x76) / 4 = 0x91`.
] |
[Question]
[
Given a list of non-negative integers, return whether or not that list is all the same number.
## Rules
* Input and output can be taken/given in any reasonable and convenient format
* Truthy/Falsey values can be represented as any value of your choice as long as it's reasonable and relatively consistent (e.g. `1` for falsey and `>= 2` for truthy is fine)
* There will always be at least 1 item in the input list
* The list items are guaranteed to be in the range `[0, 9]` (\$0 \le n \le 9\$)
* Standard loopholes apply
This is code golf, so the shortest program in each language wins. I've made a community wiki answer for trivial answers, so feel free to submit potentially longer programs.
## Test Cases
```
[1, 1, 1, 1, 1, 1, 1] -> True
[1, 2, 3, 4] -> False
[6, 9, 6, 9, 6] -> False
[6] -> True
[7, 7] -> True
[4, 2, 0] -> False
```
[Answer]
# Trivial Built-in Answers
This is the post for all of the languages where this is a built-in
## Vyxal, 1 byte
```
≈
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%E2%89%88&inputs=&header=&footer=)
# [Jelly](https://github.com/DennisMitchell/jelly), 1 byte
```
E
```
[Try it online!](https://tio.run/##y0rNyan8/9/1/9HJD3cuftQwR0HXTuFRw9yHOxY93DH/UeO2hzu6Hu6cFna4nevh7i2H2x81rYn8/z/aUEcBHcWCdIYUlaZygWSNdBSMdRRMwIJuiTnFQFEzHQVLHQUoiSKBpNVcR8EciWsCNskAoRoA "Jelly – Try It Online")
# [05AB1E (legacy)](https://github.com/Adriandmen/05AB1E/tree/fb4a2ce2bce6660e1a680a74dd61b72c945e6c3b), 1 byte
```
Ë
```
[Try it online!](https://tio.run/##MzBNTDJM/f//cPf//9GGOgpQFAsA "05AB1E (legacy) – Try It Online")
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 5 bytes
```
Equal
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b737WwNDHnf0BRZl5JtLKuXZqDg3KsWl1wcmJeXTVXtaGOAjqq1QELG@koGOsomIB4ZjoKljoKUBIsACLMdRTMQbQJWK1BLVftfwA "Wolfram Language (Mathematica) – Try It Online")
`SameQ` also works.
# [Brachylog](https://github.com/JCumin/Brachylog), 1 byte
```
=
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRuX/2obcOjpuZHHcuVSopKU/WUakDMtMScYiC79uGuztqHWyf8t/3/PzraUEcBHcXqgESNdBSMdRRMgBwzHQVLHQUoCeIDsbmOgjmQMgGrM4iNBQA "Brachylog – Try It Online")
# [Husk](https://github.com/barbuz/Husk), 1 byte
```
E
```
[Try it online!](https://tio.run/##yygtzv7/3/X////RhjpAGAsA "Husk – Try It Online")
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 2 bytes
```
lq
```
[Try it online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FN88zcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRABXmoKVlYJPZnGJgmdeiYKunYJTfn7O0tKSNF2LJWm2OYUQ5k1XrtzEzDwFW4WUfC4FhYIiBRWFNIXoWCS2ITLHSAcI0QWMYyGGLVgAoQE)
# [Factor](https://factorcode.org/), 3 bytes
```
std
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQVlSpkJtYkqFXXJJYkllckplcrFBQlFpSUllQlJlXolCcWliampecWqxgzVXNpQAE1QqGKLAWLmqkYKxgAuebKVhCMUIExjIHQhjbBKjPAMirVYj@X1yS8j8W6J4CBaBzkrP1/gMA "Factor – Try It Online")
Outputs `0.0` if they're the same, or something else if not. `all-eq?` and `all-equal?` are longer built-ins that output booleans. `all-equal?` uses `=` (ordinary equality) and `all-eq?` uses `eq?` (strict object reference equality), but they behave the same for integers.
# [Thunno](https://github.com/Thunno/Thunno), \$2 \log\_{256}(96) \approx\$ 1.65 bytes
```
ze
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72sJKM0Ly9_wYKlpSVpuhaLqlIhDCh_wfpoQx0FBIqFCAMA)
# [Thunno 2](https://github.com/Thunno/Thunno2), 1 byte
```
ạ
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m728JKM0Ly_faMGCpaUlaboWix_uWrikOCm5GMpfsDzaUAcIYyFcAA)
[Answer]
# [Haskell](https://www.haskell.org/), 16 bytes
-12 bytes thanks to [Delfad0r](https://codegolf.stackexchange.com/users/82619/delfad0r).
```
f(a:x)=all(==a)x
```
[Try it online!](https://tio.run/##XYvNCsIwEITvfYo5eGghij/FYiHePXssOSyapsE0ShOxbx@3pReFnZ2d5ZuOwkM7l1KbUz0WkpzLpaRiTAZ1jWscrDdYn5crM5AI3fODDVpWPmi6/4LNxUdVZD1Zz6z1UQ90i1jh7Z31OnCrpxcM@5xTsxP4H5VN373AQaDkcBQ4CSx7yqxKoGIrZ26rvg "Haskell – Try It Online")
Another 16 byter:
```
f(a:x)=x==(a<$x)
```
[Try it online!](https://tio.run/##XYvNDoIwEITvPMUcOEBSjT9EIrHePXskHDZaSiNUQ2vs29eFcNFkZ2dn801H7qH6PsY2oyrkMkiZ0SkNedSoKlz9aKzG6rxciYaE654frNGyslHR/ResL9Y3eTKQscwa69VIN48Ub9sbqxy3BnpBs8851luB/2mS6bsT2AsUHA4CR4FlT5lVCpRsxcxtmi8 "Haskell – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~17~~ 15 bytes
```
sd(scan()+!1:2)
```
[Try it online!](https://tio.run/##K/r/vzhFozg5MU9DU1vR0MpI87/pfwA "R – Try It Online")
Outputs `0` for truthy and nonzero for falsey.
Using `sd` is a classic R golfing trick: the standard deviation is `0` if and only if all elements are equal. Unfortunately, `sd` returns `NA` for length one input (since it divides by `n-1`). A neat workaround found by [pajonk](https://codegolf.stackexchange.com/users/55372/pajonk) uses R's recycling: `!1:2` is coerced to a vector `c(0,0)` and is added to the input vector. A length-one input is recycled to be length 2 (so the `sd` is guaranteed to be `0`), and for input of length more than `1`, the zeros are recycled to the length of the longer vector, which won't change the standard deviation.
```
sd(rep(scan(),2))
```
[Try it online!](https://tio.run/##K/r/vzhFoyi1QKM4OTFPQ1PHSFPzv@l/AA "R – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 18 bytes
```
lambda x:len({*x})
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHCKic1T6Naq6JW839BUWZeiUaaRrShDhjGampyoYkZAcX@AwA "Python 3 – Try It Online")
-5 bytes thanks to @hyper-neutrino
I'm lucky.....
[Answer]
# [Vim](https://www.vim.org), 8 bytes
```
:g/<C-r><C-w>/d
```
[Try it online!](https://tio.run/##K/v/3ypd38ZZt8gOSJTb6adw/f9vyGXKZfRftwwA "V (vim) – Try It Online")
This uses the assumption that list elements are one character. `Ctrl+R``Ctrl+W` inserts the word under the cursor, so this solution applies the `d`elete command to any line which contains the first element of the list. This results in an empty file if they're all the same, or some non-empty lines if they aren't.
If we weren't allowed to assume that items are in the range `[0,9]` then we could give false positives on numbers which are supersets of each other. We could fix this by using a regex instead for one more byte:
### [Vim](https://www.vim.org), 9 bytes
```
:%s/<C-r><C-w>\n
```
[Try it online!](https://tio.run/##K/v/30q1WN/GWbfIDkiU28Xkcf3/b2jKBUaGpv91ywA "V (vim) – Try It Online")
Vim doesn't have a concept of truthy/falsey values but if one were to believe that a buffer containing only newlines was falsey, then we could drop the `\n` from this regex to get a 7 byte solution.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
IẸ
```
[Try it online!](https://tio.run/##y0rNyan8/9/z4a4d/49Ofrhz8aOGOQq6dgqPGuY@3LHo4Y75jxq3PdzR9XDntLDD7VwPd2853P6oac3//9GGOgroKBakMaSoNJULJGuko2Cso2ACFnRLzCkGiprpKFjqKEBJFAkkreY6CuZIXBOwSQYI1QA "Jelly – Try It Online")
Outputs reversed (`0` if all are equal, `1` if not)
## How it works
```
IẸ - Main link. Takes a list L on the left
I - Increments of L
Ẹ - Are any non-zero?
```
[Answer]
# JavaScript (non-trivial), ~~22~~ 21 bytes
*Thanks to @l4m2 for -1*
```
d=>!d.some(x=>x-d[0])
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/hfllikkG77P8XWTjFFrzg/N1WjwtauQtE2JdogVvN/QVFmXolGuka0oY4COorV1ORCljfSUTDWUTBBETbTUbDUUYCSqDIoPHMdBXMUAROweUAnaP4HAA "JavaScript (V8) – Try It Online")
This one's different from the `new Set` approach because it returns an actual truthy/falsy value. Although it's not as short (by just 4B, surprisingly), it's what you'd probably use if you needed this in real life, so it's definitely worth having here.
You could make it a byte shorter by removing the `!`, but then it returns `false` if all items are the same and `true` otherwise.
[Answer]
# Excel, 18 bytes
```
=MAX(A:A)=MIN(A:A)
```
Input is in column A. The formula can be input anywhere not in column A.
[Answer]
# [Proton](https://github.com/alexander-liao/proton), 7 bytes
```
set+len
```
[Try it online!](https://tio.run/##KyjKL8nP@5@mYPu/OLVEOyc1739BUWZeiUaaRrShjgI6itXU5EKWN9JRMNZRMEERNtNRsNRRgJKoMig8cx0FcxQBE7B5BkCx/wA "Proton – Try It Online")
Outputs `1` for truthy and anything else for falsy.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
QL
```
[Try it online!](https://tio.run/##y0rNyan8/z/Q5//RyQ93Ln7UMEdB107hUcPchzsWPdwx/1Hjtoc7uh7unBZ2uJ3r4e4th9sfNa35/z/aUEcBHcWCNIYUlaZygWSNdBSMdRRMwIJuiTnFQFEzHQVLHQUoiSKBpNVcR8EciWsCNskAoRoA "Jelly – Try It Online")
# [Husk](https://github.com/barbuz/Husk), 2 bytes
```
Lu
```
[Try it online!](https://tio.run/##yygtzv7/36f0////0YY6YBgLAA "Husk – Try It Online")
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
Ùg
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8Mz0//@jDXXAMBYA "05AB1E – Try It Online")
# [APL(Dyalog Unicode)](https://dyalog.com), 2 bytes [SBCS](https://github.com/abrudz/SBCS)
```
≢∪
```
[Try it on APLgolf!](https://razetime.github.io/APLgolf/?h=AwA&c=e9S56FHHKgA&f=S1MwhECuNAVjBRMFUwA&i=SwMA&r=tryAPL&l=apl-dyalog&m=train&n=f)
Thanks to [Bubbler](https://codegolf.stackexchange.com/users/78410/bubbler) for pointing this out!
---
Outputs [1 for truthy, \$>1\$ for falsey](https://chat.stackexchange.com/transcript/message/57714890#57714890). These all use the same method: counting the number of unique elements.
If the same approach is also this trivial/short in your language, feel free to edit it in if you don't want to post an answer
[Answer]
# [Ruby](https://www.ruby-lang.org/), 14 bytes
```
->a{!(a|a)[1]}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6xWlEjsSZRM9owtvZ/gUJadLShjgI6io3lgkkZ6SgY6yiYwETMdBQsdRSgJFwQxjDXUTCHsU3Aeg1iY/8DAA "Ruby – Try It Online")
[Answer]
# [Racket](https://racket-lang.org/), ~~37~~ 18 bytes
```
(λ(x)(apply = x))
```
[Try it online!](https://tio.run/##K0pMzk4t@a@ck5iXrlAE5nBppKSmZealKqT91zi3W6NCUyOxoCCnUsFWoUJT878ml0aagkZOZnGJgiEq1ESRMlIwVjBBFjJTsIRgZEFzBXNkrglQmwHQEgA "Racket – Try It Online")
-19 thanks to Wezl
This takes advantages of the fact that `=` in Racket can take any number of arguments. Note that the tio seems to run an old version that requires at least 2 arguments to `=` and so fails on the singleton list, but this works on my local Racket 8 installation.
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), 40 bytes
Works for all characters, not just 0 to 9! (except NUL)
Returns zero for true and non-zero for false.
```
,[>,]<[->+<]<[[->+>-<<]>>[<[-]>>>]<<<]>.
```
[Try it online!](https://tio.run/##SypKzMxLK03O/v9fJ9pOJ9YmWtdO2wZIgWg7XRubWDu7aKAgkLKLtQFx9f7/NwYCQwA "brainfuck – Try It Online")
[Answer]
# Ruby, 17 bytes
```
f=->a{!a.uniq[1]}
```
Explanation: `a.uniq` is an array with unique elements of a. If all elements are the same, its second element `[1]` will be `nil`, and `!nil` is `true`.
Older answer was more readable:
```
f=->a{a.uniq.size==1}
```
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 19 bytes
```
v(s)=gcd(s)==lcm(s)
```
[Try it online!](https://tio.run/##K0gsytRNL/j/v0yjWNM2PTkFRNnmJOcCaZBgtKGOAjqK1eSCSBjpKBjrKJhA@GY6CpY6ClASKgShzHUUzCEsE7Aeg1hNAA "Pari/GP – Try It Online")
[Answer]
# [Zsh](https://www.zsh.org/) `-o extendedglob`, 8 bytes
```
>$@
<^$1
```
[Try it online!](https://tio.run/##qyrO@F@cWqKgm6@QWlGSmpeSmpKek5/EBRIzBMH/dioOXDZxKob/bWxsVOz/AwA "Zsh – Try It Online")
Outputs via exit code; `1` for all the same, `0` for not all the same
* `>$@`: create files according to the input. This de-duplicates elements because a file can only be created once
* `^$1`: find a file that doesn't match the first element of the input (`-o extendedglob` is necessary to enable the `^` feature)
* `<`: and try to read from it. If there is no matching file (because all elements are the same) this will fail and exit with `1`
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 5 bytes
```
1=#?:
```
[Try it online!](https://ngn.codeberg.page/k#eJxLszK0Vba34uLSVwhKLSktyitWMFRIyy9SKCkqTdVRMACz0xJzilO50oAyyFBfQddOIQSoDCxjpGCsYAIRc4MqN1OwhGJk4Wgds1gUveZAiMw3AZplgKQFAA3pJ7c=)
*-2 bytes thanks to ngn*
Returns `1` for true, `0` for false.
Checks if `1` is equal to the length of unique elements in `x`
[Answer]
# [Uiua](https://uiua.org), 4 [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=ZiDihpAg4omF4oa7MS4KCmYgWzEgMSAxIDEgMSAxIDFdICMgLT4gVHJ1ZQpmIFsxIDIgMyA0XSAgICAgICAjIC0-IEZhbHNlCmYgWzYgOSA2IDkgNl0gICAgICMgLT4gRmFsc2UKZiBbNl0gICAgICAgICAgICAgIyAtPiBUcnVlCmYgWzcgN10gICAgICAgICAgICMgLT4gVHJ1ZQpmIFs0IDIgMF0gICAgICAgICAjIC0-IEZhbHNl)
```
≅↻1.
. # duplicate
↻1 # rotate an array by one
≅ # do they match?
```
[Answer]
# [Arn 1.0](https://github.com/ZippyMagician/Arn) `-s`, 2 bytes
```
:@
```
Outputs 1 if all the same, >1 if they aren't all the same.
[Try it online (works in older version)](https://zippymagician.github.io/Arn?code=OkA=&input=MSAxIDEgMSAxIDEgMQoxIDIgMyA0CjYgOSA2IDkgNgo2&flags=LXM=)
`:@` groups identical values, `-s` takes size. This could be written as `(:@)#` as well, which would be 4 bytes (`«×+0`)
[Answer]
# [Branch](https://github.com/hyper-neutrino/branch-lang/), 27 bytes
```
1O,[^\,N![o#)]n^=/;^\o^*On]
```
Try it on the [online Branch interpreter](https://branch.hyper-neutrino.xyz/#WyIxTyxbXlxcLE4hW28jKV1uXj0vO15cXG9eKk9uXSIsIjExMTExMTExMTExMiIsIiJd)!
There's got to be a much shorter way to do this...
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 3 bytes
```
$=g
```
Full program; takes the items from command-line arguments. [Try it online!](https://tio.run/##K8gs@P9fxTb9////RmBoDAA "Pip – Try It Online")
Alternately, a function solution that takes a list as its argument (also 3 bytes):
```
$=_
```
[Try it online!](https://tio.run/##K8gs@K/xX8U2/n@0kQIYxmr@BwA "Pip – Try It Online")
### Explanation
Not *quite* a builtin.
Pip, like Python, has chaining comparison operators: `1<5>=3` means `1<5 & 5>=3`, and `1=1=1=2` means `1=1 & 1=1 & 1=2`. Unlike Python, Pip also has the meta-operator `$`, which folds a list on a binary operator. For example, `$+` folds a list on addition, returning the sum; and `$=` folds a list on `=`. Because `=` chains, this returns the result we want: 1 if all elements are equal and 0 otherwise. The program `$=g` applies this compound operator to the full arglist `g`.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 5 bytes
```
⁼⌊θ⌈θ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1jDNzMvM7c0V6NQU0fBN7ECytbUtP7/3xAC/uuW5QAA "Charcoal – Try It Online") Link is to verbose version of code. Takes input as a string of digits by default but you can feed it an array if you insist. Outputs a Charcoal boolean, i.e. `-` for equal, nothing if not. Explanation: Simply compares the minimum and maximum input element.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 7 bytes
```
D`.
^.$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7w3yVBjytOT@X/f0MI4DI0MjbhMrMEQi4zLnNzLhMjAy4A "Retina 0.8.2 – Try It Online") Link includes test cases. Takes input as a string of digits. Explanation:
```
D`.
```
Remove duplicate digits.
```
^.$
```
Check that only one digit is left.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~35~~ 32 bytes
```
f(int*l){l=~l[1]&&*l-*++l+f(l);}
```
[Try it online!](https://tio.run/##ZU/NToQwGLz3KSY1u4FSDH/rRhG8@QTeWA4NP9qkggHWC8FXRwqakmzSNNOZ@eabFu57UcxzbclmYMoeVfKjMj8/HplymeMop7aUHU/znWwKdS0rPPdDKdv7j5QsExBeliejz3FzXH@KN4v/Zwk4Qo5opwRaeeB45Pi/jRhuoiEiTZw5zjvupLlozfY2mpDvVpYYqn5Y/4RSDMIeCb665VnDohmoHRPUbQftAJOJ9sRMpokXO460CYz7UIJyJvUEdiE53BSHHpfm0lBeW@uWF/rWXSv6RF@F6iu9ZVprfgrZWDaWEmst4em0DfoGBgaGBkYGnjQk0/wL "C (gcc) – Try It Online")
* recursive function taking an array -1 ended
* return False if all elements are equal, True otherwise
```
{l= - return using eax trick
~l[1]&& - return False if next item is end and skip next part ending recursion
*l-*++l - 0 if different
+f(l);} - plus check next item
```
[Answer]
## x86-16 machine code, 6 bytes
Hexdump:
```
0000:0000 89 F7 AC F3 AE C3 ......
```
## Explanation
```
; Routine A. [All The Same?]
; Expects CX = Length of input,
; SI = Initial address of list.
0000:0000 89F7 MOV DI, SI ; A1 [Load]. Set DI to SI.
0000:0002 AC LODSB ; AL = [SI++].
0000:0003 F3AE REPZ SCASB ; A2 [Compare].
; ZF = 1
; Loop CX times:
; If AX != [DI]:
; ZF = 0
; Proceed to A3
; DI ++
0000:0105 C3 RET ; A3 [End]. End of algorithm.
; ZF = 0 if not all same.
; ZF = 1 if all same. █
```
[Answer]
# [Fig](https://github.com/Seggan/Fig), \$2\log\_{256}(96)\approx\$ 1.646 bytes
```
LU
```
If you test input cases, the Fig site demands no spaces, ie. `[x,y,z]` not `[x, y, z]`. Outputs `1` if all equal, else `>1`.
[Try it online!](https://fig.fly.dev/#WyJMVSIsIlsxLDEsMSwxLDEsMSwxXSJd)
```
LU
U : Uniquify with implicit input
L : Length
```
[Answer]
# dc, 27 characters
```
?[0p3Q]sq[d3R!=qz0<c]dscx1p
```
Sample run:
```
bash-5.1$ dc -e '?[0p3Q]sq[d3R!=qz0<c]dscx1p' <<< '1 1 1 1 1 1 1'
1
bash-5.1$ dc -e '?[0p3Q]sq[d3R!=qz0<c]dscx1p' <<< '6 9 6 9 6'
0
```
[Try all test cases online!](https://tio.run/##lVCxTsMwEJ3jr7haoW6HKElTqBCxgIGBCbWrsVBqu2pElKRxIlUUvj3YjhrKwIAs33t3fme/8zbT@14qUWSNguARWqXbN5FpRWfIYySGi0U4jYfiAhJYmjSy6Q3cgttj4SxcwepMl6YncoI5QnWTl@0OyCdcBfG1BofRL1yY@FoSIM9l3bUGN0p3hSVPx1qJVklDX94JQruqgdyKTATsnybjCOyBf@E7kBXyGtdNsT@DsNNNWFQiK8JtXoZSQKCA9PcsqpM11wcmk82EHj6iVHCpxTGuewJpmpq73TMY5hgh7x8zjI3YH3xYdvqxORwbr2D9MXaho/QvKecwnYIS@8r9gzUlq1L13w "Bash – Try It Online")
(Note that choosing `dc` as interpreter and running the test separately fails both in TIO and ATO. ☹)
[Answer]
# [Ly](https://github.com/LyricLy/Ly), 6 bytes
```
a0I=u;
```
[Try it online!](https://tio.run/##y6n8/z/RwNO21Pr/fzMuSy4wBgA "Ly – Try It Online")
This one works by sorting the list of number and comparing the top and bottom of the stack.
```
a - sort the stack, implicitly reads the numbers first
0I - copy the bottom entry to top of the stack
= - compare the top two entries
u; - print boolean result, exit to stop from auto printing the stack
```
# [jq](https://stedolan.github.io/jq/), 14 bytes
```
unique[1]//"T"
```
[Try it online!](https://tio.run/##yyr8/780L7OwNDXaMFZfXylE6f//aDMdBUsdBSgZCwA "jq – Try It Online")
This one generates a list of unique numbers, then attempts to print the second member of that list. The `//` operator catches the exception and substitutes `T` if there's only one number.
[Answer]
# [sed](https://www.gnu.org/software/sed/), 26 bytes
```
$!{N;/^\(.*\)\n\1$/D;Q1};Q
```
[Try it online!](https://tio.run/##K05N0U3PK/3/X0Wx2s9aPy5GQ08rRjMmL8ZQRd/FOtCw1jrw/39DLiMuYy4TAA "sed – Try It Online") - Takes input as a newline separated list of numbers, exits with a non-zero exit code for "false" (i.e. not a uniform list).
##### Explanation
```
$!{ } if not last line, do these
N; append next input line to pattern space
/^\(.*\)\n\1$/ if pattern space is two identical lines
D; delete first line, and GOTO beginning
Q1 quit with exit code 1 (no printing)
;Q quit with exit code 0 (no printing)
```
[Answer]
# [V (vim)](https://github.com/DJMcMayhem/V), 10 bytes
```
:sor u
Gd{
```
[Try it online!](https://tio.run/##K/v/36o4v0ihlMs9pfr/f0MuCDT5r1sGAA "V (vim) – Try It Online")
Input as a list of lines. Outputs a falsy value (Empty output) for all items equal, and outputs a number otherwise.
Gets the unique lines, goes to the last line and deletes till the beginning.
] |
[Question]
[
# Task
Given a string as input, generate a "blurred" version of that string.
# Input
Your input will be a single-line string of ASCII characters, containing a minimum of 2 alphanumeric characters
# Output
A string that is the "blurred" version of the input string.
A blurred string is one where every alphanumeric character from the original string has been paired with the ones adjacent to it, and each pair is separated by a space.
Any non-alphanumeric characters (whitespace, puncuation) in the input string must be ignored when determining adjacency of alphanumeric characters, and they must not included in the blurred string.
There must be no leading or trailing whitespace in the output string.
# Examples
`Ab` -> `Ab`
`Abc` -> `Ab bc`
`Abcd` -> `Ab bc cd`
`E?h?` -> `Eh`
`Blurry vision` -> `Bl lu ur rr ry yv vi is si io on`
`We're #1!` -> `We er re e1`
`I'm an example!` -> `Im ma an ne ex xa am mp pl le`
`This is _not_ legible` -> `Th hi is si is sn no ot tl le eg gi ib bl le`
`(a*b*c)+5^-x` -> `ab bc c5 5x`
`??a_%,1!=z#@` -> `a1 1z`
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so fewest bytes wins!
[Answer]
# [Python 3](https://docs.python.org/3/), ~~57~~ 55 bytes
```
lambda s:"".join((c+" "+c)*c.isalnum()for c in s)[2:-2]
```
[Try it online!](https://tio.run/##PVBda8IwFH3PrzirjLV@FLrhi1A7Bz74PtjD5iSt0WakaUiitIq/3d10MAiXe8/HvZyY3tetfrkf8q@74k2553CLKEp/WqnjuJpEiCZVMq5S6bjSpyZODq1FBanhks/nxex5e5eNaa2H6x1jgVVSi0HQu9T5vdQLBrgpuHbI0XATO2@JsdJMB3HqjJI@jmbLKElIa0l2iF1ojZXax4fo6m6YLXG1N3xebZ7Trts2Su6rMsCrkq3K6q9DWYVh/z@h2rN1URcBWNfsTZ2s7XGWTrY6YG8K6oSThaXXoz8TB@ngqLZoNfsQT1ZglD0E9YeAIB3VjG2eGgoF0fHGKDHQm4YCBpC@QHToqCfEwNARwd5r2ktvp1u/I@AoSyWC7b1G/X@UKvnptIcPNogjjoRTmGFLzMfluEom8@9ZF8z8L@Uc844VBd89TrOH/DJ6HbgM2eUX "Python 3 – Try It Online")
**How**:
* For each alpha-numeric character `c` in the string, replace it with `c+" "+c`.
E.g: `"abcd" -> "a ab bc cd d"`
* Remove the redundant first and last 2 characters:
E.g: `"a ab bc cd d" -> "ab bc cd"`
[Answer]
# [Husk](https://github.com/barbuz/Husk), 5 bytes
```
wX2f□
```
[Try it online!](https://tio.run/##yygtzv7/vzzCKO3RtIX///9X0kjUStJK1tQ2jdOtUAIA "Husk – Try It Online")
# Explanation
```
f Keep all items that
□ Is an alphanumeric character.
X Pick all sublists
2 With a length of 2.
w Join the output list by spaces.
```
[Answer]
# [sed] -E (C locale), ~~46~~ ~~33~~ 23 bytes
```
s/\W|_//g;s/\B.\B/& &/g
```
[Try it online!](https://tio.run/##RY7BSsNAFEX37ytuU221GkMXrmwSkxJBKLgRuikOk@SZDKRJmBk1Sv89HQoSeFwe98Dl5NLUYyEtoshwKUyhVW@x2XjZ24s3muCwP4kgqJ7clz4c0mCBRVCNDhLx0HfaYrcVyW4Xbol@atUwNMsSlo1tVMsElJ0LgIu6g9/Cu/pnCCN4E5uAhxOcDPwM/icmrcuY2xyTHJTkxSVKUBbXMShtvrT@xbcyqmtBe15qxnw9A70uj5AteJDHvmFXvNfKwJ1oOyvQcKVyJ043cpWvitu7xw9/AMWxFNf361n4N3@mMw "Bash – Try It Online")
*Thanks to pizzapants184 for a 13-byte improvement.*
*10 more bytes off thanks to Dom Hastings.*
---
Input on stdin, and output on stdout.
If your locale isn't set to C, you can set it with: `export LC_ALL=C`
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), ~~27 24 22~~ 21 bytes
```
" "/2':(2!"/9@Z`z"')_
```
[Try it online!](https://ngn.bitbucket.io/k#eJy9kk1Lw0AQhu/5FW8XIUlFCoUcTA7WQg+9e7LEZFPzRfPFJikbRX+771oUz1KyDLPDu8s8M8NkvoBYrW3fWS/E6n7zHL8J240sa/Dfbw7Tp/Iz6CBuT4ETZ7KsAh1MgXLDD2s4iMdEhMZh1nMhH7/R4D07+fUHDYbzkXfFA8G7Yt5xG/K2GpWacC77sm1Yw7ZCNWJUULQJ05lPKHv09C345WrkvV1DNki1rLsqXZC9r1FLozUpZWjGVDp0rCm90mgM+algQ7SoaYeIqfMyYf6QOorfZulZCFseMBg+0hw5dS7H/8oxZEcuk+XRvfVe7jSB8rJpHjz9N98XjjmwXw==)
`"/9@Z`z"'` binary search in the given string
`2!` mod 2
`(2!"/9@Z`z"')_` drop non-alphanumeric chars
`2':` make a list of pairs of adjacent chars
`" "/` join with spaces
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 14 bytes
```
jd.::Q"\W|_"k2
```
[Try it online!](https://tio.run/##K6gsyfj/PytFz8oqUCkmvCZeKdvo/3@lkIzMYgUgis/LL4lXyElNz0zKSVUCAA "Pyth – Try It Online")
* `:Q"\W|_"k` replaces each non-alphanumeric character of the input with the empty string by matching each character against the regex `\W|_`
* `.: --- 2` finds all substrings of length 2
* `jd` joins the substrings using spaces
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
fØB;ƝK
```
A monadic Link accepting a list of characters which yields a list of characters.
**[Try it online!](https://tio.run/##y0rNyan8/z/t8Awn62Nzvf///6@kkaiVpJWsqW0ap1uhBAA "Jelly – Try It Online")**
### How?
```
fØB;ƝK - Link: list of characters, S
ØB - base-62 characters = "01...89AB...YZab...yz"
f - (S) filter keep if in (that)
Ɲ - for neighbours:
; - concatenate
K - join with spaces
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~8~~ ~~7~~ 8 bytes
*-1 byte thanks to @CommandMaster*
*+1 byte again thanks to @KevinCruijssen finding an issue*
```
žKÃüJðý?
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6D7vw82H93gd3nB4r/3///b2ifGqOoaKtlXKDgA "05AB1E – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~17~~ 16 bytes
```
t8Y2m)2YC!Z{0&Zc
```
[Try it online!](https://tio.run/##y00syfn/v8Qi0ihX0yjSWTGq2kAtKvn/f3WnnNKiokqFsszizPw8dQA) Or [verify all test cases](https://tio.run/##y00syfmf8L/EItIoV9Mo0lkxqtpALSr5v0vIf3XHJHUuIJEMIVOAlKt9hj2QcsopLSqqVCjLLM7MzwPyw1PV1YtSFZQNFYEcT3X1XIXEPIXUisTcgpxUkFBIRmaxAhDF5@WXxCvkpKZnJuWkAsU1ErWStJI1tU3jdCuAXHv7xHhVHUNF2yplB3UA).
### Explanation
Consider input `'Blurry vision'`.
```
t % Implicit input. Duplicate
% STACK: 'Blurry vision', 'Blurry vision'
8Y2 % Push '012...9ABC...Zabc...z' (predefined literal)
% STACK: 'Blurry vision', 'Blurry vision', '012...9ABC...Zabc...z'
m % Ismember: true for chars of the first string that are in the second
% STACK: 'Blurry vision', [1 1 1 1 1 1 0 1 1 1 1 1 1]
) % Use as logical index. This keeps only letters and numbers in the input
% STACK: 'Blurryvision'
2YC % Character matrix with sliding blocks of length 2 as columns
% STACK: ['Blurryvisio';
'lurryvision']
! % Transpose
% STACK: ['Bl';
'lu';
...
'on']
Z{ % Cell array of matrix rows
% STACK: {'Bl' 'lu ... 'on'}
0&Zc % Join with character 0 (which will be displayed as space)
% STACK: 'Bl lu ur rr ry yv vi is si io on'
% Implicit display
```
[Answer]
# TEX (INITEX), 372 bytes
```
\catcode`~13\let~\catcode~`{1~`}2~`#6~`\ 12~`|13\let|\expandafter\def\z{}\def\f#1{#1}\def\i#1{}\def\b#1#2{\ifx#2\e|||\i|\i\else|\f\fi{\ifcat#1a|\f\else|||\b|||#2|\i\fi}{\ifcat#2a #1#2|\b|#2\else|\b|#1\fi}}\def\t{~`011~`111~`211~`311~`411~`511~`611~`711~`811~`911~`\|12~`\~12~`\#12~`\{12~`\}12~127=12~`\%12~`\\12\read16to\x\edef\r{|\b\x\e}\immediate\write16{|\i\r\z}\end}\t
```
For example, the program being saved in a file named "codegolf.tex", provided with input `??a_%,1!=\z#@`, `initex codegolf.tex` outputs:
```
This is TeX, Version 3.14159265 (TeX Live 2019/dev/Debian) (INITEX)
(./codegolf.tex
\x=??a_%,1!=\z#@
a1 1z
)
No pages of output.
Transcript written on codegolf.log.
```
In the case of a degraded input, for example the strings `??`, `?a`, or `a?`, this implementation does not print any pair.
# Explanation
## Basis for a TEX program
```
\read16
```
Per [this Meta answer](https://codegolf.meta.stackexchange.com/a/13652/94729), the input of a program written in TEX should come from standard input, which is the *in register* number 16.
```
\immediate\write16
```
The TEX Codegolf community prefers to output to DVI or PDF, because it is simpler than writing to the terminal. However, this requires a valid `\output` routine, which either requires a format (with more category codes to alter1) or is longer to define. So I write to the terminal. (`\message` could also have been used, but I don't like how the output is surrounded by TEX chat on the same line).
Because I output to the terminal, I also feel that no DVI file should get produced, so `\immediate` is required2.
```
\end
```
This is a complete program, so it must end with `\end` to run cleanly.
## Category codes
Running on alphanumerics and ignoring punctuation is a trivial matter for TEX. All I have to do is to customize the category codes of those characters.
For this subject, I will use category code 11 ("letter") for characters that need to be blurred, and category code 12 ("other") for characters that are to be dropped. That choice comes from the defaults of (ini)TEX, where letters are already set to 11 and most of the other characters to 12.
```
\catcode`~13\let~\catcode
```
To save bytes, I make `~` an active character and set its meaning to `\catcode`. In the rest of the explanation, that alias will be ungolfed.
```
\catcode`{=1 \catcode`}=2 \catcode`#=6 \catcode`\ =12
```
These are required for INITEX to interpret my program correctly: `{` is now the begin-group character, `}` the end-group, `#` the macro argument, and `␣` is considered a normal character (so that the first spurious space of output can be removed). These choices are widely used in the TEX world and do not cost bytes3.
```
\catcode`|=13 \let|=\expandafter
```
This is an useful alias for later.
```
\def\t{\catcode`0=11 ... \end}
\t
```
This is a TEX design pattern that fools TEX's eyes. Everything that is written in the `\todo` macro definition will get a category code assigned, and this category code will not be reconsidered when TeX expands the macro. Most notably:
```
\catcode`\\=12
```
This makes the escape character `\` a normal character when read from the user input.
```
\read16to\x \edef\r{|\b\x\e} \immediate\write16{|\i\r\z} \end
```
When reading the macro definition, TEX has decided that these were control words, and TEX will not reconsider this choice after the macro has been expanded, even if `\` has lost its special meaning in the meantime.
```
\catcode127=12
```
The `DEL` character is contained in ASCII, so it should be valid input per the subject's rules. But in order to change its category code to 12, the DEL character has to be written, and the most efficient4 way to input it in TEX is to name it by its code point.
```
\catcode`0=11 ... \catcode`\\=12
```
Here are three groups of category code assignments: make the digits like letters, revert the changes made at the beginning of the program, and cancel other INITEX defaults (`DEL`, `%`, `\`, but not the new line because the subject emits the hypothesis:)
>
> Your input will be a single-line string
>
>
>
## The blurring command
Because I opted for terminal output, and because `\write` does not executes its argument (only expands it), I am forced to write the `\blur` macro as fully expandable.
```
\def\z{} \def\firstofone#1{#1} \def\ignore#1{}
```
As a prolog, I define three macros, which are commonly used in various fully-expandable design patterns. The first one is the empty macro, the second one is the identity macro, and the third one is the zero macro.
```
\def\blur#1#2{ ... }
```
The `\blur` macro is recursive5. It takes two characters at a time (because the rules say that the input is longer than two). Its definition is made of three parts.
```
\ifx#2\e \expandafter\expandafter \expandafter\ignore \expandafter\ignore
\else \expandafter\firstofone
\fi
```
is the recursion condition: if the end-of-string marker (the undefined command `\e`6) is found, ignore the two other parts. (More precisely, drop the unused portion of the conditional `\else...\fi` at `\expandafter` level 0, then ignore the second part at `\expandafter` level 1, then ignore the third part at `\expandafter` level 2.) Otherwise, close the conditional and interpret the second part.
```
\ifcat#1a \expandafter\firstofone
\else \expandafter\expandafter \expandafter\blur
\expandafter\expandafter \expandafter#2
\expandafter \ignore
\fi
```
handles the first character. If it is a letter or digit, go analysing a second character. Otherwise, skip the remaining of the conditional, ignore the third part, and call `\blur` recursively with #1 being dropped and #2 as the first character7 (an other one will get extracted from input).
```
\ifcat#2a ␣#1#2 \expandafter\blur \expandafter#2
\else \expandafter\blur \expandafter#1
\fi
```
handles the second character. If it is a letter or digit, output a space then the first part of the blur, then forget about #1 and call `\blur` recursively on #27. Otherwise, forget about it and call `\blur` recursively on #17.
## Calling the blurring command on real input
```
\read16 to \x
```
will store the input into an (expandable) macro `\x`.
```
\expandafter\blur \x \e
```
This is how the `\blur` macro is called. Because `\blur` acts on tokens, the input contained in `\x` must be expanded first. The end-of-string marker follows.
```
\edef\result{\expandafter\blur \x \e}
```
The result of the expansion, including the whitespace at front, is stored into the `\result` macro.
```
\expandafter\ignore \result \z
```
Inside the `\write16` command, the `\result` macro is first expanded. Then, `\ignore` eliminates the first token of output: the first space if the output is non-empty, or the `\z` macro call if the output is empty. In the first case, the `\z` macro will survive; but `\write16` will finally expand it, and its expansion is a no-op. This is the most efficient way of handling the “no trailing space” requirement, even if it requires 24 bytes (the definition and call of `\z` and `\return`); suppressing a space at the end of the output would have been nearly impossible.
## ☡ Footnotes
1. `$`, `&`, `^`, `\_`, `NUL`, `SPC`, `TAB`, `~` for plain TEX; 5 bytes each = 40 bytes.
2. Without `\immediate`, `\write` adds its content to a whatsit box, thus generating a page of output.
3. Because there are only three category code changes, it is not worth putting them in a group to save the reverting.
4. Decimal: `127=` (4); Hexadecimal: `"7F=` (4, harder to read); Octal: `'199=` (5); Escape sequence: ```\^^?` (5, plus `\catcode`^7` and revert)
5. It is even *tail-recursive*, which in TEX has the meaning of "it does not add tokens after the recursive call", and by doing so is more memory-friendly.
6. Because all input other than my program does not get interpreted, the `\e` command cannot be defined later.
7. This would fail if #2 was a simple group of arguments, but fortunately the input cannot contain simple groups, because no character has category code 1 nor 2.
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 13 bytes
```
\W|_
Lw| `..
```
[Try it online!](https://tio.run/##K0otycxLNPz/Pya8Jp6Ly6e8RiFBT@//f6ec0iLFokqFsszizPw8AA "Retina – Try It Online")
## Explanation
`\W|_` Replace each character NOT in the regex group \W (which is `A-Z,a-z,0-9,_`) or a `_` with nothing
`Lw| `..` Compute lists (`L`) for each set of two characters (`..`) starting at all positions in the string (`w`) and separate the lists with a space (`|` )
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 74 bytes
This ended up very similar to the Python answer. I was trying something noticeably more interesting with Aggregate, but the terrible no trailing whitespace requirement made it too long.
```
s=>s.SelectMany(c=>char.IsLetterOrDigit(c)?c+" "+c:"").Skip(2).SkipLast(2)
```
[Try it online!](https://tio.run/##JY3LCsIwEEX3/YqQ1aSvheBG24ighUJFoa6FdBhqsEZJUrRfHytdnQuHy0GXodOhGg0Wzltt@pTVRzM@yapuoALvykrJKlay4Erp8pYGQn9SZgIs5V/ntWvIe7Jne9C99oBihwlnPMEN5yJvH/oNq4WNcn7eYRtFlznmwdCHLV2ogIOKuxhFsr5l3/l5fe2tVRMIIcIP "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [AWK](https://www.gnu.org/software/gawk/manual/gawk.html), 52 54 bytes
```
{gsub("\\W|_",a);for(b=$0;c=substr(b,++d,2);)$d=c}--NF
```
[Try it online!](https://tio.run/##SyzP/v@/Or24NElDKSYmvCZeSSdR0zotv0gjyVbFwDrZFihTXALk6Whrp@gYaVprqqTYJtfq6vq5/f/vqZ6rkJinkFqRmFuQk6oIAA "AWK – Try It Online")
*Fixed underscore rule goof (+2 chars), thanks to Pedro Maimere*
Here's what's going on with this one...
```
gsub("\\W",a)
```
Removes all the non-alphabetic characters from the input string since `$0` is the default target for `gsub`. Using an unitialized variable `a` instead of `""` saves a byte.
Next the code loops through the string taking 2 character slices and assigns them to positional variables.
```
for(b=$0;
```
The setup has to save `$0` to another variable, since changing the positional variables impacts the collected input in `$0` as well.
```
c=substr(b,++d,2);
```
The "test" at the top of the loop does a couple of things in one statement:
* increments `d`, the "current character" pointer
* sets variable `c` to the next 2 character slices of the input
* the true/false test simple has the code looping until we run off the string and get a null
The body of the loop sets the next positional variable to the slice we just took.
```
$d=c
```
After all the positional variables have been set, there's one "garbage" entry on the end with one character. So the test:
```
--NF
```
effectively drops that last positional variable and triggers the default action, which prints all the positional variables separated by a space.
[Answer]
# [Factor](https://factorcode.org/), ~~51~~ 37 bytes
-14 bytes thanks to chunes
```
[ [ alpha? ] filter 2 clump " "join ]
```
[Try it online!](https://tio.run/##JYrNSgMxFIX38xSnU6RaUajgRpHYgkg3blRclDrcibczVzJJTDLSWvrsY0rh8J0fzoZ0cmF4f12@PN@BohZBE1zvxTaI/NOz1RzhA6e080Fswn1R7FHO6/IIfeJXtifVqmwL04eww69EcTb3D54Exng2ynk56UAWvKXOGz4ub61EZFXWpQqGG6kN5/2cpvVUX1zefl5tc1WKqrPZ6OFv/FjiUAwrrEDGt6SwxkZM4oAbaNN3Hvn@7cRiPXTkcT38Aw "Factor – Try It Online")
# [Factor](https://factorcode.org/), 51 bytes
```
: b ( s -- s ) [ alpha? ] filter 2 clump " " join ;
```
[Try it online!](https://tio.run/##JY5fS8MwFMXf9ynOOmR/JMIEXzokUxDpy15UfBizpPGuzUiTmKTSKX72mjLu5XfuOQ@HexQyWj@8vRS75xwiSKVQe9s5ZWoE@urISApwnmI8O69MxGZS7HI86s6z2BCL1MchR4UFAhhLWGIPoV0jOA44Kh3J4xZSd61DluZklcFm@EX2UGUj5IWfSZ54w5OM7f6MbxWUNcm/09wTZutpuot5C2FAvWidpjF5bVRA2tLYWEJTrSpNKV@IVbWSy@u7D9Yny7kor9bT@5/ZNsPfZJ9@PqAVDjfDPw "Factor – Try It Online")
Unbelievably [Factor](https://factorcode.org/) is competitive with Python and JavaScript :)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~17~~ 16 bytes
```
\W|_
M&!`..
¶
```
[Try it online!](https://tio.run/##K0otycxL/K@q4Z7wPya8Jp6Ly1dNMUFPj@vQNi6F//8dk7gck5JBOIXL1T7Dnsspp7SoqFKhLLM4Mz@PKzxVvShVQdlQkctTPVchMU8htSIxtyAnVZErJCOzWAGI4vPyS@IVclLTM5NyUrk0ErWStJI1tU3jdCu47O0T41V1DBVtq5QdAA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Now basically a port of @Jarmex's Retina 1 solution, except that `M!` always joins with newlines, so I have explicitly change them to spaces. Previous 17-byte approach:
```
\W|_
\B.\B
$& $&
```
[Try it online!](https://tio.run/##FcPdCoIwFADg@/MUR/zNfsCLLmM5iOg@8EZamx5yMGdMC4vefRV8n6NJW@nj7Hj1dfURADXf1ByiBKPE@1JBqZr/Fg6sY8DNw7kXPvWoBwsVpY4wLAI4pT1KizTL/m4ogHOnR/wRdpgEGrppZQgymau8WSy3l/UMjEkRr4pg9w73Xw "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
\W|_
```
Delete any non-word character and any underscore (which is the only non-alphanumeric character that counts as a word character).
```
\B.\B
$& $&
```
Duplicate each inner character and space separate the results.
[Answer]
# JavaScript (ES6), 57 bytes
```
s=>s.replace(/\W|_|(.)/g,(_,c)=>c?c+' '+c:'').slice(2,-2)
```
[Try it online!](https://tio.run/##dZHRboIwFIbv9xRHzQIVhGDizRJkmnjhvYk3y0ipFVhKS1owaHx3dtyyxVVGmpOm/b@vp@WDnqhhuqybmVQH3h/j3sRLE2heC8q4G77tr@nVDUiY@27qMxIvWcI8BxyPvTgOCYwoMTb3Z3PSMyWNEjwQKneP7niVjQmBgS8MYZU9PaTZcPwrDRkbAA6DxA8A7GAzm6RI/mM2hZ1ei1brM5xKUyp5j2F6LUC00GrQOM5wPmEMSgMGqwIlbdeeO5rDJBrZx6Nrz4GjBWtkY1unAiqBd7SqBb@DEdtWUNHbrkSygw7nuFJDja1xW7QrsDkcqVRNivt5mQl@06FoV0Dx2zxWNOIVGmhuIuA55LiOLzrkdek0mzLiLd5n3Z@roZd@/4UFLDobSxKaPvvRKL5MXh@wCKJL/wk "JavaScript (Node.js) – Try It Online")
[Answer]
# Q/KDB+, 38 bytes
**Solution:**
```
{" "sv -2_2#'next\[x inter .Q.an _52]}
```
**Examples:**
```
q){" "sv -2_2#'next\[x inter .Q.an _52]}"Ab"
"Ab"
q){" "sv -2_2#'next\[x inter .Q.an _52]}"Abc"
"Ab bc"
q){" "sv -2_2#'next\[x inter .Q.an _52]}"E?h?"
"Eh"
q){" "sv -2_2#'next\[x inter .Q.an _52]}"This is _not_ legible"
"Th hi is si is sn no ot tl le eg gi ib bl le"
```
**Explanation:**
```
{" "sv -2_2#'next\[x inter .Q.an _52]} / solution
{ } / lambda taking implicit x
.Q.an / "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ_0123456789"
_52 / drop element at index 52
x inter / intersection of x and alphanumerics
next\[ ] / scan along input
2#' / take first 2 characters of each
-2_ / drop final two items
" "sv / join (sv) with " "
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 bytes ([SBCS](https://github.com/abrudz/SBCS))
Port of Surculose Sputum's Python answer.
```
{¯2↓2↓⊃,/{⍵' '⍵}¨⍵∩⎕A,819⌶⎕A,⎕D}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R24TqQ@uNHrVNBuFHXc06@tWPereqK6gDydpDK4Dko46Vj/qmOupYGFo@6tkGZgIJl1qgbgV1xcSkZEV7dS4gUyNRK0krWVPbNE63Qh0A)
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), 18 bytes
```
1↓∊' ',¨2,/⍵
\W|_
```
[Try it online!](https://tio.run/##KyxNTCn6/9/wUdvkRx1d6grqOodWGOnoP@rdyhUTXhPP9f9/SEZmsQIQxefll8Qr5KSmZyblpAIA "QuadR – Try It Online")
Replaces all non-word characters and underscores (`\W|_`) with nothing , and then:
`2,/⍵` adjacent pairs
`' ',¨` prepend a space to each pair
`∊` **ϵ**nlist (flatten)
`1↓` drop the first space
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 80 bytes
```
p,b;f(char*s){for(p=b=0;*s;s++)isalnum(*s)?p&&printf(" %c%c"+!b--,p,*s),p=*s:0;}
```
[Try it online!](https://tio.run/##HUzNaoQwGLznKT5ddBN/QA@9NIjdQg@9F3oorSRp1ECMIdF228Vnt7Ewwwwzw4hyEGLfbcFpj8XIXObJrZ8dtg1vKpp56vOcKM@0WSccytamqXXKLD2OIRGJiPOIl2Vhi1AWtsn8fUW3/bgC/1ZX1TtFYQ0TUwYTuCH4HpWWgAe5eJx68p9Bjz2hQe0a0jg@/IbAyWV1BiqKNtgvHF24OPiJntqxRY96de4HvpRXs0Gv8uwknOoIPZ8nYAbklU1Wywi9jMpDQGfmpQMtB8W1RJhlPBMkv/sor6htWZcUddT8nh7@AA "C (gcc) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~23~~ ~~19~~ 18 bytes
```
žKég<F®Nè?®N>è?ð?
```
[Try it online!](https://tio.run/##yy9OTMpM/f//6L6sQysONx9amW7jdmid3@EV9kDSDkgd3mD//7@9fWK8qo6hom2VsgMA)
This probably could be really shorter, but I just wasn't able to find the right tools for the job. -4 bytes thanks to petStorm and a further byte thanks to Command Master.
## Old Answer Explained
```
žj'_ммм©g<F®Nè?®N>è?' ?
žj # Push [a-zA-Z0-9_]
'_м # Remove the "_" from the above string
м # Remove all alphanum characters from the input, leaving non-alphanum chars
м # Remove those non-alphanum chars from the input, leaving alphanum chars
© # Put this string into the register
g<F # For N in range(0, len(input) - 1):
®Nè? # Index the string at position N and print
®N>è? # Index the string at position N + 1 and print
' ? # Print a space
```
[Answer]
# Javascript ES6, ~~55~~ 54 chars
```
s=>s.replace(/\W|_/g,"").replace(/.(?=(.).)/g,"$&$1 ")
```
Test:
```
f=s=>s.replace(/\W|_/g,"").replace(/.(?=(.).)/g,"$&$1 ")
console.log(`Ab -> Ab
Abc -> Ab bc
Abcd -> Ab bc cd
E?h? -> Eh
Blurry vision -> Bl lu ur rr ry yv vi is si io on
We're #1! -> We er re e1
I'm an example! -> Im ma an ne ex xa am mp pl le
This is _not_ legible -> Th hi is si is sn no ot tl le eg gi ib bl le
(a*b*c)+5^-x -> ab bc c5 5x
??a_%,1!=z#@ -> a1 1z`.split`
`.map(s=>s.split` -> `).map(([s,k])=>f(s)==k).every(x=>x))
```
[Answer]
# [Kotlin](https://kotlinlang.org), ~~77~~ 76 bytes
```
{it.filter{it.isLetterOrDigit()}.zipWithNext{a,b->"$a$b"}.joinToString(" ")}
```
Old solution
```
{it.replace("\\W|_".toRegex(),"").zipWithNext{a,b->"$a$b"}.joinToString(" ")}
```
[Answer]
# [R](https://www.r-project.org/), 98 bytes
```
function(x,y=grep("[a-z0-9]",el(strsplit(x,"")),T,,T))for(i in seq(y)[-1])cat(y[i-1:0],' ',sep='')
```
[Try it online!](https://tio.run/##Hc2xCsMgEADQX7Eu3sEJydiCez8g0EEc0tQU4VCrBmp/3pbOb3hl3PkoZuxH3FpIEd7UzbP4DNKu@jPps5PkGWorNXNoP5cSkRaiBXFPBYIIUVT/go5Wzw63tUG3Qc@XyZESiqrPRin8RyCvnjmRuKXCj5PE8QU "R – Try It Online")
Unusually for [R](https://www.r-project.org/), a `for` loop is significantly shorter than a [matrix-based approach](https://tio.run/##Hc1LCsIwEADQq2hWMzCBZimYvetQcFG6SJOpFoY25APWy1fpBd7LxyQt22Nua6jLtsKHnHUcW2B0kHypTD4l2eHNPkKYljXCftevzAnU4PW307dREQuUmkuSpf4JpRCpJ@qR9kGbEUkbJEOOZnuaHeIZg3qwyEaX55YlXhUePw), mainly because it allows us to just use `cat` instead of the much-more-verbose `Reduce(paste` vectorized way to build a text string from a list of characters.
[Answer]
# [R](https://www.r-project.org/), 76 bytes
```
function(s)cat(substring(S<-gsub("[^a-z0-9]","",s,T),N<-1:(nchar(S)-1),N+1))
```
[Try it online!](https://tio.run/##K/qflFNapGCj@z@tNC@5JDM/T6NYMzmxRKO4NKm4pCgzL10j2EY3HcjTUIqOS9StMtC1jFXSUVLSKdYJ0dTxs9E1tNLIS85ILNII1tQ1BIpoG2pqgg3VUPJIzcnJ11EIzy/KSVFU0vwPAA "R – Try It Online")
Similar to Dominic van Essen's [answer](https://codegolf.stackexchange.com/a/220084/67312), uses `cat` to join by spaces; uses `substring` which recycles (as opposed to `substr` which doesn't).
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 26 bytes
```
≔ΦS№⁺α⁺β⭆χλιθ⪫E⊖Lθ✂θι⁺²ι¹
```
[Try it online!](https://tio.run/##LYzBCsIwEETv/Yq1HtxABOu1J6kIikKhB88xLm0gbtt06@/HRr3MHN6bsZ0Jtjc@xsM0uZbx5LxQwDMPszQSHLeoNFT9zIK1nyc0Gr790PDjNzNgsdPglVpMl2JUZVYvTPDSO8ZkHMkGehELPfFK3EqHY1Ib7yzhuAz/v/v0oaFIMIdcqTLGO20CwbpYZXH79h8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
≔ΦS№⁺α⁺β⭆χλιθ
```
Filter out any character that can't be found in the upper or lower case alphabet and isn't a digit.
```
⪫E⊖Lθ✂θι⁺²ι¹
```
Extract all substrings of length 2 and join them together on spaces.
[Answer]
# [Icon](https://github.com/gtownsend/icon), 92 bytes
```
procedure f(s)
t:=""
find(k:=!s,&letters++&digits--'_')&t||:=k||' '||k&\z
return t[3:-2]
end
```
[Try it online!](https://tio.run/##TU9Na4NAEL37K0ZD3d2oh7T0IohNoIfeCz2kifgxJou6ht2xTcP@99SVHjoM83hv4PGerEd1v1/0WGMzaYSWG@FRmgWB10rV8C7NfBOHPRKhNlEUNvIkySQJK5gIydo066xlwKztws@bp5EmrYD2T2nyePBQNf/Mh1IqLjyYh9CQgTSDfbCtghjmW/9B4/A1P@cOd/2k9Q98SSNH5YQPZLPTauM78sYGKBXgtRwuPS7S@1kamLdQIxXQ40lWPboHL9fVuhbR8zG5Op7nZfEQb/zstnqZ@WGJ9a0lIW@5v@QTwlVyHX4B "Icon – Try It Online")
[Answer]
# [Red](http://www.red-lang.org), 130 bytes
```
func[s][a: charset[#"0"-#"9"#"A"-#"Z"#"a"-#"z"]parse s[any[p: change
a(rejoin[p/1" "p/1])| remove skip]]take/part/last s 2 at s 3]
```
[Try it online!](https://tio.run/##RY5vS8NADMbf91NkKbI/UuYUXzjQOsEXvhVB2HGWtE3Xc@31uOvGNvzu9To7DCH55XkSiOW8e@dcyKBYQlfsdCacFLSErCTruBUh3mAU4gOGuOph7YF6OKE0/Qo4QfoozPlEbzigieXvRmlh5gsE9FVOf8By3ez98lYZKVva8txft/OKXAsOboH6die7orFMWQkte0ME4ANXKV4g@6d8wNe4jAd8qXbWHmGvnGr0oH3y2DKEi9Ewv41rIA18oNpUfFE/SuXAZ6KbNoGKNyqtePAmNEtn2fT6/is6DFIcU3K1GD2ewmcMpABjlfbvZo05/n2O0RNCcWYpu18 "Red – Try It Online")
[Answer]
# JavaScript (ES6), ~~54~~ 76 bytes
```
a=>[...a.replace(/[\W_-]/g,'')].map((a,b,c)=>a+c[b+1]).slice(0,-1).join(' ')
```
[Try it online!](https://tio.run/##DcpBDoMgEADArxgv7EZY6wPwGz1Q0qwUDQaBiG36e9o5z84fru4M5VIpv3xbdWM9GyJiOn2J7DyM5nF/KjtuUgi0dHABYLlIh3rmwZllmCxSjeF/b1JNSHsOCUQnsLmcao6eYt5ghd5/@SjRdyGV99Ujth8 "JavaScript (ES6) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 6 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
£Q·H°·
```
[Run and debug it at staxlang.xyz!](https://staxlang.xyz/#p=9c51fa48f8fa&i=Ab%0AAbc%0AAbcd%0AE%3Fh%3F%0ABlurry+vision%0AWe%27re+%231%21%0AI%27m+an+example%21%0AThis+is+_not_+legible%0A%28a*b*c%29%2B5%5E-x%0A%3F%3Fa_%25,1%21%3Dz%23%40&a=1&m=2)
### Unpacked (7 bytes) and explanation:
```
VL|&2BJ
VL Push string of all alphanumeric characters.
|& Remove from the input all letters not in this string.
2B All length-2 substrings
J Join with spaces
```
[Answer]
# [C#], ~~163~~ ~~155~~ ~~133~~ ~~128~~ ~~127~~ ~~128~~ ~~114~~ ~~112~~ ~~133~~ 98 bytes
```
i=>{var b=i.Where(char.IsLetterOrDigit);return b.Select((n,i)=>i==0|i==b.Count()-1?n+"":n+" "+n);}
```
[Run it](https://tio.run/##XVHva9swEP1s/xVXd6NynZjmw77MdbKta6GQsbEW8qF0QVYutkCWE/3IkmX@27NTksEYiHvcuyfd052wQ2HFwVupa3jaWYdtEf@b5VOp1/9Rz7h1@XesveLmfrsyaK3stC3ieOUrJQUIxa2Fb6arDW/jfRydeeu4I9h0cgFfuNQsjSOqRhtuQOqVd1CCxp@kM9Tu5RX2kHyskkGI4gyLgPfNJMAn5Y3ZwUaG/oGY4ZVBuBxdhOTxqgWuAbe8XSk8Us@NtEBnrjs3B4W1rBSGAuPX1bVIs3c/htuQTyZ8/nYwuih/XX5IoKevnW0uzxYfvBa3J58DWOw0b6UYMzjIcrwPuqqU@axBg0w03OSPdorOoflqPstaurQw6LzRUOVPqFA4xvRApuVYluXNbwpVftd57Vg6HE10liTvKUCS6bToD1GUFsHOsjPAQi9Pnm4KgtvTFPMp6to1xGQZTfg4YoCgXJNyyY6iF/9Kz4TCHe2uU5jPjHRI60b2Jtn/1fQwHNMaTj8lU1pwx9Yp9Mnxdh/T6Q9/AA)
~~Have not used a Regex yet in a Codegolf, so very excite.~~ Regex uses way too many characters. No longer excite.
* 127 bytes: removed a "." in the regex string
* 126 bytes: replaced String.Join("" with String.Concat
* 114 bytes: changed || to |, removed the ( ) { return; } from inside the Select
* 112 bytes: Removed + from regex
* 128 bytes: Reverting back to older solution. Entry now legal (thanks to @Neil and @my pronoun is monicareinstate)
* 98 bytes: Realization that char is way more powerful than I thought (thanks to @my pronoun is monicareinstate's C# solution), removed the string -> char -> string conversions
] |
[Question]
[
## Background
Hello is a language "written" by [Anne Veling](https://esolangs.org/wiki/Anne_Veling), which errors if the program does not contain only `h`, and will print `Hello World` for every `h`
## Task
You are to write an interpreter/compiler for Hello.
## Example in Python
```
import os
i = input("Program: ")
for a in i:
if a != 'h':
print("err")
quit()
else:
print("Hello World")
```
## Details
* If the program is not only `h`s, it must print `err` or `error` (case-insensitive)
* It's okay if you print "Hello World"s before your program discovers a non-`h` character and errors, however, the program must halt if a non-`h`
* You may throw an error, as long as you print `err`/`error` before throwing, or by using a custom error builtin, like `raise SyntaxError('err')` in python. (basically, you have to **purposefully** error with `err`/`error`
* Assume the program will not be empty
* Output can have a trailing newline, space, or nothing to separate `Hello World`s
* If a program has multiple lines, it should error (due to `\n` not being an `h`)
* You can assume that input will always be ASCII 33-126 and 10 (decimal)
* The `h`s are case sensitive (so `H` is not a valid program)
instruction is found
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), shortest answer wins
## Test cases
```
Input:
h
Output:
Hello World
Input:
hhhhhh
Output:
Hello WorldHello WorldHello WorldHello WorldHello WorldHello World
(again, it doesn't matter whether it's spaces, newlines, or nothing to separate `Hello World`s
Input:
rubbish
Output:
err
Input:
huh
Output:
Hello Worlderr
Or
err
```
First challenge so please have mercy
[Answer]
# [Lenguage](https://esolangs.org/wiki/Lenguage), \$1.42 \times 10^{122}\$ bytes
*minus a lot of bytes thanks to Kevin Cruijssen and Bubbler*
```
hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh...
```
This is 142099843608359281286315447494338058415442968773543757980908246691462388164856076679905341690709953072132211450166077106439 `h`s, which also makes it a valid Hello program, though not one you'd want to run. The original brainfuck code is ~~140~~ 135 bytes:
```
,[>-[<-->-----]+<--[>]>[[-->-[>>+>-----<<]<--<---]>-.>>>+.>>..+++.>>.>.<<<.+++.------.<<-.[>]>>>>,>]<]<[[>++<+++++]>-.+++++++++++++..>]
```
[Try it online!](https://tio.run/##TUxJDoBACHsQwgtIP0I4qNGMMfHg@vwRxos9AF3osPfLNl/jWmtnYFNmcMIpToPDLCUD6DNUPRzNCFgQegwRorYhqtpIC3NQlqwJdPD4NQORUiIL6A8ReK2llKf053QfLw "brainfuck – Try It Online")
This prints Hello World every time it sees a `h` through a modification of the [shortest known Hello, World! program](https://codegolf.stackexchange.com/a/163590/76162), stopping the loop and printing `err` if it sees anything other than a `h`.
[Answer]
# [Python 3](https://docs.python.org/3/), 49 bytes
```
lambda s:{*s}-{'h'}and'err'or'Hello World'*len(s)
```
[Try it online!](https://tio.run/##HcGxCoMwEADQ3a/IdongUNyE7v0DF5eERC5wXsIlIkX89iv0vfrtWHjW/b0p@SNEb9pyj@2ZbkB4PEdIIlAEPomomLUIRRgpsW1OL8yUzGupkrnb3WauZ7fOOcUB/wY5Q8gN9Qc "Python 3 – Try It Online")
**Python 2, 51 bytes**
```
lambda s:s.strip('h')and'err'or'Hello World'*len(s)
```
[Try it online!](https://tio.run/##HcHBCsIwDADQ@76itzQeBD0OvPsHXgRpaUcKMS1Jx9jXR/C9cU7qcvft8XZO31xSsNWuNrWNCASYpEBVha7wrMw9vLpygQtXiYZ@UOMabuvQJjNuUdPxaTL2GRHRaaG/Rfecm5H/AA "Python 2 – Try It Online")
**Python 2, 51 bytes**
```
lambda s:['err','Hello World'*len(s)]['h'+s==s+'h']
```
[Try it online!](https://tio.run/##HcaxCsIwEADQvV@R7RLromMhu3/g0BZJaMoFziTcpRS//hTf9NqnYy133f2iFN5xC0amGRIzXOGRiKp5VqYNLpSKFbfOgDCK9zL@suqJmZK5TY1z6Xa3HM5XLu3o1jmnOODfwEeMWVC/ "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 32 [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.
```
{'h'=⍵:'Hello World'⋄-⎕←'err'}⍤0
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qp/@jtgkG/6vVM9RtH/VutVL3SM3JyVcIzy/KSVF/1N2iC1QDVKGeWlSkXvuod4nB/zQg91Fv36Ou5ke9ax71bjm03vhR20SgsuAgZyAZ4uEZ/D9NAWgel7o6F4gBAkgcDxjbQx0A "APL (Dyalog Unicode) – Try It Online")
`{`…`}⍤0` replace each character (`⍵`) with the result of applying the following lambda to it:
`'h'=⍵:` if the character is `h`:
`'Hello World'` return the required phrase
`⋄` else:
`⎕←'err'` print `err`
`-` negate it (causing an error and terminating)
[Answer]
# [R](https://www.r-project.org/), 76 bytes
```
function(p,n=nchar(p))ifelse(p==strrep('h',n),strrep("Hello World",n),'err')
```
[Try it online!](https://tio.run/##RYxBDoAgDATvvsJwoU34And/4FmxBJOmkIrvR1ET97Qzya62RMzZt3hKqHsWKE68hLQoFMQ9Eh8ExfujqlIBm6wTdB@ZqY/HOStvpntLqhbfTzAGh6@lJz@vTDe1Cw "R – Try It Online")
Should be a comment on <https://codegolf.stackexchange.com/a/210520/98085> - I didn't realise you could do functions like that! Slight change to be more robust when n = 0 and to use direct comparison rather than regex. -1 byte thanks to <https://codegolf.stackexchange.com/users/90265/zippymagician>.
Bonus version with side-effects (like redefining subtraction) thanks to <https://codegolf.stackexchange.com/users/92901/dingus>.
# [R](https://www.r-project.org/), 71 bytes
```
{`-`=strrep;function(p,n=nchar(p))`if`(p=='h'-n,'Hello world'-n,'err')}
```
[Try it online!](https://tio.run/##K/qfkZqTk2/7vzpBN8G2uKSoKLXAOq00L7kkMz9Po0AnzzYvOSOxSKNAUzMhMy1Bo8DWVj1DXTdPR90DpE@hPL8oJwXMTy0qUteshRinoaSkyQVlZYABgp@Ukwrk/QcA "R – Try It Online")
[Answer]
# [Gema](http://gema.sourceforge.net/), 23 characters
```
h=Hello World
?=err@end
```
Sample run:
```
bash-5.0$ echo -n 'hohoho' | gema 'h=Hello World;?=err@end'
Hello Worlderr
```
### Gema (old version with err on empty code), 32 characters
```
\A\Z=err
h=Hello World
?=err@end
```
[Try it online!](https://tio.run/##S0/NTfz/P8PWIzUnJ18hPL8oJ4XL3ja1qMghNS8FKJEPggA "Gema – Try It Online") / [Try all test cases online!](https://tio.run/##nVDBSsQwED03XzGGuukeStSLBwmuB0FPghcPbVnaZtYWa1KSFIR1v70mKegqeNAcZl4mb2beS1PbbpbYDrVByG/AoXXbtrYoMpIUrGOVYHc4DBqetBkki8V4frz8E8aBZmqa3saJaAwja0JG0yu3A/YOp/n5mYWQL7/nCx9LxYDdq3FyPj@inYYAbt9GbB1KDx9eGCE7baAPJB@BpvuTT5fFpjrQK5CaJCZ2C5pmgG2nIQ/U2EX9Nq5Hx5/xtebWtBEAmztx5IRcCy9@g0rODNaUkOQPHryouIrzlPk7L0t1oL66iApo/6V5UVVFQgZFccQT4jdqVcFqtTgLnxIUSq1w/gA "Bash – Try It Online")
[Answer]
# x86-16 machine code, IBM PC DOS, ~~41~~ 40 bytes
Binary:
```
00000000: be82 00ba 1801 b409 ac3c 0d74 0a3c 6874 .........<.t.<ht
00000010: 02b2 24cd 2174 f1c3 4865 6c6c 6f20 576f ..$.!t..Hello Wo
00000020: 726c 6424 6572 7224 rld$err$
```
Listing:
```
BE 0082 MOV SI, 82H ; SI to DOS PSP
BA 0118 MOV DX, OFFSET HW ; point to 'Hello World' string
B4 09 MOV AH, 9 ; DOS write string function
CHAR_LOOP:
AC LODSB ; AL = next input byte
3C 0D CMP AL, 0DH ; is a CR (end of input string)?
74 0A JZ DONE ; if so, end
3C 68 CMP AL, 'h' ; is an 'h'?
74 02 JZ WRITE_STR ; if so, write Hello(s)
B2 24 MOV DL, LOW OFFSET ER ; otherwise, point to 'err' string
WRITE_STR:
CD 21 INT 21H ; write string to stdout
74 F1 JZ CHAR_LOOP ; if 'h', keep looping
DONE:
C3 RET ; return to DOS
HW DB 'Hello World$'
ER DB 'err$'
```
Standalone PC DOS executable COM program. Input via command line. This version prints `Hello Worlderr` if an error is in the input code.
[](https://i.stack.imgur.com/Bhhx2.png)
And for fun (and since I did it first), this version will only print `err` if an error is in the code.
### x86-16 machine code, IBM PC DOS, ~~47~~ ~~45~~ 44 bytes
Binary:
```
00000000: bf80 00ba 1c01 8a0d 4951 abb8 6809 f3ae ........IQ..h...
00000010: 5974 04b2 28b1 01cd 21e2 fcc3 4865 6c6c Yt..(...!...Hell
00000020: 6f20 576f 726c 6424 6572 7224 o World$err$
```
Listing:
```
BF 0080 MOV DI, 80H ; DI to DOS PSP
BA 011C MOV DX, OFFSET HW ; point to 'Hello World' string
8A 0D MOV CL, BYTE PTR[DI] ; CL = input length
49 DEC CX ; remove leading space from length
51 PUSH CX ; save length for later
AB STOSW ; DI to start of command line input
B8 0968 MOV AX, 0968H ; AL = 'h', AH = 9
F3/ AE REPZ SCASB ; search input for 'h': ZF if Hello, NZ if error
59 POP CX ; restore input length
74 04 JZ HELLO_LOOP ; if no error, write Hello(s)
B2 28 MOV DL, LOW OFFSET ER ; otherwise, point to 'err' string
B1 01 MOV CL, 1 ; only show 'err' once
WRITE_LOOP:
CD 21 INT 21H ; write string to stdout
E2 FC LOOP WRITE_LOOP ; loop until done
C3 RET ; return to DOS
HW DB 'Hello World$'
ER DB 'err$'
```
[](https://i.stack.imgur.com/c7LbM.png)
Props:
* -1 byte for both thanks to @MatteoItalia for suggestion to change only the low byte on the error string pointer.
[Answer]
# Excel, 63 bytes
```
=IF(SUBSTITUTE(A1,"h","")="",REPT("Hello World",LEN(A1)),"err")
```
---
`SUBSTITUTE(A1,"h","")=""` returns `TRUE` iff `A1` contains nothing but `h`.
`REPT("Hello World",LEN(A1))` repeats the string for however many characters are in `A1`.
`=If(Substitute(~)="",REPT(~),"err")` returns the repeated string if `A1` contains only `h` and `err` if it contains anything else.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 17 bytes
14 if we can print `Err` as a substring of the output (e.g. `“½,⁾ẇṭ»€!fƑ?”h` [TIO](https://tio.run/##ASwA0/9qZWxsef//4oCcwr0s4oG@4bqH4bmtwrvigqwhZsaRP@KAnWj///9oaHhoaA)).
```
“½,⁾ẇṭ»€“¹ṫ»fƑ?”h
```
**[Try it online!](https://tio.run/##y0rNyan8//9Rw5xDe3UeNe57uKv94c61h3Y/aloDEtv5cOfqQ7vTjk20f9QwN@P///8ZGRUZGQA "Jelly – Try It Online")**
### How?
```
“½,⁾ẇṭ»€“¹ṫ»fƑ?”h - Main Link: program
”h - set right argument to 'h'
? - if...
Ƒ - ...condition: is (program) invariant under?:
f - keep only ('h's)
€ - ...then: for each (c in program):
“½,⁾ẇṭ» - "Hello World"
“¹ṫ» - ...else: "error"
- implicit, smashing print
```
[Answer]
# [Ruby](https://www.ruby-lang.org/) `-0p`, ~~42...35~~ 33 bytes
*The idea to use the `-0p` flags (instead of `-n` like I originally had) came from [@DomHastings's Perl answer](https://codegolf.stackexchange.com/a/210509/92901), saving 4 bytes.*
```
$_=/[^h]/?:err:'Hello World'*~/$/
```
[Try it online!](https://tio.run/##KypNqvz/XyXeVj86LiNW394qtajISt0jNScnXyE8vygnRV2rTl9F////jIyMf/kFJZn5ecX/dQ0KAA "Ruby – Try It Online")
Reads the program from STDIN. A regex is used to check whether the program contains any character other than `h`. If so, print `err`; otherwise, print `Hello World` as many times as the number of characters in the program (given by `~/$/`).
Using a bare regex literal as a boolean is a deprecated Perlism that (since Ruby 1.9) only works with the `-n` or `-p` flags.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 17 bytes
```
'hÃQig”Ÿ™‚ï”×ë'‰ë
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fPeNwc2Bm@qOGuUd3PGpZ9Khh1uH1QM7h6YdXqz9q2HB49f//SkpKGVwZGUAKAA)
Big thanks to @Kevin for your [dictionary compression tool](https://codegolf.stackexchange.com/a/166851/78850)!
And once again, Kevin has struck and managed to shave 3 bytes from my answer! So the aforementioned thanks is to be multiplied by a massive magnitude.
## Explained (old)
```
Ð'hÃQig”Ÿ™‚ï”и»ë"err
Ð # Triplicate the input. STACK = [input, input, input]
'h # Push the letter 'h'. STACK = [input, input, input, 'h']
à # Keep _only_ the letter h in the input. STACK = [input, input, input.keep('h')]
Q # Compare this with the original input. STACK = [input, 1 OR 0]
i # If the comparison is truthy (i.e. it's only h's):
g # Push the length of the input. STACK = [len(input)]
”Ÿ™‚ï” # Push the compressed string "Hello World". STACK = [len(input), "Hello World"]
и» # Repeat that string length of input times and join upon newlines. STACK = ["\n".join("Hello World" * len(input))]
ë # Else:
"err # Push the string "err" to the stack. STACK = [input, "err"]
# Implicitly output the top of the stack
```
[Answer]
# Haskell (Hugs 2006), 31 bytes
```
mapM(\'h'->putStr"Hello World")
```
Pending a question to the OP r.e. "error" in a larger error message.
The spec says "it must print err or error", which it does on Hugs 2006, specifically the `Raskell 1.0.13 interpreter based on Hugs 2006`:
```
> mapM(\'h'->putStr"Hello World") "huh"
Hello World
Program error: pattern match
failure: ww_v4136 'u'
```
[Answer]
# [Arn](https://github.com/ZippyMagician/Arn), [24 bytes](https://github.com/ZippyMagician/Arn/wiki/Carn)
```
ùÝ└ån<⁼aLw$■v&Z(#▄╗└·I╔║
```
[Try it!](https://zippymagician.github.io/Arn?code=KCR7PSJoIn0pIz0jJiYneXQgYnMnXiN8fCJlcnI=&input=aApoaGhoaGgKcnViYmlzaA==)
# Explained
Unpacked: `(${="h"})#=#&&'yt bs'^#||"err`
And this is why I need to add an if else...
```
( Begin expression
$ Filter
{ Block with index of _
_ Implicit
= Equals
"h" String
} End block
_ Variable initialized to STDIN; implied
) End expression
# Length
= Equals
_ Implied
#
&& Boolean AND
'yt bs' Compressed string equal to "Hello World"
^ Repeated
_ Implied
#
|| Boolean OR
"err
```
[Answer]
# [SNOBOL4 (CSNOBOL4)](http://www.snobol4.org/csnobol4/), 94 bytes
```
I =INPUT
I NOTANY('h') :S(E)
OUTPUT =DUPL('Hello World',SIZE(I)) :(END)
E OUTPUT ='err'
END
```
[Try it online!](https://tio.run/##K87LT8rPMfn/n9NTwdbTLyA0hAvI8vMPcfSL1FDPUNfktArWcNXk4vQPDQFKKti6hAb4aKh7pObk5CuE5xflpKjrBHtGuWp4agKVarj6uWhyucIVq6cWFalzAQX///dwBQA "SNOBOL4 (CSNOBOL4) – Try It Online")
```
I =INPUT ;* Read input
I NOTANY('h') :S(E) ;* If there is a character that's not 'h' in the input, goto E
OUTPUT =DUPL('Hello World',SIZE(I)) :(END) ;* else print "Hello World" repeatedly and goto END
E OUTPUT ='err' ;* print 'err'
END
```
[Answer]
# JavaScript, 49 bytes
-4 bytes if we can *throw* an error instead of outputting a string.
```
f=([c,...a])=>c?c==`h`?`Hello World`+f(a):`err`:a
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/f8/zVYjOllHT08vMVbT1i7ZPtnWNiEjwT7BIzUnJ18hPL8oJyVBO00jUdMqIbWoKMEq8X9yfl5xfk6qXk5@ukaahlKGkqYmF7oYCGAVr8Aq7gEU@w8A)
[Answer]
## JavaScript ~~72~~ 66 bytes
-6 bytes thanks to @Ismael Miguel
```
alert(/^h*$/.test(a=prompt())?a.replace(/h/g,'Hello World'):'err')
```
[Answer]
# [flex](http://web.mit.edu/gnu/doc/html/flex_1.html), ~~76~~ \$\cdots\$ ~~55~~ 52 bytes
```
%%
h puts("Hello World");
[^h] puts("err");exit(1);
```
Put the above code in a file called `hello.l` and make the interpreter with:
```
flex hello.l && gcc lex.yy.c -o hello -lfl
```
Trying it on my terminal:
```
> echo -n hhh|./hello.exe
Hello World
Hello World
Hello World
```
With newline:
```
> echo hhh|./hello.exe
Hello World
Hello World
Hello World
err
```
notice the `err` because of the trailing newline `echo` normally sends.
With non-`h` character:
```
> echo -n hhhehhh|./hello.exe
Hello World
Hello World
Hello World
err
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~71~~ 65 bytes
```
f(char*p){p=*p-'h'?*p&&puts("err"):f(p+1)||!puts("Hello World");}
```
[Try it online!](https://tio.run/##VY7NDoIwEITvfYq1RmlRTLyK4tUHMPHiASg/bVKgacsJeHYskKjsaWd28s2yoGRsHAvCeKJ9RTt181Xgce/uq/1etdYQnGuN6aUg6nCmfb9ZzEcuZQOvRssM03AYn7mxQGDGgNJNqZMKaIfcLmpbAMFRFO9M/K7x8XcPERRkJRe6Q6IBoa2omWyzHK7GZqI58Qg5GFSJqAkFB19aMZ/yXzHNv6HbNBVmnZm@n0vGDw "C (gcc) – Try It Online")
* Thanks to @rtpax for saving 6!
`f(char*p){p=` - function tacking a `program` and returning with the eax trick, reusing `p`.
Calls itself recursively.
Recursion happens before `program` execution so if all steps are correct a `false` value is returned and the `program` is executed.
If there's an error a `truthy` value is returned and `program` is not executed at all, an error message is displayed.
```
*p-'h'? `...` :f(p+1)||!puts("Hello World");
- check each character in ***program*** : if ***h*** continue recursion and
if result is ***false*** program do its job.
***p*** is ***true*** if there was an error, ***false*** instead.
- if not ***h*** stop recursion and :
*p - if end of ***program***
***p*** is ***false***
&&puts("err") - if not end of ***program*** display error
***p*** is ***true***.
```
---
[~~61~~ 58 bytes](https://tio.run/##VU9BDoIwELz3FZs1YotiYuJJTL36ABMvHoBCoUmBpoUT4e0VMFHZ08zs7ExWRKUQ3ksqqtSGhg2hCQLTd46GJtpVuxsW1uIF74XWLTxbq3Nk/BwEkpr9icWjfxSuAwrLPRjbljatgQ1kwqrpJFDkPNm65NXg4bePCUi6oksp4gRHQjaqEbrPC7i6LlftseJkCoM6VQ1lMIV/WrGa/V8yz79g@yxTbu2Z/1hK/Bs "C (gcc) – Try It Online") alternative less interesting solution which runs the program and stops when an error happens
```
f(char*p){*p&&puts(*p-'h'?"err":"Hello World")>4&&f(p+1);}
```
* Saved 3 thanks to @rtpax !
[Answer]
# [Python 3](https://docs.python.org/3/), 52 bytes
```
lambda x:(x=='h'*len(x))*len(x)*'Hello World'or'err'
```
[Try it online!](https://tio.run/##LcYxDsMgDEDRvafwZjtDlm6V2HuDLFmoIALJwcgwkNOTDP3L@/XqSct7HuBgn@LPX/AwPjScw4SLxEKD@e@C3yiisKlJQDWMZjjzWdU6tKu9quXS6aDn19ZDLqtFH4iZZ3q6AQ "Python 3 – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), 58 bytes
```
lambda s:s and s=="h"*len(s)and"Hello World"*len(s)or"err"
```
[Try it online!](https://tio.run/##NcoxCsMwDEDR3acQnuwOWboVvPcGXbq4yCECRTaSOuT0Tlvo9nn8cfjW5TrX8pxc9xdWsJtBFQQrJW7xwk2S5Q/Ee2Pu8OjK@OeusanGSfvo6mCHBZLxdijfXsyRZNFWkUlaCENJPK3p96Sc8zwB "Python 3 – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~23~~ 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
-4 bytes thanks to @Shaggy
```
rh ?`r`:¡`HÁM Wld
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=cmggP2CAcmA6oWBIwU0gV45sZA&input=Imgi)
## Explanation
```
rh ?`...`:¡`...
? // if
rh // input with 'h' removed
`...` // then "err"
: // else
¡ // each char in input
`... // replaced with "Hello World"
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~28~~ 27 bytes
```
aRM'h?"err""Hello World"X#a
```
-1 byte from DLosc.
If the string without h's is empty, print "Hello World" required number of times.
Otherwise, error.
This program errors on empty input as well.
[Try it online!](https://tio.run/##K8gs@P8/MchXPcNeKbWoSEnJIzUnJ18hPL8oJ0UpQjnx////GRCQAwA "Pip – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~57~~ 52 bytes
```
lambda a:a=='h'*len(a)and'Hello World'*len(a)or'err'
```
[Try it online!](https://tio.run/##VckxDoMwDEDRnVN4c8LKVik7N@jSxVWCHGFs5EZCPX3KgirG9//@bWw69SW9utD2zgT0oJSQcZSigSJpxrmIGDzNJV/ZHIs79t2rtrAEZGaMcfj7psb1A0cVAbUGh/l67v4D)
[Answer]
# [Vim](https://www.vim.org), ~~48~~ 47 bytes
*Thanks to @DLosc for -1 bytes*
```
:g/\_$\_^\|[^h]/norm HcGerr
:s/h/Hello World/g
```
[Try it online!](https://tio.run/##K/v/3ypdPyZeJSY@LqYmOi4jVj8vvyhXwSPFPTO1qIjLqlg/Q98jNScnXyE8vygnRT@d6///DBQAAA "V (vim) – Try It Online")
The `:g` command is a bit convoluted, but there's a reason for that. The `[^h]` part will match all non-`h` characters, but it won't match newlines. `$` or `\n` will match end-of-line, which means they will match a single line without a newline. To make it match only when there are multiple lines, I used `\_$\_^`. This will only match newlines (`\_$`) that are followed by another line (`\_^`).
For some reason, this doesn't work properly in TIO, so programs where the only non-`h` characters are newlines won't error. However, this does work properly in Vim.
Explanation:
```
:g/ (x) / (y) # If x exists, execute y:
\_$\_^ # x -> An end-of-line followed by a start-of-line;
\|[^h] # OR any character that isn't 'h'
norm HcGerr # y -> Delete all lines, then print 'err'
:s/h/Hello World/g # Replace every 'h' with 'Hello World'
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf/blob/master/math_golf.txt), ~~23~~ 20 [bytes](https://github.com/maxbergmark/mathgolf/blob/master/code_page.py)
```
'h-╛æ╖•p0{δ╕○ô 'W╕7ÿ
```
[Try it online.](https://tio.run/##y00syUjPz0n7/189Q/fR1NmHlz2aOu1Rw6ICg@pzWx5NnfpoevfhLQrq4UCm@eH9//8rZShxKWVkQMiYvAwwAeQUlSYlZRZnKAEA)
**Explanation:**
```
'h- '# Remove all "h" from the (implicit) input-string
╛ # Pop, and if it's now truthy (thus non-empty):
æ # Use the following four characters as single code-block:
╖•p # Push compressed string "err"
0 # And push a 0
{ # Either loop 0 times,
# or loop over each character of the (implicit) input-string:
δ # Titlecase the implicitly pushed current character ("h"→"H")
╕○ô # Push compressed string "ello"
# Push " "
'W '# Push "W"
╕7ÿ # Push compressed string "orld"
# (implicitly output the entire stack joined together as result)
```
[Answer]
# SimpleTemplate 0.84, ~~92~~ 63 bytes
This challenge was simple, yet fun!
Simply checks if the input is just "hhh...." and outputs the text, or outputs "err" to STDOUT:
```
{@ifargv.0 matches"@^h+$@"M}{@eachM.0}Hello World{@/}{@else}err
```
The big byte saving was due to [the-cobalt](https://codegolf.stackexchange.com/users/97771/the-cobalt)'s comment:
>
> Outputting to STDOUT is fine, so you could use your 63 byte version.
>
>
>
---
**Ungolfed:**
Below is a more readable version of the code:
```
{@if argv.0 matches "@^h+$@"}
{@each argv.0 as h}
{@echo "Hello World"}
{@/}
{@else}
{@echo "err"}
{@/}
```
---
You can try this on: <http://sandbox.onlinephpfunctions.com/code/e35a07dfbf6b3b56c2608aa86028b395ef457129>
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 44 bytes
```
$args|%{if($_-104){'err';exit}"Hello World"}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V8lsSi9uEa1OjNNQyVe19DARLNaPbWoSN06tSKzpFbJA6gwXyE8vygnRan2fy0Xl3oGCKjrKIGMyFcC0iAApIvzSwuUgAYphRRVZualK6jEK1gpWauppCk4xFurq9f@BwA "PowerShell – Try It Online")
Takes input by splatting
[Answer]
# Befunge-93, 58 56 bytes
```
~:1+!#v_"h"-#v_"dlroW olleH",,,,,,,,,,,
@,,,@#"err"<
```
[Try it online!](https://tio.run/##S0pNK81LT/3/v87KUFtRuSxeKUNJF0Sl5BTlhyvk5@SkeijpIICCApeCggOQ4aCslFpUpGTz/39GRgYA "Befunge-93 – Try It Online")
## How does it work?
```
~ # Read a character.
:1+! # Check whether we read -1 (end of input);
# this leaves 1 on the stack if we are at
# the end of the input, else 0.
#v_ # Exit the program if we're at the end
@ # end of the input.
"h"- # Compare the read character with the
# character "h", if equal, we leave 0 on
# the stack, otherwise, non-zero.
#v_ # If we read anything but "h", print "err"
@,,,@#"err"< # and exit the program.
"dlroW olleH",,,,,,,,,,, # Print "Hello World"
```
[Answer]
GFA Basic (Atari ST), 125 bytes
```
INPUT a$
FOR i=1 TO LEN(a$)
b$=MID$(a$,i,1)
IF b$="h"
PRINT "Hello World"
ELSE
PRINT "err"
EXIT IF 1
ENDIF
NEXT I
```
[Answer]
# [Io](http://iolanguage.org/), 63 bytes
```
method(:,:foreach(X,if(X!=104,"err"print-,"Hello World"print)))
```
[Try it online!](https://tio.run/##Jcm9CoAgFEDh3aewOykYFDQJ7b1BDi39KArmjZs9v4Wd8XwBi@N65Es5bfZ4CK20Q7Lr7oVRwQnTjH03KLBEcFFIuVUw2RiRz0jx@J@UsjgBvgaSMQBeISbGPqBn28L9SXkB "Io – Try It Online")
## Explanation
```
method(i, // Take input
i foreach(X, // For every item:
if(X!=104, // If the codepoint isn't 104:
"err"print // print "err" (w/o nl)
- // Subtract "err" by the "Object" class (causes error)
,"Hello World"print // Otherwise, print "Hello World" (w/o nl)
)))
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~84~~ 80 bytes
-4 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat). It's beautiful!
```
main(c,v)char**v;{*v[1]++-'h'?*--v[1]&&puts("err"):main(puts("Hello World"),v);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z83MTNPI1mnTDM5I7FIS6vMulqrLNowVltbVz1D3V5LVxfEU1MrKC0p1lBKLSpS0rQCa4EIeKTm5OQrhOcX5aQoaQINsa79//9/RkZGIgA "C (gcc) – Try It Online")
Not so fancy, but I like that it's a complete program **`:)`**
"Normal" version:
```
#include <stdio.h>
int main(int argc, char** argv)
{
if (*argv[1]++ - 'h')
return *--argv[1] && puts("err");
else
return main(puts("Hello World"), argv);
}
```
] |
[Question]
[
*Yet another blatant [rip-off](https://codegolf.stackexchange.com/questions/193021/i-reverse-the-source-code-you-negate-the-input) of a [rip-off](https://codegolf.stackexchange.com/q/192979/43319) of a [rip-off](https://codegolf.stackexchange.com/q/132558/43319). Go upvote those!*
Your task, if you wish to accept it, is to write a program/function that outputs/returns its string input/argument. The tricky part is that if I reverse your source code, the output must be reversed too.
For simplicity, you can assume that the input is always a single line string containing only ASCII letters (a-z), digits (0-9) and spaces.
Should support an input of at least 8 characters long (longer than 8 is not necessary).
Behaviour for empty input is undefined.
## Examples
Let's say your source code is `ABC` and its input is `xyz`. If I write `CBA` instead and run it, the output must be `zyx`.
Let's say your source code is `ABC` and its input is `96`. If I write `CBA` instead and run it, the output must be `69`.
A single leading or trailing white-space is acceptable as long as it is consistent in both normal and reversed outputs.
[Answer]
# JavaScript, 32 bytes
```
s=>s//``nioj.)(esrever.]s...[>=s
```
Reversed:
```
s=>[...s].reverse().join``//s>=s
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 9 bytes
```
cat # ver
```
Reversed:
```
rev # tac
```
[Try it online!](https://tio.run/##S0oszvj/PzmxREFZoSy16P//ktTiEgA) [!enilno ti yrT](https://tio.run/##S0oszvj/vyi1TEFZoSQx@f//ktTiEgA)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~3~~ 2 [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 byte thanks to dzaima
```
⌽⊂
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT////1HP3kddTf/THrVNeNTb96hvqqf/o67mQ@uNH7VNBPKCg5yBZIiHZ/D/NPWKyip1rjR1SzN1AA "APL (Dyalog Unicode) – Try It Online")
`⊂` enclose the argument to treat it as a singleton: `[1,2,3]` → `[[1,2,3]]`
`⌽` reverse (has no effect on singletons): `[[1,2,3]]` → `[[1,2,3]]`
An enclosed array prints with a leading an a trailing space.
[!enilno ti yrT](https://tio.run/##SyzI0U2pTMzJT////1FX06Oevf/THrVNeNTb96hvqqf/o67mQ@uNH7VNBPKCg5yBZIiHZ/D/NPWKyip1rjR1SzN1AA "APL (Dyalog Unicode) – Try It Online")
`⌽` reverse (has no effect on singletons): `[1,2,3]` → `[3,2,1]`
`⊂` enclose: `[3,2,1]` → `[[3,2,1]]`
An enclosed array prints with a leading an a trailing space.
[Answer]
# [Keg](https://github.com/JonoCode9374/Keg), ~~3~~ 2 bytes
```
#?
```
[Try it online!](https://tio.run/##y05N//9f2f7//5CiSoXMEoX8vJzMvFRFAA "Keg – Try It Online") or [!enilno ti yrT](https://tio.run/##y05N///fXvn//5CiSoXMEoX8vJzMvFRFAA "Keg – Try It Online")
## Explained
```
#? #Implicit cat
?# Reversed input
```
Heh. That's right. Keg can stand up to those 2-byte answers too (and using pure, plain ASCII)!
## Old Program
```
^#?
```
[Try it online!](https://tio.run/##y05N//8/Ttn@/3/HpGQA "Keg – Try It Online")
Or
[!enilno ti yrT](https://tio.run/##y05N///fXjnu/3/HpGQA "Keg – Try It Online")
Because two can play the 3-byte game. That's why. (did I mention that's 3 bytes of *~~utf8~~ ASCII*?)
```
^#? #Reverse an empty stack, taking implicit input
?#^ #take input
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 21 bytes
```
->x{x}#}esrever.x{x>-
```
[Try it online!](https://tio.run/##KypNqvyfZhvzX9euorqiVrk2tbgotSy1SA/Is9P9X1BaUqyQFq1UUVmlFMsF41maKcX@BwA "Ruby – Try It Online")
```
->x{x.reverse}#}x{x>-
```
[!enilno ti yrT](https://tio.run/##KypNqvyfZhvzX9euorpCryi1LLWoOLVWuRbIs9P9X1BaUqyQFq1UUVmlFMsF41maKcX@BwA "Ruby – Try It Online")
[Answer]
## [Stack Cats](https://github.com/m-ender/stackcats) `-m`, 4 bytes
```
|>I|
```
[Try it online!](https://tio.run/##Ky5JTM5OTiwp/v@/xs6z5v9/j9ScnHwdhfD8opwUxf@6uQA "Stack Cats – Try It Online")
[Try it reversed!](https://tio.run/##Ky5JTM5OTiwp/v@/xtOu5v9/j9ScnHwdhfD8opwUxf@6uQA "Stack Cats – Try It Online")
This works for any inputs that don't contain null bytes.
### Explanation
Wow, I've reached the point where I'm writing these by hand...
The full program is `|>I|I<|`.
```
| Reverse the entire stack down to the EOF marker -1 (since there are no zeros in the input).
> Move one stack over to the right (which only contains zeros).
I Does nothing on zero.
| Does nothing on zero.
I Does nothing on zero.
< Move back to the initial stack.
| Reverse the input once more.
```
As in the solution to the previous challenge, since the centre command `|` does nothing, so does the entire program.
The reversed program is then `|I>|<I|`.
```
| Reverse the entire stack down to the EOF marker -1 (since there are no zeros in the input).
I Move the -1 one stack to the left and turn it into a +1.
> Move back to the initial stack.
| Reverse it again, but this time without the EOF marker.
< Move back to the left.
I Move the +1 back onto the initial stack and turn it into a -1 again.
| Reverse the entire stack. We now have the -1 as an EOF marker again at the bottom
and the rest of the stack has been reversed three times, i.e. one net reversal.
```
Interestingly, if we use this reversing program without `-m` we still get a working solution this time, so the only additional bytes incurred by omitting `-m` are those we get from mirroring the code.
---
## [Stack Cats](https://github.com/m-ender/stackcats), 7 bytes
```
|I<|>I|
```
[Try it online!](https://tio.run/##Ky5JTM5OTiwp/v@/xtOmxs6z5v9/j9ScnHwdhfD8opwURQA "Stack Cats – Try It Online")
[Try it reversed!](https://tio.run/##Ky5JTM5OTiwp/v@/xtOuxsaz5v9/j9ScnHwdhfD8opwURQA "Stack Cats – Try It Online")
### Explanation
The reversed version of this program is `|I>|<I|`, the same as above so we can ignore that. But the non-reversed version differs. Since the `<>` now point the other way, the centre command ends up doing nothing, so the program becomes a cat:
```
| Reverse the entire stack down to the EOF marker -1 (since there are no zeros in the input).
I Move the -1 one stack to the left and turn it into a +1.
< Move another stack to the left, which contains only zeros.
| Does nothing on zero.
```
And thus, `>I|` exactly undo the first half of the program.
[Answer]
# [Haskell](https://www.haskell.org/), 11 bytes
```
id--esrever
```
[Try it online!](https://tio.run/##y0gszk7NyfmfZhvzPzNFVze1uCi1LLXof25iZp6CrUJBaUlwSZGCikKagpIHUF2@Qnh@UU6K0v9/yWk5ienF/3WTCwoA "Haskell – Try It Online") [Try it reversed!](https://tio.run/##y0gszk7NyfmfZhvzvyi1LLWoOFVXNyXzf25iZp6CrUJBaUlwSZGCikKagpIHUF2@Qnh@UU6K0v9/yWk5ienF/3WTCwoA "Haskell – Try It Online")
[Answer]
# Pyth, 5 3 bytes
`z_k`
-2 bytes by realizing the newline flips around anyways
Explanation:
```
z # Implicitly print the input
_k # Implicitly print the reversed empty string
```
Reversed Explanation:
```
k # Implicitly print the empty string
_z # Implicitly print the reversed input
```
[Answer]
# [Turing Machine Language](http://morphett.info/turing/turing.html), ~~14324~~ ~~14321~~ 13257 bytes
```
0 ( ( l 6;
0 * * l 2;
1 _ _ l 2;
2 _ ( r 3;
3 _ _ r 4;
4 _ _ l 3);
4 * * r 2;
3) _ ) l 5;
3 * * r 3;
5 ( ( * 0;
5 * * l 5;
6 _ _ l 7;
7 _ ] r 8;
8 ) ) l 9;
8 * * r 8;
9 0 @ l c0;
9 1 @ l c1;
9 2 @ l c2;
9 3 @ l c3;
9 4 @ l c4;
9 5 @ l c5;
9 6 @ l c6;
9 7 @ l c7;
9 8 @ l c8;
9 9 @ l c9;
9 a @ l a;
9 A @ l A;
9 b @ l b;
9 B @ l B;
9 c @ l c;
9 C @ l C;
9 d @ l d;
9 D @ l D;
9 e @ l e;
9 E @ l E;
9 f @ l f;
9 F @ l F;
9 g @ l g;
9 G @ l G;
9 h @ l h;
9 H @ l H;
9 i @ l i;
9 I @ l I;
9 j @ l j;
9 J @ l J;
9 k @ l k;
9 K @ l K;
9 l @ l l;
9 L @ l L;
9 m @ l m;
9 M @ l M;
9 n @ l n;
9 N @ l N;
9 o @ l o;
9 O @ l O;
9 p @ l p;
9 P @ l P;
9 q @ l q;
9 Q @ l Q;
9 r @ l r;
9 R @ l R;
9 s @ l s;
9 S @ l S;
9 t @ l t;
9 T @ l T;
9 u @ l u;
9 U @ l U;
9 v @ l v;
9 V @ l V;
9 w @ l w;
9 W @ l W;
9 x @ l x;
9 X @ l X;
9 y @ l y;
9 Y @ l Y;
9 z @ l z;
9 Z @ l Z;
c0 ] ] l c0a;
c0 * * l c0;
c0a _ 0 r @0;
c0a * * l c0a;
@0 @ 0 l nC;
@0 * * r @0;
c1 ] ] l c1a;
c1 * * l c1;
c1a _ 1 r @1;
c1a * * l c1a;
@1 @ 1 l nC;
@1 * * r @1;
c2 ] ] l c2a;
c2 * * l c2;
c2a _ 2 r @2;
c2a * * l c2a;
@2 @ 2 l nC;
@2 * * r @2;
c3 ] ] l c3a;
c3 * * l c3;
c3a _ 3 r @3;
c3a * * l c3a;
@3 @ 3 l nC;
@3 * * r @3;
c4 ] ] l c4a;
c4 * * l c4;
c4a _ 4 r @4;
c4a * * l c4a;
@4 @ 4 l nC;
@4 * * r @4;
c5 ] ] l c5a;
c5 * * l c5;
c5a _ 5 r @5;
c5a * * l c5a;
@5 @ 5 l nC;
@5 * * r @5;
c6 ] ] l c6a;
c6 * * l c6;
c6a _ 6 r @6;
c6a * * l c6a;
@6 @ 6 l nC;
@6 * * r @6;
c7 ] ] l c7a;
c7 * * l c7;
c7a _ 7 r @7;
c7a * * l c7a;
@7 @ 7 l nC;
@7 * * r @7;
c8 ] ] l c8a;
c8 * * l c8;
c8a _ 8 r @8;
c8a * * l c8a;
@8 @ 8 l nC;
@8 * * r @8;
c9 ] ] l c9a;
c9 * * l c9;
c9a _ 9 r @9;
c9a * * l c9a;
@9 @ 9 l nC;
@9 * * r @9;
a ] ] l aa;
a * * l a;
aa _ a r @a;
aa * * l aa;
@a @ a l nC;
@a * * r @a;
A ] ] l Aa;
A * * l A;
Aa _ A r @A;
Aa * * l Aa;
@A @ A l nC;
@A * * r @A;
b ] ] l ba;
b * * l b;
ba _ b r @b;
ba * * l ba;
@b @ b l nC;
@b * * r @b;
B ] ] l Ba;
B * * l B;
Ba _ B r @B;
Ba * * l Ba;
@B @ B l nC;
@B * * r @B;
c ] ] l ca;
c * * l c;
ca _ c r @c;
ca * * l ca;
@c @ c l nC;
@c * * r @c;
C ] ] l Ca;
C * * l C;
Ca _ C r @C;
Ca * * l Ca;
@C @ C l nC;
@C * * r @C;
d ] ] l da;
d * * l d;
da _ d r @d;
da * * l da;
@d @ d l nC;
@d * * r @d;
D ] ] l Da;
D * * l D;
Da _ D r @D;
Da * * l Da;
@D @ D l nC;
@D * * r @D;
e ] ] l ea;
e * * l e;
ea _ e r @e;
ea * * l ea;
@e @ e l nC;
@e * * r @e;
E ] ] l Ea;
E * * l E;
Ea _ E r @E;
Ea * * l Ea;
@E @ E l nC;
@E * * r @E;
f ] ] l fa;
f * * l f;
fa _ f r @f;
fa * * l fa;
@f @ f l nC;
@f * * r @f;
F ] ] l Fa;
F * * l F;
Fa _ F r @F;
Fa * * l Fa;
@F @ F l nC;
@F * * r @F;
g ] ] l ga;
g * * l g;
ga _ g r @g;
ga * * l ga;
@g @ g l nC;
@g * * r @g;
G ] ] l Ga;
G * * l G;
Ga _ G r @G;
Ga * * l Ga;
@G @ G l nC;
@G * * r @G;
h ] ] l ha;
h * * l h;
ha _ h r @h;
ha * * l ha;
@h @ h l nC;
@h * * r @h;
H ] ] l Ha;
H * * l H;
Ha _ H r @H;
Ha * * l Ha;
@H @ H l nC;
@H * * r @H;
i ] ] l ia;
i * * l i;
ia _ i r @i;
ia * * l ia;
@i @ i l nC;
@i * * r @i;
I ] ] l Ia;
I * * l I;
Ia _ I r @I;
Ia * * l Ia;
@I @ I l nC;
@I * * r @I;
j ] ] l ja;
j * * l j;
ja _ j r @j;
ja * * l ja;
@j @ j l nC;
@j * * r @j;
J ] ] l Ja;
J * * l J;
Ja _ J r @J;
Ja * * l Ja;
@J @ J l nC;
@J * * r @J;
k ] ] l ka;
k * * l k;
ka _ k r @k;
ka * * l ka;
@k @ k l nC;
@k * * r @k;
K ] ] l Ka;
K * * l K;
Ka _ K r @K;
Ka * * l Ka;
@K @ K l nC;
@K * * r @K;
l ] ] l la;
l * * l l;
la _ l r @l;
la * * l la;
@l @ l l nC;
@l * * r @l;
L ] ] l La;
L * * l L;
La _ L r @L;
La * * l La;
@L @ L l nC;
@L * * r @L;
m ] ] l ma;
m * * l m;
ma _ m r @m;
ma * * l ma;
@m @ m l nC;
@m * * r @m;
M ] ] l Ma;
M * * l M;
Ma _ M r @M;
Ma * * l Ma;
@M @ M l nC;
@M * * r @M;
n ] ] l na;
n * * l n;
na _ n r @n;
na * * l na;
@n @ n l nC;
@n * * r @n;
N ] ] l Na;
N * * l N;
Na _ N r @N;
Na * * l Na;
@N @ N l nC;
@N * * r @N;
o ] ] l oa;
o * * l o;
oa _ o r @o;
oa * * l oa;
@o @ o l nC;
@o * * r @o;
O ] ] l Oa;
O * * l O;
Oa _ O r @O;
Oa * * l Oa;
@O @ O l nC;
@O * * r @O;
p ] ] l pa;
p * * l p;
pa _ p r @p;
pa * * l pa;
@p @ p l nC;
@p * * r @p;
P ] ] l Pa;
P * * l P;
Pa _ P r @P;
Pa * * l Pa;
@P @ P l nC;
@P * * r @P;
q ] ] l qa;
q * * l q;
qa _ q r @q;
qa * * l qa;
@q @ q l nC;
@q * * r @q;
Q ] ] l Qa;
Q * * l Q;
Qa _ Q r @Q;
Qa * * l Qa;
@Q @ Q l nC;
@Q * * r @Q;
r ] ] l ra;
r * * l r;
ra _ r r @r;
ra * * l ra;
@r @ r l nC;
@r * * r @r;
R ] ] l Ra;
R * * l R;
Ra _ R r @R;
Ra * * l Ra;
@R @ R l nC;
@R * * r @R;
s ] ] l sa;
s * * l s;
sa _ s r @s;
sa * * l sa;
@s @ s l nC;
@s * * r @s;
S ] ] l Sa;
S * * l S;
Sa _ S r @S;
Sa * * l Sa;
@S @ S l nC;
@S * * r @S;
t ] ] l ta;
t * * l t;
ta _ t r @t;
ta * * l ta;
@t @ t l nC;
@t * * r @t;
T ] ] l Ta;
T * * l T;
Ta _ T r @T;
Ta * * l Ta;
@T @ T l nC;
@T * * r @T;
u ] ] l ua;
u * * l u;
ua _ u r @u;
ua * * l ua;
@u @ u l nC;
@u * * r @u;
U ] ] l Ua;
U * * l U;
Ua _ U r @U;
Ua * * l Ua;
@U @ U l nC;
@U * * r @U;
v ] ] l va;
v * * l v;
va _ v r @v;
va * * l va;
@v @ v l nC;
@v * * r @v;
V ] ] l Va;
V * * l V;
Va _ V r @V;
Va * * l Va;
@V @ V l nC;
@V * * r @V;
w ] ] l wa;
w * * l w;
wa _ w r @w;
wa * * l wa;
@w @ w l nC;
@w * * r @w;
W ] ] l Wa;
W * * l W;
Wa _ W r @W;
Wa * * l Wa;
@W @ W l nC;
@W * * r @W;
x ] ] l xa;
x * * l x;
xa _ x r @x;
xa * * l xa;
@x @ x l nC;
@x * * r @x;
X ] ] l Xa;
X * * l X;
Xa _ X r @X;
Xa * * l Xa;
@X @ X l nC;
@X * * r @X;
y ] ] l ya;
y * * l y;
ya _ y r @y;
ya * * l ya;
@y @ y l nC;
@y * * r @y;
Y ] ] l Ya;
Y * * l Y;
Ya _ Y r @Y;
Ya * * l Ya;
@Y @ Y l nC;
@Y * * r @Y;
z ] ] l za;
z * * l z;
za _ z r @z;
za * * l za;
@z @ z l nC;
@z * * r @z;
Z ] ] l Za;
Z * * l Z;
Za _ Z r @Z;
Za * * l Za;
@Z @ Z l nC;
@Z * * r @Z;
Sp ] ] l Sp1;
Sp * * l Sp;
Sp1 _ ~ r @Sp;
Sp1 * * l Sp1;
@Sp @ _ l nC;
@Sp * * r @Sp;
nC _ @ l Sp;
nC 0 0 * 9;
nC 1 1 * 9;
nC 2 2 * 9;
nC 3 3 * 9;
nC 4 4 * 9;
nC 5 5 * 9;
nC 6 6 * 9;
nC 7 7 * 9;
nC 8 8 * 9;
nC 9 9 * 9;
nC - - * 9;
nC a a * 9;
nC A A * 9;
nC b b * 9;
nC B B * 9;
nC c c * 9;
nC C C * 9;
nC d d * 9;
nC D D * 9;
nC e e * 9;
nC E E * 9;
nC f f * 9;
nC F F * 9;
nC g g * 9;
nC G G * 9;
nC h h * 9;
nC H H * 9;
nC i i * 9;
nC I I * 9;
nC j j * 9;
nC J J * 9;
nC k k * 9;
nC K K * 9;
nC l l * 9;
nC L L * 9;
nC m m * 9;
nC M M * 9;
nC n n * 9;
nC N N * 9;
nC o o * 9;
nC O O * 9;
nC p p * 9;
nC P P * 9;
nC q q * 9;
nC Q Q * 9;
nC r r * 9;
nC R R * 9;
nC s s * 9;
nC S S * 9;
nC t t * 9;
nC T T * 9;
nC u u * 9;
nC U U * 9;
nC v v * 9;
nC V V * 9;
nC w w * 9;
nC W W * 9;
nC x x * 9;
nC X X * 9;
nC y y * 9;
nC Y Y * 9;
nC z z * 9;
nC Z Z * 9;
nC ( ( * fC;
fC ] ] l fC1;
fC * * l fC;
fC1 _ [ * cl;
fC1 * * l fC1;
cl [ _ r cl;
cl ] _ r cl;
cl ~ _ r cl;
cl ( _ r clO;
clO ) _ * halt-accept;
clO * _ r clO;
cl ) ) * halt-accept;
cl * * r cl;
;lc r * * lc
;tpecca-tlah * ) ) lc
;Olc r _ * Olc
;tpecca-tlah * _ ) Olc
;Olc r _ ( lc
;lc r _ ~ lc
;lc r _ ] lc
;lc r _ [ lc
;1Cf l * * 1Cf
;lc * [ _ 1Cf
;Cf l * * Cf
;1Cf l ] ] Cf
;Cf * ) ) Cn
;9 * Z Z Cn
;9 * z z Cn
;9 * Y Y Cn
;9 * y y Cn
;9 * X X Cn
;9 * x x Cn
;9 * W W Cn
;9 * w w Cn
;9 * V V Cn
;9 * v v Cn
;9 * U U Cn
;9 * u u Cn
;9 * T T Cn
;9 * t t Cn
;9 * S S Cn
;9 * s s Cn
;9 * R R Cn
;9 * r r Cn
;9 * Q Q Cn
;9 * q q Cn
;9 * P P Cn
;9 * p p Cn
;9 * O O Cn
;9 * o o Cn
;9 * N N Cn
;9 * n n Cn
;9 * M M Cn
;9 * m m Cn
;9 * L L Cn
;9 * l l Cn
;9 * K K Cn
;9 * k k Cn
;9 * J J Cn
;9 * j j Cn
;9 * I I Cn
;9 * i i Cn
;9 * H H Cn
;9 * h h Cn
;9 * G G Cn
;9 * g g Cn
;9 * F F Cn
;9 * f f Cn
;9 * E E Cn
;9 * e e Cn
;9 * D D Cn
;9 * d d Cn
;9 * C C Cn
;9 * c c Cn
;9 * B B Cn
;9 * b b Cn
;9 * A A Cn
;9 * a a Cn
;9 * - - Cn
;9 * 9 9 Cn
;9 * 8 8 Cn
;9 * 7 7 Cn
;9 * 6 6 Cn
;9 * 5 5 Cn
;9 * 4 4 Cn
;9 * 3 3 Cn
;9 * 2 2 Cn
;9 * 1 1 Cn
;9 * 0 0 Cn
;pS l @ _ Cn
;pS@ r * * pS@
;Cn r _ @ pS@
;1pS l * * 1pS
;pS@ r ~ _ 1pS
;pS l * * pS
;1pS l ] ] pS
;Z@ r * * Z@
;Cn r Z @ Z@
;aZ l * * aZ
;Z@ r Z _ aZ
;Z l * * Z
;aZ l ] ] Z
;z@ r * * z@
;Cn r z @ z@
;az l * * az
;z@ r z _ az
;z l * * z
;az l ] ] z
;Y@ r * * Y@
;Cn r Y @ Y@
;aY l * * aY
;Y@ r Y _ aY
;Y l * * Y
;aY l ] ] Y
;y@ r * * y@
;Cn r y @ y@
;ay l * * ay
;y@ r y _ ay
;y l * * y
;ay l ] ] y
;X@ r * * X@
;Cn r X @ X@
;aX l * * aX
;X@ r X _ aX
;X l * * X
;aX l ] ] X
;x@ r * * x@
;Cn r x @ x@
;ax l * * ax
;x@ r x _ ax
;x l * * x
;ax l ] ] x
;W@ r * * W@
;Cn r W @ W@
;aW l * * aW
;W@ r W _ aW
;W l * * W
;aW l ] ] W
;w@ r * * w@
;Cn r w @ w@
;aw l * * aw
;w@ r w _ aw
;w l * * w
;aw l ] ] w
;V@ r * * V@
;Cn r V @ V@
;aV l * * aV
;V@ r V _ aV
;V l * * V
;aV l ] ] V
;v@ r * * v@
;Cn r v @ v@
;av l * * av
;v@ r v _ av
;v l * * v
;av l ] ] v
;U@ r * * U@
;Cn r U @ U@
;aU l * * aU
;U@ r U _ aU
;U l * * U
;aU l ] ] U
;u@ r * * u@
;Cn r u @ u@
;au l * * au
;u@ r u _ au
;u l * * u
;au l ] ] u
;T@ r * * T@
;Cn r T @ T@
;aT l * * aT
;T@ r T _ aT
;T l * * T
;aT l ] ] T
;t@ r * * t@
;Cn r t @ t@
;at l * * at
;t@ r t _ at
;t l * * t
;at l ] ] t
;S@ r * * S@
;Cn r S @ S@
;aS l * * aS
;S@ r S _ aS
;S l * * S
;aS l ] ] S
;s@ r * * s@
;Cn r s @ s@
;as l * * as
;s@ r s _ as
;s l * * s
;as l ] ] s
;R@ r * * R@
;Cn r R @ R@
;aR l * * aR
;R@ r R _ aR
;R l * * R
;aR l ] ] R
;r@ r * * r@
;Cn r r @ r@
;ar l * * ar
;r@ r r _ ar
;r l * * r
;ar l ] ] r
;Q@ r * * Q@
;Cn r Q @ Q@
;aQ l * * aQ
;Q@ r Q _ aQ
;Q l * * Q
;aQ l ] ] Q
;q@ r * * q@
;Cn r q @ q@
;aq l * * aq
;q@ r q _ aq
;q l * * q
;aq l ] ] q
;P@ r * * P@
;Cn r P @ P@
;aP l * * aP
;P@ r P _ aP
;P l * * P
;aP l ] ] P
;p@ r * * p@
;Cn r p @ p@
;ap l * * ap
;p@ r p _ ap
;p l * * p
;ap l ] ] p
;O@ r * * O@
;Cn r O @ O@
;aO l * * aO
;O@ r O _ aO
;O l * * O
;aO l ] ] O
;o@ r * * o@
;Cn r o @ o@
;ao l * * ao
;o@ r o _ ao
;o l * * o
;ao l ] ] o
;N@ r * * N@
;Cn r N @ N@
;aN l * * aN
;N@ r N _ aN
;N l * * N
;aN l ] ] N
;n@ r * * n@
;Cn r n @ n@
;an l * * an
;n@ r n _ an
;n l * * n
;an l ] ] n
;M@ r * * M@
;Cn r M @ M@
;aM l * * aM
;M@ r M _ aM
;M l * * M
;aM l ] ] M
;m@ r * * m@
;Cn r m @ m@
;am l * * am
;m@ r m _ am
;m l * * m
;am l ] ] m
;L@ r * * L@
;Cn r L @ L@
;aL l * * aL
;L@ r L _ aL
;L l * * L
;aL l ] ] L
;l@ r * * l@
;Cn r l @ l@
;al l * * al
;l@ r l _ al
;l l * * l
;al l ] ] l
;K@ r * * K@
;Cn r K @ K@
;aK l * * aK
;K@ r K _ aK
;K l * * K
;aK l ] ] K
;k@ r * * k@
;Cn r k @ k@
;ak l * * ak
;k@ r k _ ak
;k l * * k
;ak l ] ] k
;J@ r * * J@
;Cn r J @ J@
;aJ l * * aJ
;J@ r J _ aJ
;J l * * J
;aJ l ] ] J
;j@ r * * j@
;Cn r j @ j@
;aj l * * aj
;j@ r j _ aj
;j l * * j
;aj l ] ] j
;I@ r * * I@
;Cn r I @ I@
;aI l * * aI
;I@ r I _ aI
;I l * * I
;aI l ] ] I
;i@ r * * i@
;Cn r i @ i@
;ai l * * ai
;i@ r i _ ai
;i l * * i
;ai l ] ] i
;H@ r * * H@
;Cn r H @ H@
;aH l * * aH
;H@ r H _ aH
;H l * * H
;aH l ] ] H
;h@ r * * h@
;Cn r h @ h@
;ah l * * ah
;h@ r h _ ah
;h l * * h
;ah l ] ] h
;G@ r * * G@
;Cn r G @ G@
;aG l * * aG
;G@ r G _ aG
;G l * * G
;aG l ] ] G
;g@ r * * g@
;Cn r g @ g@
;ag l * * ag
;g@ r g _ ag
;g l * * g
;ag l ] ] g
;F@ r * * F@
;Cn r F @ F@
;aF l * * aF
;F@ r F _ aF
;F l * * F
;aF l ] ] F
;f@ r * * f@
;Cn r f @ f@
;af l * * af
;f@ r f _ af
;f l * * f
;af l ] ] f
;E@ r * * E@
;Cn r E @ E@
;aE l * * aE
;E@ r E _ aE
;E l * * E
;aE l ] ] E
;e@ r * * e@
;Cn r e @ e@
;ae l * * ae
;e@ r e _ ae
;e l * * e
;ae l ] ] e
;D@ r * * D@
;Cn r D @ D@
;aD l * * aD
;D@ r D _ aD
;D l * * D
;aD l ] ] D
;d@ r * * d@
;Cn r d @ d@
;ad l * * ad
;d@ r d _ ad
;d l * * d
;ad l ] ] d
;C@ r * * C@
;Cn r C @ C@
;aC l * * aC
;C@ r C _ aC
;C l * * C
;aC l ] ] C
;c@ r * * c@
;Cn r c @ c@
;ac l * * ac
;c@ r c _ ac
;c l * * c
;ac l ] ] c
;B@ r * * B@
;Cn r B @ B@
;aB l * * aB
;B@ r B _ aB
;B l * * B
;aB l ] ] B
;b@ r * * b@
;Cn r b @ b@
;ab l * * ab
;b@ r b _ ab
;b l * * b
;ab l ] ] b
;A@ r * * A@
;Cn r A @ A@
;aA l * * aA
;A@ r A _ aA
;A l * * A
;aA l ] ] A
;a@ r * * a@
;Cn r a @ a@
;aa l * * aa
;a@ r a _ aa
;a l * * a
;aa l ] ] a
;9@ r * * 9@
;Cn r 9 @ 9@
;a9c l * * a9c
;9@ r 9 _ a9c
;9c l * * 9c
;a9c l ] ] 9c
;8@ r * * 8@
;Cn r 8 @ 8@
;a8c l * * a8c
;8@ r 8 _ a8c
;8c l * * 8c
;a8c l ] ] 8c
;7@ r * * 7@
;Cn r 7 @ 7@
;a7c l * * a7c
;7@ r 7 _ a7c
;7c l * * 7c
;a7c l ] ] 7c
;6@ r * * 6@
;Cn r 6 @ 6@
;a6c l * * a6c
;6@ r 6 _ a6c
;6c l * * 6c
;a6c l ] ] 6c
;5@ r * * 5@
;Cn r 5 @ 5@
;a5c l * * a5c
;5@ r 5 _ a5c
;5c l * * 5c
;a5c l ] ] 5c
;4@ r * * 4@
;Cn r 4 @ 4@
;a4c l * * a4c
;4@ r 4 _ a4c
;4c l * * 4c
;a4c l ] ] 4c
;3@ r * * 3@
;Cn r 3 @ 3@
;a3c l * * a3c
;3@ r 3 _ a3c
;3c l * * 3c
;a3c l ] ] 3c
;2@ r * * 2@
;Cn r 2 @ 2@
;a2c l * * a2c
;2@ r 2 _ a2c
;2c l * * 2c
;a2c l ] ] 2c
;1@ r * * 1@
;Cn r 1 @ 1@
;a1c l * * a1c
;1@ r 1 _ a1c
;1c l * * 1c
;a1c l ] ] 1c
;0@ r * * 0@
;Cn r 0 @ 0@
;a0c l * * a0c
;0@ r 0 _ a0c
;0c l * * 0c
;a0c l ] ] 0c
;Z l @ Z 9
;z l @ z 9
;Y l @ Y 9
;y l @ y 9
;X l @ X 9
;x l @ x 9
;W l @ W 9
;w l @ w 9
;V l @ V 9
;v l @ v 9
;U l @ U 9
;u l @ u 9
;T l @ T 9
;t l @ t 9
;S l @ S 9
;s l @ s 9
;R l @ R 9
;r l @ r 9
;Q l @ Q 9
;q l @ q 9
;P l @ P 9
;p l @ p 9
;O l @ O 9
;o l @ o 9
;N l @ N 9
;n l @ n 9
;M l @ M 9
;m l @ m 9
;L l @ L 9
;l l @ l 9
;K l @ K 9
;k l @ k 9
;J l @ J 9
;j l @ j 9
;I l @ I 9
;i l @ i 9
;H l @ H 9
;h l @ h 9
;G l @ G 9
;g l @ g 9
;F l @ F 9
;f l @ f 9
;E l @ E 9
;e l @ e 9
;D l @ D 9
;d l @ d 9
;C l @ C 9
;c l @ c 9
;B l @ B 9
;b l @ b 9
;A l @ A 9
;a l @ a 9
;9c l @ 9 9
;8c l @ 8 9
;7c l @ 7 9
;6c l @ 6 9
;5c l @ 5 9
;4c l @ 4 9
;3c l @ 3 9
;2c l @ 2 9
;1c l @ 1 9
;0c l @ 0 9
;8 r * * 8
;9 r ( ( 8
;8 r ] _ 7
;7 l _ _ 6
;5 l * * 5
;0 * ( ( 5
;3 r * * 3
;5 l ) _ )3
;3 r * * 4
;)3 l _ _ 4
;4 r _ _ 3
;3 r ( _ 2
;2 l _ _ 1
;2 l * * 0
;6 l ( ( 0
```
[Try it online!](http://morphett.info/turing/turing.html?67f42ba8015588ecb3e12e29615173be)
[Try it reversed!](http://morphett.info/turing/turing.html?4fc5af29f3c957f9fce02b43d49e192b)
I used [this site](http://www.textreverse.com/) to reverse it.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 2 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
RI
```
[Try it online](https://tio.run/##yy9OTMpM/f8/yPP//8Sk5JRUAA) or [try it online reversed](https://tio.run/##yy9OTMpM/f/fM@j//8Sk5JRUAA).
**Explanation:**
```
R # Reverse the (implicit) input
I # Push the input
# (output the top of the stack implicitly as result)
I # Push the input
R # Reverse it
# (output the top of the stack implicitly as result)
```
[Answer]
# [J](http://jsoftware.com/), 7 bytes
```
,&.|:@]
```
Reversed:
```
]@:|.&,
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/ddT0aqwcYv9rcoEVxPo56Tn56dVwpYN4NXpgbixXanJGvkKaenF@bqpCcUlRZl66OkQsHVUMYgjUTIgZsQ5WNXpqOsQa8R8A "J – Try It Online")
[Jonah's comment on Adam's APL answer](https://codegolf.stackexchange.com/questions/193315/i-reverse-the-source-code-you-reverse-the-input#comment460515_193316) made me take the challenge. It was pretty hard indeed, because the inflections `.` and `:` always attach to the symbol on their left, and a sole `|` (abstract value) isn't happy with strings.
### How these work
Basically, it is a random mix of no-ops connected through various connectors.
```
,&.|:@]
@] Pass the argument unchanged
&.|: Apply inverse of |: (transpose), no-op on single string
, Ravel, no-op on a single string
&.|: Apply |: again, still no-op
]@:|.&,
&, Ravel, no-op
@:|. Reverse
] Pass the argument unchanged
```
This answer is one byte shorter than the trivial comment-abuse:
# [J](http://jsoftware.com/), 8 bytes
```
]NB.BN.|
```
Reversed:
```
|.NB.BN]
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/Y/2c9Jz89Gr@a3KBVcD4XOkgXo0emBvLlZqcka@Qpl6cn5uqUFxSlJmXrg4RS0cVgxiio6ZXY@UQCzEj1sGqRk9Nh1gj/gMA "J – Try It Online")
In J, the in-line comment marker is `NB.`, which is longer than every other language I know of.
[Answer]
# [Python 3](https://docs.python.org/3/), 27 bytes
```
lambda s:s#]1-::[s:s adbmal
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqlg51lDXyioayFJITEnKTcz5X1CUmVeikaahHpKRWawARLmVCpl5BaUliuqamv8B "Python 3 – Try It Online")
[!enilno ti yrT](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUaHYqjjaykrXMFYZyFJITEnKTcz5X1CUmVeikaahHpKRWawARLmVCpl5BaUliuqamv8B "Python 3 – Try It Online")
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 2 bytes
```
S←
```
[Try it online!](https://tio.run/##S85ILErOT8z5///9ns2P2ib8/19RWQUA "Charcoal – Try It Online") Explanation: `S` implicitly prints the explicit input and `←` moves the cursor left (no effect on the final output). Reversed:
```
←S
```
[Try it online!](https://tio.run/##S85ILErOT8z5//9R24T3ezb//19RWQUA "Charcoal – Try It Online") `←` changes the direction of the implicit print of the explicit input `S` thus reversing the output.
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), 2 bytes
```
pv
```
[Try it online!](https://tio.run/##S0/MTPz/v6Ds///EpGQA "Gaia – Try It Online")
[Try it reversed!](https://tio.run/##S0/MTPz/v6zg///EpGQA)
Very similar solution to other golfing languages.
### Explanation
```
p Print the (implicitly grabbed) input
v Reverse the input
```
### Reverse
```
v Reverse the (implicitly grabbed) input
p Print the result
```
[Answer]
# [J](https://www.jsoftware.com) 9, 4 bytes
```
][.|
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m70wa8FOJT0F9TQFWysFdR0FAwUrINbVU3AO8nFbWlqSpmuxJDZarwbCvGmlycWVmpyRr5CmoJ6YlKwO56hzpYNMqNGLjoWIpSMrAHLUISYsWAChAQ)
See [this answer](https://codegolf.stackexchange.com/a/194789/78410) for the 7-byter that works in previous versions.
J 9 (re-)introduces modifier trains and adds some adverb and conjunction equivalents of identity functions (`]` and `[`):
```
]: Ident (adverb) / u]: evaluates to u
]. Dex (conjunction) / u].v evaluates to v
[. Lev (conjunction) / u[.v evaluates to u
```
The above code parses as
```
] [. | left operand ([.) out of identity(]) and absolute value(|),
which is identity
```
while the reverse `|.[]` parses as a 3-train:
```
|. [ ] left argument ([) out of the results of reverse (|.) and identity (])
which is reverse
```
[Answer]
# [Cubix](https://github.com/ETHproductions/cubix), 19 bytes
```
.@o?A^;/|?$oqBA.UW.
```
[Try it online!](https://tio.run/##Sy5Nyqz4/1/PId/eMc5av8ZeJb/QyVEvNFzv/39HJ2cXVzd3AA "Cubix – Try It Online")
Cubified
```
. @
o ?
A ^ ; / | ? $ o
q B A . U W . .
. .
. .
```
* `A^` get all the input and enter the loop
* `o?` output the TOS of stack and test
* `@` exit if it tests to negative
* `/;^` reflect back, pop TOS and re-enter loop
All other commands are avoided.
**Reversed**
```
.WU.ABqo$?|/;^A?o@.
```
[Try it online!](https://tio.run/##Sy5Nyqz4/18vPFTP0akwX8W@Rt86ztE@30Hv/39HJ2cXVzd3AA "Cubix – Try It Online")
Cubified
```
. W
U .
A B q o $ ? | /
; ^ A ? o @ . .
. .
. .
```
* `ABq` Get all input, reverse and drop TOS to bottom of stack
* `o$?|?` output TOS, skip the test and relect back onto test
* `@` halt if test if negative
* `WUq` change lane, u-turn onto drop TOS start of loop
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 4 bytes
```
aVRa
```
[Try it online!](https://tio.run/##K8gs@P8/MSwo8T@QSkpOAQA "Pip – Try It Online") [!enilno ti yrT](https://tio.run/##K8gs@P8/MSgs8T@QSkpOAQA)
Makes use of the fact that `RV` is the reverse operator but `VR` is an undefined variable. Both versions print the value of their last expression; in the standard version, that's `a` (with the first `a` and the `VR` being no-ops), while in the reversed version, that's `RVa` (with the first `a` being a no-op).
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 16 bytes
```
1&esreveR//#& &1
```
[Try it online!](https://tio.run/##Xc29CsIwFEDhPU9xSSAoVEoXwUHpAziIa8gQ0lu90CQluRV/8NkjLg4uZ/xOcHzF4Ji8q@O@dhpLxhue21Zp0F09ZYps1OYw9srqtn8JeX88ZSPkbvvtMWUMQHNZAgxpShkKMbiA3IBPsaBn5CWDG2im4ileACdiKd7iRytjrTar//da2/oB "Wolfram Language (Mathematica) – Try It Online")
**Reversed**:
```
1& &#//Reverse&1
```
[Try it online!](https://tio.run/##XY69CsIwFEb3PMUlgdBCpXQRBC0FVwdxLRlCmtoLTVOSW/EHnz3WxcHlWw6H8zlNg3Wa0OjUH1IlQYqyvNibDdHKKp0DTtSKTZ1xvq/75jjooA2ttBG5kmXzYvz@ePKC8d32uycfrAOc4@Kg86MPEJFAO0sFGD9Fu8q0BNAdzhgNTlewIxJnb/ZriVYp2Wb/Z3Kp0gc "Wolfram Language (Mathematica) – Try It Online")
Takes a list of characters as input. For string input, use `StringReverse`.
[Answer]
# [Perl 5](//perldoc.perl.org) `-p`, 11 bytes
The obvious.
```
#esrever=_$
```
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 4 bytes
```
"\"@
```
Try it online: [Forwards](https://tio.run/##Kygtzqj8/18pRsnhP5DKSM3JyVcCAA "Pushy – Try It Online"), [Backwards](https://tio.run/##Kygtzqj8/99BKUbp////ShmpOTn5SgA "Pushy – Try It Online")
Simple implementation with the comment character `\`. In the forwards program, `"` prints the input and the rest is a comment; in the backwards program, `@` reverses the input before printing.
We could alternatively replace `\` with `c`, which would clear the input from the stack.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
Uṛ
```
[Try it online!](https://tio.run/##y0rNyan8/z/04c7Z////V3LOT0lVSM/PSVMCAA "Jelly – Try It Online")
[Reversed!](https://tio.run/##y0rNyan8///hztmh////V3LOT0lVSM/PSVMCAA "Jelly – Try It Online")
## Explanation
```
U | Reverse
ṛ | Right argument (when used in a monadic chain like this, will return the original argument to the chain)
```
## Explanation (reversed)
```
ṛ | Right argument (when used in a monadic chain and followed by a monadic link, will return the output of that monadic link)
U | Reverse
```
[Seven other two-byters `Ṛṛ ḷU ḷṚ Uȧ Ṛȧ ȯU ȯṚ`](https://tio.run/##y0rNyan8//9Rw5yHO2c/3LH9xPIT6x81zNV5tHHdo6Y1jxr3hT7cOevhrj7vhztbgCqObTq6J1QFKBN6eEI@UFhBp@zQUpBCkNod3hBWJBBnAbUe2nZo2////5Wc81NSFdLzc9KUAA "Jelly – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÔU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=1FU&input=InJldmVyc2Ui) | [Reversed](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VdQ&input=InJldmVyc2Ui)
[Answer]
## [MathGolf](https://github.com/maxbergmark/mathgolf), 3 bytes
```
x;l
```
## Explanation:
```
x Reverse the implicit input
; Discard the string
l Push a string input
Implicit output TOS
```
Reversed:
```
l Push a string input
; Discard it
x Reverse the implicit input
Implicit output TOS
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 56 bytes
Nothing fancy. Would have used `puts()` but then trailing whitespace would not have been consistent between the two variants.
```
f(int*s){printf(s);}//};))1+s(f,s*(rahctup&&s*{)s*rahc(f
```
[Try it online!](https://tio.run/##FcoxDoAgDEDRWU5hHEhbNcSZ02BN1UFCrE6EsyNu/yWf5525VoEzPqSY091CQNEX54pHXEYFmZTgDgc/b7JWKaPST5Da7v4KZwQ02XQCQ1h5G9CbUj8 "C (gcc) – Try It Online")
```
f(char*s){*s&&putchar(*s,f(s+1));}//};)s(ftnirp{)s*tni(f
```
[Reversed!](https://tio.run/##FccxDoAgDADAWV5hGEiLGuLMa7CmyiAhFifC21G3O1oOot4Z6Ay3FaxWjMlP@QtWZgaZVkTfnGseBbikeOeKYj8A95jKeIWYAFVVA4MOG@0avWr9BQ "C (gcc) – Try It Online")
[Answer]
## [W](https://github.com/A-ee/w), 2 bytes
Pretty much the same as the 05AB1E solution.
```
a_
```
## Explanation
```
a % Push the input
_ % Reverse the input
% Implicit print the top of the stack
```
## noitanalpxE
```
_ % Reverse the implicit input
a % Push the input
% Implicit print the top of the stack
```
[Answer]
# [BRASCA (brasca-online)](https://sjoerdpennings.github.io/brasca-online/), 5 bytes
The broken loops crash the Python-based interpreter, but it works on [brasca-online](https://sjoerdpennings.github.io/brasca-online/).
```
,[o],
```
```
,]o[,
```
[Try it!](https://sjoerdpennings.github.io/brasca-online/?code=%2C%5Bo%5D%2C&stdin=123123) | [!ti yrT](https://sjoerdpennings.github.io/brasca-online/?code=%2C%5Do%5B%2C&stdin=123123)
## Explanation
```
, - Reverses stack (1,2,3 => 3,2,1)
[o] - Output stack one by one (3,2,1 => empty)
, - Reverse it again (empty => empty)
```
Reversed:
```
, - Reverses stack (1,2,3 => 3,2,1)
]o[ - Broken loops, output top of stack (3,2,1 => 3,2 )
, - Reverses it again (3,2 => 2,3 )
- Implicit output the stack reversed (2,3 => empty)
```
[Answer]
# [Factor](https://factorcode.org/), 17 bytes
```
[ ] ! ] esrever [
```
[Try it online!](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjUFCUWlJSWVCUmVeiUJxaWJqal5xarGDNpZSWn5@UWKT0P1ohVkERiFOLi1LLUosUov8nJ@bkKOj9BwA "Factor – Try It Online")
[!enilno ti yrT](https://tio.run/##S0tMLskv@h8a7OnnbqWQnVqUl5qjUFCUWlJSWVCUmVeiUJxaWJqal5xarGDNpZSWn5@UWKT0P1qhKLUstag4VSFWQRGIo/8nJ@bkKOj9BwA "Factor – Try It Online")
Fixed thanks to Bubbler
[Answer]
# [Stack Exchange](https://github.com/ysthakur/StackExchange), 2 bytes
```
EP
```
Reversed:
```
PE
```
Sadly, there is no online interpreter, especially since this language is still a work in progress (although `P` and `E` are two of the commands I've finalized).
Stack Exchange is a language that resolves around stacks. It is a stack-based language where the only data structure is a stack. A string is represented as a stack of characters, and a character is represented by a stack of empty stacks where the length represents a codepoint.
The `E` command encloses all elements of the main stack in a stack and pushes that stack onto the main stack. The `P` dumps all elements of the top stack onto the main stack in reverse. `P` does this in reverse because it's easier to make it stack-safe that way, but I didn't realize until now that it's perfect for this challenge. Whereas `PE` dumps the input onto the stack in reverse and bundles it back up in a stack so it can be returned, `EP` encloses the input in a singleton stack and then unwraps it again, making no change.
As an example, running `EP` on the input `{ {{}{}{}} {} {{}{}} {{}} {} }` returns the same stack back, whereas running `PE` returns `{ { {} {{}} {{}{}} {} {{}{}{}} } }`. `{ {{}{}{}} {} {{}{}} {{}} {} }` represents the string made of the characters `\u0003`, `\u0000`, `\u0002`, `\u0001`, and `\u0000`.
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 13 bytes
```
#><}><)><}{({
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/X9nOptbORhNIVmtU///vll9UnliU8l83GQA "Brain-Flak – Try It Online")
Forward: Just a comment, so that it just outputs the input
Reversed:
```
{({}<>)<>}<>#
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1qjutbGTtPGDkgq//8flFqWWlScmvJfNxkA "Brain-Flak – Try It Online")
Move everything to the second stack, so it is reversed.
[Answer]
# [CJam](https://sourceforge.net/p/cjam), 7 bytes
```
qe#e%Wq
```
Boring version with comments. If CJam would fail silently i could have saved like 3 bytes in 2 questions already!
* [Try it online!](https://tio.run/##S85KzP3/vzBVOVU1vBDICFcFMgsB "CJam – Try It Online")
* [Try it reversed!](https://tio.run/##S85KzP3/vzBcNVU5tRDOAAA "CJam – Try It Online")
] |
[Question]
[
## Implement a simple integer operation scriptable calculator.
**Concept**
The accumulator starts at 0 and has operations performed on it. At the end of the program output the value of the accumulator.
**Operations:**
* `+` adds `1` to the accumulator
* `-` subtracts `1` from the accumulator
* `*` multiplies the accumulator by `2`
* `/` divides the accumulator by `2`
**Sample script**
The input `++**--/` should give the output `3`.
**Example implementation**
```
def calc(s)
i = 0
s.chars.each do |o|
case o
when '+'
i += 1
when '-'
i -= 1
when '*'
i *= 2
when '/'
i /= 2
end
end
return i
end
```
## Rules
* This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so lowest answer in bytes wins, but is not selected.
* Creative implementations are encouraged.
* Standard loopholes are prohibited.
* You get the program via stdin or arguments, and you can output the answer via return value or stdout.
* Have fun.
* Division truncates down because it is integer division.
* The program `-/` returns `-1`.
**Test cases**
```
*///*-*+-+
-1
/*+/*+++/*///*/+-+//*+-+-/----*-*-+++*+**+/*--///+*-/+//*//-+++--++/-**--/+--/*-/+*//*+-*-*/*+*+/+*-
-17
+++-+--/-*/---++/-+*-//+/++-*--+*+/*/*/++--++-+//++--*/***-*+++--+-*//-*/+*/+-*++**+--*/*//-*--**-/-*+**-/*-**/*+*-*/--+/+/+//-+*/---///+**////-*//+-+-/+--/**///*+//+++/+*++**++//**+**+-*/+/*/*++-/+**+--+*++++/-*-/*+--/++*/-++/-**++++/-/+/--*/-/+---**//*///-//*+-*----+//--/-/+*/-+++-+*-*+*+-/-//*-//+/*-+//+/+/*-/-/+//+**/-****/-**-//+/+-+/*-+*++*/-/++*/-//*--+*--/-+-+/+/**/-***+/-/++-++*+*-+*+*-+-//+/-++*+/*//*-+/+*/-+/-/*/-/-+*+**/*//*+/+---+*+++*+/+-**/-+-/+*---/-*+/-++*//*/-+-*+--**/-////*/--/*--//-**/*++*+/*+/-+/--**/*-+*+/+-*+*+--*///+-++/+//+*/-+/**--//*/+++/*+*////+-*-//--*+/*/-+**/*//+*+-//+--+*-+/-**-*/+//*+---*+//*/+**/*--/--+/*-*+*++--*+//+*+-++--+-*-*-+--**+/+*-/+*+-/---+-*+-+-/++/+*///*/*-+-*//-+-++/++/*/-++/**--+-////-//+/*//+**/*+-+/+/+///*+*///*-/+/*/-//-*-**//-/-+--+/-*--+-++**++//*--/*++--*-/-///-+/+//--+*//-**-/*-*/+*/-*-*//--++*//-*/++//+/-++-+-*/*-+++**-/-*++++**+-+++-+-***-+//+-/**-+/*+****-*+++*/-*-/***/-/*+/*****++*+/-/-**-+-*-*-++**/*+-/*-+*++-/+/-++*-/*-****-*
18773342
```
[Answer]
## Python 2, 48 bytes
```
i=0
for c in input():exec"i=i%s2&-2"%c
print i/2
```
Does `+2`, `-2`, `*2`, or `/2`. By doing `+2` and `-2` rather than `+1` and `-1`, we're working in doubled units, so the final output needs to be halved. Except, the floor-division `/` now needs to round down to a multiple of 2, which is done with `&-2`.
[Answer]
## Haskell, 51 bytes
```
x#'+'=x+1
x#'-'=x-1
x#'*'=x*2
x#_=div x 2
foldl(#)0
```
Usage example: `foldl(#)0 $ "++**--/"` -> `3`.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~18~~ 17 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
‘
’
:2
Ḥ
O0;ṛĿ/
```
[Try it online!](http://jelly.tryitonline.net/#code=4oCYCgrigJkKCjoyCuG4pApPMDvhuZvEvy8&input=&args=KysqKi0tLw)
### How it works
The first six lines define helper links with indices ranging from **1** to **6**; they increment, do nothing, decrement, do nothing, halve (flooring), and double.
The main link – `O0;ṛĿ/` – converts the input characters to their code points (`O`), prepends a **0** (initial value) to the array of code points `0;`, then reduces the generated array as follows.
The initial value is the first element of the array, i.e., the prepended **0**. The quicklink `ṛĿ` is called for every following element in the array, with the last return value as left argument and the current element as right one. It inspects its right argument (`ṛ`) and evaluates the link with that index monadically (`Ŀ`), thus applying the desired operation.
[Answer]
# Python 2, 54 bytes
```
i=0
for c in input():exec"i=i"+c+`~ord(c)%5%3`
print i
```
Input is taken as a string literal. `~ord(c)%5%3` maps the operators to the corresponding right operands.
Previously, I used `hash(c)%55%3` which didn't yield consistent results between different versions of Python. This encouraged me to explore other formulas.
[Answer]
# [S.I.L.O.S](https://github.com/rjhunjhunwala/S.I.L.O.S), ~~133~~ 211 bytes
```
:s
def : lbl G GOTO
readIO
i-46
if i a
i+2
if i b
i+2
if i c
i+1
if i d
G e
:a
G v
:p
a-1
a/2
G o
:v
a+1
if a p
a-1
j=a
j/2
k=j
k*2
k-a
a/2
if k t
G o
:t
a-1
:o
G s
:b
a-1
G s
:c
a+1
G s
:d
a*2
G s
:e
printInt a
```
Takes the ASCII codes of operators.
Try it online with test cases:
[`-/`](http://silos.tryitonline.net/#code=OnMKZGVmIDogbGJsIEcgR09UTwpyZWFkSU8KaS00NgppZiBpIGEKaSsyCmlmIGkgYgppKzIKaWYgaSBjCmkrMQppZiBpIGQKRyBlCjphCkcgdgo6cAphLTEKYS8yCkcgbwo6dgphKzEKaWYgYSBwCmEtMQpqPWEKai8yCms9agprKjIKay1hCmEvMgppZiBrIHQKRyBvCmxibHQKYS0xCjpvCkcgcwo6YgphLTEKRyBzCjpjCmErMQpHIHMKOmQKYSoyCkcgcwo6ZQpwcmludEludCBh&input=&args=NDU+NDc)
[`++**--/`](http://silos.tryitonline.net/#code=OnMKZGVmIDogbGJsIEcgR09UTwpyZWFkSU8KaS00NgppZiBpIGEKaSsyCmlmIGkgYgppKzIKaWYgaSBjCmkrMQppZiBpIGQKRyBlCjphCkcgdgo6cAphLTEKYS8yCkcgbwo6dgphKzEKaWYgYSBwCmEtMQpqPWEKai8yCms9agprKjIKay1hCmEvMgppZiBrIHQKRyBvCmxibHQKYS0xCjpvCkcgcwo6YgphLTEKRyBzCjpjCmErMQpHIHMKOmQKYSoyCkcgcwo6ZQpwcmludEludCBh&input=&args=NDM+NDM+NDI+NDI+NDU+NDU+NDc)
[`*///*-*+-+`](http://silos.tryitonline.net/#code=OnMKZGVmIDogbGJsIEcgR09UTwpyZWFkSU8KaS00NgppZiBpIGQKaSsyCmlmIGkgYwppKzIKaWYgaSB0CmkrMQppZiBpIG0KRyBlCjpkCmEvMgpHIHMKOmMKYS0xCkcgcwo6dAphKzEKRyBzCjptCmEqMgpHIHMKOmUKcHJpbnRJbnQgYQ&input=&args=NDI+NDc+NDc+NDc+NDI+NDU+NDI+NDM+NDU+NDM)
[Answer]
# Turing Machine - 23 states (684 bytes)
Try it here - [permalink](http://morphett.info/turing/turing.html?a7f0ec58ccc0040e49b75282d8caf030)
```
0 * * r 0
0 _ . l 1
1 * * l 1
1 _ * l 2
2 * 0 r 3
3 _ * r 3
3 + _ l +
3 - _ l -
3 x _ l x
3 / _ l /
+ _ * l +
+ * * * 4
4 - * l 5
4 _ 1 r 6
4 0 1 l 7
4 1 0 l 4
- _ * l -
- * * * 5
5 - * l 4
5 _ * r 8
5 0 1 l 5
5 1 0 l 7
x * * l x
x 1 0 l 9
x 0 0 l a
9 _ 1 r 6
9 1 1 l 9
9 0 1 l a
a _ _ r 6
a 1 0 l 9
a 0 0 l a
/ _ * l /
/ * * l b
b * * l b
b _ * r c
c 0 0 r d
c 1 0 r e
d * * l 7
d 0 0 r d
d 1 0 r e
e _ * l 7
e - * l 4
e 0 1 r d
e 1 1 r e
8 * * r 8
8 - _ r 3
8 _ - r 3
7 * * l 7
7 _ * r f
f 0 _ r f
f 1 * r 6
f * _ l g
g * 0 r 6
6 * * r 6
6 _ * r 3
3 . _ l h
h _ * l h
h - _ l i
h * * l halt
i * * l i
i _ - r halt
```
Input should not contain any '\*' since it is a special character in Turing machine code. Use 'x' instead.
Outputs the answer in binary.
**Unobfuscated Code**
```
init2 * * r init2
init2 _ . l init0
init0 * * l init0
init0 _ * l init1
init1 * 0 r readop
readop _ * r readop
readop + _ l +
readop - _ l -
readop x _ l x
readop / _ l /
+ _ * l +
+ * * * inc
inc - * l dec
inc _ 1 r return
inc 0 1 l zero
inc 1 0 l inc
- _ * l -
- * * * dec
dec - * l inc
dec _ * r neg
dec 0 1 l dec
dec 1 0 l zero
x * * l x
x 1 0 l x1
x 0 0 l x0
x1 _ 1 r return
x1 1 1 l x1
x1 0 1 l x0
x0 _ _ r return
x0 1 0 l x1
x0 0 0 l x0
/ _ * l /
/ * * l //
// * * l //
// _ * r div
div 0 0 r div0
div 1 0 r div1
div0 * * l zero
div0 0 0 r div0
div0 1 0 r div1
div1 _ * l zero
div1 - * l inc
div1 0 1 r div0
div1 1 1 r div1
neg * * r neg
neg - _ r readop
neg _ - r readop
zero * * l zero
zero _ * r zero1
zero1 0 _ r zero1
zero1 1 * r return
zero1 * _ l zero2
zero2 * 0 r return
return * * r return
return _ * r readop
readop . _ l fin
fin _ * l fin
fin - _ l min
fin * * l halt
min * * l min
min _ - r halt
```
**Explanation of the states:**
*Initialization:*
*These states are visited once at the beginning of each run, starting with init2*
* init2: Move all the way to the right and put a '.'. That way the TM knows when to stop. Change to 'init0'.
* init0: Move all the back to the left until the head reads a space. Then move one cell to the left. Change to 'init1'.
* init1: Put a zero and move one cell to the right and change to 'readop'.
*Reading instructions:*
*These states will be visited multiple times throughout the program*
* readop: Moves all the way to the right until it reads an operator or the '.'. If it hits an operator, change to the corresponding state (+,-,x,/). If it hits a '.', change to state 'fin'.
* return: Returns the head to the empty space between the running total and the operators. Then changes to 'readop'.
*Operations:*
*These operations do the actual dirty work*
* +: Move to the left until the head reads any non-
whitespace character. If this character is a '-', move left and change to 'dec'. Otherwise, change to 'inc'.
* -: Similar to '+', except change to 'inc' if there is a '-' and 'dec' otherwise.
* inc: If the digit under the head is a 0 (or a whitespace), change it to 1 and change to 'zero'. If the digit is a 1, change it to 0, then repeat on the next digit.
* dec: Similar to inc, except 1 goes to 0, 0 goes to 1, and if the head reads a whitespace, change to 'neg'.
* x, x0, x1: Bitshift the number one to the left. Change to 'return'.
* /, //, div, div0, div1: Move all the way to the right of the number, then bitshift one to the right. If there is a '-', change to 'inc'. This simulates rounding down negative numbers. Otherwise, change to 'zero'
* neg: Place a '-' after the number then change to 'readop'
* zero, zero1, zero2: Remove leading zeros and change to 'readop'
*Cleanup:*
*Makes the output presentable*
* fin, min: Move the '-' in front of the number if necessary. Halt.
[Answer]
# [Perl 6](http://perl6.org), ~~53~~ 52 bytes
```
{([Ro] %(<+ - * />Z=>*+1,*-1,* *2,*div 2){.comb})(0)}
```
```
{[Ro](%(<+ - * />Z=>*+1,*-1,*×2,*div 2){.comb})(0)}
```
## Explanation:
```
# bare block lambda that has one implicit parameter 「$_」
{
(
# reduce the code refs using ring operator 「∘」 in reverse 「R」
[R[o]]
# produce a hash from:
%(
# list of pairs of "operator" to code ref
# ( similar to 「'+' => { $^a + 1 }」 )
# keys
< + - * / >
# keys and values joined using infix zip operator 「Z」
# combined with the infix Pair constructor operator 「=>」
Z[=>]
# values (Whatever lambdas)
* + 1,
* - 1,
* × 2, # same as 「* * 2」
* div 2,
){
# split the block's argument into chars
# and use them as keys to the hash
# which will result in a list of code refs
.comb
}
# call composed code ref with 0
)(0)
}
```
## Usage:
```
my $input = '++**--/'
my $output = {[Ro](%(<+ - * />Z=>*+1,*-1,*×2,*div 2){.comb})(0)}.( $input );
say $output; # 3
say $output.^name; # Int
```
[Answer]
# C, ~~63~~ ~~62~~ 57 bytes
```
s,t;c(char*x){for(;*x;s+=t<4?t?2-t:s:-s>>1)t=*x++%6;s=s;}
```
[Wandbox](http://melpon.org/wandbox/permlink/w5TOvhR7SKgy2akp)
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 20 bytes
*Thanks to **Emigna** for fixing the `-/`-bug!*
For 16 bytes if it wasn't integer division: `Î"+-*/""><·;"‡.V`.
```
Î…+-*"><·"‡'/"2÷":.V
```
Explanation:
```
Î # Push 0, which is our starting variable, and input
…+-* # Push the string "+-*"
"><·" # Push the string "><·"
‡ # Transliterate. The following changes:
"+" -> ">"
"-" -> "<"
"*" -> "·"
'/"2÷": # Replace "/" by "2÷"
.V # Evaluate the code as 05AB1E code...
'>' is increment by 1
'<' is decrement by 1
'·' is multiply by 2
'2÷' is integer divide by two
# Implicitly output the result
```
Uses the **CP-1252** encoding. [Try it online!](http://05ab1e.tryitonline.net/#code=w47igKYrLSoiPjzCtyLigKEnLyIyw7ciOi5W&input=LS8)
[Answer]
# JavaScript ES6, ~~80~~ 68 bytes
```
k=>[...k].reduce((c,o)=>+{"+":c+1,"-":c-1,"*":c*2,"/":c/2|0}[o],0)
```
Saved a whopping 12 bytes thanks to Neil!
[Answer]
# Ruby, ~~48~~ ~~44~~ 42 + 1 = 43 bytes
+1 byte for `-n` flag. Takes input on STDIN.
```
i=0
gsub(/./){i=i.send$&,"+-"[$&]?1:2}
p i
```
See it on ideone (uses `$_` since ideone doesn't take command line flags): <http://ideone.com/3udQ3H>
[Answer]
# PHP 76 Bytes
```
for(;$c=$argv[1][$n++];)eval('$s=floor($s'.$c.(2-ord($c)%11%3).');');echo$s;
```
[Answer]
# Python 2, ~~58~~ 56 bytes
-2 bytes thanks to @Lynn
```
r=0
for c in input():exec'r=r'+c+`2-ord(c)%11%3`
print r
```
The ordinals of the characters `+-*/` are `43,45,42,47` modulo 11 these are `10,1,9,3` modulo 3 those are `1,1,0,0`, 2 less those are `1,1,2,2` giving the amounts we need for each operation: `r=r+1`, `r=r-1`, `r=r*2`, and `r=r/2`
---
Previous:
```
r=0
for c in input():exec'r=r'+c+`(ord(c)%5==2)+1`
print r
```
[Answer]
# Mathematica, ~~83~~ ~~73~~ 70 bytes
*10 bytes saved due to [@MartinEnder](http://ppcg.lol/users/8478).*
```
(#/*##2&@@#/.Thread[{"+","-","*","/"}->{#+1&,#-1&,2#&,⌊#/2⌋&}])@0&
```
Anonymous function. Takes a list of characters as input and returns a number as output. Golfing suggestions welcome.
[Answer]
# [S.I.L.O.S](http://github.com/rjhunjhunwala/S.I.L.O.S), ~~175~~ 164 bytes
```
loadLine
a=256
o=get a
lbla
a+1
o-42
p=o
p-1
p/p
p-1
r-p
s=o
s-3
s/s
s-1
r+s
m=o
m/m
m-2
m|
r*m
t=r
t%2
d=o
d-5
d/d
d-1
t*d
d-1
d|
r-t
r/d
o=get a
if o a
printInt r
```
[Try it online!](http://silos.tryitonline.net/#code=bG9hZExpbmUKYT0yNTYKbz1nZXQgYQpsYmxhCmErMQpvLTQyCnA9bwpwLTEKcC9wCnAtMQpyLXAKcz1vCnMtMwpzL3MKcy0xCnIrcwptPW8KbS9tCm0tMgptfApyKm0KdD1yCnQlMgpkPW8KZC01CmQvZApkLTEKdCpkCmQtMQpkfApyLXQKci9kCm89Z2V0IGEKaWYgbyBhCnByaW50SW50IHI&input=&args=KysqKi0tLw)
Sane input method. Correct integer division (round towards -infinity).
[Answer]
# C#, ~~87~~ 81 bytes
```
int f(string s){int i=0;foreach(var c in s)i=c<43?i*2:c<46?i+44-c:i>>1;return i;}
```
Ungolfed:
```
int f(string s)
{
int i = 0;
foreach (var c in s)
i = c < 43 ? i * 2
: c < 46 ? i + 44 - c
: i >> 1;
return i;
}
```
Input is assumed to be valid. Division by two is done by shifting right one bit, because regular division always rounds towards zero, and bit shifting always rounds down. Increment and decrement make handy use of the 1 distance between the ASCII codes for `+` and `-`.
[Answer]
## Javascript (ES6), 57 bytes (array) / 60 bytes (integer)
Returning an array of all intermediate results:
```
o=>[...o].map(c=>x=[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],x=0)
```
For instance, the output for `"++**--/"` will be `[1, 2, 4, 8, 7, 6, 3]`.
Returning only the final result:
```
o=>[...o].reduce((x,c)=>[x>>1,x+1,x*2,x-1][eval(2+c+3)&3],0)
```
### How it works
Both solutions are based on the same idea: using the perfect hash function `eval(2+c+3)&3` to map the different operator characters `c` in `[0, 3]`.
```
operator | eval(2+c+3) | eval(2+c+3)&3
----------+--------------+---------------
+ | 2+3 = 5 | 5 & 3 = 1
- | 2-3 = -1 | -1 & 3 = 3
* | 2*3 = 6 | 6 & 3 = 2
/ | 2/3 ~= 0.67 | 0.67 & 3 = 0
```
[Answer]
# JavaScript (ES6), 57
```
a=>[...a].map(c=>a=c<'+'?a<<1:c<'-'?-~a:c<'/'?~-a:a>>1)|a
```
Note: the initial value for accumulator is the program string, using bit operations (~, >>, <<, |) it is converted to 0 at first use.
As a side note, the clever answer of @xnor would score 40 ported to javascript:
```
a=>[...a].map(c=>a=eval(~~a+c+2))&&a>>1
```
(if you like this, vote for him)
**Test**
```
f=a=>[...a].map(c=>a=c<'+'?a<<1:c<'-'?-~a:c<'/'?~-a:a>>1)|a
function update() {
O.textContent = f(I.value);
}
update()
```
```
<input value='++**--/' id=I oninput='update()'><pre id=O></pre>
```
[Answer]
# Java, 77 bytes
```
int f(String s){return s.chars().reduce(0,(r,c)->c<43?r*2:c<46?r+44-c:r>>1);}
```
Uses java 8 streams.
[Answer]
## GNU sed, ~~65~~ ~~59~~ 57 bytes
**Edit:** 2 bytes shorter thanks to [Toby Speight](/users/39490)'s comments
```
s/[+-]/1&/g
s/*/2&/g
s:/:d0>@2&:g
s/.*/dc -e"0[1-]s@&p"/e
```
**Run:**
```
sed -f simple_calculator.sed <<< "*///*-*+-+"
```
**Output:**
```
-1
```
The `sed` script prepares the input for the `dc` shell call at the end, the latter accepting the input in [Reverse Polish notation](https://en.wikipedia.org/wiki/Reverse_Polish_notation "Reverse Polish notation"). On division, if the number is negative (`d0>`), the `[1-]` decrement command stored in register `@` is called. Conversion example: `+ - * /` --> `1+ 1- 2* d0>@2/`.
[Answer]
# PHP, 75 bytes
This uses a modified version of [Jörg Hülsermann's](https://codegolf.stackexchange.com/users/59107/j%C3%B6rg-h%C3%BClsermann) answer.
```
eval(preg_replace('~.~','$s=($s\0(2-ord("\0")%11%3))|0;',$argv[1]));echo$s;
```
It heavily relies on string substitution, using a simple regular expression (`~.~`).
The variable `$s` is re-assigned with the new value for each character. At the end, it outputs the result.
---
**Note**: This is meant to be executed using the `-r` flag.
---
Try it here:
```
if('\0' == "\0")
{
$argv = Array($s = 0, prompt());
function preg_replace($pattern, $replacement, $subject)
{
$regexp = new RegExp($pattern.replace(new RegExp('~', 'g'), ''), 'g');
return $subject.replace($regexp, $replacement.split('\0').join('$&'));
}
function printf($string)
{
console.log($string);
}
function ord($chr)
{
return $chr.charCodeAt(0);
}
}
else
{
if(!isset($argv))
{
$argv = array('', '++*+');
}
}
eval(preg_replace('~.~','$s=($s\0(2-ord("\0")%11%3))|0;',$argv[1]));printf($s);
```
Or try on: <http://sandbox.onlinephpfunctions.com/code/7d2adc2a500268c011222d8d953d9b837f2312aa>
Differences:
* Instead of `echo$s`, I'm using `sprintf($s)`.
Both perform the same action on numbers. Since this is just for testing, it is fine.
* In case there's no passed argument, it will run as if you passed `++*+` as the first argument, which should show `5`.
[Answer]
## Batch, 61 bytes
```
@set n=
@for %%a in (%*)do @set/an=n%%a2^&-2
@cmd/cset/an/2
```
Translation of @xnor's xcellent Python answer.
[Answer]
## Pyke, ~~24~~ 22 bytes
```
\*\}:\/\e:\+\h:\-\t:0E
```
[Try it here!](http://pyke.catbus.co.uk/?code=%5C%2a%5C%7D%3A%5C%2F%5Ce%3A%5C%2B%5Ch%3A%5C-%5Ct%3A0E&input=%2B%2B%2a%2a--%2F)
### Or 12 bytes (noncompetitive)
```
~:"ht}e".:0E
```
[Try it here!](http://pyke.catbus.co.uk/?code=%7E%3A%22ht%7De%22.%3A0E&input=%2B%2B%2a%2a--%2F)
Add `translate` node - basically multiple find and replace.
```
~: - "+-*/"
.: - input.translate(^, V)
"ht}e" - "ht}e"
0E - eval(^, stack=0)
```
[Answer]
# PHP, ~~104~~ ~~102~~ 82 bytes
First version with eval:
```
$i=0;while($c<9999)eval('$i'.['+'=>'++','-'=>'--','*'=>'*=2','/'=>'>>=1'][$argv[1]{$c++}].';');echo$i;
```
Second version with ternary operators:
```
while($o=ord($argv[1]{$c++}))$i=$o<43?$i*2:($o<44?$i+1:($o<46?$i-1:$i>>1));echo$i;
```
Takes the input string as first argument from the command line.
~~This "only" works for input strings shorter than 10,000 characters - which should be plenty. Tested with all the test cases, unfortunately can't save on the initialization in the beginning.~~ Second version works with strings of any length and without initialization. :-)
The main element is the eval function which manipulates `$i` based on a map of arithmetic operations, which are pretty straightforward except for the division. PHP returns a float when using `/` and `intdiv` is too many bytes, so we do [a right-shift](http://php.net/manual/en/language.operators.bitwise.php).
## Updates
1. Saved 2 bytes by shortening `$i=$i>>1` to `$i>>=1` for integer division.
2. Threw out eval in favor of ternary operators.
[Answer]
# Python 3, ~~98~~ ~~66~~ 60 bytes
Thanks Tukkax!
Not as golfy as the other answer, but I can't compete with them without plagiarism.
```
i=0
for c in input():i+=[1,-i//2,-1,i][ord(c)%23%4]
print(i)
```
Also, I have a recursive lambda solution as well
**~~73~~ 67 bytes** (improved!)
```
s=lambda x,z=0:s(x[1:],z+[1,-z//2,-1,z][ord(x[0])%23%4])if x else z
```
[Answer]
# R, 201 bytes
**Golfed**
```
p=.Primitive;"-"="+"=function(x)p("+")(x,1);body(`-`)[[1]]=p("-");"*"="/"=function(x)p("*")(x,2);body(`/`)[[1]]=p("%/%");Reduce(function(f, ...)f(...),rev(mget(strsplit(scan(stdin(),""),"")[[1]])),0,T)
```
**Commented**
```
p = .Primitive # Redefine
"-" = "+" = function(x)p("+")(x,1) # Define - and +
body(`-`)[[1]] = p("-") # Change the body, what we do to save a byte
"*" = "/" = function(x)p("*")(x,2) # Same as above
body(`/`)[[1]] = p("%/%") # Same as above
Reduce(function(f, ...)f(...), # Function wrapper to evaluate list of func.
rev(mget(strsplit(scan(stdin(),""),"")[[1]])), # Strsplit input into list of functions
init = 0, # Starting Arg = 1
right = T) # Right to left = True
```
Strategy is to refine the `+, -, %` operators. Split the string then parse the string into a long list of functions, to be fed into `Reduce()'s` accumulator.
Couldn't golf it anymore. If someone can get `b=body<-` to work, there could be a few bytes of savings (refine every function with `b` after `"-"="+"="/"="*"`). Initially tried to substitute and parse eval, but the order of operations and parentheses were terrifying.
[Answer]
# Lex + C, ~~78~~, ~~74~~, 73 bytes
The first character is a space.
```
c;F(){yylex(c=0);return c;}
%%
\+ c++;
- c--;
\* c*=2;
\/ c=floor(c/2.);
```
Reads from `stdin`, returns result.
Compile with `lex golfed.l && cc lex.yy.c main.c -lm -lfl`, test main:
```
int main() { printf("%d\n", F()); }
```
[Answer]
# Javascript (ES5), 127 bytes
```
function(b){for(a=c=0;a<b.length;++a)switch(b[a]){case"+":++c;break;case"-":--c;break;case"*":c*=2;break;case"/":c/=2}return c}
```
Ungolfed:
```
function c(a){
c=0;
for(var i=0;i<a.length;++i){
switch(a[i]){
case "+":++c;break;
case "-":--c;break;
case "*":c*=2;break;
case "/":c/=2;break;
}
}
return c;
}
```
[Answer]
# Pyth, 23 bytes
```
FNQ=Z.v%".&%sZ2_2"N;/Z2
```
A full program that takes input as a string and prints the result.
This is a port of @xnor's [Python answer](https://codegolf.stackexchange.com/a/91509/55526).
[Try it online](https://pyth.herokuapp.com/?code=FNQ%3DZ.v%25%22.%26%25sZ2_2%22N%3B%2FZ2&debug=0)
**How it works**
```
FNQ=Z.v%".&%sZ2_2"N;/Z2 Program. Input: Q. Z initialised as 0
FNQ For. For N in Q:
".&%sZ2_2" String. Literal string ".&%sZ2_2"
% N String format. Replace %s with the current operator N
%sZ2 Operator. Yield Z*2, Z//2, Z+2, Z-2 as appropriate
.& _2 Bitwise and. Result of above & -2
.v Evaluate. Yield the result of the expression
=Z Assignment. Assign result of above to Z
; End. End for loop
/Z2 Integer division. Yield Z//2
Print. Print the above implicitly
```
[Answer]
## PHP, 79 bytes
```
<?$i=0;switch($_POST['a']){case"+":$i+1;case"-":$i-1;case"/":$i/2;case"*":$i*2}
```
] |
[Question]
[
The code should take input a text (not mandatory can be anything file, stdin, string for JavaScript, etc):
```
This is a text and a number: 31.
```
The output should contain the words with their number of occurrence, sorted by the number of occurrences in descending order:
```
a:2
and:1
is:1
number:1
This:1
text:1
31:1
```
Notice that 31 is a word, so a word is anything alpha-numeric, number are not acting as separators so for example `0xAF` qualifies as a word. Separators will be anything that is not alpha-numeric including `.`(dot) and `-`(hyphen) thus `i.e.` or `pick-me-up` would result in 2 respectively 3 words. Should be case sensitive, `This` and `this` would be two different words, `'` would also be separator so `wouldn`and `t` will be 2 different words from `wouldn't`.
Write the shortest code in your language of choice.
Shortest correct answer so far:
* **[grep and coreutils - 42 bytes](https://codegolf.stackexchange.com/a/19572/12328)**
[Answer]
## grep and coreutils ~~44~~ 42
```
grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr
```
Test:
```
printf "This is a text and a number: 31." |
grep -io '[a-z0-9]*'|sort|uniq -c|sort -nr
```
Results in:
```
2 a
1 This
1 text
1 number
1 is
1 and
1 31
```
### Update
* Use case-insensitive option and shorter regex. Thanks Tomas.
[Answer]
# Java 8: 289
Which is pretty good, since java is a very non-golfy language.
```
import java.util.stream.*;class C{static void main(String[]a){Stream.of(a).flatMap(s->of(s.split("[\\W_]+"))).collect(Collectors.groupingBy(x->x,Collectors.counting())).entrySet().stream().sorted(x,y->x.getValue()-y.getValue()).forEach(e->System.out.println(e.getKey()+":"+e.getValue()));}
```
Ungolfed:
```
import java.util.stream.*;
class C {
static void main(String [] args){
Stream.of(args).flatMap(arg->Stream.of(arg.split("[\\W_]+")))
.collect(Collectors.groupingBy(word->word,Collectors.counting()))
.entrySet().stream().sorted(x,y->x.getValue()-y.getValue())
.forEach(entry->System.out.println(entry.getKey()+":"+entry.getValue()));
}
}
```
Run from the command line:
```
java -jar wordCounter.jar This is a text and a number: 31.
```
[Answer]
## APL (57)
```
⎕ML←3⋄G[⍒,1↓⍉G←⊃∪↓Z,⍪+⌿∘.≡⍨Z←I⊂⍨(I←⍞)∊⎕D,⎕A,⎕UCS 96+⍳26;]
```
e.g.
```
⎕ML←3⋄G[⍒,1↓⍉G←⊃∪↓Z,⍪+⌿∘.≡⍨Z←I⊂⍨(I←⍞)∊⎕D,⎕A,⎕UCS 96+⍳26;]
This is a text and a number: 31.
a 2
This 1
is 1
text 1
and 1
number 1
31 1
```
Explanation:
* `⎕D,⎕A,⎕UCS 96+⍳26`: numbers, uppercase letters, lowercase letters
* `(I←⍞)∊`: read input, store in `I`, see which ones are alphanumeric
* `Z←I⊂⍨`: split `I` in groups of alphanumeric characters, store in `Z`
* `+⌿∘.≡⍨Z`: for each element in `Z`, see how often it occurs
* `Z,⍪`: match each element in `Z` pairwise with how many times it occurs
* `G←⊃∪↓`: select only the unique pairs, store in `G`
* `⍒,1↓⍉G`: get sorted indices for the occurrences
* `G[`...`;]`: reorder the lines of `G` by the given indices
[Answer]
# C#: ~~153c~~ ~~144c~~ ~~142c~~ ~~111c~~ ~~115c~~ ~~118c~~ ~~114c~~ 113c
*(via LINQPad in "C# Statements" mode, not including input string)*
## Version 1: 142c
```
var s = "This is a text and a number: 31."; // <- line not included in count
s.Split(s.Where(c=>!Char.IsLetterOrDigit(c)).ToArray(),(StringSplitOptions)1).GroupBy(x=>x,(k,e)=>new{s,c=e.Count()}).OrderBy(x=>-x.c).Dump();
```
Ungolfed:
```
var s = "This is a text and a number: 31.";
s.Split( // split string on multiple separators
s.Where(c => !Char.IsLetterOrDigit(c)) // get list of non-alphanumeric characters in string
.ToArray(), // (would love to get rid of this but needed to match the correct Split signature)
(StringSplitOptions)1 // integer equivalent of StringSplitOptions.RemoveEmptyEntries
).GroupBy(x => x, (k, e) => new{ s = k, c = e.Count() }) // count by word
.OrderBy(x => -x.c) // order ascending by negative count (i.e. OrderByDescending)
.Dump(); // output to LINQPad results panel
```
Results:

## Version 2: 114c
(`[\w]` includes `_`, which is incorrect!; `[A-z]` includes `[ \ ] ^ _ ``; settling on `[^_\W]+`)
```
var s = "This is a text and a number: 31."; // <- line not included in count
Regex.Matches(s, @"[^_\W]+").Cast<Match>().GroupBy(m=>m.Value,(m,e)=>new{m,c=e.Count()}).OrderBy(g=>-g.c).Dump();
```
Ungolfed:
```
Regex.Matches(s, @"[^_\W]+") // get all matches for one-or-more alphanumeric characters
.Cast<Match>() // why weren't .NET 1 collections retrofitted with IEnumerable<T>??
.GroupBy(m => m.Value, (m,e) => new{ m, c = e.Count() }) // count by word
.OrderBy(g => -g.c) // order ascending by negative count (i.e. OrderByDescending)
.Dump(); // output to LINQPad results panel
```
Results:
(as Version 1)
[Answer]
### R, 58 char
```
sort(table(unlist(strsplit(scan(,""),"[[:punct:]]"))),d=T)
```
Usage:
```
sort(table(unlist(strsplit(scan(,""),"[[:punct:]]"))),d=T)
1: This is a text and a number: 31.
9:
Read 8 items
a 31 and is number text This
2 1 1 1 1 1 1
```
[Answer]
## perl6: 49 characters
```
.say for get.comb(/\w+/).Bag.pairs.sort(-*.value)
```
Comb input for stuff matching `\w+`, put resulting list of words in a `Bag`, ask for their pairs and sort them by negative value. (The `*` is a [Whatever](http://perlcabal.org/syn/S02.html#The_Whatever_Object) star, it's not multiplication here)
output:
```
"a" => 2
"This" => 1
"is" => 1
"text" => 1
"and" => 1
"number" => 1
"31" => 1
```
[Answer]
# Python ~~101~~ 97
```
import re
a=re.split('[_\W]+',input())
f=a.count
for w in sorted(set(a),key=f)[::-1]:print w,f(w)
```
Now works with newline:
```
$ python countword.py <<< '"This is a text and a number: 31, and a\nnewline"'
a 3
and 2
31 1
number 1
newline 1
is 1
text 1
This 1
```
[Answer]
## PHP - 84 bytes
```
<?$a=array_count_values(preg_split('/[_\W]+/',$argv[1],0,1));arsort($a);print_r($a);
```
Input is accepted as a command line argument, e.g.:
```
$ php count-words.php "This is a text and a number: 31."
```
Output for the sample string:
```
Array
(
[a] => 2
[number] => 1
[31] => 1
[and] => 1
[text] => 1
[is] => 1
[This] => 1
)
```
[Answer]
**PowerShell (40)**
```
$s -split"\W+"|group -ca|sort count -des
```
$s is a variable that contains the input string.
[Answer]
# GNU awk + coreutils: 71 69
```
gawk 'BEGIN{RS="\\W+"}{c[$0]++}END{for(w in c)print c[w],w}'|sort -nr
```
Although `gawk asort` works on associative arrays, it apparently does not preserve the index values, necessitating the external `sort`
```
printf "This is a text and a number: 31." |
gawk 'BEGIN{RS="\\W+"}{c[$0]++}END{for(w in c)print c[w],w}'|sort -nr
2 a
1 This
1 text
1 number
1 is
1 and
1 31
```
# GNU awk 4.x: 100 93
A slightly larger but pure gawk solution using `PROCINFO` to set the default sort order for the associative array (appears to require a relatively recent gawk - > 4.x?)
```
BEGIN{RS="\\W+";PROCINFO["sorted_in"]="@val_num_desc"}
{c[$0]++}
END{for(w in c)print c[w],w}
```
[Answer]
## Perl 69
```
$h{$_}++for<>=~/\w+/g;print"$_: $h{$_}
"for sort{$h{$b}-$h{$a}}keys%h
```
Added recommendations from @primo and @protist
[Answer]
## Powershell: ~~57~~ ~~55~~ ~~53~~ ~~62~~ 57
*(not including input string)*
```
$s = "This is a text and a number: 31." # <-- not counting this line...
[Regex]::Matches($s,"[^_\W]+")|group -ca|sort{-$_.Count}
```
returns:
```
Count Name Group
----- ---- -----
2 a {a, a}
1 and {and}
1 31 {31}
1 number {number}
1 This {This}
1 is {is}
1 text {text}
```
(with props to @microbian for group -ca)
[Answer]
# EcmaScript 6
## Version 1 (108 characters)
```
s.split(_=/[^a-z\d]/i).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x&&console.log(x+':'+_[x]))
```
## Version 2 (102 characters)
```
s.split(_=/[^a-z\d]/i).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x&&alert(x+':'+_[x]))
```
## Version 3 (105 characters)
```
s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);alert(keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x+':'+_[x]).join('\n'))
```
## Version 4 (94 characters)
```
s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>alert(x+':'+_[x]))
```
## Version 5 (without alert; 87 characters)
```
s.match(_=/\w+/g).map(x=>_[x]=-~_[x]);keys(_).sort((a,b)=>_[a]<_[b]).map(x=>x+':'+_[x])
```
## Version 6 (100 characters)
```
keys(_,s.match(_=/\w+/g).map(x=>_[x]=-~_[x])).sort((a,b)=>_[a]<_[b]).map(x=>console.log(x+':'+_[x]))
```
---
## Output:
```
a:2
31:1
This:1
is:1
text:1
and:1
number:1
```
[Answer]
# Groovy 77 82
changed regex from `[^\w]+` to `[^\d\p{L}]+` in order to solve problem with underscore
```
String s = 'This is a text and a number: 31'
def a=s.split(/[^\d\p{L}]+/)
a.collectEntries{[it, a.count(it)]}.sort{-it.value}
```
without first line, 82 characters
output:
```
[a:2, This:1, is:1, text:1, and:1, number:1, 31:1]
```
[Answer]
# Javascript - ~~132~~ 126 chars !
### (Shortest JS code)
```
o={},a=[]
for(i in s=s.split(/[\W_]+/))o[z=s[i]]=o[z]+1||1
for(j in o)a.push([j,o[j]])
a.sort(function(b,c){return c[1]-b[1]})
```
Improved the regex and some edits.
---
## Ungolfed
```
s = s.split(/[\W_]+/), o={}, a=[]; // split along non-char letters, declare object and array
for (i in s) { n = s[i]; o[n] = o[n] + 1 || 1 } // go through each char and store it's occurence
for (j in o) a.push( [j, o[j]] ); // store in array for sorting
a.sort(function (b, c){ return c[1] - b[1]; }); // sort !
```
---
>
> <= // make s = "How shiny is this day is isn't is"
>
>
> =>
> [ [ 'is', 3 ],
>
> [ 'How', 1 ],
>
> [ 'shiny', 1 ],
>
> [ 'this', 1 ],
>
> [ 'day', 1 ],
>
> [ 'isn', 1 ],
>
> [ 't', 1 ] ]
>
>
>
---
### Old - ~~156~~ ~~143~~ ~~141~~ ~~140~~ 132 chars
```
s=s.split(/[^\w]+/g),o={}
for(i in s){n=s[i];o[n]=o[n]+1||1}a=[]
for(j in o)a.push([j,o[j]])
a.sort(function(b,c){return c[1]-b[1]})
```
---
Gave a first try at golfing. Feedback appreciated.
[Answer]
## EcmaScript 6, 115 100 87 (without prompt&alert)
Thanks to @eithedog:
```
s.match(/\w+/g,a={}).map(w=>a[w]=-~a[w]),keys(a).map(w=>[w,a[w]]).sort((a,b)=>b[1]-a[1])
```
With prompt and alert (100):
```
prompt(a={}).match(/\w+/g).map(w=>a[w]=-~a[w]);alert(keys(a).map(w=>[w,a[w]]).sort((a,b)=>b[1]-a[1]))
```
Run it in Firefox.
[Answer]
# Ruby ~~58~~ ~~82~~ 65
```
h=Hash.new 0
gets.scan(/[\d\w]+/){h[$&]+=1}
p *h.sort_by{|k,v|-v}
```
Test run:
```
$ ruby counttext.rb <<< "This is a text and a number: 31."
["a", 2]
["text", 1]
["This", 1]
["is", 1]
["and", 1]
["number", 1]
["31", 1]
```
---
Edit 58->80: Ok, I was way off. I forgot to sort the words by occurrences. Also, `Array#uniq` is not an enumerator, but uses a given block to compare elements, so passing `puts` to it didn't filter out duplicates (not that it says that we should).
[Answer]
**F# - 169**
```
let f s=(s+"").Split(set s-set(['a'..'z']@['A'..'Z']@['0'..'9'])|>Set.toArray)|>Seq.where((<>)"")|>Seq.countBy id|>Seq.sortBy((~-)<<snd)|>Seq.iter((<||)(printfn"%s:%d"))
```
Degolfed:
```
let count (s : string) =
s.Split (set s - set (['a'..'z']@['A'..'Z']@['0'..'9']) |> Set.toArray)
|> Seq.where ((<>) "")
|> Seq.countBy id
|> Seq.sortBy ((~-) << snd)
|> Seq.iter ((<||) (printfn "%s:%d"))
```
Output when called from fsi:
```
> "This is a text and a number: 31." |> f
a:2
This:1
is:1
text:1
and:1
number:1
31:1
val it : unit = ()
```
**Update:** Some explanation as requested in the comments.
Uses set functions to generate an array of non alphanumeric characters in the input to pass to String.Split, then uses sequence functions to filter out empty strings, generate word counts and print the result.
Some golfing tricks: Adds an empty string to the function argument s to force type inference of the argument as a string rather than explicitly declaring the type. Uses Seq.where rather than Seq.filter to save a few characters (they are synonyms). Mixes forward pipe and ordinary function application in an attempt to minimize characters. Uses currying and (op) syntax to treat <> ~- and <|| operators as regular functions to avoid declaring lambdas to filter empty strings, sort by descending count and print tuples.
[Answer]
## Python - 95 ( now ***87*** thanks to @primo)
```
d=__import__('re').findall(r'\w+',raw_input())
print sorted(map(lambda y:(y,d.count(y)),d))
```
Sample input :
```
'This is a text and a number: 31'
```
Sample output :
```
[('This', 1),('is', 1), ('a', 2),('text', 1),('and', 1),('a', 2),('number', 1),('31', 1)]
```
Any improvement sugestion would be appreciated
[Answer]
# JavaScript 160 144 (Edited: to meet requirements)
```
f=Function;o={};s.replace(/\w+/g,f('a','o[a]=++o[a]||1'));Object.keys(o).sort(f('b,c','return o[c]-o[b]')).map(f('k','console.log(k+" "+o[k])'))
```
Unminified:
```
f=Function;
o = {};
s.replace(/\w+/g, f('a','o[a]=++o[a]||1'));
Object.keys(o).sort(f('b,c', 'return o[c]-o[b]')).map(f('k','console.log(k+" "+o[k])'))
```
Logs each word to console in order, passing the following string:
`s="This is sam}}ple text 31to test the effectiveness of this code, you can clearly see that this is working-as-intended, but you didn't doubt it did you?.";`
Outputs:
```
you 3
this 2
is 2
can 1
text 1
31to 1
test 1
the 1
effectiveness 1
of 1
This 1
code 1
sam 1
ple 1
clearly 1
see 1
that 1
working 1
as 1
intended 1
but 1
didn 1
t 1
doubt 1
it 1
did 1
```
I don't have the heart to use `alert()`.
[Answer]
# k [71 chars]
```
f:{s:" ",x;`_k!m@k:|(!m)@<.:m:#:'=`$1_'(&~((),/:s)like"[a-zA-Z0-9]")_s}
```
Any other character except alphanumeric chars will be considered as delimiter.
### example
```
f "This is a text and a number: 31."
a | 2
31 | 1
number| 1
and | 1
text | 1
is | 1
This | 1
```
### example
```
f "won't won won-won"
won| 4
t | 1
```
[Answer]
# Javascript (135)
```
u=/\w+/g
for(i=s.length;i--;)for(w in a=s.match(u))u[w=a[w]]=u[w]||a.reduce(function(p,c){return p+=w==c},0)==i&&!console.log(w+":"+i)
```
Unminified:
```
u=/\w+/g;for (i=s.length;i--;)
for(w in a=s.match(u))
u[w=a[w]] = u[w] ||
a.reduce(function(p,c){return p+=w==c},0)==i && !console.log(w+":"+i)
```
Loops over every possible number of matches in descending order, and outputs words with that number of occurrences. Just to be horrible.
Notes: Alert would have reduced the length some. Strictly speaking alphanumeric should be `[^\W_]`
[Answer]
# Haskell (153 = 104 code + 49 import)
Pretty straight-forward, totally composed function... no argument even necessary! This is my first golf, so go easy, maybe? :)
```
import Data.Char
import Data.List
import Data.Ord
so=reverse.(sortBy$comparing snd).(map(\t@(x:_)->(x,length t))).group.sort.(map$filter isAlphaNum).words
```
Output:
```
*Main> so "This is a text and a number: 31."
[("a",2),("text",1),("number",1),("is",1),("and",1),("This",1),("31",1)]
```
[Answer]
# q (50)
```
desc count each group" "vs ssr[;"[^0-9A-Za-z]";" "]
```
* ssr replaces non alphanumeric
* " "vs splits the result into a symbol list
* count each group counts creates a dict matching distinct elements of the list with the number of occurances
* desc sorts the dict by descending values
edit: fixed accidentally matching ascii 58-64 and 91-96
[Answer]
# Pure Bash (no external programs), 164
This is longer than I'd hoped, but I wanted to see if the necessary counting and sorting (in the right direction) could be done purely with `bash` arrays (associative and non-associative):
```
declare -A c
for w in ${@//[[:punct:]]/ };{ ((c[$w]++));}
for w in ${!c[@]};{ i=${c[$w]};((m=i>m?i:m));s[$i]+=$w:;}
for((i=m;i>0;i--));{ printf "${s[i]//:/:$i
}";}
```
Save as a script file, `chmod +x`, and run:
```
$ ./countoccur This is a text and a number: 31.
a:2
and:1
number:1
text:1
31:1
is:1
This:1
$
```
[Answer]
# AWK
```
awk -vRS='[^A-Za-z0-9]' '$0{c[$0]++}END{for(i in c)print c[i]"\t"i": "c[i]|"sort -nr|cut -f2-"}'
```
Does the job without gawkish extensions:
```
$ echo 'This is a text and a number: 31.' | awk -vRS='[^A-Za-z0-9]' '$0{c[$0]++}END{for(i in c)print c[i]"\t"i": "c[i]|"sort -nr|cut -f2-"}'
a: 2
This: 1
text: 1
number: 1
is: 1
and: 1
31: 1
```
If printing "count: word" instead, it would be a bit shorter but I wanted to mimic the given example output...
[Answer]
# [Tcl](http://tcl.tk/), 99 bytes
```
proc C s {lmap w [split [regsub -all \[^\\w|\ \] $s {}]] {dict inc D $w}
lsort -s 2 -inde 1 -de $D}
```
[Try it online!](https://tio.run/##HU3NCsMgGLv3KULp1UG3267tI@ymDqyVTbBW9CsOOp/dySAkOeSHtKs1xF1jQsLpNhWQwVNwlsCjeaVjAVPOQfCnEPkrICSGFi1S4lytJlivMWPIpXNpjwSWcAWzfjUYwRoPc6n/5Vbr@sfbJjQokPkQlF@b9ce2mHjHbbz0XcEZDkrtRoBPTWSpPw "Tcl – Try It Online")
[Answer]
Python 2.X (108 - Characters)
```
print'\n'.join('{}:{}'.format(a,b)for a,b in __import__("collections").Counter(raw_input().split()).items())
```
Python 3.X (106 - Characters)
```
print('\n'.join('{}:{}'.format(a,b)for a,b in __import__("collections").Counter(input().split()).items())
```
[Answer]
# Haskell - 137
```
import Data.List
count text=let textS=(words(text\\".-\':")) in (sortBy (\(_,n) (_,m) -> compare m n)).nub$map(\t->(t,(length.(filter(==t)))textS)) textS
```
[Answer]
# Python 3 - 76
The requirement of splitting on non-alphanumeric chars unfortunately extends the code by 19 chars. The output of the following is shown correctly. If you are not sure, add a `.most_common()` after the `.Counter(...)`.
```
i=__import__
print(i('collections').Counter(i('re').findall('\w+',input())))
```
### In/Output
Given the input of `This is a text and a number: 31.` you get following output:
```
Counter({'a': 2, 'is': 1, 'This': 1, 'and': 1, '31': 1, 'number': 1, 'text': 1})
```
I tried it with other values like
```
1 2 3 4 5 6 7 8 2 1 5 3 4 6 8 1 3 2 4 6 1 2 8 4 3 1 3 2 5 6 5 4 2 2 4 2 1 3 6
```
to ensure, the output-order does not rely on the key's value/hash. This example produces:
```
Counter({'2': 8, '3': 6, '1': 6, '4': 6, '6': 5, '5': 4, '8': 3, '7': 1})
```
But as I said, `print(i('collections').Counter(i('re').findall('\w+',input())).most_common())` would return the results as an *definitly* ordered list of tuples.
---
## Python 3 - 57 *(if a space would be enough for splitting :P)*
```
print(__import__('collections').Counter(input().split()))
```
] |
[Question]
[
Take the string of brackets `]][][[`. When you rotate it to the right once, you get `[]][][`. If you rotate it again, you get `[[]][]`. All brackets in this string are balanced.
**The Task:**
Your program (or function) will be given a string of brackets, represented in any reasonable format (including using other things in place of the brackets, like `-1` and `1`). The numbers of opening and closing brackets will always be equal, so `[` or `][]` won't be given as inputs.
Output should be a rotation of those brackets which is balanced. You can check this by repeatedly removing pairs of brackets (`[]`). With a balanced string of brackets, none will be left over.
Rotating a string to the right involves taking the last character, and moving it to the beginning. For example, `01234567` rotated right 3 times would be `56701234`. The direction of rotation doesn't matter, but no brackets should be added, discarded, mirrored, etc. If multiple solutions are possible, such as `[][[]]` or `[[]][]`, you can return any of them.
**Test Cases:**
```
[] -> []
]][[ -> [[]]
[][]][ -> [[][]]
][][[] -> [[]][] OR [][[]]
[[[][][]]] -> [[[][][]]]
]]][][][[[ -> [[[]]][][] OR [][[[]]][] OR [][][[[]]]
```
**Other:**
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest answer in bytes per language wins!
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~7~~ 5 bytes
```
ṙ¹η◄∫
```
[Try it online!](https://tio.run/##yygtzv6vkPuoqfHQNi6FXA1FpehYpUN7H7VN0nzU1JSr8ahtgoutevT/hztnHtp5bvuj6S2POlb///8/OpYrNjY6mis6NhpIcwHJaKBQdDSIDxQByYJZQBEkJgA "Husk – Try It Online")
No loops, no recursion, just a straightforward simple operation. Encodes `[` as `1` and `]` as `-1`.
```
ṙ¹η◄∫
·πô¬π Rotate the list left by
η the (1-based) index
‚óÑ of the minimum
‚à´ in the list of cumulative sums
```
This comes from observing that the list of cumulative sums will have a minimum at the point where the most closed brackets are preceding open brackets. By moving all the previous brackets to the end, we can guarantee that there won't be any prefix containing more closed than open brackets.
---
## Previous answer, 7 bytes
```
Ωȯ¬▼∫ṙ1
```
[Try it online!](https://tio.run/##yygtzv6fq6GoFB2rdGjvo7ZJmo@aGnM1HrVNcLFVj/5/buWJ9YfWPJq251HH6oc7Zxr@//9fKTY2NhoEo6OVAA "Husk – Try It Online")
Encodes `[` as `1` and `]` as `-1`, following [HyperNeutrino's idea](https://codegolf.stackexchange.com/a/221295/62393) to use the cumulative sum, but then uses an additional observation:
Since we are working with an equal number of open and closed brackets, the total sum will always be `0`. If at any point the string is unbalanced, the cumulative sum at that point will be negative. From this, we can say that a string will be balanced if the minimum of its cumulative sum is exactly `0`.
```
Ω(¬▼∫)ṙ1
·πô1 Rotate by 1
Ω until
▼ the minimum
‚à´ of the cumulative sums
¬ is 0
```
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), ~~42~~ 34 bytes
```
{({S/.//~$/}...{try !.EVAL}).tail}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwv1qjOlhfT1@/TkW/Vk9Pr7qkqFJBUc81zNGnVlOvJDEzp/Z/cWKlQppCXa5@TLCWvkJafpFCTmZeavH/6FgFONC1U1CIjuWKjY2ORhGKjo3lio4FktEogiBhIBENMwKmFsj3D1IASwD1gRUCWbEwBTA@0B4wKxpkG0wKIgTTD@FDeVA@AA "Perl 6 – Try It Online")
In Raku, a set of balanced square brackets is entirely valid syntax, so we can simply rotate the string until it `EVAL`s successfully, and take the last element.
### Explanation
```
{ } # Anonymous codeblock taking a string
{S/.// } # Remove the first character
~$/ # And add it to the end
( ... ) # Repeat until
{try !.EVAL} # The program can be eval'd
# This returns ![] (true) if successful
.tail # Return the last element
```
I thought [this 31 byte program](https://tio.run/##K0gtyjH7/79YX0NPS1NDT1NfxVDFQL80ryQzR6GkqFJBUc81zNHn///oWK7Y2OhorujYaCDNBSSjgULR0SA@UAQkC2YBRf7lF5Rk5ucV/9ctAAA) using the `-p` flag would work, but either TIO is too outdated or Raku has some sort of weird behaviour about `until`/`while` and `$_`. Until I can test it using the latest version, you can check it [like so](https://tio.run/##K0gtyjH7n5ZfpKCRk5mXWqypoGunoJKoUM2lEq9gC2RZ/y/W19DT0tTQ09RXMVQx0C/NK8nMUSgpqlRQ1HMNc/T5b81VnFipoBLPVfs/OpYrNjY6mis6NhpIcwHJaKBQdDSIDxQByYJZQBEA).
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
ÄMṙ@
```
[Try it online!](https://tio.run/##y0rNyan8//9wi@/DnTMd/ts@apgb@3DHkkcNMw@3P2qY4fFwd/ejxn2x0ZH//yvFxsZGg2B0tBIA "Jelly – Try It Online")
Similar approach to [Leo's answer](https://codegolf.stackexchange.com/a/221300/66833), give that an upvote!
Uses `-1` and `1` for `[` and `]` and returns all valid rotations
By swapping the signs from Leo's approach, we can operate on the maximal elements, rather than minimal, as Jelly has a builtin `M` to return the indices of maximal elements, thus saving a byte
## How it works
```
ÄMṙ@ - Main link. Takes a list of 1 and -1, A
Ä - Take the cumulative sums
M - Yield the indices of the maximal elements
·πô@ - Rotate A that many times for each index
```
[Answer]
# [Python 2](https://docs.python.org/2/), ~~74~~ ~~72~~ 69 bytes
```
def f(s):
try:exec s.replace(')','),');print s
except:f(s[1:]+s[0])
```
[Try it online!](https://tio.run/##PYtBCoMwEEX3OcXgJn@olOoyPYq4kHRCC2JDkoWePo61LQzMvP/nxa0830tf60MCBWR2hkranKziKV@TxHnyAsu2taxzj@m1FMqGZPUSi1Nn6Nx4ycNt5BrQgBs2upmB8wJD4Zsq/D6Ao9Hub3wQh1d3 "Python 2 – Try It Online")
Tried a similar approach to *Jo King*'s Raku answer by evaluating the bracket string, only difference being an added `,` after every `)` so that the expression is valid.
Takes `(` and `)` instead of `[` and `]`.
*-2 bytes thanks to Sisyphus, -3 bytes thanks to dingledooper*
[51 bytes if it's allowed to take ( and ), instead of ( and ) üëÄ](https://tio.run/##TYwxDoAgEAR7XnGx2osUaolPMVZ6RBslQKGvR9Bo7HZn586dcdm3LqVZLFkENoqiP40cMlHonV@3SEGRHJO4aLIxtGasw9CMnCwqsK5Y5cCaNfDkDHH3dyrgM4Fnv5X/@UtR/qQL)
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 10 [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"))
[This algorithm.](https://codegolf.stackexchange.com/a/221304/43319)
Anonymous prefix lambda, taking `-1` for `[` and `1` for `]`.
```
{⍵⌽⍨⊃⍒+\⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v/pR79ZHPXsf9a541NX8qHeSdgxQoPZ/2qO2CY96@4Bih9YbP2qb@KhvanCQM5AM8fAM/l9QlAqUP7TeUEs9Wt32UdciroL84hKgULV6tEKserSRNtCQ2FqwqEKaAlC5gnp0rDoKPzY2OlodTUU0UBBNFVAQXWd0NEglUC2GiWDhaJC5XJr5aWlcXNGxCnCga6egEB3LBbIXRQhoEBfEahRBkDDEdlS1QL5/kAJYAqgP7hSYAhifC@EahBRECKYfwofyoHwA "APL (Dyalog Unicode) – Try It Online") ([This template](https://codegolf.stackexchange.com/a/221298/43319))
`{`…`}` "dfn"; argument is `⍵`:
‚ÄÉ`+\‚çµ`‚ÄÉcumulative sum of the argument
‚ÄÉ`‚çí`‚ÄÉindices that would sort that descending (i.e. index of the largest, index of the next-largest, etc.)
 `⊃` the first of that (i.e. the index of the largest)
 `⍵⌽⍨` use that to rotate the argument to the left
[Answer]
# [Haskell](https://www.haskell.org/), 37 bytes
```
until(all(>0).scanl(+)1)$drop<>take$1
```
[Try it online!](https://tio.run/##bY7NDoIwEITvPMUeOLSREnsHTl55AuSw4Ucbl7ah6@tbhQQlarLJ7peZzcwVw20gimbybmY4IWNeO@tMD0IUlZTJWJ7j3bIhgUSiOso8dGhJHKSWaT87X1SMtyHVkYfAAUpoGp2B0m0GjVqvDJZZ@INvZbPtnNv3Dr@X@olQ/6xrQJskExr7ajahr8HPxjKkC8AIa@n46EbCS4iq8/4J "Haskell – Try It Online")
*Saved 2 bytes using `<>`.*
Takes in a list of 1's and -1's. Actually pretty readable:
```
until until
(all(>0). we get all positive values from
scanl(+)1) the cumulative sums of the list starting from 1,
$drop<>take rotate the list
$1 by 1
```
The `drop<>take` rotates by using `<>` to concatenate the list with elements `drop`ped from the start and the list with that many elements `take`n from the start. The `(<>)` is imported in the TIO link but is available in base starting with 8.4.1; [see this tip](https://codegolf.stackexchange.com/a/177774/20260). We could also do `tail<>take 1` for the same length.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 bytes
```
ṙJÄ-eƊÐḟ
```
[Try it online!](https://tio.run/##y0rNyan8///hzpleh1t0U491HZ7wcMf8/7aPGuZGP9yx5FHDzMPtjxpmeDzc3f2ocV90bOT//0qxsbHRIBgdrQQA "Jelly – Try It Online")
-2 bytes thanks to ChartZ Belatedly + 1 byte saved from being allowed to return all valid configurations instead of just one
## Explanation
```
ṙJÄ-eƊÐḟ Main Link
·πô Rotate by
J [1, 2, ..., len(input)]
Ðḟ Filter: keep all elements where the following is falsy (in this case, a list of all zeroes):
Ä Cumulative Sum
e equal to (vectorize)
- -1
```
Basically, keep all arrangements where the cumulative sum is never equal to -1 (clever observation from ChartZ that since the cumsum changes by 1 each time and starts at 0, if any value is negative, then there must be a -1 somewhere, so rather than doing `<0$` we can do `-e`. and then also that the filter quick accepts a list of zeroes as falsy so I don't have to use the `any` atom)
[Answer]
# [Python 3.8](https://docs.python.org/3.8/), 57 bytes
```
f=lambda s,t=1:s*all((t:=t+n)for n in s)or f(s[1:]+s[:1])
```
[Try it online!](https://tio.run/##bYzBCsMgEETv/Yo9ro0ell6K4JeIB0sjEawRtS39emtDaEPosrDz2JlJrzrN8XROuTWngr1drhYKr4pkOdoQEKtUdYjMzRki@AiFdeWwaJJmKFqSYe05@TACyZR9rOhwfNiAPqZ7RdanaeIgyBy0WASHz3b80fexmja@Nbqh/RH7evHPubS/AQ "Python 3.8 (pre-release) – Try It Online")
Takes in a list of 1's and -1's.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 11 [bytes](https://github.com/abrudz/SBCS)
```
(⊢⌽⍨1∊+\)⍣≡
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@NR16JHPXsf9a4wfNTRpR2j@ah38aPOhf/THrVNeNTb96ir@dB640dtEx/1TQ0OcgaSIR6ewf8LilKB8ofWG2qpR6vbAo3gKsgvLgEKVatHK8SqRxtpP@rdGlsLFlVIUwAqV1CPjlVH4cfGRkero6mIBgqiqQIKouuMjgapBKrFMBEsHA0yl0szPy2Niys6VgEOdO0UFKJjuUD2oggBDeKCWI0iCBKG2I6qFsj3D1IASwD1wZ0CUwDjcyFcg5CCCMH0Q/hQHpQPAA "APL (Dyalog Unicode) – Try It Online")
An APL port of [Jonah's golfed answer](https://codegolf.stackexchange.com/a/221296/78410), which in turn uses [Leo's observation](https://codegolf.stackexchange.com/questions/221293/rotate-brackets-until-theyre-balanced#comment514707_221295). Like Jonah's, the input is `-1` for `[` and `1` for `]`.
### How it works
```
(⊢⌽⍨1∊+\)⍣≡ ⍝ Input: a vector of -1s and 1s, -1 for open and 1 for close
(...)⍣≡ ⍝ Repeat until it does not change...
1‚àä+\ ‚çù 1 if cumulative sum has a 1, 0 otherwise
⊢⌽⍨ ⍝ Rotate left ^ times (so it stops when the above result is zero)
```
[Answer]
# Scratch 3.0, 49 blocks/407 bytes
[](https://i.stack.imgur.com/kGumm.png)
As SB Syntax:
```
define C
set[T v]to(0
set[i v]to(1
set[Y v]to(1
repeat(length of[S v
if<(item(i)of[S v])=[a]>then
set[T v]to((T)+(1
else
set[T v]to((T)-(1
end
if<(T)<(0)>then
set[Y v]to(0)
end
set[i v]to((i)+(1
define(s
set[i v]to(1
repeat(length of(s
add(letter(i)of(s))to[S v]
set[i v]to((i)+(1
end
C
repeat until<(Y)=(1
set[t v]to(item(length of[S v])of[S v]
delete(length of[S v])of[S v
insert(t)at(1)of[S v
C
end
say(S
```
Because rotating a string in Scratch/bracket matching is a really good idea. Use `a` for opening brackets and `b` for closing brackets.
## Explained
```
define C -- Helper function used for checking if the brackets are balanced
set[T v]to(0
set[i v]to(1 --- T = running tally, i = string index, Y = return value
set[Y v]to(1
repeat(length of[S v
if<(item(i)of[S v])=[a]>then
set[T v]to((T)+(1
else ---- Opening brackets (a) increment the tally by 1. Closing brackets (b) decrement the tally by 1. If the brackets are balanced, this tally will never go below 0, as the brackets will cancel each other out
set[T v]to((T)-(1
end
if<(T)<(0)>then
set[Y v]to(0)
end
set[i v]to((i)+(1
define(s --- Main function
set[i v]to(1
repeat(length of(s
add(letter(i)of(s))to[S v] --- Place every character of the input into a list
set[i v]to((i)+(1
end
C ---- Check if the inital input is balanced
repeat until<(Y)=(1
set[t v]to(item(length of[S v])of[S v] --- Rotate the string once
delete(length of[S v])of[S v
insert(t)at(1)of[S v
C ---------- And check each rotation
end
say(S
```
[Answer]
# [J](http://jsoftware.com/), 40 29 19 18 15 14 13 bytes
```
|.~1+0{&\:+/\
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/a/TqDLUNqtVirLT1Y/5rcpWkFpfY6imkJmfkO2joWqVpqmnEG2qrRyvEqmfqxWpycXGpR8eqK4CUKYBYQG50LFwgNjY6GiKEJAjmgIVjUdSCuWDVIBVAGYQOhAhYVyxIANmWWKig@n8A "J – Try It Online")
-11 after applying HyperNeutrino's scan sum idea
-10 after reading Leo's comment to HyperNeutrino: `while(any of the cumulative sum is negative)(rotate by 1)`
-3 thanks to a clever observation by Bubbler
Takes input as a list of integers, where `[ = _1` and `] = 1` -- reversing the more natural order saves 1 byte.
## how
* `|.~` Rotate by...
* `1+` 1 plus...
* `0{` the first element of...
* `\:` the grade down of...
* `+/\` the scan sum.
That is, take the index of the max element of the scan sum, add one to it, and rotate by that amount.
[Answer]
# [Perl 5](https://www.perl.org/), 30 bytes
```
$_=chop.$_ while s/<(?R)*>//gr
```
[Try it online!](https://tio.run/##K0gtyjH9/18l3jY5I79ATyVeoTwjMydVoVjfRsM@SFPLTl8/vej/fxs7Ljs7GxsuGzsbIM0FJG2AQjY2ID5QBCQLZgFF/uUXlGTm5xX/1y3IAQA "Perl 5 – Try It Online")
Uses `<>` as the bracket delimiters.
The regex `s/<(?R)*>//gr` recursively substitutes bracket patterns with the empty string, and instead of mutating the string returns the final value. If this is empty, then all our brackets are fully matched and since the empty string is falsy, the loop stops. Else we rotate the string one using the construction `$_=chop.$_`.
-1 thanks to [Dom Hastings](https://codegolf.stackexchange.com/users/9365/dom-hastings) by replacing the ugly `s/.//,$_.=$&` with the much more elegant `$_=chop.$_`.
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 53 bytes
```
f=a=>([c,...r]=a).some(v=>(c+=v)>=0)?f([...r,a[0]]):a
```
[Try it online!](https://tio.run/##dY0xDoMwDEX3nsJbYrVEsFIZDmJ5iFKoQEAQQVw/DbAhunh473//3m42uKWb12zynybGlixVmt3LGLMIWTTBj43eEnRP2rCiHOtW865flnMRLG1cKVB10iBmtLN2QBWkQwSKFdSQFVBCgXi1iddHpAQlCk3vu0krhQ/np@CHxgz@q1etOEl8X6kI8x1n4aRuG0nd/2LeW6n3Z@mQfO7FHw "JavaScript (Node.js) – Try It Online")
Input array of \$\pm 1\$, output rotated array.
Thanks [user81655](https://codegolf.stackexchange.com/users/46855/user81655) for -1 byte.
[Answer]
# Javascript, 52 bytes
(Sorry if i formatted my answer wrong, i'm brand new here.)
## Golf version
```
a=>{while(t=0,a.some(v=>(t+=v)<0))a.push(a.shift())}
```
## More readable version (and you can try it out)
```
function rotateArrayUntilBalanced(array) {
var total; // Create a total variable
while (total=0,array.some(value => (total += value) < 0)) { // This tests if the array is still unbalanced
array.push(array.shift()); // Shift array right
}
}
button.onclick = function () {
const array = input.value.split('').map(value => (value == '[' ? 1 : -1));
rotateArrayUntilBalanced(array);
resultArea.innerText = array.map(value => (value == 1 ? '[' : ']')).join('');
}
```
```
<input id="input" placeholder="brackets go here">
<button id="button">Go</button>
<div id="resultArea"></div>
```
[Answer]
# [R](https://www.r-project.org/), 80 bytes
```
function(x){while(min(cumsum(92-(y=utf8ToInt(x)))))x=intToUtf8(c(y[-1],y[1]));x}
```
[Try it online!](https://tio.run/##bY@9CsIwFIV3nyLokoAd6qRI3Z0EqdPlIjW0GLQJtAm2iM9eY5pI0dztnPPdv2ZolC50eb40Bb@Vus2GykiuhZK0Y8/HVdxLWgtJualbU9PNKqF9ZnS1ztVeast8qsuE1Lk6WZty2kOS4rKHFBnbdq/fDXQOOGdkQb6V7AgBnP1xiABT0nGAERLQ2hPWk1HWujC9IEwFJIcjcWFsgxtnI985dgUvdruLIHwQ@NEOm0btldfDGw "R – Try It Online")
Input is string of square-brackets.
Alternatively, a port of [Leo's Husk answer](https://codegolf.stackexchange.com/a/221300/95126) using a vector of `1`s & `-1`s as input is only [48 bytes](https://tio.run/##rZFPS8QwEMXvfophFyTBrbCedKF79yTIegqhxJiyQZpZk4nWT1/Tv1qht@aUmeT93pvENx5JkSlevdLvhkLelNFpsuhYzTWrdzUXwXwwldf85uts9fm2so7pWIVYpStcNlvQ6D6NJyCEayg9VmBU@M4IM2/UG4xssC5Q28AS9rtsD6ptXSIdrgZCQVigM0WyiCFt8j9hHu6ySOX9CR8dpXKStH6LIuvohC9JxpI8iZZV7N9DsIVIbCPkhnMOW5hWdgQQcg22lELM6R1bSLlO8gSa8Qf6SvzEEfPXGdMLCU/P0B2vM0kXOsEmt95p7K7zFx1M/P7I6NEfjBP19VANdfMD).
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 74 bytes
```
a=>eval("try{Function(a.replace(/]/g,'-1]'));a}catch{f(a.slice(1)+a[0])}")
```
[Try it online!](https://tio.run/##dY1BDoMgFET3PYYbIK1a1waXXuKHxQ9FS0PAADVpjGen1O4aup03b@aBKwbp9RJr624qTTwhH9SKhlbRv7bxaWXUzlJsvFoMSkVb0c4XUneCMNbjLjHK@zblQjA6446dEa6C7RVLkQc@TDSw/iSdDc6oxriZRkrgsH9TIQBKOQjIqGhkVN4C@FjZ@/N0QPj@pTc "JavaScript (Node.js) – Try It Online")
Convert each `]` to `-1]`, and try to check if there are any syntax error...
This is ES2019.
[Answer]
# [Python 3](https://docs.python.org/3/), ~~74~~ 72 bytes
```
f=lambda a:min(sum(a[:i])for i in range(len(a)))<0and f([a.pop()]+a)or a
```
[Try it online!](https://tio.run/##XYrBCsIwEETvfsUedzGVBm9Fv6TkMKWNBppNiPXg18e0Bw/CMAPvTf5sz6TXWv19RZxmEIYYlF/vyBiH4MSnQoGCUoE@Fl4XZYjIrYfO5HnEJafM4s6Q9kTNJejGTVhDnXUipx/pDmRoz7@w5qh9mqpf "Python 3 – Try It Online")
Takes input as a list of 1s and -1s, with 1 denoting `[` and -1 denoting `]`.
For a valid bracket sequence, no prefix of the array will have a sum less than 0, so if the current array is not a valid bracket sequence, rotate it by 1 and try again.
*-2 bytes thanks to tsh*
[Answer]
# [Python 3](https://docs.python.org/3/), 63 bytes
```
lambda a:min((sum(a[:i]),a[i:]+a[:i])for i in range(len(a)))[1]
```
[Try it online!](https://tio.run/##XYzBDoIwEETvfsXeuo1oQrw16Zese1gj6BooBOrBr68FjAGO82bm9Z/47MIl1f6aGmlvdwFxrQbE8d2ikFO2hZA6Pi6h7gZQ0ACDhEeFTRVQrLVUcor@ZxidMedXly2G2JCC93AqGf7fGonKYmJLadis2pGtPfSDhohxNqwjM5HZ9pTZdpPZ7kY07fJyb5spzc70BQ "Python 3 – Try It Online")
---
# [JavaScript (Node.js)](https://nodejs.org), 76 bytes
```
a=>a.map(v=>(++i,c+=v)<m?0:o=[...a.slice(i),...a.slice(0,i,m=c)],i=c=m=0)&&o
```
[Try it online!](https://tio.run/##dY0xDoMwDEX3niITiUWIYKV1OIiVIUqhCgKCGsT1aaBLhehiyf/5@fd2tdG9/bwUU3i2W4ebRW3VaGexohZ57qXLcYXH2JR1QFJKWRUH71rhQf5spfRyRAdGenQ4YglZFrYFI@pO7Fo0x1fHULM0EBknzhpWVKxmFcCZprw5TmrGDQfVBz8JzuHmwhTD0KohvMQiOCUI93NqDNFVToYSujQSuv5FtFvJ@9N0QPr2bR8 "JavaScript (Node.js) – Try It Online")
Input an array of \$\pm 1\$.
Count each `[` as \$-1\$, each `]` as \$+1\$. Find out the position \$p\$ where \$\sum\_{i=0}^{p}a\_i\$ has max value. And rotate it there. I believe this approach may be golfed more bytes, but I didn't find out an obvious way.
[Answer]
# [Red](http://www.red-lang.org), 50 bytes
```
func[s][while[error? try[load s]][move s tail s]s]
```
[Try it online!](https://tio.run/##RY09DsIwDIX3nsLKzgUY4A6sTx7SxFEjlaZyAqinDy6o4Mnf@9FTif0mETykM/X0WAIq4zXlWSCqRa/UdMNcfKTKjHt5ClVqPs/GlXsqKj5MNBIGsnNg930sDXdoMDp0o18I2D1z/60PY@8yVs1LQyjrZgPudHGUaGTubw "Red – Try It Online")
### Explanation
[Red](http://www.red-lang.org) uses brackets for its `block!` datatype so every set of balanced brackets is a valid value. That's why I'm trying to load the string holding the brackets (that is to convert the string to a Red value) and if this throws an error, I move the leading character of the string at the tail.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ 7 bytes
*-2 thanks to [@Command Master](https://codegolf.stackexchange.com/users/92727/command-master).*
```
ηOWk>._
```
[Try it online!](https://tio.run/##yy9OTMpM/f//3Hb/8Gw7vfj//6N1DXUUQBhBGcYCAA "05AB1E – Try It Online") Takes input as a list, with `1` for `[` and `-1` for `]`.
```
ηOWk>._ # full program
._ # rotate...
# implicit input...
._ # left...
> # 1...
k # -based index of...
W # maximum...
η # cumulative...
O # sum...
η # of...
# implicit input...
k # in...
η # cumulative...
O # sums...
η # of...
# implicit input...
._ # times
# implicit output
```
`>._` can also be `._À` with no change in functionality.
As a bonus, this works too!
```
ηOWk>
._.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), ~~110~~ 108 bytes
```
x=>{for(s=x,i=0;++i<x.length;s=s.slice(1)+s[0])for(y=0,h=s;++y<s.length;h=h.replace('[]',''))if(!h)return s}
```
[Try it online!](https://tio.run/##NcpBDsIgEADAr@gJCJXUc7t@hHAgdVswhG1YNG2Mb8d6cM7z8C/PU4lrvWS6YyNoG9zeMxXJsHUR@kHrOG4mYV5qGBjYcIoTyqvSbHunfnWHvgvAR91H/tcAwRRckz@ysE50QigVZ3kOqmB9lnziT5soMyU0iRZJUjhnnbXHa18 "JavaScript (Node.js) – Try It Online")
This was very tricky, but I managed to abuse for loops a lot.
Explained:
```
x=>{ // declare function
for( //repeat:
s=x,i=0; //initiate string and looper to 0
++i<x.length; //repeat while i+1 is less than string length, and increment i at the same time
s=s.slice(1)+s[0] // loop string along by 1
)
for( //repeat:
y=0,h=s; //initiate looper, and string to use to check if matching
++y<s.length; //repeat while incremented y is less than string length (since there are only so many brackets)
h=h.replace('[]','')// remove a single occurrence of [] from h - if this is repeated enough and brackets match, it will eventually be empty.
)
if(!h)return s // if h is an empty string, this means s's brackets match, so return s. No point in dealing with invalid input since it will always be valid.
}
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), 47 bytes
```
->s{s.rotate (0..s.size).min_by{|r|s[0,r].sum}}
```
[Try it online!](https://tio.run/##JYxLCsMwDESv4k0ggUYkq67aiwhRLHAgi7TBciiu5bO7SruZzxuYeHBuy62NdykC8ZV8Cq6fAARk/YQBtvX54Fw0quB0iQRybLW23XXvHskRITokNHemaAjx7EbO9ZeM2JHfi3pd0APnFOQPWOeRu2ul2r4 "Ruby – Try It Online")
[Answer]
# [K (Kona)](https://github.com/kevinlawler/kona), 13 bytes
```
{(1+*>+\x)!x}
```
[Try it online!](https://tio.run/##LcoxDoAgDAXQ3VPULorEGFZM9CC1g4uQkOhKQjg7FnTq/@83zOG5z1Ium0ajp00fUfUxF2fTbDQSMO6LjbnzdmzNaNUlDxc4iHkQY1wBmYnqJSaJTSR@G1FV8f@zFUFU5QU "K (Kona) – Try It Online")
Uses -1 for [ and 1 for ].
A port of [Ad√°m's APL answer](https://codegolf.stackexchange.com/a/221310/75681)
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 28 bytes
```
(.*?)(((<)|(?<-4>>))+)$
$2$1
```
[Try it online!](https://tio.run/##K0otycxL/K@qEZIQHZtgY/dfQ0/LXlNDQ8NGs0bD3kbXxM5OU1NbU4VLxUjF8H8IUAVQ3f/oWK7Y2OhorujYaCDNBSSjgULR0SA@UAQkC2YBRQA "Retina 0.8.2 – Try It Online") Takes input as a string of `<`s and `>`s but link includes test suite which maps `[` and `]` for convenience. Explanation: This is a fairly direct application of .NET balancing groups. The `<` character is captured into group `$4`, which works like a stack. Meanwhile, `>` characters can only be matched by popping `<`s from the `$4` stack. This ensures that we take the first suffix of the input that does not contain a mismatched `>`. (It can of course have a mismatched `<` but that will be matched by a `>` in the prefix.) It then remains to exchange the prefix with the suffix.
[Answer]
# [PHP](https://php.net/) < 7 -F, 59 bytes
```
for($a=$argn;eval($a)!==null;)$a=substr($a,1).$a[0];echo$a;
```
[Try it online! (not working, PHP 7)](https://tio.run/##K8go@G9jXwAk0/KLNFQSbVUSi9LzrFPLEnOAPE1FW9u80pwca02gTHFpUnEJSI2OoaaeSmK0Qax1anJGvkqi9f//tbW11SBYXf0vv6AkMz@v@L@uGwA "PHP – Try It Online")
[Try with onlinephpfunctions (working PHP 5.6)](http://sandbox.onlinephpfunctions.com/code/1ae2ca44e65132d5718163fd5da26656281ae574)
Inspired by [Jo King's answer](https://codegolf.stackexchange.com/a/221299/90841). Works with `{}` braces instead of square ones.
[From the docs](https://www.php.net/manual/en/function.eval.php):
>
> eval() returns null unless return is called in the evaluated code, in which case the value passed to return is returned. As of PHP 7, if there is a parse error in the evaluated code, eval() throws a ParseError exception. Before PHP 7, in this case eval() returned false and execution of the following code continued normally.
>
>
>
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 89 bytes
This solution uses parenthesis rather than brackets.
```
for($n=$args){try{$n-replace"\(",",@("|iex *>0;break}catch{$n=-join$n[1..$n.Length+0]}}$n
```
[Try it online!](https://tio.run/##RY1da8IwFIbv@yuknM2TWUu9lozArgaDCrvsitR4anVdWtIUN2J@e5fIpnfvc96P03dn0kNDbTtBze1UdxpBcaj0YWDW6B8LaqmpbytJ8QfGSZwIjC9H@p49PWfrnabq08nKyMYH@fLUHRWoYpWmoNI3UgfTLLLSOVCTi8BILjASOEc2Z0kQjCH@SWTo6f/u6RZCDJ53760rY@hGLAJNgx9m4cHlwQZc8GLz/jIOpvvKdyeSpixyvSdN@1LYV9WPhsO2yMp1PpoA@Aj1TGyZc9e16Rc)
## Bonus [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), Regex-Based 129 127 bytes
Sure, the other way is shorter, but how often do I get a chance to use my balanced-bracket-matching regex?? Almost never!
```
for($n=$args;!($n-match'((\[(?=[^\]]*(?<s>\]))|\k<s>(?<-s>))+?(?(s)(?!)))*'-and$n-eq$Matches[0])){$n=-join$n[1..$n.Length+0]}$n
```
[Try it online!](https://tio.run/##RY5BT4NAEIXv/AqbrLJThNRzu4XEk4kGE4/D2iAspbVd6u4SD5TfjrNN1dv75s17M6fuWxnbqsNhYo0YpqYznGnBSrO1yxnJ@Fi6qg05L5CnAt8LKec8Xdl1IQHOxScpwtiuAaKUp9wCT2cAMA/jUteUV1/sxVcoiwuKDNQe77udZhofkoTp5FnprWujhRyZnsaAuUpkPMh4iDKEey@kRLxKlEj0Oyf6W0L0Hrn/qQujzwYQMKMsFYM/cL4dPEYCX98ee@u6Y/6xV5WTmJtaGVXLbHjSp94JtqGvl3nvPPA71txkGxjHS9v0Aw "PowerShell – Try It Online")
[Answer]
# JavaScript, 56 bytes
```
q=>q.map(async _=>q.push(q.shift())|eval(q+'')|alert(q))
```
[Try it online!](https://tio.run/##TYxbDoMgEEX/XUX/mElTNtDgRiakEopVQ0EETZq4d4rGPv7uua9BLSrqqR/Txfm7ycqaKQktau1d9NZw6x@g@eB71zR4rVqRg6gDf6oRVHw5fbptOM6xg8Bj17cJEFezKAvhzBiu@yMExJxEFHULxDmPEqsEjCQrn0VISXRIklTo4xf6loi2rKS/1c70tz3q@Q0 "JavaScript (Node.js) – Try It Online")
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), ~~87~~ 86 bytes
Inspired by [Zaelin Goodman](https://codegolf.stackexchange.com/a/221331/80745)
```
param($n)$n|% t*y|%{($n=($n|% S*g 1)+$n[0])}|?{try{$_-replace'\(',',(0'|iex;1}catch{}}
```
[Try it online!](https://tio.run/##RZDNboMwEITvfgorcup1SqTkjFAj9dRTqnKkKKJm81MRQo1RExk/OzVgqE8zs/vNSq5uv6jqMxZFx46R6apMZVdgpWBlu6R69WiXxtkIBh@vTnQrnlmZbFJh2xej1cOww1phVWQS@SfwgAew4e0F7@HWykzLs7G2s4TsgJAAOAhO/Qto70SfCgHA/1MQPgfh5DgZ83niFPiuoWdgPDu1wgC4wE9m528O1sV8bOjltOs1zOS47EgiqPsJQwirtbqUp4DhvUKpMacRZQfCFNZNoWvnntiR@i2SvMevTa1v1/3Xt9tOk73KUWGe7kzcSIl1DywmeEHX@OPsVL0I6VtZNbo/MRaG9GO@M1Hul233Bw "PowerShell – Try It Online")
The script returns all solutions.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
{:k[√∏o|«ì
```
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%7B%3Ak%5B%C3%B8o%7C%C7%93&inputs=%27%5D%5D%5D%5B%5D%5B%5D%5B%5B%5B%27&header=&footer=)
Takes as a string of `[]`.
```
{ # While...
√∏o # Removing until no change...
k[ # The string `[]`
: # From the top of stack
√∏o # Eventually yields a truthy value (i.e. non-balanced)
|«ì # Rotate left.
```
[Answer]
# [Python 2](https://docs.python.org/2/), 147 bytes
```
def f(u):
k=set()
for x in permutations(u):
s=''.join(x)
try:eval(s)
except:pass
else:k.add(s)
print "\n".join(k)
from itertools import*
```
[Try it online!](https://tio.run/##PYsxDsMgDEX3nMJiiemQoSNSbtIFNUalSTACt0pOTyFpu/n5vR93eXC4ljKRA4cvbTqYx0yCugPHCTbwASKl9SVWPId8NpDHvh@e7ANutQRJu6G3XTA3ou1OUUy0OTdaMpl5sNN02Jh8EFC3oM79rDuXeAUvlIR5yeDXyEkuxaFCrapGpTXieaHGCt9vhV@B2Ex1/8WB2HblAw "Python 2 – Try It Online")
Slow, permutation based approach
] |
[Question]
[
**Input**
A list of words separated by any number of spaces.
**Output**
A horizontal ASCII art graph, where the n-th line is composed by as many asterisks (`*`) as the n-th word is long.
**Example usage**
The `>` signals user input, you should not input it when testing the program.
```
> This is an example histogram of word length
****
**
**
*******
*********
**
****
******
```
---
```
> a aa aaa aaaa aaaaa
*
**
***
****
*****
```
---
```
> double space example
******
*****
*******
```
**Reference implementation**
In case of doubt over the specification, the output of your program should match exactly that of the below program under all inputs.
```
puts gets.chomp.split.map{|word| '*' * word.length}.join("\n")
```
[Answer]
# [Retina](https://github.com/mbuettner/retina), 5 + 3 = 8 bytes
```
+
\n
.
*
```
Every line goes in its own file, so I've added 1 byte for each additional file. Also, the `\n` should be replaced with an actual newline.
Each pair of lines is a pattern-replacement pair. `+` matches one or more spaces and replaces it with a newline. `.` matches any character *except* a newline, and it replaces that with a `*`. This is applied globally, so every character is replaced with a `*`.
[Answer]
# Pyth, 9 bytes
```
jm*ld\*cz
```
Explanation:
```
jm*ld\*cz
cz chop input on whitespace
m map to
ld length of the segment
* \* number of asterisks
j joined on newlines
```
[Answer]
# CJam, 10 bytes
```
r{,'**Nr}h
```
**How it works**:
```
r{ r}h e# This do-while loop basically reads all the whitespace separated tokens
e# from input. It separates the tokens on running lengths of whitespace
, e# Take the length of the token
'** e# Get a string of that many '*' characters
N e# Print a new line
```
[Try it online here](http://cjam.aditsu.net/#code=r%7B%2C%27**Nr%7Dh&input=This%20is%20an%20example%20histogram%20of%20word%20%20%20%20%20length)
[Answer]
## R - 33
```
write(gsub(".","*",scan(,"")),"")
```
where
* `scan(,"")` reads from stdin and splits on white-space into a character vector.
* `gsub(".", "*", ...)` replaces all characters into `*`.
* `write(..., "")` prints to stdout with "\n" as the default separator.
[Answer]
## Python 3, 43 bytes:
```
for w in input().split():print('*'*len(w))
```
Thanks to [@BetaDecay](https://codegolf.stackexchange.com/users/30525/beta-decay) for pointing out a syntax error.
Sample run:
```
> This is an example histogram of word length
****
**
**
*******
*********
**
****
******
```
(The string below is entered as a literal, rather than as text)
```
> 'example\twith\nweird\rwhite space'
*******
****
*****
**********
```
### Bonus: vertical histogram
Thanks to [@Caridorc](https://codegolf.stackexchange.com/users/18173/caridorc) for pointing out my error that made the bonuses have 1 to many rows.
```
l=[len(x)for x in input().split()]
for i in range(len(l)-1,0,-1):print(''.join(['*'if j>=i else' 'for j in l]))
```
Demo:
```
> This is an example histogram of word length
**
** *
** *
* ** **
* ** **
********
********
```
Bonus: vertical histogram (upside down)
```
l=[len(x)for x in input().split()]
for i in range(len(l)-1):print(''.join(['*'if j>i else' 'for j in l]))
```
Demo:
```
> This is an example histogram of word length
********
********
* ** **
* ** **
** *
** *
**
```
[Answer]
# R, 38 bytes (with some help in comments)
```
cat(gsub(" +|$","\n",gsub("\\S","*",x)))
```
**How it works**
* `gsub` replaces all no-spaces with `*`
* second `gsub` adds `\n` (newline) to the end of each element
* `cat` prints accordingly
[**Demo**](http://www.r-fiddle.org/#/fiddle?id=0E1emf4z&version=5)
[Answer]
## [><>](http://esolangs.org/wiki/Fish), ~~38~~ 37 Bytes
Curse you double space case \*shakes fish\*.
```
<v&0
>i:84*=?v0(?;67*o&1&
\ &0o?&a/
```
You can [try it online](http://fishlanguage.com/playground) (all you need to do is give input through the field near the bottom and then hit the `Give` button). Suggestions for further golfing are always welcome, especially ideas to remove those wasteful spaces in front of the second and third lines.
If you were allowed to print an additional newline for extra spaces, the code could be a whopping **27 bytes**:
```
>i:84*=?v0(?;67*o
^ oa<
```
---
## Explanation
Note: the order of the explanation will correspond to the pointer's location (so if the code is explained out of what one would consider order, it is because it is the order in which the pointer executes it).
**Line 1:**
```
<v&0
< redirects flow leftward
0 pushes 0 onto the stack
& pops 0 and puts it in the register
v redirects flow downward
```
**Line 2:**
```
>i:84*=?v0(?;67*o&1&
> redirects flow leftward
i: pushes input and then duplicates it
84* pushes 32 (the space character numerically)
=?v pops 32 and input and redirects flow downward if they're equal
0(?; pops input and terminates if input is less than 0*
67*o pushes 42 (asterisk) and prints it
&1& pushes register value and then puts 1 in the register
*in ><>, the command i returns -1 if no input is given
```
**Line 3:**
N.B. This line goes in reverse, so read right to left.
```
^ &0o?&a<
< redirects flow leftward
a pushes 10 (newline) onto the stack
o?& prints a newline if the register is not 0
&0 sets the register to 0
^ redirects flow upwards (back to the second line)
```
Basically, the program test to make sure the input (which is read one character at a time) is not a space and then prints an asterisk. It terminates if there is no input (the input value is -1). To make sure it doesn't print additional newlines, it uses the register value, which it either sets to 0 or 1. Because of the way I set it up, it doesn't care about the extraneous values pushed onto the stack (e.g. the value of the register when it sets it to `1` after printing an asterisk); they remain on the stack when the program terminates but do nothing.
I know it might be a bit confusing since I used `84*` and `67*` instead of `" "` and `"*"` respectively, but that was because I didn't feel like putting strings in the program for whatever reason.
[Answer]
# Javascript ES6
## Function, 46 chars
```
f=s=>s.replace(/\S/g,'*').replace(/\s+/g,'\n')
```
## Program, 55 chars
```
alert(prompt().replace(/\S/g,"*").replace(/\s+/g,"\n"))
```
[Answer]
# [Perl 5](https://www.perl.org/) + `-p040l012`, 7 bytes
```
s/./*/g
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX09fSz/9//@QjMxiBSBKVChJLS7R@5dfUJKZn1f8X7fAwMQgx8DQCAA "Perl 5 – Try It Online")
---
# [Perl 5](https://www.perl.org/) + `-p`, 15 bytes
```
y/ /
/s;s/./*/g
```
[Try it online!](https://tio.run/##K0gtyjH9/79SX0GfS7/YulhfT19LP/3//5CMzGIFIEpUKEktLtH7l19QkpmfV/xftwAA "Perl 5 – Try It Online")
[Answer]
# Gema, ~~11~~ 9 characters
```
=\n
?=\*
```
Sample run:
```
bash-4.3$ gema ' =\n;?=\*' <<< 'This is an example histogram of word length'
****
**
**
*******
*********
**
****
******
bash-4.3$ gema ' =\n;?=\*' <<< 'a aa aaa aaaa aaaaa'
*
**
***
****
*****
bash-4.3$ gema ' =\n;?=\*' <<< 'double space example'
******
*****
*******
```
[Answer]
# PHP 5.3, ~~55~~ ~~53~~ ~~51~~ 50 bytes
```
<?for(;$i<strlen($a);){echo$a{$i++}!=' '?'*':"
";}
```
**Usage:**
Call the Script and define a global variable ($a)
`php -d error_reporting=0 script.php?a="This is an example histogram of word length"`
**Output:**
```
****
**
**
*******
*********
**
****
******
```
[Answer]
# Java, 102 bytes
```
class R{public static void main(String[]a){for(String s:a)System.out.println(s.replaceAll(".","*"));}}
```
[Answer]
# Haskell, 31 bytes
```
putStr.unlines.map(>>"*").words
```
Usage example:
```
Main> putStr.unlines.map(>>"*").words $ "This is an example histogram of word length"
****
**
**
*******
*********
**
****
******
```
[Answer]
# CJam, 11 bytes
Competing for second place in CJam after @Optimizer found a clever 10 byte solution. This is a straightforward 11 byte solution:
```
lS%:,'*f*N*
```
[Try it online](http://cjam.aditsu.net/#code=lS%25%3A%2C'*f*N*&input=This%20is%20an%20example%20histogram%20of%20word%20length)
Alternate solution that uses a loop instead of the two maps, also 11 bytes:
```
lS%{,'**N}/
```
Explanation for first solution:
```
l Get input.
S% Split at spaces.
:, Apply length operator to each word.
'*f* Map each length to corresponding repetitions of '*.
N* Join with newlines.
```
[Answer]
# JavaScript (ES6), 37
```
f=s=>s.replace(/./g,m=>m<"!"?`
`:'*')
```
Shorter version using only one `replace`.
[Answer]
# J, 10 bytes
```
'*'$~$&>;:'This is an example histogram of word length'
****
**
**
*******
*********
**
****
******
```
Bonus: vertical (12 bytes)
```
|:'*'$~$&>;:'This is an example histogram of word length'
********
********
* ** **
* ** **
** *
** *
**
*
*
```
Bonus: flipped vertical (14 bytes)
```
|.|:'*'$~$&>;:'This is an example histogram of word length'
*
*
**
** *
** *
* ** **
* ** **
********
********
```
[Answer]
# Python 3, 72 bytes
A nice one liner :)
```
print(''.join(map(lambda x:"*"*len(x)+"\n"*int(x!=""),input().split())))
```
### Output:
```
>>> print(''.join(map(lambda x:"*"*len(x)+"\n"*int(x!=""),input().split())))
Hello world how are you?
*****
*****
***
***
****
```
There's a trailing newline here. If you want it without, you've got to add 5 bytes:
```
print(''.join(map(lambda x:"*"*len(x)+"\n"*int(x!=""),input().split()))[:-1])
```
[Answer]
# Julia, 50 bytes
```
s->print(join(["*"^length(w)for w=split(s)],"\n"))
```
This creates an unnamed function that takes a string as input and prints to STDOUT.
Ungolfed:
```
function f(s::String)
# Construct a vector of horizontal bars
bars = ["*"^length(w) for w in split(s)]
# Join the bars with newlines
j = join(bars, "\n")
# Print the result to STDOUT
print(j)
end
```
[Answer]
## JavaScript (ES5)
### Program, 54 chars
```
alert(prompt().replace(/\S/g,'*').replace(/ +/g,'\n'))
```
### Function, 60 chars
```
function(i){return i.replace(/\S/g,'*').replace(/ +/g,'\n')}
```
Example usage:
```
var h=function(i){return i.replace(/\S/g,'*').replace(/ +/g,'\n')},
d=document,g=d.getElementById.bind(d),i=g('i'),o=g('o')
i.onchange=function(){o.textContent=h(i.value)}
```
```
<input id="i"/>
<pre id="o"></pre>
```
[Answer]
## Matlab - 54 bytes
```
s=input('');o=repmat('*',1,numel(s));o(s==32)=char(10)
```
---
This runs from the console, will take a string in input from `stdin` and will output the horizontal word graph in `stdout`:
*Exemple:*
```
>> s=input('');o=repmat('*',1,numel(s));o(s==32)=char(10)
'This is an example histogram of word length'
o =
****
**
**
*******
*********
**
****
******
```
Or we could try to make some fancy shapes:
```
>> s=input('');o=repmat('*',1,numel(s));o(s==32)=char(10)
'a aa aaa aaaaaa aaaaaaaaaa aaaaaaaaaaa aaaaaaaaaa aaaaaa aaa aa a aa aaa aaaaaa aaaaaaaaaa'
o =
*
**
***
******
**********
***********
**********
******
***
**
*
**
***
******
**********
```
[Answer]
## Matlab / Octave, 75 bytes
Using an anonymous function:
```
@(s)char(arrayfun(@(n)repmat('*',1,n),diff([0 find([s 32]==32)])-1,'un',0))
```
Thanks to Hoki for spotting a mistake which prevented the last word from being detected.
Example use (Matlab):
```
>> @(s)char(arrayfun(@(n)repmat('*',1,n),diff([0 find([s 32]==32)])-1,'un',0)) % define function
ans =
@(s)char(arrayfun(@(n)repmat('*',1,n),diff([0,find([s,32]==32)])-1,'un',0))
>> ans('This is an example histogram of word length') % call function
ans =
****
**
**
*******
*********
**
****
******
```
Or [try it online](http://ideone.com/QuzT3C) (Octave).
[Answer]
# PowerShell, 35 31 Bytes
Pretty competitive for a change. Go go gadget unary operators. I also keep forgetting that parens on some functions, like the `-split` and `-replace` used here, are optional.
```
%{$_-split"\s+"-replace".","*"}
```
Called via pipeline input (equivalent to stdin for PowerShell):
```
PS C:\Tools\Scripts\golfing> "a aa aaa" | %{$_-split"\s+"-replace".","*"}
*
**
***
```
As a bonus, if we can instead use command-line arguments, we can get down to **20 Bytes** and have something that works both with and without a single-string as input:
```
$args-replace".","*"
PS C:\Tools\Scripts\golfing> .\horizontal-graph-word-length.ps1 "double space example"
******
*****
*******
PS C:\Tools\Scripts\golfing> .\horizontal-graph-word-length.ps1 double space example
******
*****
*******
```
[Answer]
# Javascript (ES6)
New solution (39 bytes):
```
s=>[...s].map(c=>c==' '?`
`:'*').join``
```
Regex solution (42 bytes):
```
s=>s.replace(/\S/g,"*").replace(/ +/g,`
`)
```
Non-regex solution (71 bytes):
```
s=>s.split(" ").map(v=>"*".repeat(v.length)).filter(a=>a!="").join(`
`)
```
These solutions define anonymous functions. Assign them to variables or call them like so:
```
(s=>s.replace(/\S/g,"*").replace(/ +/g,`
`))("[your string here]")
(s=>s.split(" ").map(v=>"*".repeat(v.length)).filter(a=>a!="").join(`
`))("[your string here]")
```
[Answer]
# SWI-Prolog, 40 bytes
```
a([A|T]):-(A=32,nl;put(42)),(T=[];a(T)).
```
Called with code strings, e.g. `a(`This is an example histogram of word length`).`
[Answer]
## STATA, 72 bytes
```
di _r(a)
token "$a"
while ("`1'")!=""{
di _d(`=length("`1'")')"*"
ma s
}
```
Ungolfed
```
display _request(a) //get input via prompt
tokenize "$a" //split a by spaces into the variables 1,2,...
while ("`1'")!=""{ //while the first variable is not empty
display _dup(`=length("`1'")')"*" //display "*" duplicated for every character in variable 1.
macro shift //move variable 2 to 1, 3 to 2, etc.
}
```
Note that this code does not work in the online interpreter and requires the non-free proprietary STATA interpreter.
[Answer]
# C++14, 107 106 bytes
```
#include<iostream>
main(){std::string s;for(;std::cin>>s;){for(char c:s)std::cout<<'*';std::cout<<'\n';}}
```
[Answer]
# K5, 31 bytes
```
`0:{(#x)#"*"}'f@&0<#:'f:" "\0:`
```
[Answer]
# O, 22 bytes
```
i' /rl{e{'.'*%p}{;}?}d
```
## Explanation
```
i Read the user input
' /r Split on spaces and reverse
l{ }d For each element
e ? If it's not empty
{'.'*% Replace every char with an asterick
p} And print it
{;} Else, just pop it off the stack
```
[Answer]
# Beam, 92 Bytes
This isn't a competitive answer at all and really quite late, but I've been playing around with Beam a bit lately and wanted to see if I could get it to do this. Finally got some success:)
```
'''''''>`++++++)v
vgLsP-(---`<''P'<
>rnp+v
>Sv>++v
(>`v+
H^ )+
^Sp`@p'<+
^ @++++<
```
```
var ITERS_PER_SEC = 100000;
var TIMEOUT_SECS = 50;
var ERROR_INTERRUPT = "Interrupted by user";
var ERROR_TIMEOUT = "Maximum iterations exceeded";
var ERROR_LOSTINSPACE = "Beam is lost in space";
var code, store, beam, ip_x, ip_y, dir, input_ptr, mem;
var input, timeout, width, iterations, running;
function clear_output() {
document.getElementById("output").value = "";
document.getElementById("stderr").innerHTML = "";
}
function stop() {
running = false;
document.getElementById("run").disabled = false;
document.getElementById("stop").disabled = true;
document.getElementById("clear").disabled = false;
document.getElementById("timeout").disabled = false;
}
function interrupt() {
error(ERROR_INTERRUPT);
}
function error(msg) {
document.getElementById("stderr").innerHTML = msg;
stop();
}
function run() {
clear_output();
document.getElementById("run").disabled = true;
document.getElementById("stop").disabled = false;
document.getElementById("clear").disabled = true;
document.getElementById("input").disabled = false;
document.getElementById("timeout").disabled = false;
code = document.getElementById("code").value;
input = document.getElementById("input").value;
timeout = document.getElementById("timeout").checked;
code = code.split("\n");
width = 0;
for (var i = 0; i < code.length; ++i){
if (code[i].length > width){
width = code[i].length;
}
}
console.log(code);
console.log(width);
running = true;
dir = 0;
ip_x = 0;
ip_y = 0;
input_ptr = 0;
beam = 0;
store = 0;
mem = [];
input = input.split("").map(function (s) {
return s.charCodeAt(0);
});
iterations = 0;
beam_iter();
}
function beam_iter() {
while (running) {
var inst;
try {
inst = code[ip_y][ip_x];
}
catch(err) {
inst = "";
}
switch (inst) {
case ">":
dir = 0;
break;
case "<":
dir = 1;
break;
case "^":
dir = 2;
break;
case "v":
dir = 3;
break;
case "+":
++beam;
break;
case "-":
--beam;
break;
case "@":
document.getElementById("output").value += String.fromCharCode(beam);
break;
case ":":
document.getElementById("output").value += beam+"\n";
break;
case "/":
switch (dir) {
case 0:
dir = 2;
break;
case 1:
dir = 3;
break;
case 2:
dir = 0;
break;
case 3:
dir = 1;
break;
}
case "\\":
switch (dir) {
case 0:
dir = 3;
break;
case 1:
dir = 2;
break;
case 2:
dir = 1;
break;
case 3:
dir = 0;
break;
}
break;
case "!":
if (beam != 0) {
switch (dir) {
case 0:
dir = 1;
break;
case 1:
dir = 0;
break;
case 2:
dir = 3;
break;
case 3:
dir = 2;
break;
}
}
break;
case "?":
if (beam == 0) {
switch (dir) {
case 0:
dir = 1;
break;
case 1:
dir = 0;
break;
case 2:
dir = 3;
break;
case 3:
dir = 2;
break;
}
}
break;
case "|":
switch (dir) {
case 0:
dir = 1;
break;
case 1:
dir = 0;
break;
}
break;
case "_":
switch (dir) {
case 0:
dir = 1;
break;
case 1:
dir = 0;
break;
}
break;
case "H":
stop();
break;
case "S":
store = beam;
break;
case "L":
beam = store;
break;
case "s":
mem[beam] = store;
break;
case "g":
store = mem[beam];
break;
case "P":
mem[store] = beam;
break;
case "p":
beam = mem[store];
break;
case "u":
if (beam != store) {
dir = 2;
}
break;
case "n":
if (beam != store) {
dir = 3;
}
break;
case "`":
--store;
break;
case "'":
++store;
break;
case ")":
if (store != 0) {
dir = 1;
}
break;
case "(":
if (store != 0) {
dir = 0;
}
break;
case "r":
if (input_ptr >= input.length) {
beam = 0;
} else
{
beam = input[input_ptr];
++input_ptr;
}
break;
}
// Move instruction pointer
switch (dir) {
case 0:
ip_x++;
break;
case 1:
ip_x--;
break;
case 2:
ip_y--;
break;
case 3:
ip_y++;
break;
}
if (running && (ip_x < 0 || ip_y < 0 || ip_x >= width || ip_y >= code.length)) {
error(ERROR_LOSTINSPACE);
}
++iterations;
if (iterations > ITERS_PER_SEC * TIMEOUT_SECS) {
error(ERROR_TIMEOUT);
}
}
}
```
```
<div style="font-size:12px;font-family:Verdana, Geneva, sans-serif;">Code:
<br>
<textarea id="code" rows="4" style="overflow:scroll;overflow-x:hidden;width:90%;">'''''''>`++++++)v
vgLsP-(---`<''P'<
>rnp+v
>Sv>++v
(>`v+
H^ )+
^Sp`@p'<+
^ @++++<
</textarea>
<br>Input:
<br>
<textarea id="input" rows="2" style="overflow:scroll;overflow-x:hidden;width:90%;">This is an example histogram of word length</textarea>
<p>Timeout:
<input id="timeout" type="checkbox" checked="checked">
<br>
<br>
<input id="run" type="button" value="Run" onclick="run()">
<input id="stop" type="button" value="Stop" onclick="interrupt()" disabled="disabled">
<input id="clear" type="button" value="Clear" onclick="clear_output()"> <span id="stderr" style="color:red"></span>
</p>Output:
<br>
<textarea id="output" rows="6" style="overflow:scroll;width:90%;"></textarea>
</div>
```
[Answer]
# [Vyxal](https://github.com/Lyxal/Vyxal) `j`, 7 bytes
```
⌈';vL×*
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%E2%8C%88%27%3BvL%C3%97*&inputs=This%20is%20an%20example%20%20histogram%20of%20word%20length%20note%20the%20double%20space&header=&footer=)
Vertical, 17 bytes
```
⌈';vL:G$×*v↲ÞTṘvṅ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%E2%8C%88%27%3BvL%3AG%24%C3%97*v%E2%86%B2%C3%9ET%E1%B9%98v%E1%B9%85&inputs=This%20is%20an%20example%20%20histogram%20of%20word%20length%20note%20the%20double%20space&header=&footer=)
Vertical flipped, 16 bytes
```
⌈';vL:G$×*v↲ÞTvṅ
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=j&code=%E2%8C%88%27%3BvL%3AG%24%C3%97*v%E2%86%B2%C3%9ETv%E1%B9%85&inputs=This%20is%20an%20example%20%20histogram%20of%20word%20length%20note%20the%20double%20space&header=&footer=)
] |
[Question]
[
### Instructions
Given an unknown input string `i` with a value of either *heads* or *tails*, return `1` for *heads* or `-1` for *tails* with the shortest code.
### Sample not golfed code (55b):
```
if(i == "heads"){
print(1);
}else{
print(-1);
}
```
### Sample golfed code (16b):
```
print("t">i||-1)
```
---
*Javascript was used for the example but it's **not** a requirement*. Sorry if it's too simple for most users, it can be improved.
[Answer]
## C, 18 bytes
Pretty easy, but let's do it just for fun...
```
puts("-1"+*i/8%2);
```
Given the string `char *i` it prints 1 for `heads` and -1 for `tails`, with trailing newline.
## Explanation
In C, `"-1" + 1` points to 1 character forward, so it is the same as `"1"`. Let's take a look at the first characters:
```
"heads"[0] = 'h' = 104 = 0b01101000
"tails"[0] = 't' = 116 = 0b01110100
```
If we count the bits from the rightmost one starting at zero, bit 3 is 1 in `heads` and 0 in `tails`: summing it to `"-1"` gives the right string. It looks like this:
```
"-1" + ((i[0] >> 3) & 1)
```
Now, substitute `i[0]` with `*i` and the right shift with the power-of-two division to save some bytes. Also remove useless parentheses:
```
"-1" + (*i / 8 & 1)
```
Now, `& 1` can be substituted with `% 2`. The character count is the same, but the modulus has higher priority, allowing to drop the parentheses. Remove the whitespace:
```
"-1"+*i/8%2
```
## Bonus
I think the shortest way to get an integer 1 or -1 (not a string) in C is:
```
18-*i/6
```
Explanation:
```
'h' = 104
't' = 116
('h' + 't') / 2 = 110
110 - 'h' = 6
110 - 't' = -6
(110 - 'h') / 6 = 1
(110 - 't') / 6 = -1
Apply distributive property (integer division):
18 - 'h' / 6 = 1
18 - 't' / 6 = -1
```
[Answer]
# Ruby, 8 (6 without output)
```
p ?t<=>i
```
Rocketship operator!
[Answer]
# CJam, 4 bytes
```
I'e#
```
Assumes that the variable `I` holds the input, since `i` isn't a valid identifier in CJam.
[Try it online.](http://cjam.aditsu.net/#code=%22heads%22%3AI%3B%20e%23%20Store%20input.%0AI'e%23%20%20%20%20%20%20%20e%23%20Execute%20code.%0AS%20%20%20%20%20%20%20%20%20%20e%23%20Push%20a%20space.%0A%22tails%22%3AI%3B%20e%23%20Store%20input.%0AI'e%23%20%20%20%20%20%20%20e%23%20Execute%20code.%0A "CJam interpreter.")
This is equivalent to the JavaScript code `I.indexOf('e')`.
[Answer]
## PHP - 11 Bytes
```
<?=1-$i^=F;
```
This works because `'tails' ^ 'F'` ‚Üí `'2'` and `'heads' ^ 'F'` ‚Üí `'.'`, which when typed as an integer is `0`.
You may test this solution (or any of the below) in the following way:
```
<?php foreach(['heads', 'tails'] as $i): ?>
<?=1-$i^=F;
endforeach; ?>
```
[Ideone Link](http://ideone.com/kLyO5M)
---
**Alternatives**
*15*: `<?=1-md5($i)%3;`
*16*: `<?=md5($i)[5]-5;`
*16*: `<?=-crc32($i)%5;`
[Answer]
# TI-BASIC, 9-10 bytes
```
cos(œÄ ≥inString(Ans,"t
```
Straightforward. "t" is in position 1 of "tails", but "t" is not in the string "heads", so inString( returns 1 for tails and 0 for heads.
If your calculator is in radian mode (as any mathematician's should be), it takes only nine bytes:
```
cos(πinString(Ans,"t
```
Note that TI calculators do not have named strings, so the input is in the calculator's answer variable. Also note that lowercase letters are two bytes each, so this solution actually takes less memory than than the word "heads".
[Answer]
# [Fission](http://esolangs.org/wiki/Fission), ~~26~~ 21 Bytes
```
O/';'1
"S@]_"-
R? <tL
```
Martin (and his excellent answer [here](https://codegolf.stackexchange.com/a/50858/31054)) convinced me to learn a new language, and what better place than a quick golf? This is almost certainly not optimal, but hey, it was fun! Once I feel good about it, I may provide some form of explanation if it is requested.
[Answer]
# x86-16 machine code, 8 bytes
As a callable function, input string at `DS:SI`, output in `AL`.
```
80 3C 74 CMP BYTE PTR[SI], 't' ; if 'h': CF = 1, if 't': CF = 0
1A C0 SBB AL, AL ; AL = AL - AL - CF (AL = -CF)
; if 't': AL = 0 and CF = 0
; if 'h': AL = -1 and CF = 1
1C FF SBB AL, -1 ; AL = AL - (-1) - CF
; if 't': AL = AL + 1 = 1
; if 'h': AL = AL + 0 = -1
C3 RET
```
### x86-16 machine code, IBM PC DOS, 17 bytes
Or as a standalone DOS COM executable. Input from command line, output to stdout.
```
00000000: b402 0826 8200 7a04 b22d cd21 b231 cd21 ...&..z..-.!.1.!
00000010: c3
```
**Unassembled:**
```
B4 02 MOV AH, 02H ; DOS API display char function
08 26 0082 OR DS:[82H], AH ; set parity flag from input
7A 04 JPE HEADS ; if even, heads - display just '1'
B2 2D MOV DL, '-' ; otherwise first display a '-''
CD 21 INT 21H ; output DL to console
HEADS:
B2 31 MOV DL, '1' ; display the '1'
CD 21 INT 21H ; output DL to console
C3 RET
```
**Explanation:**
Use the CPU's parity flag to determine if first char is an `'h'` (even number of binary `1`'s) or a `'t'` (odd number of binary `1`'s). This saves one byte over comparing the char in ASCII.
**Input/Output:**
[](https://i.stack.imgur.com/TqxaG.png)
[Answer]
## Python 2, 16 bytes
```
print(i<'t')*2-1
```
[Answer]
# Pyth - 4 bytes
---
```
xz"e
```
Run with [heads](https://pyth.herokuapp.com/?code=xz%22e&input=heads&debug=0) or [tails](https://pyth.herokuapp.com/?code=xz%22e&input=tails&debug=0). As `i` is `int` in Pyth, this uses `z` as the variable name, which contains any user input. It is equivalent to the Python `print(z.find("e"))`, so uses @Dennis's method.
[Answer]
# VBA (Excel), 12 bytes
Not a fantastic bit of golfing, but it's fun to try with VBA to get anywhere near to a proper programming language...
```
?13-asc(i)/6
```
i is the string, and it just exploits the ASCII value of the first character, divided by 6 and substracted from 13 to give 1 or -1. Very simple.
Example run in immediate window (10 extra bytes to set the input variable) :
```
i="Heads":?13-asc(i)/6
1
```
[Answer]
# C, 22 bytes
```
puts(*i>'h'?"-1":"1");
```
Credits goes to [@TheE](https://codegolf.stackexchange.com/users/40904/the-e) [for telling me about this](https://codegolf.stackexchange.com/questions/50270/quickgolf-heads-or-tails/50284#comment119324_50284)!
Explanation:
If the first character of the string is greater than `'h'`, the string `"-1"` is printed. Otherwise, the string `"1"` gets printed. Note that this approach comes with a trailing newline character.
---
Old version (25 bytes):
```
printf("%d",*i>'h'?-1:1);
```
Explanation:
If the first character of the string is greater than `'h'`, -1 is printed. Otherwise, 1 is printed.
[Answer]
# Tr: ~~17~~ 13 characters
(Or ~~14~~ 10 if you count only the arguments…)
```
tr -s ta-s -1
```
Sample run:
```
bash-4.3$ tr -s ta-s -1 <<< heads
1
bash-4.3$ tr -s ta-s -1 <<< tails
-1
```
Brief explanation:
`tr` stands for transliterate, that means, replaces each character of the input found in the first argument with character at the same position in the second argument:
```
tr ta -1 <<< tails # replaces t ⇢ -, a → 1
‚áí -1ils
```
If the first argument is longer, the characters without positional match in the second argument are replaced with second argument's last character:
```
tr tals -1 <<< tails # replaces t ⇢ -, a → 1, l → 1, s → 1
‚áí -1i11
```
When `-s` (`--squeeze-repeats`) option is used, successive characters which would be replaced with the same character are replaced at once:
```
tr -s tals -1 <<< tails # replaces t ⇢ -, a → 1, l+s → 1
‚áí -1i1
```
So if we enumerate all characters in “tails”, we get what we need:
```
tr -s tails -1 <<< tails # replaces t ⇢ -, a+i+l+s → 1
‚áí -1
```
Same for “heads”, but wee need to keep the “t” in front to consume the minus (characters sorted alphabetically for creepiness):
```
tr -s taedhs -1 <<< heads # replaces h+e+a+d+s ‚Üí 1
‚áí 1
```
Merging all uniques characters of “tails” and “heads” in a single first argument, keeping “t” in front leads to final solution:
```
tr -s tadehils -1 <<< tails # replaces t ‚Üí -, a+i+l+s ‚Üí 1
‚áí -1
tr -s tadehils -1 <<< heads # replaces h+e+a+d+s ‚Üí 1
‚áí 1
```
To avoid enumerating the characters, an interval in *from***-***to* format can be used instead.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 2 bytes
```
ae
```
[Try it online](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=YWU&input=ImhlYWRzIg)
[Answer]
# shell (portable/POSIX), 16 bytes
`expr $i : he - 1`
[Try It Online!](https://tio.run/##S0kszvhfnpGZk6pQlJqYopBprZCS/z@1oqBIQSVTwUohI1VBV8Hwf0p@Xur/DKCCYq6SxMycYi4A)
Thanks to [@StéphaneChazelas](https://unix.stackexchange.com/users/22565/st%c3%a9phane-chazelas) in [unix.stackexchange.com](https://unix.stackexchange.com/q/536172/265604)
Other solutions tried:
`echo $[30#$i%7-1] # 17 bytes but only in bash, zsh.` [Try It Online!](https://tio.run/##qyrO@F@ekZmTqlCUmpiikGmtkJL/PzU5I19BJdrYQFklU9Vc1zD2f0p@Xur/DKCKYq6SxMycYi4A)
Note: Using `dash` as a reasonable simile of a portable shell tester.
* `expr $i : he - 1` works by counting how many characters match `he` with `$i : he`. A `heads` match `2` and a `tails` match 0 (none).Then substracting `1` with `- 1`.
* `$[30#$i%7-1]` works by converting the string to an integer. The base 30 and the mod by 7 were selected to obtain a difference of 2 between `heads` and `tails`. Then subtracting 1 converts the numbers to `1` and `-1`.
Note that a `$[...]` is an archaic form of arithmetic expression `$((...))` valid only in some shells.
* `he=2;echo $[${i%a*}-1]` works by making a variable of some value and then using Arithmetic Expansion to expand that variable (from the text value). The `${i%a*}` converts `heads` to `he` and `tails` to `t` (that, as a variable, has a value of 0).
* `IFS=h;set $i;echo ${1:+-}1` works in two steps. Setting IFS to `h` breaks the unquoted `$i` in `set $i` into parts divided by the character `h`, `heads` is divided to `''` and `'eads'`, thus setting `$1` to null. `tail` is not divided by `h`, thus making `$1` equal to `tails`. Then, `${1:+-}` generates a `-` if the value of `$1` is non-null (as in `tails`) or nothing (as with a null `$1`). That sign (or nothing) is concatenated with `1`.
* `(IFS=h;set $i;echo $(($#*2-3)))` works in a similar way but use the number of parts (`$#`) that the string in `$i` got broken into.
[Answer]
# Python, 20 bytes
```
print(('h'in i)*2-1)
```
This returns `False` if it isn't, and `True` if it is. In python `False` and `0` are the same, and `True` and `1` are as well.
So:
```
True (1) * 2 -1 = 2-1 = 1
False (0) * 2 - 1 = 0-1 = -1
```
[Answer]
# Python 2, 17 bytes
```
print'-1'['t'>i:]
```
`'heads'` is less than `'t'`, so it evaluates to `True == 1`, and prints the string after the first character. `'tails'` is greater than `'t'`, so it evaluates to `False == 0` and the whole string is printed.
If we're doing this from the command line, with implicit printing, it just becomes:
```
'-1'['t'>i:]
```
...for 12 bytes, but it adds single quotes to the output.
[Answer]
# QBasic, 11 bytes
This has got to be the shortest piece of QBasic I've ever written.
```
c=i>"t
?c^c
```
**Explanation:**
The above is some pretty heavily golfed QBasic. Once the autoformatter gets through with it, it'll look like this:
```
c = i > "t"
PRINT c ^ c
```
The first line compares the string `i` with `"t"`. If `i` is `"heads"`, `i > "t"` is false and `c = 0`. If `i` is `"tails"`, `i > "t"` is true and `c = -1`. Yes, `-1` is the default value for boolean true in QBasic!
The second line maps `-1` to `-1` and `0` to `1` via a math trick: `(-1)^(-1) == 1/(-1) == -1`, and `0^0`, though technically mathematically undefined, returns `1`.
This code requires that `i` be explicitly declared as a string variable; otherwise, it would have to be `i$`. Full test program (tested on [QB64](http://qb64.net)):
```
DIM i AS STRING
DATA heads, tails
FOR x = 1 TO 2
READ i
c=i>"t
?c^c
NEXT x
```
[Answer]
# [Gaia](https://github.com/splcurran/Gaia), ~~5~~ 4 bytes
```
'eI(
```
Similar to [Dennis' CJam answer](https://codegolf.stackexchange.com/a/50271/87923), finds the index of `e` in the input string
Saved one byte since I didn't realise input was automatically used as an argument if there isn't enough stack values
# How it works
```
'e Push e
I Index of e in the the input. 2 if heads, 0 if tails
( Subtract One
Stack gets automatically outputted
```
[Try it Online!](https://tio.run/##S0/MTPz/Xz3VU@P//5LEzJxiAA)
[Answer]
# [Bash](https://www.gnu.org/software/bash/), 22
```
echo $[0x${1:1:1}/2-6]
```
Takes the 2nd letter (`e` or `a`) and interprets it as a hex digit (14 or 10), then divide by 2 and subtract 6 to get the right answers.
[Try it online!](https://tio.run/##S0oszvifpqFZ/T81OSNfQSXaoEKl2tAKCGv1jXTNYv/XcpVnZOakKhSlJqYo5GTmpVorpORzKQABREM1SKzWCiySpqAC4nGl5Oel/s8AaijmKknMzCnmAgA "Bash – Try It Online")
[Answer]
# [ed](https://en.wikipedia.org/wiki/Ed_(text_editor)), ~~27~~ ~~25~~ 21 bytes
**`ed`** gave me a headache. Finally figured it out with help from [`@ed1conf`](https://twitter.com/ed1conf/status/1161687587360313355) on twitter and some peeps on [`unix.se`](https://unix.stackexchange.com/questions/535595/ed1-script-with-multiple-search-replace). You can't just match things with `s/re/newtext/`, you have to prefix it with `g` otherwise **`ed`** packs a sad. It's like a grumpy 50 year old unix program saying "get off my lawn".
```
g/t/s//-
,s/\w\+/1
w
```
[Try it online!](https://tio.run/##S035/z9dv0S/WF9fl0unWD@mPEZb35CrnOv//5LEzJzi///yC0oy8/OK/@sWAwA)
***-2*** bytes by dropping the final `/`s
***-4*** bytes thanks to @manatwork (& whose `sed` answer i plagiarised)
*Old version:
`g/t/s//-
g/\w\+/s//1
wq
.`*
[Answer]
# [golflua](http://mniip.com/misc/conv/golflua/) 25 20 18
```
w(I.r():f'h'&1|-1)
```
Probably could be golfed some more by using some tricks that I'm not thinking about at the moment. (see [history](https://codegolf.stackexchange.com/posts/50290/revisions) for old version) Saved 5 chars by moving input to `write` and ignoring the `if` statement there. Two more chars were saved by ignoring the optional parenthesis on `find`. It does not check for failed conditions (i.e., input that isn't *heads* or *tails*).
A Lua equivalent would be
```
io.write(io.read():find('h') and 1 or -1)
```
[Answer]
# Haskell, 18 bytes
```
f('h':_)=1
f _= -1
```
Every string starting with the letter `h` is mapped to `1`, all others to `-1`.
[Answer]
# Sed: 16 characters
```
s/t/-/
s/\w\+/1/
```
Sample run:
```
bash-4.3$ sed 's/t/-/;s/\w\+/1/' <<< 'heads'
1
bash-4.3$ sed 's/t/-/;s/\w\+/1/' <<< 'tails'
-1
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 5 bytes
```
3-3⊃⍋
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P03hUdsEBWNd40ddzY96u0EC6iWJmTnF6lxAVkZqYkqxOgA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 3 bytes
```
'eI
```
[Run and debug it](http://stax.tomtheisen.com/#c=%27eI&i=%22heads%22%0A%22tails%22&m=2)
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 4 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
‚îî0Y.
```
[Run and debug it](https://staxlang.xyz/#p=c030592e&i=heads%0Atails&a=1&m=2)
It's the codepoint of the first character mod 7 minus 5.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 15 bytes
```
($args[1]-99)/2
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfmvkmZb/V9DJbEovTjaMFbX0lJT3@h/LReXSoWCrYJ6RmpiSrE6l5pKmoJDBVSsJDEzBy72HwA "PowerShell – Try It Online")
Takes input via splatting. Uses the `e` vs the `a` to do ASCII math
[Answer]
# [dc](https://www.gnu.org/software/bc/manual/dc-1.05/html_mono/dc.html), 8 bytes
```
?z2*1r-p
```
dc can't do anything meaningful with strings other than read them in and attempt to evaluate them. Doing this, "heads" outputs some warnings about unimplemented commands and empty stack, which we ignore, but importantly the stack remains empty. "tails" does almost the same with the important exception that the final "ls" loads a value from the s register to the stack.
We then use "z" to get the stack length and arithmetically fiddle to get the right answers.
[Try it online!](https://tio.run/##JYxNCoAgFAb37xQf4ipoUcsyOov5HihIRgZB0dntb5YzMJPNvrBziWVQZTzaqlnrpSjafYiCVSwjhll6cCI8iPMJ@nzd1X2GHWqB0v9FwRgD/XbiNEvxzyLTZkPMdAM "Bash – Try It Online")
[Answer]
# [Triangular](https://github.com/aaronryank/triangular), 10 bytes
```
F.~%.7/-_<
```
[Try it online!](https://tio.run/##KynKTMxLL81JLPr/302vTlXPXF833ub//5LEzJxiAA "Triangular – Try It Online")
Divides the ASCII value of a character input by 7. Subtracts the quotient from 15. Execution stops when the IP runs out of the program space. This works because Triangular can only manage integer division. Conveniently, "h" has a value of 104, which is 14 when integer divided by 7; "t" is 116, which is 16 when integer divided by 7.
Ungolfed/Explanation:
```
F
. ~
% . 7
/ - _ <
---------------------------------------------------------------
F - Push 15 to Top of Stack
~ - Read a character from input, push its value to ToS
7 - Push 7 to ToS
<_ - Change directions, then pop ToS-1 and ToS, push their integer quotient
- - Pop ToS-1 and ToS, push their difference
% - Print ToS as an integer
```
---
**Previous version (14 bytes):**
```
~\81|m/,!<.>i%
```
Read a character from input; if that character's ASCII value divided by 8 has a remainder, print -1, otherwise print 1.
[Answer]
## [Keg](https://github.com/JonoCode9374/Keg), ~~8~~ ~~12~~ 8 bytes
```
_d=2*1-.
```
[Try it online!](https://tio.run/##y05N//8/PsXWSMtQV@///5LEzJxiAA)
## Explanation (syntactically invalid)
```
_ Take input and discard the last item
d= If the top of the stack is d:
2* Re-set the top of the stack as 2
1- Decrement the top of the stack by 1
. Explicitly output the top of the stack
```
>
> -4 bytes thanks to manatwork
>
>
>
] |
[Question]
[
Given strings X and Y, determine whether X is a [subsequence](http://en.wikipedia.org/w/index.php?title=Subsequence&oldid=594253998) of Y. The empty string is regarded as a subsequence of every string. (E.g., `''` and `'anna'` are subsequences of `'banana'`.)
### Input
* X, a possibly-empty case-sensitive alphanumeric string
* Y, a possibly-empty case-sensitive alphanumeric string
### Output
* True or False (or equivalents), correctly indicating whether X is a subsequence of Y.
### I/O examples
```
X Y output
'' 'z00' True
'z00' 'z00' True
'z00' '00z0' False
'aa' 'anna' True
'anna' 'banana' True
'Anna' 'banana' False
```
### Criteria
* The shortest program wins, as determined by the number of bytes of source code.
### Example programs
* Several programs that could be adapted are in this [related posting](https://stackoverflow.com/q/6877249/1033647).
[Answer]
# [Perl 5](https://www.perl.org/), 17 bytes (+1?), full program
```
s//.*/g;$_=<>=~$_
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX19PSz/dWiXe1sbOtk4l/v//xLy8RK6kxDwgLOb6l19QkpmfV/xftwAA "Perl 5 – Try It Online")
Invoke with the `p` flag to the perl interpreter, as in `perl -pe 's//.*/g;$_=<>=~$_'`. Per [the established scoring rules when this challenge was originally posted](https://codegolf.meta.stackexchange.com/questions/273/on-interactive-answers-and-other-special-conditions), this flag costs one extra byte. Under [more recent rules](https://codegolf.meta.stackexchange.com/questions/14337/command-line-flags-on-front-ends), AFAICT, it may be free.
Either way, the input strings should be supplied on separate newline-terminated lines on stdin. Output (to stdout) will be `1` if the first input string is a substring of the second, or nothing at all if it's not.
Note that *both* input lines must have a newline at the end, or the program won't work correctly. Alternatively, you can add the `l` command line flag to the invocation to make perl strip the newlines; depending on the scoring rules in effect, this may or may not cost one extra byte. Note that using this flag will also append a newline to the output.
## Original version (snippet, 18 bytes / chars)
```
$x=~s//.*/g,$y=~$x
```
Input is given in the variables `$x` and `$y`, result is the value of the expression (in scalar context). Note that `$x` is modified in the process.
(Yes, I know using `$_` instead of `$x` would let me save four chars, but doing that in a snippet that feels a bit too cheesy for me.)
### How does it work?
The first part, `$x=~s//.*/g`, inserts the string `.*` between each character in `$x`. The second part, `$y=~$x`, treats `$x` as a regexp and matches `$y` against it. In Perl regexps, `.*` matches zero or more arbitrary characters, while all alphanumeric characters conveniently match themselves.
[Answer]
### Ruby, 32 characters
```
s=->x,y{y=~/#{[*x.chars]*".*"}/}
```
This solution returns `nil` if `x` isn't a subsequence of `y` and a number otherwise (i.e. ruby equivalents to `false` and `true`). Examples:
```
p s['','z00'] # => 0 (i.e. true)
p s['z00','z00'] # => 0 (i.e. true)
p s['z00','00z0'] # => nil (i.e. false)
p s['anna','banana'] # => 1 (i.e. true)
p s['Anna','banana'] # => nil (i.e. false)
```
[Answer]
## Haskell, ~~51~~ 37
```
h@(f:l)%(g:m)=f==g&&l%m||h%m;x%y=x<=y
```
Thanks to Hammar for the substantial improvement. It's now an infix function, but there seems to be no reason why it shouldn't.
Demonstration:
```
GHCi> :{
GHCi| zipWith (%) ["" , "z00", "z00" , "anna" , "Anna"]
GHCi| ["z00", "z00", "00z0", "banana", "banana"]
GHCi| :}
[True,True,False,True,False]
```
[Answer]
# [Python](https://www.python.org), 45 bytes
```
lambda a,b:{1,l:=iter(b)}>{c in l for c in a}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=XY3BCoMwDIbvPkVurUOh3obgYO_hJd1aLHSpuLqh4pPsIoztnXybWd3JHJL_-0jI61t3vnI0vXVRflqv0-OcWrzJKwImMh-yxOaF8arhMh5PwwUMgQXtGlgjjv8jeFbGKsjyujHkueYH9UDLDdWt5_FS2940V4wlwHohWLT2PQjRB0IMgEQYIIwFJRKu4rwXKO_Otl7ZLmhynkXbwx8)
Builds on [@qwatry's method](https://codegolf.stackexchange.com/a/217976) used in [@xnor's answer](https://codegolf.stackexchange.com/a/180287): `iter` consumes elements as they are searched for, so `c in l` "uses up" the character if it is found.
Some trickery lets us combine the `all` and the iterator assignment:
* `{c in l for c in a}` is a set comprehension which effectively deduplicates its contents, so it's always one of `{}`, `{False}`, `{True}`, or `{False, True}`
* `1` and `0` are equivalent to `True` and `False`
* The `>` operator tests if `{True, iter(b)}` is a strict superset of the result, which is true only if that result is `{}` or `{True}`, i.e. all the `c in l` expressions were true
* By including `l:=iter(b)` in the set, we can sequence the evaluation order correctly with minimal parentheses by reusing the set's `{}` grouping
* It also lets us use `>` instead of `>=` because the iterator will never be present in the boolean set
* Otherwise, `>=` would be necessary because `{True}` is not a strict superset of `{True}`
[Answer]
## Python (48 chars)
```
import re;s=lambda x,y:re.search('.*'.join(x),y)
```
Same approach as Howard's Ruby answer. Too bad about Python's need to import the regex package and its "verbose" `lambda`. :-)
[Answer]
# [Python 3.8 (pre-release)](https://docs.python.org/3.8/), 42 bytes
```
lambda a,b:''in[a:=a[a[:1]==c:]for c in b]
```
[Try it online!](https://tio.run/##XcqxDoMgFAXQWb@CDUgcMF0aEoZ@B2W4WI0k9kkItqk/T8XR5d2ce1/85Xml2z2mMplnWfD2LzB0XnMeyEIbWFjdO2MG7aY1sYEFYt6V7xyWkfW6bY5vM36wiEBxy0LKtokpUBaTOCYpC@cd47tSvD3vFUrtVUAFiFBR46AH4Swel@IP "Python 3.8 (pre-release) – Try It Online")
**[Python 3.8 (pre-release)](https://docs.python.org/3.8/), 48 bytes**
```
lambda a,b,j=0:all((j:=1+b.find(c,j))for c in a)
```
[Try it online!](https://tio.run/##XctBCsMgEAXQdTyFO2eoFEM3JeCi9@hmTCJR7ERC2tJc3sYss5nP@5/Jv3Wa@XbPS/H2WRK93ECStNPRmo5SAoidbS/u6gMP0OuI6OdF9jKwJCzfKaRRtp1o9h87fihB4PxeAVE0eQm8god9QixKaak2Y5Q47hnGbFVEFcRMFTV2OmI6isep@AM "Python 3.8 (pre-release) – Try It Online")
In Python 3.10+, we don't need parens around the walrus expression for [46 bytes](https://ato.pxeger.com/run?1=XYxBDoIwEEXXcIru2molZWdIuuAMbt1MgYYmdSCkaOQqbkiM3onb2CIb3czP-z9vHu_-7tsO56dR59fozeG4ZA4uugYCQgurZAHOMVsonRmLNauE5fvcdAOpiEUCfLN2t9a6huRFmgRRNVcIFvajZ5ynST9Y9MywMPHNmJcTpYLQSUqarvcfpJwiAUQARIgQI6AGhLUof4vv7w8).
**[Python 2](https://docs.python.org/2/), 48 bytes**
```
lambda a,b:re.search('.*'.join(a),b)>0
import re
```
[Try it online!](https://tio.run/##XctBCsMgEIXhdTyFu9EiYrsMpNB7dDO2Bi3JKNZSmstbzTKbeXw/TPoVH@lS5@leF1ztEzkqO2an3w7zwwvQJ9CvGEigVFZeDQtrirnw7OrXh8Xx88iG9jMFSp8iJBtSDlTELFqUsgIoDpsxwPZ7hDFbF2IHEmFHn0aLhHu4HcIf "Python 2 – Try It Online")
Copied from [this answer of Lynn](https://codegolf.stackexchange.com/a/180248/20260). The `>0` can be omitted if just truthy/falsey output is OK.
**[Python 2](https://docs.python.org/2/), 49 bytes**
```
def f(a,b):l=iter(b);print all(c in l for c in a)
```
[Try it online!](https://tio.run/##XcwxDsMgDAXQOZzCGyBloB1TZehRTAuKJctBiKpqLk8CmdLF3@9LdvqVZZV7re8QIRocvZ14phKy8faRMkkBZDYvIAGGuGboK9r6XYgD3CY1HFczSfoUY9VwPqlaj6A357Tq8x/ObU2IDSiCDS0OehTsxfNa7A "Python 2 – Try It Online")
A dazzling new method [introduced to me by qwatry](https://codegolf.stackexchange.com/a/217976/20260). The idea is that turning `b` into the iterator `l` will consume values whenever they are read. So, checking `c in l` will consume values left to right until it finds one that equals `c` or it reaches the end.
**[Python 2](https://docs.python.org/2/), 50 bytes**
```
f=lambda a,b:b and f(a[a[:1]==b[0]:],b[1:])or''==a
```
[Try it online!](https://tio.run/##XcuxCoMwGATgWZ8i228gQ@wYyNDnCBnux4qC/Q2SUurLp4mjyx3fwaVfXnZ5lDL7DW@eoGDYsYJMah4QENwYvedgo4uGw@ii3g8i71G@y7q91Oj6rn78KumTB9136VglD/VsWOtCZBSd1lJ/5R3Wnk1AA0TQ0KqSIbiG5234Aw "Python 2 – Try It Online")
**[Python 2](https://docs.python.org/2/), 50 bytes**
```
lambda a,b:reduce(lambda s,c:s[c==s[:1]:],b,a)==''
```
[Try it online!](https://tio.run/##XcuxDoMgEMbxWZ6CDUgYsCMJQ5/DOhyIkcReiWBMfXkKppPLffn9k4vfvHzwUWbzKiu87QQUpNWbn3bn@b8k6XQanDFp0P2oR2klCGMYK8cSVk97Tbr6ZQLGPXNBurgFzHzmNQpRGJOUnUoxct07lDqbABoAERraVFpAuMLzFn4 "Python 2 – Try It Online")
[Answer]
## Python, 59 characters
```
def s(x,y):
for c in y:
if x:x=x[c==x[0]:]
return x==""
```
I figured my answer would be better expressed in Python.
Edit: Added r.e.s.'s suggestions.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
⊆ᵈ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuZHHcuVSopKU5VqQKy0xJziVKXaciU9BaWHuzprH26d8P9RV9vDrR3//0dHKynpKFUZGCjF6kSDaXSegUEVhJuYCOQl5uUlQnggho5SUmJeIlTEEVUkFgA "Brachylog – Try It Online")
As with [this answer,](https://codegolf.stackexchange.com/a/180657/85334) `⊆` is a built-in predicate that declares a relationship between the input and output variables, and `ᵈ` is a meta-predicate that modifies it to declare that same relationship between the first and second elements of the input variable instead (and unify the output variable with the second element but as this is a decision problem that doesn't end up mattering here). `X⊆Y` is an assertion that X is a subsequence of Y, therefore so is `[X,Y]⊆ᵈ`.
This predicate (which of course outputs through success or failure which prints `true.` or `false.` when it's run as a program) takes input as a list of two strings. If input is a bit more flexible...
# [Brachylog](https://github.com/JCumin/Brachylog), 1 byte
```
⊆
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFSuVv2obcOjpuaHWzsedSxXKikqTVWqAbHSEnOKU5Vqy5X0FJQe7uqsfbh1wv9HXW3//0dHKynpKFUZGCjF6kSDaXSegUEVhJuYCOQl5uUlQnggho5SUmJeIlTEEVUkFgA "Brachylog – Try It Online")
Takes string X as the input variable and string Y as the output variable. Outputs through success or failure, as before. [If run as a full program,](https://tio.run/##SypKTM6ozMlPN/r//1FX2///Sol5eYlK/5WSEvOAUAkA) X is supplied as the input and Y is supplied as the first command line argument.
[Answer]
## GolfScript (22 chars)
```
X[0]+Y{1$(@={\}*;}/0=!
```
Assumes that input is taken as two predefined variables `X` and `Y`, although that is rather unusual in GolfScript. Leaves `1` for true or `0` for false on the stack.
[Answer]
## C (52 chars)
```
s(char*x,char*y){return!*x||*y&&s(*x-*y?x:x+1,y+1);}
```
[Test cases](http://ideone.com/kMU8Y)
[Answer]
# Burlesque (6 chars)
6 chars in Burlesque:
`R@\/~[`
(assuming x and y are on the stack. See [here](http://eso.mroman.ch/cgi/burlesque.cgi?q=%22anna%22%22banana%22R%40%5C%2F~%5B) in action.)
[Answer]
# C, 23:
```
while(*y)*x-*y++?0:x++;
```
result in \*x
<http://ideone.com/BpITZ>
[Answer]
## PHP, 90 characters
```
<?function s($x,$y){while($a<strlen($y))if($y[$a++]==$x[0])$x=substr($x,1);return $x=="";}
```
[Answer]
### Scala 106:
```
def m(a:String,b:String):Boolean=(a.size==0)||((b.size!=0)&&((a(0)==b(0)&&m(a.tail,b.tail))||m(a,b.tail)))
```
[Answer]
## CoffeeScript ~~112~~ ~~100~~ ~~95~~ 89
My first attempt at code golf... hope I don't shame my family!
```
z=(x,y)->a=x.length;return 1if!a;b=y.indexOf x[0];return 0if!++b;z x[1..a],y[b..y.length]
```
**Edit**: turns out Coffeescript is more forgiving than I thought with whitespace.
**Thanks to r.e.s. and Peter Taylor for some tips for making it a bit sleeker**
[Answer]
# C #, ~~70~~ ~~113~~ ~~107~~ 90 characters
```
static bool S(string x,string y){return y.Any(c=>x==""||(x=x.Remove(0,c==x[0]?1:0))=="");}
```
[Answer]
# Mathematica 19 17 27
`LongestCommonSequence` returns the longest non-contiguous subsequence of two strings. (Not to be confused with `LongestCommonSubsequence`, which returns the longest contiguous subsequence.
The following checks whether the longest contiguous subsequence is the first of the two strings. (So you must enter the shorter string followed by the larger string.)
```
LongestCommonSequence@##==#&
```
**Examples**
```
LongestCommonSequence@## == # &["", "z00"]
LongestCommonSequence@## == # &["z00", "z00"]
LongestCommonSequence@## == # &["anna", "banana"]
LongestCommonSequence@## == # &["Anna", "banana"]
```
True True True False
The critical test is the third one, because "anna" is contained non contiguously in "banana".
[Answer]
# PHP, 41 Bytes
prints 1 for true and nothing for false
```
<?=!levenshtein($argv[1],$argv[2],0,1,1);
```
If only insertions from word 1 to word 2 done the count is zero for true cases
[levenshtein](http://php.net/manual/en/function.levenshtein.php)
[Try it online!](https://tio.run/nexus/php#ZczBCoJAEAbgu09hW7AKE@x21ZIuPUE328MkUyvIKm55MHp2U9fEaE7D//H/cVLpyruVNWGmgzRlWwacA2@F4Mpfn@sneeDSIZrB729A/1eFaL98wsLOXcQe0RiccLk7xsCvaHDypR7/1A0rtBus7034Sg5dnOxXBTVkrH5QboJRUqnAPTsFAiTIMOoo0yW7GBa9uw8 "PHP – TIO Nexus")
## PHP, 57 Bytes
prints 1 for true and 0 for false
Creates a Regex
```
<?=preg_match(_.chunk_split($argv[1],1,".*")._,$argv[2]);
```
[Try it online!](https://tio.run/nexus/php#Zc9NDoIwEAXgPacg1aRgKiluQYkbT@AOm2YkhRqxNAVcYDw78ifBOMv3zbxkwkhLbaWFEZBIJ47RFhGMCW4oxcxenU0tLDKmfTSD3U2P9q9S2nz5BHk53wJ0CErBhMveISb4CgomX@rxT8diBuUaTPZ0X9GhDaO9NiLjD6i6L7iXyFrdeanzW@UMW7HPiE@Qt0Gux8kY7ZgbtCKRBbooFLzbDw "PHP – TIO Nexus")
[Answer]
# [Haskell](https://www.haskell.org/), 36 bytes
```
(a:b)%(c:d)=([a|a/=c]++b)%d
s%t=s<=t
```
[Try it online!](https://tio.run/##TYq9DsIgFIV3n@LmRhJINTI33sGncGgYbqlaIhIiTMRnF2nj0JzhO38zp@fN@1ol96MS0vaTIjnwh09kTde1btolkSmdKdcXuwAE8e1Chj0UF68uzyCFggERAA6ARWv8Y4kcAuM6XBZn2nHzaNC6rBw5NG2cqV979/xI9Whj/AE "Haskell – Try It Online")
---
**37 bytes**
```
(.map concat.mapM(\c->["",[c]])).elem
```
[Try it online!](https://tio.run/##TYtBCsMgEEX3PcUgLRhIghew0AN03UXiYiraSHUijSsPX6uhizCL9z7/z4Lb23hfrJwLHwNG0CtpTE3vfNbDdWKsn7RSXTcab0Lhl07aU0BHICF@HCU4Q3bx4dICtYT6AAA9sCwE@6NFJEK2F7dmqg4Piwoh8s4nUr2DqfLV1uNrK4OO8Qc "Haskell – Try It Online")
I think `mapM` postdates this challenge. If we can assume the characters are printable, we can do
**36 bytes**
```
(.map(filter(>' ')).mapM(:" ")).elem
```
[Try it online!](https://tio.run/##TYrBCsIwEETvfsWwKE1AJWchQj/AswftYS2JDSYhtDn1441p8VD28N7szMDTx3hfrH4WcQ6chHU@m1FcGzRSLp@buBCouvEmFHGQ2u4CuwiNNLqYscfs0t3lAbXEgwjAETQrRX8skWNkWot2sa4ON4sKpeaVL471NtaVb289v6dy6lP6AQ "Haskell – Try It Online")
---
**37 bytes**
```
(null.).foldr(?)
c?(h:t)|c==h=t
c?s=s
```
[Try it online!](https://tio.run/##TYqxCgIxEER7v2IJFgnokVpYDr/CQq9YozHBNRcusQl@uzF3WBxTvHnMOErPO3O1eKkyvJk71dmRb5Ps1cb00h2y@hhEh7lpwlRf5AMgxMmHDFsoPp58dmDhLAQA7EAUrcUfs1IIJJbhOLehHVePBq3LwiuFllUb6tdYpkeqexPjDw "Haskell – Try It Online")
[Answer]
## JavaScript (no regex), 45 bytes
```
y=>x=>(i=0,[...y].map(c=>c==x[i]&&i++),!x[i])
```
Should be called like
```
f(haystack)(needle)
```
[Answer]
# C - 74 71 64
This doesn't beat Peter Taylor's solution, but I think it's pretty fun (plus, this is a complete working program, not just a function)
```
main(int c,char**v){for(;*v[1]!=0;++v[1])v[2]+=*v[1]==*v[2];return*v[2];}
```
---
```
main(int c,char**v){for(;*v[1];++v[1])v[2]+=*v[1]==*v[2];return*v[2];}
```
---
```
main(c,v)char**v;{while(*v[1])v[2]+=*v[1]++==*v[2];return*v[2];}
```
And ungolfed:
```
main(int argc, char** argv){
char * input = argv[1];
char * test = argv[2];
// advance through the input string. Each time the current input
// character is equal to the current test character, increment
// the position in the test string.
for(; *input!='\0'; ++input) test += *input == *test;
// return the character that we got to in the test string.
// if it is '\0' then we got to the end of the test string which
// means that it is a subsequence, and the 0 (EXIT_SUCCESS) value is returned
// otherwise something non-zero is returned, indicating failure.
return *test;
}
```
To test it you can do something like:
```
./is_subsequence banana anna && echo "yes" || echo "nope"
# yes
./is_subsequence banana foobar && echo "yes" || echo "nope"
# nope
```
[Answer]
## Python, ~~66~~ ~~62~~ ~~59~~ 58 chars
Kind of a fun solution, definitely a neat problem.
```
def f(n,h,r=0):
for c in h:r+=n[r:r+1]==c
return r==len(n)
```
[Answer]
## Ruby ~~32~~ ~~30~~ 28
```
f=->a,b{b.match a.tr'','.*'}
```
This will return `MatchData` instance if `a` is subsequence of `b` or `nil` otherwise.
**Old version that find substring instead of subsequence**
## Ruby 15
```
f=->a,b{!!b[a]}
```
Using `String#[](str)` method that returns `str` if `str` is a substring of `self` and `!!` to return `Boolean` if returned value can be usable as boolean (and don't need to be `true` or `false`) then it can be only 13 chars:
```
f=->a,b{b[a]}
```
It will return `nil` if `a` is not a substring of `b`.
[Answer]
# SWI-Prolog, SICStus
The built-in predicate [sublist/2](http://www.swi-prolog.org/pldoc/doc_for?object=sicstus_lists%3asublist/2) of SICStus checks whether all the items in the first list also appear in the second list. This predicate is also available in SWI-Prolog via compatibility library, which can be loaded by the query `[library(dialect/sicstus/lists)].`.
Sample run:
```
25 ?- sublist("","z00").
true.
26 ?- sublist("z00","z00").
true .
27 ?- sublist("z00","00z0").
false.
28 ?- sublist("aa","anna").
true .
29 ?- sublist("anna","banana").
true .
30 ?- sublist("Anna","banana").
false.
```
The byte count can technically be 0, since all we are doing here is querying, much like how we run a program and supply input to it.
[Answer]
# [Red](http://www.red-lang.org), 82 bytes
```
func[x y][parse/case y collect[foreach c x[keep reduce['to c 'skip]]keep[to end]]]
```
[Try it online!](https://tio.run/##bckxDoMwDEDRnVNYWRibuVuv0NXy4DqOikBJlIAEXD6QpQKp438/q6tvdUidf0L1SxBcYSNMnIs@hIvCBhKnSWVGH7OyfEFgxVE1QVa3iGI/x9P6Mg6JqA08QYMjopryEGbwYAyY3VrT/aDVf7N2vyLzaRwCX60lmA8Hvvnr5vUA "Red – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 3 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
æQà
```
[Try it online](https://tio.run/##yy9OTMpM/f//8LLAwwv@/09KzANCrsS8vEQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/8PLAg8v@K/zPzpaSUlHqcrAQClWRyEazMDgGhhUQfmJiUBuYl5eIpQLYukoJSXmJcKEHFGFYgE).
Or alternatively:
```
æså
```
[Try it online](https://tio.run/##yy9OTMpM/f//8LLiw0v//09KzANCrsS8vEQA) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfWXC/8PLig8v/a/zPzpaSUlHqcrAQClWRyEazMDgGhhUQfmJiUBuYl5eIpQLYukoJSXmJcKEHFGFYgE).
With both programs the first input is \$Y\$ and the second input is \$X\$.
**Explanation:**
```
æ # Get the powerset of the (implicit) input-string `Y`
Q # Check for each if it's equal to the (implicit) input-String `X`
à # And check if any are truthy by taking the maximum
# (after which this result is output implicitly)
æ # Get the powerset of the (implicit) input-String `Y`
s # Swap to take the (implicit) input-String `X`
# (could also be `I` or `²` to simply take input)
å # Check if this string is in the powerset-list of strings
# (after which this result is output implicitly)
```
[Answer]
# x86-16 machine code, ~~12~~ 10 bytes
**Binary:**
```
00000000: 41ac f2ae e303 4a75 f8c3 A.....Ju..
```
**Unassembled listing:**
```
41 INC CX ; Loop counter is 1 greater than string length
SCAN_LOOP:
AC LODSB ; load next char of acronym into AL
F2 AE REPNZ SCASB ; search until char AL is found
E3 03 JCXZ DONE ; stop if end of first string reached
4A DEC DX ; decrement second string counter
75 F8 JNZ SCAN_LOOP ; stop if end of second string reached
DONE:
C3 RET ; return to caller
```
Callable function. Input: `Y` string pointer in `SI`, length in `CX`. `X` string pointer in `DI`, length in `DX`. Output is `ZF` if `Truthy`.
**Example test program:**
This test program uses additional PC DOS API I/O routines to take multi-line input from `STDIN`.
[](https://i.stack.imgur.com/KLrYN.png)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), ~~18~~ 17 bytes
```
FηF⁼ι∧θ§θ⁰≔Φθμθ¬θ
```
[Try it online!](https://tio.run/##HYg7DoQwDAV7TuHSlkCip6IAaRvEFbzhFynrKB/Q3t4E5hXzNObgaDw71c1HwIPg9RBOdgltDb0sGIryR5b1/9yWCtCnZHfB0bq8xif/qIZAXTVHKxknnzEQdaoswtWXpUyby90 "Charcoal – Try It Online") Link is to verbose version of code. Uses Charcoal's default Boolean output of `-` for true, nothing for false. Explanation:
```
Fη
```
Loop over the characters of `Y`.
```
F⁼ι∧θ§θ⁰
```
See if this character is the next character of `X`.
```
≔Φθμθ
```
If so then remove that character from `X`.
```
¬θ
```
Were all the characters of `X` consumed?
[Answer]
# [Factor](https://factorcode.org/) + `math.combinatorics`, 19 bytes
```
[ all-subsets in? ]
```
[Try it online!](https://tio.run/##Zc@xCsIwGATgPU9xzW7JrKA4iYtLcRKHP6HBQJuW5newpc8eQ2ul4o33ccNZMtx08VqcL6ctauJHbppaO0@pdiYglBzQdiXzq@2cZ1AITep3QgwCKQOkhOyVkhjxSQZebII1J8MvKtUvmsEuRpSIvKfV8GtTLTV5mn1lx3@zYhTxBqqqTXjq6ZHzB9yjnd/sa2qRxzc "Factor – Try It Online")
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 2 bytes
```
iS
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m708I7E4OzUnZ8FNlczcgvyiEoXC0sSczLTM1BSFgKLUnNKUVC6oRABXte7S0pI0XYtFmcEQxs3purVcXLmJmXkKtgop-VwKCgVFCioKmcEKSol5eYlKCkpJiXlAqIQsAxStMjBAEQLxMUUTQQaAzcFUa2BQharYEWKfE8Q-iPMWLIDQAA)
So this is a builtin. There are actually a couple of builtins. There's also `fiS` which is the same function but the arguments flipped, there `iSW eq` which how `iS` is defined internally. There's `fe<ss` which gets all subsequences of `y` and checks if `x` is among them. There's `ap eq<lSW` which tests if the longest common subsequence is equal to the second element.
But these are no fun. Let's have a true no builtins solution
# Regex based, 17 bytes
```
pP<rXx<ic".*"<m p
```
Also
```
pP<rXx<ic".*"<!<p
```
This works like all the other regex answers here. It adds `.*` between items and then matches a regex.
# Parser based, 15 bytes
```
pP<mF(aK h'<χ)
```
This works similarly to the regex answer. It replace every character in the string with a parser that matches anything ending in that character. It then sequences all the parsers and checks if there is any partial matches.
It's cheaper than the regex which is a little surprising.
# Reflections
The regex answer is the one with the most room for improvement.
* There should be functions that build and apply regexes all in one. It's silly to have to build and then apply the regex separately. This would save 3 bytes on the regex solution
* Hard to imagine a situation in which `<!<` is going to be useful. Here we can see it's not saving anything. Maybe this should be shortened, the docs should have some info about when it is useful.
* There should be more versions of `ic` and `is`. Some that add copies to the outside, and a versions that are mapped with pure like the regex answer.
With the above changes the regex answer could look like
```
pPX<icp".*"
```
The only other suggestion I have is that *maybe* `aK h'` should get a synonym. It's basically "ends with", which seems like a concept that might come up again.
] |
[Question]
[
# Challenge
Given a string of any length which contains only digits from `0` to `9`, replace each consecutive run of the digit `0` with its length.
## Test Cases
1. `1234500362000440` → `1234523623441`
2. `123450036200044` → `123452362344`
3. `000000000000` → `12`
4. `0123456789` → `1123456789`
5. `1234567890` → `1234567891`
6. `123456789` → `123456789`
7. `010203004050` → `11121324151`
## Note
The shortest answer in bytes wins as per [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") rules
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 6 bytes
```
0+
$.&
```
[Try it online!](https://tio.run/##K0otycxL/P/fQJtLRU/t/39DI2MTUwMDYzMjAwMDExMDLjQBLgMkwGUAljUzt7DkgrMMEEygvIGRgTFQn4GpAQA "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Unary to decimal conversion.
[Answer]
# JavaScript, 31 bytes
```
s=>s.replace(/0+/g,x=>x.length)
```
[Try it online!](https://tio.run/##BcHhDkAgEADg16khJ/Evz6LlCrtVKzNvf77vdq9rvl7lGVI@kIPlZremKhZyHsUI3Rj7z26fIkzxOSX7nFomVJSjCGKf9GwWgHnVAGAM7FLyDw)
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 7 bytes
-1 byte by jezza\_99 / DLosc
```
aR+X0#_
```
Wow pip is really good at regex
[Try It Online!](https://dso.surge.sh/#@WyJwaXAiLCIiLCJhUmAwK2AjXyIsIiIsIjEyMzQ1MDAzNjIwMDA0NDAiLCIiXQ==)
```
aR+X0#_
aR+X0 Replace all occurrences of (regexified zero with a +)
#_ with it's length
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 7 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
r+iT Èl
```
[Try it here](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=citpVCDIbA&input=IjEyMzQ1MDAzNjIwMDA0NDAi)
```
r+iT Èl :Implicit input of string
r :Replace
+i : "+" prepended with
T : 0, giving the RegEx /0+/g
È : Pass each match through a function
l : Length
```
[Answer]
# [QuadR](https://github.com/abrudz/QuadRS), 5 bytes
```
0+
⍵L
```
[Try it online!](https://tio.run/##KyxNTCn6/99Am@tR71af//8NjYxNTA0MjM2MDAwMTEwMuNAEuAyQAJcBWNbM3MKSC84yQDCB8gZGBsZAfQamBgA "QuadR – Try It Online")
`0+` Replace any runs of zeros
`⍵L` with the match Length
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 7 bytes
```
ĠṠƛ0cßL
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwixKDhuaDGmzBjw59MIiwiIiwiXCIwMDExMTFcIiJd)
## Explained
```
ĠṠƛ0cßL
Ġ # Group on consecutive items
Ṡ # join each into a single string
ƛ # To each group:
0c # if it contains 0:
ßL # push the length of the string
# the s flag joins into a single string
```
An alternate 8 byter that uses regex match replacement
```
‛0+$⁽Løṙ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLigJswKyTigb1Mw7jhuZkiLCIiLCJcIjEwMDAwMDAwMVwiIl0=)
## Explained
```
‛0+$⁽Løṙ
‛0+ # The string "0+"
$ # pushed under the input
⁽L # a function object that returns the length of its argument
øṙ # replace instances of runs of 0 with their length
```
[Answer]
# ><>, 55 bytes
```
i:'0'= ?v>:0(?;o
='0':i<1<\n$v?
\+1~ /
```
[Try it](https://mousetail.github.io/Fish/#eyJ0ZXh0IjoiaTonMCc9ID92PjowKD87b1xuPScwJzppPDE8XFxuJHY/XG4gICAgICBcXCsxfiAgL1xuICAgICAgICAgIiwiaW5wdXQiOiIxMDAxIiwic3RhY2siOiIiLCJtb2RlIjoibnVtYmVycyJ9)
[Answer]
# [Python 3](https://docs.python.org/3/), ~~91~~ 90 bytes
```
lambda x:''.join(l>"0"and l or f'{len([*g])}'for l,g in groupby(x))
from itertools import*
```
[Try it online!](https://tio.run/##dcuxDsIgFIXh3ae46QI0xlxLdTDRF1EHmhbEAJcgJm2Mz46MOnjG/8uJS75RkEUfL8UpP4wK5gNjmzvZwN2pwUaFERxQAs1ebgr83JqreDNdi1sbsAFMomccFj4LsdKJPNg8pUzkHmB9pJTbEpMNmWvOtp3sd4hy3yFi3yOrn3/4Y/i1CuUD "Python 3 – Try It Online")
*-1 byte thanks to The Thonnu*
I use the `itertools` module's `groupby` function to group consecutively.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
0ÃηRāR:
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f4HDzue1BRxqDrP7/NzQyNjE1MDA2MzIwMDAxMQAA "05AB1E – Try It Online")
* -6 thanks to Kevin Cruijssen
#### Explanation
```
0ÃηRāR: # Implicit input
0Ã # List intersection with [0]
ηR # Reversed prefixes
āR # Reversed length range
: # Infinite replacement
```
Previous 13 byte answer
```
.γ}εD0.åig}}J # Implicit input
.γ} # Group by consecutive items
ε } # For each group:
D # Duplicate the group
0.åi } # If 0 is in the group:
g # Push its length
J # Join everything into a single string
```
[Answer]
# [R](https://www.r-project.org), ~~64~~ ~~58~~ 57 bytes
*Edit: -1 byte thanks to [@Dominic van Essen](https://codegolf.stackexchange.com/users/95126/dominic-van-essen)*.
```
\(x){regmatches(x,t)=Map(attr,t<-gregexpr("0+",x),"m")
x}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=ddBLCsIwFAVQnLqKEAdJMMLLp7aCXYI7cFKkrROx1BQC4kqcVMFF6WqMTf23bxLCPQk3OZ7K-pzFl8pkk-g6W1LL9mWabxKzWqc7arlh8SIpaGJMyc18krswtUVJMYwxt4zjDWZDe_AX3AZhRomQSgcAaioBQGsgbIS2lSkqg2LkU-lCpbUgw39PUK9vOHwMQW5-uEfNsWkYzRryi97pq8BjB534mYpv3Noe3LYACco9CoKuqq6GUFKLQBD_f3Xt1zs)
`R` has some weird string manipulation functions...
[Answer]
# [Raku](https://raku.org/), 18 bytes
```
{S:g[0+]=$/.chars}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OtgqPdpAO9ZWRV8vOSOxqLj2f3FipYKSSryCrZ1CdZqCSnytkkJafpGCjaGRsYmpgYGxmZGBgYGJiYECmoCCARJQMADLmplbWCrAWQYIJlDewMjAGKjPwNTA7j8A "Perl 6 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 16 bytes
```
s/0+/length$&/eg
```
[Try it online!](https://tio.run/##K0gtyjH9r6xYAKQVdAv@F@sbaOvnpOall2SoqOmnpv//b2BoYGRgbGBgYmBqAAA "Perl 5 – Try It Online")
[Answer]
# [Vim](https://github.com/DJMcMayhem/V), 28 bytes
`:s/0\+/\=len(submatch(0))/g`
`Enter`
[Try it online!](https://tio.run/##K/v/36pY3yBGWz/GNic1T6O4NCk3sSQ5Q8NAU1M/nev/f0MjYxNTAwNjMyMDAwMTEwMkAAA "V (vim) – Try It Online")
We cannot use `0*` because it matches the empty string between digits.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 8 bytes
```
(0+)
$.1
```
[Try it online!](https://tio.run/##K0otycxL/P9fw0Bbk0tFz/D/fwNDAyMDYwMDEwNTAwA "Retina 0.8.2 – Try It Online")
### How it works
Match runs of zeros (`0+`), capture each match in a group (`( )`), replace it with the length of the most recent capture (`$.1`).
[Answer]
# [><>](https://esolangs.org/wiki/Fish), 28 bytes
```
0i:"0"=?v{:?n}ol?!
~1+00. >
```
[Try it online!](https://tio.run/##S8sszvj/3yDTSslAyda@rNrKPq82P8dekavOUNvAQE9Bwe7/f0MjYxNTAwNjMyMDAwMTEwMA "><> – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 16 bytes
```
gsub /0+/,&:size
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72kqDSpclm0km6BUuyCpaUlaboWG9KLS5MU9A209XXUrIozq1IhwlDZBXsNjYxNTA0MjM2MDAwMTEwMuAwMDYwMjIFsA1MDiCIA)
[Answer]
# [Python](https://www.python.org), ~~62~~ 57 bytes
```
lambda n:re.sub("0+",lambda s:str(len(s[0])),n)
import re
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vweI025ilpSVpuhY3LXMSc5NSEhXyrIpS9YpLkzSUDLSVdKCCxVbFJUUaOal5GsXRBrGamjp5mlyZuQX5RSUKRakQA24x8hYUZeaVaKRpqBsaGZuYGhgYmxkZGBiYmBioa9raQgSNgGLGJiaG6ppcuFRjKEZWa4AEoApRpMH6zMwtLCGSSFw0-0CCSO4CcTEdhTAImzkGhgZGBsZAJxuYQk0C2mdobGRiaAo0ChIqCxZAaAA)
-5 bytes thanks to @xnor
Regex solution, port of [@mathcat's Pip answer](https://codegolf.stackexchange.com/a/255826/110555)
[Answer]
# Bash - ~~181~~ 158 chars
*Edit 1: I used [this trick](https://codegolf.stackexchange.com/a/25802/116162) for the `for` loop, remove whitespace, condence an `if` statement*
```
n=0;for ((i=0;i<${#1};i++));{ c="${1:$i:1}";if [ $c = '0' ]; then ((n++)); else [ $n -ne 0 ] && { echo -n $n;n=0;};echo -n $c;fi;};[ $n -ne 0 ] && echo -n $n
```
## Explanation
```
# a counter of how far into a sequence of zeros we are
# this is zero if we're not in a 'zero-sequence'
n=0
# iterate over all the characters
# $1 is the first function argument ($0 would be the script name)
for (( i=0; i<${#1}; i++ )); do
# get the current char
c="${1:$i:1}"
# if it is a zero, then increment the counter
if [ $c = '0' ]; then
((n++));
# if it is NOT a zero
else
# if a zero sequence is over (given that the counter is
# not equal to zero and the current char isn't zero)
if [ $n -ne 0 ]; then
# print the number of zeros in the sequence,
# and reset the counter to zero
echo -n $n;
n=0;
fi;
echo -n $c;
fi
done
# check if there was a zero sequence terminating the string,
# as we wouldn't otherwise check as there wouldn't be a non-zero
# char initiating the check
if [ $n -ne 0 ]; then echo -n $n; fi
```
I referred to [this SO answer](https://stackoverflow.com/a/10552175/20827475) for how to iterate over a string in Bash and [this AU answer](https://askubuntu.com/a/385532/1659062) for a short way to increment a variable
[Answer]
# Excel VBA, ~~100~~ 77 bytes
Saved 23 bytes thanks to a translation by [Taylor Raine](https://codegolf.stackexchange.com/questions/255822/replace-0s-in-a-string-with-their-consecutive-counts/255867?noredirect=1#comment572654_255867)
```
For i=2^15-1To 1Step-1:[B1]=i:[A1]=[Substitute(A1,Rept(0,B1),B1)]:Next:[B1]="
```
Input is in the cell `A1` of the active sheet. Output is in the same cell. The code is run from the immediate window in VBA. The only clever bit is that Excel only allows 32,767 characters in a cell and counting down from there is less bytes than counting down from the length of the input.
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 25 bytes
```
{,/$(.'x)|#'x:(&~=':x)_x}
```
[Try it online!](https://ngn.codeberg.page/k#eJxtkN1OgzAYhs97Fc1chCV2LQXmhHjkLXi2LI7UAs0QJu20y3SHXoCX6JVYfuRnjqN+7/f0LXni4HiDp/bc0rOPK0sH9vXp3gr07El/AqCC43R1OJVBDCHU4abYhvYmjkQW6vAQlrN1xawmDnU9nxB3QQkhnkcmYRNRk7ie50zWF6gzqGHI4KuBNq7Jxe3yrgr7oe+txu7danDOlsPdXymhxDW/Qvz6pul1XOo5fnUVAAxSpXYywJgVzzwpsnguVcS2XLM0yhM+Z8ULft1zqUSRS0x9f0kpLvkuixhHRCKRowhJVYo8Qe9CpUilXJSIGZqzvRJv3Jz3uZIAPJoW+BBJbs7GNDwXCn++vuFI6SXsH1VDQ6Ut0eSdjibtxr66ltq31lrH2/Gy7e21ts2dWAB+AUx2mz8=)
* `x:(&~=':x)_x` split the input where it changes, and reassign to `x`
* `(.'x)|#'x` take the maximum of the chunk of input (converted to its corresponding integer) and its count
* `,/$` convert to strings and flatten (and implicitly return)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 70 bytes
```
n;f(char*a){*a-48?n=!printf(n?"%d":"%c",n?:*a++),*a&&f(a):f(a+!!++n);}
```
[Try it online!](https://tio.run/##FcnBCsIwDADQb2lgI2k2iFsV6ZB@S4hUdzCM4W347VUv7/JsfJi15ktFe@oelY6oY7oWv4VtX/1d0Qt0d8jQGQxeclRmGqL2fUWl/INDYHZaPu2lqyMdFeE0zeksMl8mEUlJ4N9f "C (gcc) – Try It Online")
# [C (gcc)](https://gcc.gnu.org/), 62 bytes by c--
```
n;f(int*a){*a-48?n=!printf(n?"%d":a++,n),*a&&f(a):f(a+!!++n);}
```
[Try it online!](https://tio.run/##S9ZNT07@/z/POk0jM69EK1GzWitR18TCPs9WsaAIKJKmkWevpJqiZJWora2Tp6mjlaimlqaRqGkFJLQVFbW18zSta//nJmbmaWhWp2n4KBkaGZuYGhgYmxkZGBiYmBgogeQB "C (gcc) – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 27 bytes
```
!x=replace(x,r"0+"=>length)
```
[Try it online!](https://tio.run/##fY9fa4MwFMXf8ymuMoiybtz80W4D@7ZPMcaINesyQioawYd@dxfr7Cptd8lDOOf8Lud@d9Yo1g9D1BeNrq3a6qRfNTHex8XGarfzX@nwuW/AgHHQaFVZ43SbpATCfKx@n5o/JRTQ1tb4xEwRFQT1xl@0qx7Y@1EaM@VSqhvjvHWJKjaRmsAokCEHh8PJjV/7Wm@9ruCujFMS@IE9QuuDvQs7KeNCZogi54goJVLYd77u/MnjwRJSMkr4PxyFGxwl4hzDs6Fj5QVGiVyEj4vy9dPzFF2E/zySXRQbdbwCzV64Jr8Kzcw1iJL1sh1yFOF4zC5PCfWY4JJljP4A "Julia 1.0 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Œgċ”0ȯƊ€
```
A full program that accepts a string of digit characters and prints the result.
**[Try it online!](https://tio.run/##y0rNyan8///opPQj3Y8a5hqcWH@s61HTmv///6sbGhmbmBoYGJsZGcCBiYk6AA "Jelly – Try It Online")**
### How?
```
Œgċ”0ȯƊ€ - Main Link: list of characters, S
Œg - group runs
€ - for each group:
Ɗ - last three links as a monad - f(group):
”0 - literal '0' character
ċ - count occurrences
ȯ - logical OR (group)
- implicit, smashing print
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
ṁ?IosLig
```
[Try it online!](https://tio.run/##yygtzv6f@6ip8f/DnY32nvnFPpnp////j1YyNDI2MTUwMDYzMjAwMDExUNJBFwKKGCABEBeswszcwhKmGsQ2QOaAVRkYGRgDTTAwNVCKBQA "Husk – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 42 bytes
```
[ R/ 0+/ [ length >dec ] re-replace-with ]
```
[Try it online!](https://tio.run/##bZDdSsNAEIXv8xRjbzXJmKTVRCj0RilILyxelRLiZrIpJLvrZkoVEXwIn9AXidv4QxDP3XyccxhOVQjWtr9fL1c3GViS9GSgo8c9KUEdtAXXgSlsRxaMJeZnY3eK4QqWqwykbipvcbtcrDOYlyRA7dsHsvOOnUkCnMD1UA8YpCl8vL27ZoKa2XRZGJZadEE1GIQuKdBWhkIrJsXhQdvSz3PJee56z0ZvBDW3jffigdPkPIqTKWI8ixAxSXDyL/6mONIPGpyzi8t0nDze@Bf8JjDC2LXi1Fle@w3chYCnIWygISW5/hpi66b0LZmmEOQfdg5v@7YwEPSf "Factor – Try It Online")
[Answer]
# [Zsh](https://zsh.sourceforge.io/) `--extendedglob`, 24 bytes
```
<<<${1//(#m)0##/$#MATCH}
```
[Try it Online!](https://tio.run/##qyrO@F@cWpJfUKKQWlGSmpeSmpKek5/ElaahWf3fxsZGpdpQX19DOVfTQFlZX0XZ1zHE2aP2fy0XV5qCoZGxiamBgbGZkYGBgYmJAaYQUMQACYC4YBVm5haWMNUgtgEyB6zKwMjAGGiCganBfwA)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 11 bytes
```
ḅ{ị0&lṫ|}ᵐc
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO1uqHu7sN1HIe7lxdU/tw64Tk//@VDI2MTUwNDIzNjAwMDExMDOBA6X8EAA "Brachylog – Try It Online")
### Explanation
I was hoping for some automatic number -> string conversion, but no dice.
```
ḅ{ị0&lṫ|}ᵐc
ḅ Break the input string into blocks of identical characters
{ }ᵐ Map this predicate to each block:
ị Convert to integer
0 Assert that the result is zero
&l If so, get the length of the block
ṫ and convert to string
| If that failed (because the number wasn't zero), return the block unchanged
c Concatenate the results together into a single string
```
[Answer]
# Java, 88 bytes
```
s->java.util.regex.Pattern.compile("0+").matcher(s).replaceAll(r->r.group().length()+"")
```
[Try it online!](https://tio.run/##fY7BTsMwDIbP9CminBJNjbK141KoxAMgkCZOiEPI0i4lTSLHnaimPXsJbBLigm/2/9n@BnVU5bD/WOwYAyAZci8mtE50k9dogxcvXsH8FA0oDNAUcXp3VhPtVErkUVlPTgXJlVBhnv@h73YI1vct6e6XVLa/x8H05lM8K0QDXugwRusMo3JFuRgV6oMBlnjGolPaPDjHoGxB9BCmyLhwxvd4YHxFKV@an/dXravFMdg9GbMcuxi8vhEFfeKn4mY3JzSjCBOKmCN0nnVCxehmRtebqt5KWd1upJR1LSnnzf8bci03ssqw3F7ob5dzcV6@AA)
[Answer]
# [><>](https://esolangs.org/wiki/Fish), ~~23~~ 18 bytes
```
\&l:?n&o]
\i:'0'-?
```
[Try it online!](https://tio.run/##S8sszvj/P0Ytx8o@Ty0/lism00rdQF3X/v9/QyNjE1MDA2MzIwMDAxMTAwA "><> – Try It Online")
[Answer]
# Java 19, 156 ~~161~~ ~~162~~ bytes
```
interface A{static void main(String[] a){var i=0;var s="";for(var c:a[0].toCharArray())if(c==48)i++;else{s+=i>0?i+""+c:c;i=0;}System.out.print(i>0?s+i:s);}}
```
## Without Java's golfing tax, 113 bytes
```
var i=0;var s="";for(var c:a[0].toCharArray())if(c==48)i++;else{s+=i>0?i+""+c:c;i=0;}System.out.print(i>0?s+i:s);
```
[Try it online!](https://tio.run/##LYzRCoIwFEB/Zfi0IclNLcJhIX2Cj@LDZc26pi7mEkT89pXU04Fz4LQ44a69Pb2nwWnboNKsWEaHjhSbDN1YjzTw0lka7lXNUCwTWkY5yI0mL@fR6T4ybycbYxnfrMqwgjpy5vpAW1iLMxeCGq7yPD0JCkOpu1EvJnp9r47TGS4UBkGoMiXktl7/qRt@MQsCIdfVe7@Pk/QAkBxjAEhT@AA "Java (JDK) – Try It Online")
Edit: replaced `'0'` with `48` as suggested in the comments. Thanks!
Edit: String concatentation is shorter than doing `var o=System.out;`
] |
[Question]
[
I [didn't](https://github.zhaw.ch/munt/Gulf) invent this challenge, but I find it very interesting to solve.
For **every** input number, e.g.:
```
4
```
Generate a range from 1 to that number:
```
[1 2 3 4]
```
And then, for every item in that list, generate a list from 1 to that number:
```
[[1] [1 2] [1 2 3] [1 2 3 4]]
```
Then, reverse every item of that list.
```
[[1] [2 1] [3 2 1] [4 3 2 1]]
```
## Notes:
* 1 being a loose item is allowed, since flattening will not matter with this anyway.
* To preserve the spirit of the challenge, the range has to be 1-indexed.
* You may flatten the list if your platform doesn't support the concept of nested lists.
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~5~~ 4 [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.
```
,⍨\⍳
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///X@dR74qYR72b/6c9apvwqLfvUd9UT/9HXc2H1hs/apsI5AUHOQPJEA/P4P9A2ivY308hTcEEAA "APL (Dyalog Unicode) – Try It Online")
`,⍨\` cumulative reverse-concatenation reduction of
`⍳` the iota
[Answer]
# [R](https://www.r-project.org/), ~~22~~ 19 bytes
```
Map(`:`,1:scan(),1)
```
[Try it online!](https://tio.run/##K/r/3zexQCPBKkHH0Ko4OTFPQ1PHUPO/6X8A "R – Try It Online")
`Map(f,...)` applies `f` elementwise to each member of `...`, recycling as needed, resulting in a `list`, so we just supply `1` as the `to` argument to `:` to get the reversed.
-3 bytes thanks to [Vlo](https://codegolf.stackexchange.com/users/30693/vlo)!
[Answer]
# Jelly, 3 bytes
```
RRU
```
```
R Range from 1 to input
R (implicitly) map over said range and create a range from 1 to this element
U reverse each of those
```
You can [try it online!](https://tio.run/##y0rNyan8/z8oKPT///8mAA)
Courtesy of @JonathanAllan, we also have two other 3-"byters"
```
RrL
RrE
```
I think it is not often that golfing languages solve a challenge with only `a-zA-Z` characters
[Answer]
# Pure [Bash](https://www.gnu.org/software/bash/) (no external utilities), 29
```
eval eval echo \\{{1..$1}..1}
```
[Try it online!](https://tio.run/##S0oszvj/P7UsMUcBQiRn5CvExFRXG@rpqRjW6ukZ1v7//98EAA "Bash – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 3 bytes
```
LLí
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fx@fw2v//TQA "05AB1E – Try It Online")
[Answer]
# [shell + sed](https://www.gnu.org/software/bash/), 15 bytes
```
seq $1|sed G\;h
```
[Try it online!](https://tio.run/##S0oszvj/vzi1UEHFsKY4NUXBPcYaKPDfBAA "Bash – Try It Online")
Outputs like so, `1\n\n2\n1\n\n3\n2\n1\n\n[...]`
`seq $1` creates a sequence from 1 to the first argument `$1`
`|sed ...` which is piped into a sed script
sed works on a line-by-line basis; it first reads the first line into the buffer, called the "pattern space", after which the program commands is run on it. At the end of the program's execution on the first line, the remaining pattern space is implicitly printed. Then sed reads the next line into the pattern space, replacing the previous contents, and runs the commands on it, repeating for all lines of input (unless a command specifies otherwise).
The pattern space is not saved between lines, but what is is the hold space. The hold space is another buffer, that starts empty, and can be modified by program commands. Its contents are carried on to the execution of the next line of input.
The `G` command appends a newline followed by the content of the hold space to that of the pattern space. Then the `h` command replaces the hold space with the content of the pattern space. This effectively reverses the lines of input encountered so far, writing them to the pattern space – implicitly printing at the end of processing the current line – and saving them to the hold space so that upon reading subsequent lines of input, the new reversed "list" can be constructed with `G;h`.
The `;` is escaped in the program as `\;` because otherwise the shell interprets it as terminating a shell command.
[Answer]
# [~~Perl 6~~ Raku](https://github.com/nxadm/rakudo-pkg), ~~24 15 13~~ 10 bytes
-2 removed parenthesis
-3 thanks to nwellnhof
```
^*+1 X…1
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPs/TkvbUCHiUcMyw//WXMWJlQppCib/AQ)
## Explanation
```
^*+1 # make a range from 1 .. argument (whatever star).
X…1 # create ranges descending to 1 using cross product metaoperator.
```
## Previous version, 24 bytes
```
(^<<(^*+1)X+1)>>.reverse
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfI87GRiNOS9tQMwKI7ez0ilLLUouKU/9bc3EVJ1YqpCmY/AcA "Perl 6 – Try It Online")
### Explanation
```
^*+1 # make a range from 1 .. argument (whatever star)
^<<( ) # replace each element with a range from 0 .. element - 1
# (via hyper prefix operator)
X+1 # shift the range to 1 .. element
# (via cross product metaoperator)
( )>>.reverse # reverse each list (via hyper method operator)
```
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 8 bytes
```
|',\1+!:
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqkZdJ8ZQW9Hqf5qCyX8A "K (ngn/k) – Try It Online")
-2 thanks to ngn :-)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 20 bytes
```
Range[Range@#,1,-1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277PygxLz01Gkw6KOsY6ugaxqr9DyjKzCtRcEiPNon9/x8A "Wolfram Language (Mathematica) – Try It Online")
-3 bytes from @att
[Answer]
# JavaScript (ES6), ~~50~~ 49 bytes
*Saved 1 byte thanks to @Shaggy*
```
f=n=>n?[...f(n-1),(g=_=>n?[n,...g(--n)]:[])()]:[]
```
[Try it online!](https://tio.run/##HchRCoAgDADQ62zQBkFfgXUQkRBTKWRGRtdf4deDd/rXt3Af10NS96iajJhFVsvMCYRGHCCbrZcMf2YgEnSzdQgdDVVaLZFLzZBgQtQP "JavaScript (Node.js) – Try It Online")
[Answer]
# [PHP](https://php.net/), 54 bytes
```
function($x){for(;$y<$x;$a[]=range(++$y,1));return$a;}
```
[Try it online!](https://tio.run/##Fc0xCsIwFAbgPafI8A8JtYPg9hrcvEQpEmLS6PBeSFtoEa9uxO8CX8mlDdeSi0JyLW0c1qewwW7fSaohHAN2gh8nVz3P0XQdjtPZWqpx3SrD06eRgminkYyGrzNrSyqGLPq1CN8jB3lEA7HULl8p/2Bp/e0H "PHP – Try It Online")
Or recursive:
# [PHP](https://php.net/), 54 bytes
```
function f($x){return$x?f($x-1)+[$x=>range($x,1)]:[];}
```
[Try it online!](https://tio.run/##K8go@G9jXwAk00rzkksy8/MU0jRUKjSri1JLSovyVCrsQVxdQ03taJUKW7uixLz0VKCAjqFmrFV0rHXt/9TkjHyFrOL8vPjUvOT8lFQNoH4FlcSi9DwFTQVN6/8m//ILQMYW/9d1AwA "PHP – Try It Online")
Or with PHP-formatted printed output:
# [PHP](https://php.net/), 38 bytes
```
for(;$x<$argn;print_r(range(++$x,1)));
```
[Try it online!](https://tio.run/##K8go@G9jXwAk0/KLNKxVKmxUEovS86wLijLzSuKLNIoS89JTNbS1VSp0DDU1Na3//zf5l19QkpmfV/xf1w0A "PHP – Try It Online")
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 13 bytes
```
{[\R,] 1..$_}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYKvwvzo6JkgnVsFQT08lvvZ/cWKlQpqCyX8A "Perl 6 – Try It Online")
Cumulative reverse with the range 1 to input.
[Answer]
# x86-16 machine code, 12 bytes
Binary:
```
00000000: 33c0 4050 ab48 75fc 58e2 f7c3 [[email protected]](/cdn-cgi/l/email-protection)...
```
Unassembled listing:
```
33 C0 XOR AX, AX ; AX = 0
OUT_LOOP:
40 INC AX ; start at 1
50 PUSH AX ; save starting position
IN_LOOP:
AB STOSW ; write to output buffer, increment DI
48 DEC AX ; AX--
75 FC JNZ IN_LOOP ; if AX > 0, keep looping
58 POP AX ; restore starting position
E2 F7 LOOP OUT_LOOP
C3 RET ; return to caller
```
Input Number in `CX`, output array of `WORD`, at `[DI]`.
Example I/O using DOS test driver program:
[](https://i.stack.imgur.com/qdFUf.png)
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 10 bytes
Anonymous tacit prefix function.
```
(⌽1+↕)¨1+↕
```
[Try it online!](https://bqnpad.mechanize.systems/s?bqn=eyJkb2MiOiJcblxuIyBGb3IgZXZlcnkgaW5wdXQgbnVtYmVyLCBnZW5lcmF0ZSBhIHJhbmdlIGZyb20gMSB0byB0aGF0IG51bWJlci5cbiMgRm9yIGV2ZXJ5IGl0ZW0gaW4gdGhhdCBsaXN0LCBnZW5lcmF0ZSBhIGxpc3QgZnJvbSAxIHRvIHRoYXQgbnVtYmVyLlxuIyBSZXZlcnNlIGV2ZXJ5IGl0ZW0gb2YgdGhhdCBsaXN0LlxubiDihpAgNVxuU29sMCDihpAgKOKMvTEr4oaVKcKoMSvihpVcblNvbDEg4oaQICgxK%2BKGlSl7KOKMvfCdlL0pwqjwnZS9fVxuU29sMiDihpAgKOKMveKGlSnCqOKGlVxuXG5Tb2wwIG5cblxuIiwicHJldlNlc3Npb25zIjpbXSwiY3VycmVudFNlc3Npb24iOnsiY2VsbHMiOltdLCJjcmVhdGVkQXQiOjE2NzUwMDU4NzEzMzV9LCJjdXJyZW50Q2VsbCI6eyJmcm9tIjowLCJ0byI6MjQzLCJyZXN1bHQiOm51bGx9fQ%3D%3D)
### Explanation
```
(⌽1+↕)¨1+↕
1+↕ 1. Get list of integers from 1 to n.
¨ 2a. For each integer i in the list...
( 1+↕) 2b. get a list of integers from 1 to i...
(⌽ ) 2c. and then reverse that list.
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 19 bytes
```
1.."$args"|%{$_..1}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/31BPT0klsSi9WKlGtVolXk/PsPb///8mAA "PowerShell – Try It Online")
Generates the range from `1` to input `$args`, then constructs the reversed range for each of those numbers. Tack on a [`-join`](https://tio.run/##K8gvTy0qzkjNyfn/31BPT0klsSi9WKlGtVolXk/PUDcrPzNPXUe99v///yYA "PowerShell – Try It Online") to better see how the arrays are created (because PowerShell inserts a newline between each element, it's tough to see the individual arrays).
[Answer]
# [Python 3](https://docs.python.org/3/), 46 bytes
```
lambda n:[[*range(i+1,0,-1)]for i in range(n)]
```
[Try it online!](https://tio.run/##K6gsycjPM/6fZhvzPycxNyklUSHPKjpaqygxLz1VI1PbUMdAR9dQMzYtv0ghUyEzTwEikacZ@7@gKDOvRCNNw0RT8z8A "Python 3 – Try It Online")
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 12 (13) bytes
```
,{)),(;-1%}%`
```
```
,{)),(;-1%}%` #Reversed iota of iota
, #0 to n-1 iota
{ }% #For each element in the iota
{)) } #Increment by 2
{ , } #Iota
{ (; } #Pop leading 0
{ -1%} #Reverse it
` #Pretty output, not needed if you use a better stack-interpreter
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPlv8V@nWlNTR8Na11C1VjXh/38A "GolfScript – Try It Online")
Below is my old solution, I gained inspiration after posting and improved it.
```
),(;{),(;-1%}%`
```
Comma is the function that builds an array 0 to n-1, "iota expand".
```
),(;{),(;-1%}%` #Take in a number, output reversed expanded iota
) #Increment input by 1
, #Iota expand
(; #Remove leading 0
{ }% #For every element, do the following
{) } #Increment by 1
{ , } #Iota expand
{ (; } #Remove leading 0
{ -1%} #Reverse
` #Pretty output; technically not needed
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPlv8V9TR8O6GkToGqrWqib8/w8A "GolfScript – Try It Online")
[Answer]
# [Factor](https://factorcode.org/), 45 bytes
```
: f ( n -- s ) [1,b] [ 1 [a,b] >array ] map ;
```
[Try it online!](https://tio.run/##HcwxC8IwEIbhvb/iGxVMoYNLCq7SpYPiFDqc9aodTOPdKfTXx@j2DC/vRKMtki/nrj96kAitiifZoxaKd1Yov94cx6IkbLYmmaOhrbre48QfFuWbmxejKntM2CDCOSi2CM3uOiCgQaCfDv87hrJPaPO@1HX@Ag "Factor – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~34~~ 30 bytes
```
->n,*a{(1..n).map{|x|a=[x]+a}}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y5PRyuxWsNQTy9PUy83saC6pqIm0Ta6IlY7sbb2f4FCWrRJ7H8A "Ruby – Try It Online")
Thanks Value Ink (as usual) for -4 bytes.
[Answer]
# [Haskell](https://www.haskell.org/), 27 bytes
```
f n=scanl(flip(:))[1][2..n]
```
[Answer]
# [Zsh](https://www.zsh.org/), 22 bytes
```
eval echo {{1..$1}..1}
```
[Try it online!](https://tio.run/##qyrO@J@moanxP7UsMUchNTkjX6G62lBPT8WwVk/PsPa/JhdXmoIhEBsBsTEQm4Bog/8A "Zsh – Try It Online")
`{{1..$1}..1}` -> `{1..1} {2..1} {3..1} {4..1} ...`
`eval echo {1..1} {2..1} {3..1} ...` -> `echo 1 2 1 3 2 1 ...`
If the sublists must be delimited, then [25 bytes for `,`](https://tio.run/##qyrO@J@moanBVZxaoqBb8T@1LDFHITU5I1@hutpQT0/FsFZPz7A2RkHnvyYXV5qCIRAbAbExEJv8BwA "Zsh – Try It Online") or [26 bytes for newline](https://tio.run/##qyrO@J@moanxvyi1IDWxREHFUCE1OSNfoVolWls7M1ZPz7D2vyYXV5qCIRAbAbExEJuAaAOu/wA "Zsh – Try It Online").
[Answer]
# [Fortran (GFortran)](https://gcc.gnu.org/fortran/), 47 bytes
```
read*,i
print*,("{",(j,j=k,1,-1),"}",k=1,i)
end
```
[Try it online!](https://tio.run/##S8svKilKzNNNT4Mw/v8vSk1M0dLJ5Cooyswr0dLRUKpW0tHI0smyzdYx1NE11NRRqlXSybY11MnU5ErNS/n/3wQA "Fortran (GFortran) – Try It Online")
Could remove 8 chars by getting rid of printed brackets if anyone would believe that they are lists otherwise.
[Answer]
# [Elm](https://elm-lang.org/), 45 bytes
```
r=List.range 1
f=List.map(List.reverse<<r)<<r
```
[Try it on Ellie](https://ellie-app.com/kR8mY5cqZkya1)
[Answer]
# [Arturo](https://arturo-lang.io), ~~22~~ 18 bytes
```
$=>[map&=>[@&..1]]
```
[Try it](http://arturo-lang.io/playground?yBKvvi)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
⟦₁⟧₁ᵐ
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//9H8ZY@aGh/NXw4kH26d8P@/yf8oAA "Brachylog – Try It Online")
### Explanation
```
⟦₁ Ascending range from 1 to the input
ᵐ Map:
⟧₁ Descending range from 1 to the mapped element
```
[Answer]
## Haskell, 74 73 51 bytes
`main=do i<-getLine;print[[x,x-1..1]|x<-[1..read i]]`
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzcxM882JV8h00Y3PbXEJzMv1bqgKDOvJDq6QqdC11BPzzC2psJGNxrIKkpNTFHIjI39/98EAA)
-22 bytes thanks to @79037662
[Answer]
# [Burlesque](https://github.com/FMNSSun/Burlesque), 9 bytes
```
riroq<-pa
```
[Try it online!](https://tio.run/##SyotykktLixN/f@/KLMov9BGtyDx/38TAA "Burlesque – Try It Online")
```
ri # Read int
ro # Range [1,N]
q<- # Boxed reverse
pa # Operate over ((1), (1 2), (1 2 3),...)
```
Alternative 9 byter, but this also has an empty list as the first element:
```
riroiT)<-
```
[Answer]
# [Go](https://go.dev), 105 bytes
```
func(n int)(o[][]int){for i:=1;i<=n;i++{J:=[]int{}
for j:=i;j>0;j--{J=append(J,j)}
o=append(o,J)}
return}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=NU69CsIwGNzzFMEpoa0oOEhjfIBM7qVDqE1JtF9CSF1Cn8SlCD6GD9K3sT863R133N3z1dhhxE5WN9nUuJUakG6d9WG7UW3YoIf0WPF3F1R2HLXqoCKANQRKbFEW5cyish7rnO-ZPnFgOkmiyPnixR7Npsm5Zua8YybLouDSuRquRKSG9sj-pU3FJH0dOg_9OviZ95ZThOKILn6qvANR5EAp-mWGYcUv)
[Answer]
# shell with `seq` loop, 46 bytes
```
for n in `seq $1`;do seq -s\ -t'\n' $n 1;done
```
[Answer]
# JavaScript, 60 bytes
Without recursion:
```
n=>eval('for(a=[];n;a[--n]=b)for(b=[j=n];j-->1;b[n-j]=j);a')
```
Try it:
```
f=n=>eval('for(a=[];n;a[--n]=b)for(b=[j=n];j-->1;b[n-j]=j);a')
console.log(JSON.stringify(f(1)));
console.log(JSON.stringify(f(2)));
console.log(JSON.stringify(f(3)));
console.log(JSON.stringify(f(4)));
```
] |
[Question]
[
## The challenge is to calculate the digit sum of the factorial of a number.
---
Example
```
Input: 10
Output: 27
```
10! = 10 × 9 × ... × 3 × 2 × 1 = 3628800,
and the sum of the digits in the number 10! is 3 + 6 + 2 + 8 + 8 + 0 + 0 = 27
You can expect the input to be an integer above 0.
Output can be of any type, but the answer should be in the standard base of the coding language.
---
Test cases:
```
10 27
19 45
469 4140
985 10053
```
N.B. Some languages can not support large numbers above 32-bit integers; for those languages you will not be expected to calculate large factorials.
[OEIS link here](https://oeis.org/A004152) thanks to [Martin Ender](https://codegolf.stackexchange.com/users/8478/martin-ender)
---
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest code in characters wins!
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 3 bytes
```
!SO
```
[Try it online!](http://05ab1e.tryitonline.net/#code=IVNP&input=MTA)
```
! Factorial.
S Push characters separately.
O Sum.
```
[Answer]
## [Jelly](http://github.com/DennisMitchell/jelly), 3 bytes
```
!DS
```
[Try it online!](http://jelly.tryitonline.net/#code=IURT&input=&args=MTA)
Does what you expect:
```
! Factorial.
D Decimal digits.
S Sum.
```
[Answer]
## Mathematica, 21 bytes
```
Tr@IntegerDigits[#!]&
```
[Answer]
# C++11, 58 bytes
As unnamed lambda modifying its input:
```
[](int&n){int i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
```
One of the rare cases when my C++ code is shorter than the [C code](https://codegolf.stackexchange.com/a/100844/53667).
If you want to suppport larger cases, switch to **C++14** and use:
```
[](auto&n){auto i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
```
and supply the calling argument with `ull` suffix.
Usage:
```
auto f=
[](int&n){int i=n;while(--n)i*=n;do n+=i%10;while(i/=10);}
;
main() {
int n=10;
f(n);
printf("%d\n",n);
}
```
[Answer]
## Ruby, ~~63~~ ~~61~~ ~~53~~ 38 bytes
New approach thanks to manatwork:
```
->n{eval"#{(1..n).reduce:*}".chars*?+}
```
Old:
```
->n{(1..n).reduce(:*).to_s.chars.map(&:hex).reduce:+}
```
* -3 bytes thanks to Martin Ender
* -5 bytes thanks to G B
[Answer]
# Pyth, ~~7~~ 6 bytes
*Thanks to @Kade for saving me a byte*
`sj.!QT`
[Try it online!](https://pyth.herokuapp.com/?code=sj.%21Q10&input=10&debug=0)
This is my first time using Pyth, so I'm sure that my answer could be golfed quite a bit.
Explanation:
```
s Sum
j the digits of
.! the factorial of
Q the input
T in base 10
```
[Answer]
## Haskell, ~~41~~ 40 bytes
```
f x=sum$read.pure<$>(show$product[1..x])
```
Usage example: `f 985` -> `10053`.
Make a list from `1`to `x`, calculate the product of the list elements, turn it into its string representation, turn each character into a number and sum them.
Edit: @Angs saved a byte. Thanks!
[Answer]
# Python, 54 bytes
```
f=lambda n,r=1:n and f(n-1,r*n)or sum(map(int,str(r)))
```
**[repl.it](https://repl.it/E6Vu)**
[Answer]
## R, 58 53 bytes
Edit: Saved one byte thanks to @Jonathan Carroll and a couple thanks to @Micky T
```
sum(as.double(el(strsplit(c(prod(1:scan()),""),""))))
```
Unfortunately, with 32-bit integers, this only works for `n < 22`. Takes input from stdin and outputs to stdout.
If one would like higher level precision, one would have to use some external library such as `Rmpfr`:
```
sum(as.numeric(el(strsplit(paste(factorial(Rmpfr::mpfr(scan()))),""))))
```
[Answer]
# [Pip](http://github.com/dloscutoff/pip), 8 bytes
```
$+$*++,a
```
[Try it online!](http://pip.tryitonline.net/#code=JCskKisrLGE&input=&args=MTA)
**Explanation**
```
,a # range
++ # increment
$* # fold multiplication
$+ # fold sum
```
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 8 bytes
```
rim!Ab:+
```
[Try it online!](http://cjam.tryitonline.net/#code=cmltIUFiOis&input=MTA)
### Explanation
```
r e# Read input.
i e# Convert to integer.
m! e# Take factorial.
Ab e# Get decimal digits.
:+ e# Sum.
```
[Answer]
# [APL (Dyalog Extended)](https://github.com/abrudz/dyalog-apl-extended), 8 bytes
-3 thanks to @Razetime - i forgot to drop a paren lol
```
+/⍎¨∘⍕∘!
```
Explanation:
```
+/⍎¨∘⍕∘!
! ⍝ factorial of ⍵
⍕ ⍝ convert to string
⍎¨ ⍝ produce digit vector
+/ ⍝ sum all digits
```
Has some problems with factorial of 900, this code will work fine for `⍵>40`:
```
b←({⍵⊣⍵.⎕CY'dfns'}⎕NS⍬).big
↑(+b/(⍎¨∘⍕∘(↑(×b/⍳))))
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT9dNrShJzUtJTfmv8ahvqlsQkAgI0HzUNsHQyMJcwdjkfxqQra2v8ai379CKRx0zHvVOBZKKj7oWaf4HqgVKpikYGnDBmZZwprHBfwA "APL (Dyalog Extended) – Try It Online")
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), 5 bytes
```
$!@e+
```
[Try it online!](http://brachylog.tryitonline.net/#code=JCFAZSs&input=OTg1&args=Wg)
### Explanation
Basically the described algorithm:
```
$! Take the factorial of the Input
@e Take the elements of this factorial (i.e. its digits)
+ Output is the sum of those elements
```
[Answer]
# Java 7, 148 bytes
```
int s=1,ret=0;while(i>1){s=s*i; i--;}String y=String.valueOf(s);for(int j=0;j<y.length();j++){ret+=Integer.parseInt(y.substring(j,j+1));}return ret;
```
[Answer]
# Ruby, ~~63 60 53~~ 51 bytes
```
->n{a=0;f=(1..n).reduce:*;f.times{a+=f%10;f/=10};a}
```
Thanks to Martin for golfing help.
[Answer]
# [Pushy](https://github.com/FTcode/Pushy), 4 bytes
```
fsS#
```
Give input on the command line: `$ pushy facsum.pshy 5`. Here's the breakdown:
```
f % Factorial of input
s % Split into digits
S % Push sum of stack
# % Output
```
[Answer]
# Octave, 30 bytes
```
@(n)sum(num2str(prod(1:n))-48)
```
Calculates the factorial by taking the product of the list `[1 2 ... n]`. Converts it to a string and subtracts `48` from all elements (ASCII code for `0`). Finally it sums it up :)
[Answer]
## bash (seq,bc,fold,jq), ~~34~~ 33 bytes
Surely not the most elegant but for the challenge
```
seq -s\* $1|bc|fold -1|jq -s add
```
[Answer]
## C, 58 bytes
This is not perfect. Only works ones because a have to be -1 in start. The idea is to use two recursive function in one function. It was not as easy as I first thought.
```
a=-1;k(i){a=a<0?i-1:a;return a?k(i*a--):i?i%10+k(i/10):0;}
```
Usage and understandable format:
```
a = -1;
k(i){
a = a<0 ? i-1 : a;
return a ? k(i*a--) : i? i%10+k(i/10) :0;
}
main() {
printf("%d\n",k(10));
}
```
Edit:
I found metode that let use this function multiple time but then length is 62 bytes.
```
a,b;k(i){a=b?a:i+(--b);return a?k(i*a--):i?i%10+k(i/10):++b;}
```
[Answer]
# [Perl 6](https://perl6.org), 21 bytes
```
{[+] [*](2..$_).comb}
```
## Expanded:
```
{ # bare block lambda with implicit parameter 「$_」
[+] # reduce the following with 「&infix:<+>」
[*]( # reduce with 「&infix:<*>」
2 .. $_ # a Range that include the numbers from 2 to the input (inclusive)
).comb # split the product into digits
}
```
[Answer]
# Cubix, ~~33~~ 32 bytes
```
u*.$s.!(.01I^<W%NW!;<,;;q+p@Opus
```
Net form:
```
u * .
$ s .
! ( .
0 1 I ^ < W % N W ! ; <
, ; ; q + p @ O p u s .
. . . . . . . . . . . .
. . .
. . .
. . .
```
[Try it online!](https://ethproductions.github.io/cubix/?code=dSouJHMuISguMDFJXjxXJU5XITs8LDs7cStwQE9wdXM=&input=MTA=&speed=2000)
# Notes
* Works with inputs up to and including 170, higher inputs result in an infinite loop, because their factorial yields the `Infinity` number (technically speaking, its a non-writable, non-enumerable and non-configurable property of the window object).
* Accuracy is lost for inputs 19 and up, because numbers higher than 253 (= 9 007 199 254 740 992) cannot be accurately stored in JavaScript.
# Explanation
This program consists of two loops. The first calculates the factorial of the input, the other splits the result into its digits and adds those together. Then the sum is printed, and the program finishes.
## Start
First, we need to prepare the stack. For that part, we use the first three instructions. The IP starts on the fourth line, pointing east. The stack is empty.
```
. . .
. . .
. . .
0 1 I . . . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . .
. . .
. . .
```
We will keep the sum at the very bottom of the stack, so we need to start with `0` being the sum by storing that on the bottom of the stack. Then we need to push a `1`, because the input will initially be multiplied by the number before it. If this were zero, the factorial would always yield zero as well. Lastly we read the input as an integer.
Now, the stack is `[0, 1, input]` and the IP is at the fourth line, the fourth column, pointing east.
### Factorial loop
This is a simple loop that multiplies the top two elements of the stack (the result of the previous loop and the input - n, and then decrements the input. It breaks when the input reaches 0. The `$` instruction causes the IP to skip the `u`-turn. The loop is the following part of the cube. The IP starts on the fourth line, fourth column.
```
u * .
$ s .
! ( .
. . . ^ < . . . . . . .
. . . . . . . . . . . .
. . . . . . . . . . . .
. . .
. . .
. . .
```
Because of the `^` character, the IP starts moving north immediately. Then the `u` turns the IP around and moves it one to the right. At the bottom, there's another arrow: `<` points the IP back into the `^`. The stack starts as `[previousresult, input-n]`, where `n` is the number of iterations. The following characters are executed in the loop:
```
*s(
* # Multiply the top two items
# Stack: [previousresult, input-n, newresult]
s # Swap the top two items
# Stack: [previousresult, newresult, input-n]
( # Decrement the top item
# Stack: [previousresult, newresult, input-n-1]
```
Then the top of the stack (decreased input) is checked against `0` by the `!` instruction, and if it is `0`, the `u` character is skipped.
### Sum the digits
The IP wraps around the cube, ending up on the very last character on the fourth line, initially pointing west. The following loop consists of pretty much all remaining characters:
```
. . .
. . .
. . .
. . . . . W % N W ! ; <
, ; ; q + p @ O p u s .
. . . . . . . . . . . .
. . .
. . .
. . .
```
The loop first deletes the top item from the stack (which is either `10` or `0`), and then checks what is left of the result of the factorial. If that has been decreased to `0`, the bottom of the stack (the sum) is printed and the program stops. Otherwise, the following instructions get executed (stack starts as `[oldsum, ..., factorial]`):
```
N%p+q;;,s;
N # Push 10
# Stack: [oldsum, ..., factorial, 10]
% # Push factorial % 10
# Stack: [oldsum, ..., factorial, 10, factorial % 10]
p # Take the sum to the top
# Stack: [..., factorial, 10, factorial % 10, oldsum]
+ # Add top items together
# Stack: [..., factorial, 10, factorial % 10, oldsum, newsum]
q # Send that to the bottom
# Stack: [newsum, ..., factorial, 10, factorial % 10, oldsum]
;; # Delete top two items
# Stack: [newsum, ..., factorial, 10]
, # Integer divide top two items
# Stack: [newsum, ..., factorial, 10, factorial/10]
s; # Delete the second item
# Stack: [newsum, ..., factorial, factorial/10]
```
And the loop starts again, until `factorial/10` equals 0.
[Answer]
## C, 47 bytes
```
f(n,a){return n?f(n-1,a*n):a?a%10+f(0,a/10):0;}
```
usage:
```
f(n,a){return n?f(n-1,a*n):a?a%10+f(0,a/10):0;}
main() {
printf("answer: %d\n",f(10,1));
}
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog) (v2), 3 bytes
```
ḟẹ+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//@GO@Q937dT@/9/SwvR/FAA "Brachylog – Try It Online")
Same "algorithm" as the [v1 answer](https://codegolf.stackexchange.com/a/100832/8774) by @Fatalize, just with better encoding.
[Answer]
# Python, 57 bytes
```
import math
lambda n:sum(map(int,str(math.factorial(n))))
```
[**Try it online**](https://repl.it/E6TZ)
[Answer]
## Batch, 112 bytes
```
@set/af=1,t=0
@for /l %%i in (1,1,%1)do @set/af*=%%i
:g
@set/at+=f%%10,f/=10
@if %f% gtr 0 goto g
@echo %t%
```
Conveniently `set/a` works on a variable's current value, so it works normally inside a loop. Only works up to 12 due to the limitations of Batch's integer type, so in theory I could save a byte by assuming `f<1e9`:
```
@set/af=1,t=0
@for /l %%i in (1,1,%1)do @set/af*=%%i
@for /l %%i in (1,1,9)do @set/at+=f%%10,f/=10
@echo %t%
```
But that way lies madness... I might as well hard-code the list in that case (97 bytes):
```
@call:l %1 1 1 2 6 6 3 9 9 9 27 27 36 27
@exit/b
:l
@for /l %%i in (1,1,%1)do @shift
@echo %2
```
[Answer]
## JavaScript (ES6), 50 bytes
```
f=(n,m=1,t=0)=>n?f(n-1,n*m):m?f(n,m/10|0,t+m%10):t
```
Only works up to `n=22` due to floating-point accuracy limitations.
[Answer]
# [Befunge 93](http://esolangs.org/wiki/Befunge), ~~56~~ 54 bytes
Saved 2 bytes do to using get instead of quotes. This let me shift the top 2 lines over 1, reducing unnecessary white space.
[Try it online!](http://befunge-98.tryitonline.net/#code=JiM6PF92IzotMQo6IFwqJDw6X14jCmc6OnY-OTErJSswMApfdiM8XnAwMDwvKzE5CkA-JCQu&input=MTA)
```
&#:<_v#:-1
: \*$<:_^#
g::v>91+%+00
_v#<^p00</+19
@>$$.
```
Explanation:
```
&#:< Gets an integer input (n), and reverses flow direction
&#:< _v#:-1 Pushes n through 0 onto the stack (descending order)
: \*$<:_^# Throws the 0 away and multiplies all the remaining numbers together
(reorganized to better show program flow):
vp00< /+19 _v#< Stores the factorial at cell (0, 0). Pushes 3 of whatever's in
> 91+%+ 00g ::^ cell (0, 0). Pops a, and stores a / 10 at (0, 0),
and adds a % 10 to the sum.
@>$$. Simply discards 2 unneeded 0s and prints the sum.
```
[Answer]
# Javascript ES6 - 61 54 Bytes
```
n=>eval(`for(j of''+(a=_=>!_||_*a(~-_))(n,t=0))t-=-j`)
```
**EDIT:** Thank you Hedi and ETHproductions for shaving off 7 bytes. I'll have to remember that t-=-j trick.
[Answer]
# [AHK](https://autohotkey.com/), 60 bytes
```
a=1
Loop,%1%
a*=A_Index
Loop,Parse,a
b+=A_LoopField
Send,%b%
```
AutoHotkey doesn't have a built-in factorial function and the loop functions have long names for their built-in variables. The first loop is the factorial and the second is adding the digits together.
[Answer]
# J, ~~12~~ 11 bytes
*Saved 1 byte thanks to cole!*
```
1#.10#.inv!
```
This simply applies sum (`1#.`) to the digits (using inverse `inv` of base conversion `#.` with a base of `10`) of the factorial (`!`) of the argument.
## Test cases
Note: the last two test cases are bigints, as marked by a trailing `x`.
```
f=:10#.inv!
(,. f"0) 10 19 469x 985x
10 27
19 45
469 4140
985 10053
```
] |
[Question]
[
Originally the Multiplicative digital root
# Challenge
~~Basically do what the title says~~
# Method
Given a positive integer **1** <= **N** <= **100000000** through one of our [standard input methods](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods), multiply every digit together, ignoring zeroes.
**Ex:** Take a number, say `361218402`:
* `3` \* `6` = `18`
* `18` \* `1` = `18`
* `18` \* `2` = `36`
* `36` \* `1` = `36`
* `36` \* `8` = `288`
* `288` \* `4` = `1152`
* `1152` \* `1` *(ignore zeroes or turn them into ones)* = `1152`
* `1152` \* `2` = `2304`
**The output for `361218402` is `2304`**
***Note: Treat the digit `0` in numbers as `1`.***
# Test Cases
```
1 => 1
10 => 1
20 => 2
100 => 1
999 => 729
21333 => 54
17801 => 56
4969279 => 244944
100000000 => 1
```
[Standard Loopholes](https://codegolf.meta.stackexchange.com/questions/1061/loopholes-that-are-forbidden-by-default) are disallowed, and this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so shortest byte count wins!
Congrats to [Jo King](https://codegolf.stackexchange.com/users/76162/jo-king) who got the bounty with [his 70 byte brain-flak answer!](https://codegolf.stackexchange.com/a/153479/69912)
[Answer]
# [Haskell](https://www.haskell.org/), 27 bytes
```
foldr((*).max 1.read.pure)1
```
[Try it online!](https://tio.run/##PUtLDsIgFLzKCyswSnjQtGXRI3gCdfHSgjZCJVQTTy9GNM5iZjKfC61XF0Lxw7H4W5gy5xshIz0BZXY0yfTITmCJNC8wQKS0B57yvNxBghdwYMi2wFB9WKuvr2KtrRkaY2rc9apuG9ta3dXStKixb5T@/f5gp/IafaDzWnZjSm8 "Haskell – Try It Online")
## Ungolfed with [UniHaskell](https://github.com/totallyhuman/unihaskell) and `-XUnicodeSyntax`
```
import UniHaskell
f ∷ String → Int
f = product ∘ map (max 1 ∘ read ∘ pure)
```
---
## Explanation
I'll start with what I initially had:
```
product.map(max 1.read.pure)
```
This is a *point-free* expression that evaluates to a function taking a string (or a list of characters) **s** (`"301"`) as an argument. It maps `max 1.read.pure` over **s**, essentially taking each character **i**, injecting it into a list (which makes it a string) (`["3", "0", "1"]`), then reading it, which evaluates the string (`[3, 0, 1]`) and finally taking the greater of **i** and **1** (`[3, 1, 1]`). Then it takes the `product` of the resulting list of integers (`3`).
I then golfed it by a byte with:
```
foldr((*).max 1.read.pure)1
```
This works because `product` is equivalent to `foldr (*) 1`. Instead of mapping and folding, I combined the two by folding with `(*).max 1.read.pure` which takes each non-zero digit and multiplies it with the accumulator.
[Answer]
# [Python 2](https://docs.python.org/2/), 34 bytes
```
f=lambda n:n<1or(n%10or 1)*f(n/10)
```
[Try it online!](https://tio.run/##PU3LCsIwEDzrV8wlNJGI2URat6j/UpFgQbcltAe/Pq4enMMM84CZ38tjklhrvjyH1@0@QHo501SsGApTAbldtnKg4GpWKxgF5EHBI4avKjGzOkopadCdgvZHbjl2/Bv80W83cxllQWMorthfYdq1gYEVD31xrn4A "Python 2 – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 4 bytes
```
Do1P
```
[Try it online!](https://tio.run/##y0rNyan8/98l3zDg/@H2R01r/v@3tLTUUTCxNLM0MgcyjAwA "Jelly – Try It Online") or see the **[test suite](https://tio.run/##y0rNyan8/98l3zDg/@H2R01r/v@PNtThMjTQ4TIyANFAwtLSEsgzNDY2BgqYWxgA5U0szSyNzC3BCuAgFgA "Jelly – Try It Online")**
## How it works
```
Do1P - Main link. Argument: n (integer) e.g. 1230456
D - Digits [1, 2, 3, 0, 4, 5, 6]
o1 - Replace 0 with 1 [1, 2, 3, 1, 4, 5, 6]
P - Product 720
```
[Answer]
# [R](https://www.r-project.org/), 40 bytes
```
cat(prod((x=scan()%/%10^(0:12)%%10)+!x))
```
[Try it online!](https://tio.run/##K/r/PzmxRKOgKD9FQ6PCtjg5MU9DU1Vf1dAgTsPAytBIUxXI1NRWrNDU/G9sZmhkaGFiYPQfAA "R – Try It Online")
Since input is guaranteed to have no more than 12 digits, this should work nicely. Computes the digits as `x` (including leading zeros), then replaces zeros with `1` and computes the product.
```
cat( #output
prod( #take the product of
(x= #set X to
scan() #stdin
%/%10^(0:12)%%10) #integer divide by powers of 10, mod 10, yields digits of the input, with leading zeros. So x is the digits of the input
+!x #add logical negation, elementwise. !x maps 0->1 and nonzero->0. adding this to x yields 0->1, leaving others unchanged
))
```
[Answer]
# [C (gcc)](https://gcc.gnu.org), 39 bytes
```
k;f(n){for(k=1;n;n/=10)k*=n%10?:1;k=k;}
```
Needs to be compiled without optimizations (which is the default setting for gcc, anyway).
[Try it online!](https://tio.run/##fY5BCsIwEEX3PUUoFBJRnElK2zgEL@JGIpESOkpxV3r2GHXb@Jfz/jy@P9y9TylSkKyW8JhldEhMfHQIKu4cNwjnE1J0kdY08ktM15GlqpZK5DznfAqybm4XrvciSNOhxqEFrRRtN7BMoIg0/PkqM2ttWYnGmLK1H6C8tLWd1f2GO1Px2/TNp7CmNw)
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), ~~74~~ ~~72~~ 70 bytes
-2 thanks to Nitrodon for suggesting getting the negation of the number so that you only have to increment rather than decrement later
```
{([{}]((((()()()){}){}){}){}){({<({}())><>([[]](){})<>}<><{}>)<>}{}}<>
```
[Try it online!](https://tio.run/##SypKzMzTTctJzP7/v1ojuro2VgMENEFQs7oWCWlU22hU1wJF7WzsNKKjY2M1QMI2drU2djbVtXYgVnUtkPP/v7GZoZGhhYmB0X/dRAA "Brain-Flak – Try It Online")
There might be a few ways to golf this further, such as ~~redoing the multiplication to avoid having to initialise the total with 1.~~ (-2 bytes)
### How It Works:
```
{ Loop over every number
([{}]((((()()()){}){}){}){}) Add 48 to the negative of the ASCII to get the negation of the digit
{ If the number is not 0
({<({}())><>([[]](){})<>}<><{}>)<> Multiply the total by the number
If the total is on an empty stack, add 1
}
{} Pop the excess 0
}<> Switch to the stack with the total
```
[Answer]
# [Pyt](https://github.com/mudkip201/pyt), 3 [bytes](https://github.com/mudkip201/pyt/wiki/Codepage)
```
ąžΠ
```
Explanation:
```
ą Convert input to array of digits (implicit input as stack is empty)
ž Remove all zeroes from the array
Π Get the product of the elements of the array
```
[Try it online!](https://tio.run/##K6gs@f//SOvRfecW/P9vbGZoZGhhYmAEAA)
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes
```
0KSP
```
[Try it online!](https://tio.run/##MzBNTDJM/f/fwDs44P9/E0szA0sjc0sA "05AB1E – Try It Online")
**Explanation**
```
0K # remove zeroes
S # split to list of digits
P # product
```
[Answer]
# [J](http://jsoftware.com/), ~~17~~ ~~14~~ 13 bytes
### -4 bytes courtesy of @GalenIvanov
```
[:*/1>.,.&.":
```
[Try it online!](https://tio.run/##DcSxCkBQFAbg3VP8GYg4zrlXOLdYlMlkNepKFmVQnv4yfN8ZYkp39A4pCjDcrySMyzyF1eWVDFRQQrELWeS348IO//j7hTAM/zNUFUastZC2Y0GtjZpWwwc)
Probably can be improved some. Edit: and so it was.
# Explanation
```
[: */ 1 >. ,.&.":
": Convert to string
,. Convert row to column vector
&. Convert to numbers
1 >. Maximum of each element with 1 (convert 0 to 1)
*/ Product
[: Cap fork
```
`&.`-under is a nifty adverb that applies the verb on the right, then the verb on the left, then the *inverse* of the verb on the right. Also converting back to numbers is technically using eval (`".`-do).
[Answer]
# [Python 2](https://docs.python.org/2/), 43 bytes
```
lambda n:eval('*'.join(`n`.replace(*'01')))
```
[Try it online!](https://tio.run/##PY5BDoIwEEX3nGJ2BdKYdlrAktSLAImoJWKwEKgmnh4RC7P6/@XnZYaPu/cW50aXc1c/L7cabG7edReSmBwefWvDsz0fRjN09dWEMWGcRFE0OzO5CTQUZVCIlCM/SoYUBZMVXRCnwP@BbQmXhJ7tUClFIUP1X3AhBIXEK7IjWzRJujapUoXZMkYplZSbZz8vrIKmH@H3HIXRTK/OQWvXPuUBDGNrnedaN@GPR3RdE30i1JP5Cw "Python 2 – Try It Online")
[Answer]
# JavaScript (ES6), 28 bytes
Designed for 32-bit integers.
```
f=n=>!n||(n%10||1)*f(n/10|0)
```
### Test cases
```
f=n=>!n||(n%10||1)*f(n/10|0)
console.log(f(1)) // => 1
console.log(f(10)) // => 1
console.log(f(20)) // => 2
console.log(f(100)) // => 1
console.log(f(999)) // => 729
console.log(f(21333)) // => 54
console.log(f(17801)) // => 56
console.log(f(4969279)) // => 244944
```
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + coreutils + sed + bc, ~~27~~ ~~24~~ 23 bytes
```
tr 0 1|sed s/\\B/*/g|bc
```
[Try it online!](https://tio.run/##S0oszvj/v6RIwUDBsKY4NUWhWD8mxklfSz@9Jin5/39DLkMDLiMDIGnAZWlpyWVkaGxszGVobmFgyGViaWZpZG4JkoMDLgA "Bash – Try It Online")
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 5 bytes
```
⊇ẹ×ℕ₁
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r//1FX@8NdOw9Pf9Qy9VFT4///xmaGRoYWJgZG/6MA "Brachylog – Try It Online")
### Explanation
```
⊇ Take a subset of the input
ẹ Split the subset into a list of digits
× Product
ℕ₁ This product must be in [1, +∞)
```
This works because `⊇` unifies from large subsets to small subsets, so the first one that will result in a non-zero product is when all zeroes are excluded and nothing else.
[Answer]
# [Perl 5](https://www.perl.org/), 23 + 1 (`-p`) = 24 bytes
```
$\=1;s/./$\*=$&||1/ge}{
```
[Try it online!](https://tio.run/##K0gtyjH9/18lxtbQulhfT18lRstWRa2mxlA/PbW2@v9/QwMj43/5BSWZ@XnF/3ULAA "Perl 5 – Try It Online")
[Answer]
# Java 8, ~~55~~ ~~54~~ ~~53~~ 51 bytes
```
int f(int n){return n>0?(n%10>0?n%10:1)*f(n/10):1;}
```
Port of [*@Dennis*' Python 2 answer](https://codegolf.stackexchange.com/a/153291/52210).
-1 byte thanks to *@RiaD*.
[Try it here.](https://tio.run/##XZDBbsIwDIbvPIWFNClZNRa3CEjLtifYieO0Q4AWBYpbNSnqhPrsXQjV1mIpsn7b@azfR3VRL0WZ0nF/6na5MgY@labrBMBYZfUOurygA2RMkwXi1yq1dUVA7@KD0RMKl28pRv6cMXpFwWNM2g6grLe5@95TLoXew9mR2cZWmg5f34rflgBkReXZ@g0TvUaR6CDgvgNgU2OZ5snkTzj@QIVi3BtJKeVoFqMoGo0vVwKHhblcyHApHxg@HtbcY1iMFhjiai5CX2zd@7@g93634nw2ve/Nj7HpeVbUdla6i9icWBNMY5gGGWt4j2m7Xw)
**~~55~~ 54 bytes version:**
```
n->{int r=1;for(;n>0;n/=10)r*=n%10>0?n%10:1;return r;}
```
[Try it online.](https://tio.run/##bVDLboMwELz3K1aRKpmiUBuiJI4L/YLmkmPVg0ucyilZkDERVcS3U/M4QJSVH9rZ1czOnuVVLvNC4fn426aZLEv4kBpvTwAarTInmSrYd2kPQEq6Fz3hkMZdd0orrU5hDwgxtLhMbl2LiZk45YYITKjA15hRz7zE@MxoQt@7b8eEUbYyCEY0rRi4iuo7c1wj5TXXR7i4ccjBGo0/n1/SG0bpmDsV7VT0G6NC@77XVwCsKi3R/YRj4rQnWUjntVnKOZ/1siiKZu2bLWVTYMXXPNzwO44@7mSGmILRmoVsu6Lhg3X23gcrzmc9@j78lVZdgryyQeE2YjMktb/YwcLHICW1NxI17T8)
[Answer]
# Julia 0.6, 26 bytes
```
!x=prod(max.(digits(x),1))
```
Example of use:
```
julia> !54
20
```
[Try it online!](https://tio.run/##VY1BCsMgEEX3PYXJSqGEaEzsLAKlZ@gFbBWxNLZUA7m91QZqMoth3jw@/zE/rRxirJbx/XkpPMmlwcoaGzxeyJESEmdvnUEX6XVz1T4cziFtrwOq84HuSfga3bSxbnWowpSMIy3U7pBlZBu71wCQWDAoAdp1Xfr1vITEqc0l/fB/cRiAiZxlnAPn24J1fjXaqfgF "Julia 0.6 – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 30 bytes
```
f=([a,...b])=>a?(+a||1)*f(b):1
```
[Try it online!](https://tio.run/##BcFRDkQwEADQ68wsJlqbjazgIOJjVCtEjLTiy93HexvfnFxcz6s4ZPaqoYWBcyKaRmw77iHj5zH4CTDh32jj5Eiye9plgQBnFOdTIo7LPdgRsVGtfsaa@lvaFw "JavaScript (Node.js) – Try It Online")
Takes **string** as an input, treats it as array, and by array destructuring separates the first element `[a,...b]`. `+a||1` returns digit corresponding to `a` character. I guess that rest is self explaining..
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 21 bytes
*Thanks to @Luis Mendo for saving a byte and thanks to @alephalpha for saving another byte!*
```
@(n)prod((k=n-48)+~k)
```
Takes input as a string of digits.
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPs6AoP0VDI9s2T9fEQlO7Llvzf5qCrUJiXrE1F1eahrqxmaGRoYWJgZG6JohrCKUMILSRAYwPZVhaWkJlDI2NjaGS5hYGUH0mlmaWRuaWcE1woK75HwA)
**30 bytes:**
```
@(n)prod((k=num2str(n)-48)+~k)
```
Takes input as a number.
[Try it online!](https://tio.run/##y08uSSxL/f/fQSNPs6AoP0VDI9s2rzTXqLikCCiia2KhqV2Xrfk/TcFWITGv2JqLK03D2MzQyNDCxMBIE8gxBBMGINLIAMIGU5aWlmAxQ2NjY7CwuYUBWK2JpZmlkbklVCkcaP4HAA)
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 3 bytes
```
fꜝΠ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJBIiwiIiwiZuqcnc6gIiwiIiwiMzYxMjE4NDAyIl0=)
Pyt isn't the only language to do 3 bytes :3
### Explained
```
fꜝΠ
f # flatten to a list
ꜝ # remove all 0's
Π # product
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 88 bytes
Readable version:
```
#Push a 1 onto the alternate stack. Return to the main stack
(<>())<>
#While True:
{
#Push the current digit minus 48 (the ASCII value of '0') onto the alternate stack
({}[((((()()()){}){}){}){}]<>)
#If it's not 0...
{
(<
#Multiply the top two values (the current digit and the current product that started at 1)
({}<>)({<({}[()])><>({})<>}{}<><{}>)
#Also push a 0
>)
#Endwhile
}
#Pop the 0
{}
#Return to the main stack
<>
#Endwhile
}
#Toggle to the alternate stack, and implicitly display
<>
```
[Try it online!](https://tio.run/##PY2xCoBACIb3e4pGHQ5qqkF8kbjhGoIoGlrFZze9jlRU9Pt1e@px5/2qpxkQAyJxSpLS4AaiK4RhOIr@UYjxY6TlRpPzPgehJsSC7BedJ9bYkCij6wLWru7Vn3pHbDbNyzhZri8 "Brain-Flak – Try It Online")
[Answer]
# [Clojure](https://clojure.org/), 56 bytes
```
(fn[n](apply *(replace{0 1}(map #(-(int %)48)(str n)))))
```
Pretty basic. Turns the number into a string, then subtracts 48 from each character to turn them back into numbers. It then replaces each 0 with a 1, and applies `*` to the resulting list of numbers (which reduces `*` over the list). Can accept a number, or a stringified number.
[Try it online!](https://tio.run/##S87JzyotSv2vUVCUmVeSk6eg8V8jLS86L1YjsaAgp1JBS6MotSAnMTm12kDBsFYjN7FAQVlDVwOoVkFV08RCU6O4pEghTxME/isZmxkaGVqYGBgpAXkA "Clojure – Try It Online")
```
(defn non-zero-prod [n]
(let [; Abusing strings to get each digit individually
str-n (str n)
; Then turn them back into numbers
digits (map #(- (int %) 48) str-n)
; Substitute each 0 for a 1
replaced (replace {0 1} digits)]
; Then get the product
(apply * replaced)))
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 5 bytes
```
!UXzp
```
Input is taken as a string
Try it at [MATL Online!](https://matl.suever.net/?code=%21UXzp&inputs=%27361218402%27&version=20.6.0) Or [verify test cases in Try It Online!](https://tio.run/##y00syfmf8F8xNKKq4L9LyH91Q3UudVMgNjQAEkYGYBaItLS0BAkYGhsbg8TMLQxAKk0szSyNzC0hquBAHQA)
### Explanation
```
! % Implicit input: string (row vector of chars). Transpose into
% a column vector of chars
U % Convert from string to number. Treats each row independently,
% producing a column vector of numbers
Xz % Keep only nonzeros
p % Product. Implicit display
```
[Answer]
# Befunge, ~~23~~ 22 bytes
```
1<*_$#`.#0@#:+!:-"0"~$
```
[Try it online!](http://befunge.tryitonline.net/#code=MTwqXyQjYC4jMEAjOishOi0iMCJ+JA&input=MzYxMjE4NDAy)
**Explanation**
```
1< Push 1, turn back left, and push a second 1.
$ Drop one of them, leaving a single 1, the initial product.
-"0"~ Read a char and subtract ASCII '0', converting to a number.
+!: If it's 0, make it 1 (this is n + !n).
` 0 : Then test if it's greater than 0, to check for EOF.
_ If it is greater than 0, it wasn't EOF, so we continue left.
* Multiply with the current product, becoming the new product.
1< Now we repeat the loop, but this time push only a single 1...
$ ...which is immediately dropped, leaving the current product.
_ On EOF, the input value will be negative, so we branch right.
$ We don't need the input, so drop it.
. @ Leaving us with the product, which we output, then exit.
```
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 36 33 bytes
Simple Javascript (ES6) method that takes input as number string, spreads it into an array, then reduces it through multiplication or returns the value if the result is 0.
3 bytes saved thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)
```
s=>[...s].reduce((a,b)=>b*a||a,1)
```
[Try it online!](https://tio.run/##BcFRCoMwDADQ/52kFRfWKmMg9SLiR9oG2RAjifPLu8f3fniiFvnux3PjSibJNI0TAOgMQvVfyDlss09jbvC6sA3ehkfhTXklWHlx4nbhQqqAspxTnL0fzLp3iOHTv@IN "JavaScript (Node.js) – Try It Online")
[Answer]
# Ruby, ~~42~~ ~~40~~ ~~35~~ ~~32~~ 27 bytes
```
p eval (gets.chars-[?0])*?*
```
Assumes no newlines in input
[Major influence](https://codegolf.stackexchange.com/a/153290/55458)
-2 bytes thanks to @GolfWolf
-5 bytes thanks to @Conor O'Brien
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), 45 bytes
```
s->s.chars().reduce(1,(a,b)->b<49?a:a*(b-48))
```
[Try it online!](https://tio.run/##ZU/LasMwELznKwZDQEplYSduEudVein00FN6Kz3Ir1SpIxlLDoSQb3dlOzl1QbswM5phjuIsfF3l6pj9tvJU6dri6DDeWFnyyXr0DysalVqpVUdWTVLKFGkpjMGHkArXEXBHjRXWnbOWGU6OI3tbS3X4@oaoD4b2UuBTvyv7dvfcDJIdCmxb4@8MT39EbQjldZ41aU5CRgRLqL9LNlH8IlZiQhI/WlLarns3qazzt7mxBltcETJMGWYMEcMzw5xhwbBkiBnCwHFBd92KY4dMw9nMScPFMnD/ongeTxe98D64DSGFrkFcUp@zGtIedYD9xdj8xHVjeeXK2IJ44zAwK4yzsfJYL2couKiq8vJqXHvieU8dSungfxt179b@AQ "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Ruby + `-n`](https://codegolf.meta.stackexchange.com/questions/13792/a-proposal-on-command-line-flags), 25 bytes
```
p eval ($_.chars-[?0])*?*
```
[Try it online!](https://tio.run/##KypNqvz/v0AhtSwxR0FDJV4vOSOxqFg32t4gVlPLXuv/f0MjYxNTg3/5BSWZ@XnF/3XzAA "Ruby – Try It Online")
### [Ruby (vanilla)](https://www.ruby-lang.org/), 27 bytes
```
p eval (gets.chars-[?0])*?*
```
[Try it online!](https://tio.run/##KypNqvz/v0AhtSwxR0EjPbWkWC85I7GoWDfa3iBWU8te6/9/QyNjE1MDAA)
[Answer]
# **[C#](https://docs.microsoft.com/en-us/dotnet/csharp/), 97 Bytes (First code golf)**
```
static int X(int y){var z=y.ToString();int r=1;foreach(var q in z){if(q!=48){r*=q-48;}}return r;}
```
Not sure if i had to wrap it in a method or not so just included it to be safe.
Takes an Int in, converts it to a string and returns the multiple of each of the characters ignoring 0's. Had to minus 48 due to the program using the ascii value as it reads it as a char.
[Answer]
# [C# (Visual C# Interactive Compiler)](http://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 46 bytes
```
i.Select(c=>c>48?c-48:1).Aggregate((p,c)=>p*c)
```
[Try it online!](https://tio.run/##jY/BisIwEIbvPsVQPCSiJZMUbdRmWYQFwZuHPS9DLAGJ0saT@OxVSdDLYvuf/oHvG2aonVHrup@Lp/U@NM7XU9j6oKSBA1TgoDKdy/f2aCkwqgyZovyiWVEukeffdd3Y@i9Yxs5T4pU5T4h3q9Foc/Lt6Wjz38YFu3PeMhhnao4Sy0LIJVwP7D1m/JYBX/0vQQyKKKEYQstEyyE0itfuIbjWOuKP0otLVEqlW561V8BFKTCd86w9QqHnWi7SQWn4qDx@jHm9HJOk7g4 "C# (Visual C# Interactive Compiler) – Try It Online")
[Answer]
# [Rockstar](https://codewithrockstar.com/), 61 bytes
```
Listen to N
Cut N
O's 1
While N
Let O be*roll N-0 or 1
Say O
```
[Try it](https://codewithrockstar.com/online) (Code will need to be pasted in)
] |
[Question]
[
# Challenge
Your task in this question is to write a program or a named function which takes a positive integer `n` (greater than 0) as input via STDIN, ARGV or function arguments and outputs an array via STDOUT or function returned value.
**Sounds simple enough ? Now here are the rules**
* The array will only contain integers from `1` to `n`
* Each integer from `1` to `n` should be repeated `x` times where `x` is the value of each integer.
*For example:*
Input:
```
5
```
Output:
```
[1, 2, 2, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 5]
```
The array may or may not be sorted.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") so winner is shortest code in bytes.
**Bonus**
Multiply your score by `0.5` if no two adjacent integers in your output array are same.
For example for `n = 5`, one such configuration would be
```
[5, 4, 5, 4, 3, 4, 5, 2, 5, 3, 1, 2, 3, 4, 5]
```
[Answer]
# Ruby (recursive), 41 bytes \* 0.5 = 20.5
```
def n(n,i=1);i>n ?[]:n(n,i+1)+[*i..n];end
```
Or using a lambda (as recommended by histocrat and Ventero): 34 bytes \* 0.5 = 17
```
r=->n,i=n{i>0?[*i..n]+r[n,i-1]:[]}
```
(call using `r[argument]`)
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 9 bytes \* 0.5 = 4.5
```
smrhQhdUQ
```
With help from @FryAmTheEggman
[Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py)
---
## Explanation
```
s reduce + on list
m map
rhQhd lambda d: reversed(range(d+1, Q+1)), over
UQ range(Q)
```
where `Q` is the input.
[Answer]
# APL, 4 characters
[`/⍨⍳⎕`](http://tryapl.org/index.dyalog?a=/%u2368%u23735&run)
How it works:
`⎕` reads user input. As for output, APL by default prints the result from every line.
`⍳n` is the integers from 1 to `n`. Example: [`⍳3`](http://tryapl.org/?a=%u23733&run)`←→ 1 2 3`
`/` means *replicate*. Each element from the right argument is repeated as many times as specified by its corresponding element from the left argument. Example: [`2 0 3/'ABC'`](http://tryapl.org/?a=2%200%203/%27ABC%27&run)`←→ 'AACCC'`
`⍨` is the *commute operator*. When it occurs to the right of a function, it modifies its behaviour, so it either swaps the arguments (`A f⍨ B ←→ B f A`, hence "commute") or provides the same argument on both sides (`f⍨ A ←→ A f A`, a "selfie"). The latter form is used in this solution.
---
Bonus:
[`6-∊⌽⍳¨⍳⎕`](http://tryapl.org/?a=6-%u220A%u233D%u2373%A8%u23735&run) (8 characters, [thanks @phil-h](https://codegolf.stackexchange.com/questions/42536/create-an-array-with-repeated-numbers#comment-100978))
[`⍳5`](http://tryapl.org/?a=%u23735&run) (iota five) is `1 2 3 4 5`.
[`⍳¨ ⍳5`](http://tryapl.org/?a=%u2373%A8%20%u23735&run) (iota each iota five) is `(,1)(1 2)(1 2 3)(1 2 3 4)(1 2 3 4 5)`, a vector of vectors. *Each* (`¨`) is an operator, it takes a function on the left and applies it to each item from the array on the right.
`⌽` reverses the array, so we get `(1 2 3 4 5)(1 2 3 4)(1 2 3)(1 2)(,1)`.
`∊` is *enlist* (a.k.a. *flatten*). Recursively traverses the argument and returns the simple scalars from it as a vector.
[Answer]
# Haskell, 31 characters = 15.5 score
```
f n=[y|x<-[n,n-1..1],y<-[x..n]]
```
### 27 characters without the bonus
```
f n=[x|x<-[1..n],_<-[1..x]]
```
[Beaten by Proud Haskeller](https://codegolf.stackexchange.com/posts/42577/revisions)
[Answer]
# C, 22 = 44 bytes \* 0.5
The function `h` takes two parameters. The first is an `int` specifying *n*. The second is an `int*` which is the output buffer.
```
h(n,o)int*o;{for(n&&h(~-n,o+=n);*--o=n--;);}
```
**Test program**
```
main(){
int wow[999],*i;
memset(wow,0,sizeof(wow));
h(6, wow);
for(i=wow;*i;i++)printf("%d ", *i);
}
```
[Answer]
## [Pyth](https://github.com/isaacg1/pyth) - ~~15~~ 10 \* .5 = 5
```
smr-QdhQUQ
```
[Try it online.](http://isaacg.scripts.mit.edu/pyth/index.py)
Expects input on stdin. Independently discovered algorithm. Thanks @Sp3000 for helping me stick the last Q in there :P Also, irony? XD
Explanation:
```
Q=eval(input()) : implicit
s : The sum of...
m UQ : map(...,range(Q))
r-QdhQ : range(Q-d,Q+1)
```
[Answer]
# Python 2, 53 bytes \* 0.5 = 26.5
```
i=n=input()
x=[]
while i:x+=range(i,n+1);i-=1
print x
```
Shamelessly borrowed @VisualMelon's idea
[Answer]
# CJam, ~~12~~ 15 bytes \* 0.5 = 7.5
```
li_,f{),f-W%~}`
```
This is full STDIN-to-STDOUT program. It concatenates increasing suffixes of the `1 ... n` range, which ensures that no two adjacent numbers are identical.
[Test it here.](http://cjam.aditsu.net/)
[Answer]
# Haskell, 34 bytes \* 0.5 = 17
```
0%n=[]
i%n=[i..n]++(i-1)%n
g n=n%n
```
That's the first time I've ever used Haskell for golfing. Call with `g <number>`.
[Answer]
# Bash + coreutils, 28/2 = 14
[Shamelessly stealing @pgy's idea](https://codegolf.stackexchange.com/a/42555/11259) and golfing:
```
seq -f"seq %g $1" $1 -1 1|sh
```
---
# Pure bash (no coreutils), 30/2 = 15
Eval, escape and expansion hell:
```
eval eval echo \\{{$1..1}..$1}
```
[Answer]
## GolfScript (14 bytes \* 0.5 = score 7)
```
~:x,{~x),>~}%`
```
[Online demo](http://golfscript.apphb.com/?c=Oyc1JwoKfjp4LHt%2BeCksPn59JWA%3D)
I think this is probably similar to some existing answers in that it builds up the array `concat( [n], [n-1, n], [n-2, n-1, n], ..., [1, 2, ..., n] )`
Sadly I wasn't able to golf any further the arguably more elegant:
```
~:x]{{,{x\-}/}%}2*`
```
which puts the input `x` into an array and then twice applies `{,{x\-}/}%`, which maps each element in an array to a count down of that many elements from `x`.
[Answer]
# Haskell, 14 = 28 bytes / 2
```
f n=n:[1..n-1]>>= \r->[r..n]
```
example output:
```
>f 5
[5,1,2,3,4,5,2,3,4,5,3,4,5,4,5]
```
# 24 bytes without the bonus:
```
f n=[1..n]>>= \r->[r..n]
```
[Answer]
# C# - 81 (161bytes \* 0.5)
Simple job in C#, hopefully gets the no-neibouring-numbers bonus. Reads an int from stdin, writes out an array like the example to stdout.
```
class P{static void Main(){int n=int.Parse(System.Console.ReadLine()),m=n-1,i;var R="["+n;for(;m-->0;)for(i=m;i++<n;)R+=", "+i;System.Console.WriteLine(R+"]");}}
```
More readable:
```
class P
{
static void Main()
{
int n=int.Parse(System.Console.ReadLine()),m=n-1,i;
var R="["+n;
for(;m-->0;)
for(i=m;i++<n;)
R+=", "+i;
System.Console.WriteLine(R+"]");
}
}
```
Examples output:
```
n = 5
[5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5]
```
[Answer]
# JavaScript, ES6, 41 bytes
```
f=i=>[...Array(i).fill(i),...i?f(--i):[]]
```
This creates a function `f` which can be called like `f(6)` and it returns the required array.
This uses a recursive approach, where each iteration creates an array of `i` elements all valued `i` and concatenates an array returned by `f(i-1)` with stopping condition of `i==0`.
Works on latest Firefox.
[Answer]
# vba, 76\*0.5=38
```
Sub i(q)
For Z=1 To q:For x=q To Z Step -1:Debug.?x;",";:Next:Next
End Sub
```
[Answer]
# [Haxe](http://Haxe.org), 53 bytes
```
function l(v)return[for(i in 0...v)for(j in 0...i)i];
```
Works with l(6); because of array comprehension.
Test online <http://try.haxe.org/#741f9>
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 26 \* 0.5 = 13
-8 bytes thanks to @att.
```
Join@@Range[#,Range@#,-1]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2b73ys/M8/BISgxLz01WlkHTDso6@gaxqr9DyjKzCtxSHOw/A8A "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 3 × 0.5 = 1.5 bytes
```
rRF
```
[Try it online!](https://tio.run/##y0rNyan8/78oyO3///@mAA "Jelly – Try It Online")
## Explanation
```
rRF
r Range from {input} to
R each number from 1 to {input}
F Flatten
```
For example, with input 3, the `rR` gives us a range from 3 to 1 (i.e. `[3, 2, 1]`, then a range from 3 to 2 (i.e. `[3, 2]`), then a range from 3 to 3 (i.e. `[3, 3]`). Flattening that gives `[3, 2, 1, 3, 2, 3]`), which meets the problem specifications and has no adjacent numbers.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 4 bytes \* 0.5 = 2
```
Σ↔ḣṫ
```
[Try it online!](https://tio.run/##ARUA6v9odXNr///Oo@KGlOG4o@G5q////zU "Husk – Try It Online")
### Explanation
```
Σ↔ḣṫ
ṫ range from input to 1, [5,4,3,2,1]
ḣ prefixes, [[5],[5,4],[5,4,3]...]
↔ reverse, [[5,4,3,2,1],[5,4,3,2]...]
Σ concat, [5,4,3,2,1,5,4,3,2...]
```
[Answer]
## R, 44 \*.5 = 22
```
f=function(n){r=0;for(i in 1:n)r=c(r,n:i);r}
```
A quick test
```
> f(1)
[1] 1
> f(2)
[1] 2 1 2
> f(3)
[1] 3 2 1 3 2 3
> f(4)
[1] 4 3 2 1 4 3 2 4 3 4
```
[Answer]
# JavaScript, ES6, 66 bytes \* 0.5 = 33
```
f=i=>(g=n=>[...Array(n).fill().map((v,x)=>i-x),...n?g(n-1):[]])(i)
```
Building on [Optimizer's recursive approach](https://codegolf.stackexchange.com/a/42541/7796), we can build descending runs of decreasing length, like `[4,3,2,1, 4,3,2, 4,3, 4]`.
Instead of making same-value subarrays with `Array(i).fill(i)`, we make `undefined`-filled subarrays of the appropriate length with `Array(n).fill()` and then change the values to a descending run using `.map((v,x)=>i-x)`. Also, we define and recurse over an inner function `g`; the outer function `f` exists only to store the value of `i` while `g` recurses.
[Answer]
## T-SQL, 176 \* 0.5 = 88
Since you seemed to miss the T-SQL @Optimizer, here it is in all it's verbose glory :).
A couple of function options, a Scalar and a Inline Table Valued function. The Scalar function uses while loops to recurse and returns a string of numbers, where the Inline Table Valued function uses a recursive CTE for a sequence and returns a table. Of course these will never be competitive, so I haven't spent a lot of time golfing.
**Inline Table Valued Function, 176 \* .5**
```
CREATE FUNCTION F(@ INT)RETURNS TABLE RETURN WITH R AS(SELECT @ N UNION ALL SELECT N-1FROM R WHERE N>0)SELECT B.N FROM R CROSS APPLY(SELECT TOP(R.N)N FROM R A ORDER BY N DESC)B
```
Called as follows
```
SELECT * FROM dbo.F(5)
```
[SQLFiddle](http://sqlfiddle.com/#!6/b4f86/1/0) example
**Scalar Function, 220 \* .5**
```
CREATE FUNCTION G(@ INT)RETURNS VARCHAR(MAX)AS BEGIN DECLARE @S VARCHAR(MAX),@N INT=1,@I INT,@C INT WHILE @N<=@ BEGIN SELECT @I=@N,@C=@ WHILE @C>=@I BEGIN SELECT @S=CONCAT(@S+',',@C),@C-=1 END SET @N+=1 END RETURN @S END
```
Called as follows
```
SELECT dbo.G(5)
```
[SQLFiddle](http://sqlfiddle.com/#!6/00b75/2/0 "SQL Fiddle Example of use") example
[Answer]
# perl ,26 bytes
```
for(1..$n){print"$_ "x$_;}
```
[Answer]
### JavaScript(readable), 131 bytes
I'm new to Code Golf so this isn't the best
```
function f(n) {
var arr = [];
for(var i = 1; i <= n; i++) {
for(var j = 0; j < i; j++) {
arr.push(i);
}
}
return arr;
}
```
### JavaScript(less readable), 87 bytes
Minified using [jscompress.com](http://jscompress.com)
```
function f(e){var t=[];for(var n=1;n<=e;n++){for(var r=0;r<n;r++){t.push(n)}}return t}
```
[Answer]
# TECO, 25 bytes \* 0.5 = 12.5
```
a\+1%a%b<qauc-1%b<-1%c=>>
```
The above barely beats the non-bonus version at 13 bytes:
```
a\%a<%b<qb=>>
```
[Answer]
## C#, ~~114~~ 99 \* 0.5 = 49.5 bytes
*(With a little help from VisualMelon's answer) Edit: and James Webster's comment*
```
int[]A(int n){int m=n,i,c=0;var a=new int[n*(n+1)/2];while(m-->0)for(i=m;i++<n;)a[c++]=i;return a;}
```
*Ungolfed:*
```
int[] FooBar(int n)
{
int altCounter = n, i, arrayCounter = 0;
var returnArray = new int[n * (n + 1) / 2];
while(m-->0)
for(i = altCounter; i++ < n; )
returnArray[arrayCounter++]=i;
return returnArray;
}
```
---
~~There is an unsafe version that I shamelessly took from feersum's C answer, but I'm not 100% sure it fits within the rules since you have to allocate the memory before calling the method.~~
**C# (unsafe), 82 \* 0.5 = 41 bytes**
```
unsafe void A(int n,int*p){int*z=p;int m=n,i;while(m-->0)for(i=m;i++<n;)z++[0]=i;}
```
Called as follows:
```
int n = 5, length = (int)((n / 2f) * (n + 1));
int* stuff = stackalloc int[length];
int[] stuffArray = new int[length];
A(n, stuff);
System.Runtime.InteropServices.Marshal.Copy(new IntPtr(stuffArray), stuffArray, 0, stuffArray.Length);
//stuffArray == { 5, 4, 5, 3, 4, 5, 2, 3, 4, 5, 1, 2, 3, 4, 5 }
```
Per VisualMelon's suggestion (thanks!), the unsafe code can be re-made with safe code which reduces the size even further! Still poses the question if the creation of the final result array is allowed to be done outside of the method.
**C#, 72 \* 0.5 = 36 bytes**
```
void A(int n,int[]p){int z=0,m=n,i;while(m-->0)for(i=m;i++<n;)p[z++]=i;}
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 4 bytes \* 0.5 = 2
```
L.s˜
```
[Try it online!](https://tio.run/##yy9OTMpM/f/fR6/49Jz//00B "05AB1E – Try It Online")
```
L # Inclusive range
.s # Suffixes
˜ # Flatten
```
[Answer]
### Bash with seq, expr and xargs = 59 / 2 = 29.5
Save it and run with the number as the first argument.
```
seq $1|xargs -n1 seq|xargs -n1 expr $1 + 1 -|sed 1d;echo $1
```
[Answer]
# C#, ~~116~~ 115 + 33 = 148 bytes
Not the shortest code, but... it works anyway :P
```
int[]l(int m){List<int>i=new List<int>();for(int j=1;j<=m;j++){for(int x=0;x<j;x++){i.Add(j);}}return i.ToArray();}
```
Requires this at the top of the file (33 bytes):
```
using System.Collections.Generic;
```
Un-golfed version:
```
int[] RepatedNumberList(int m)
{
List<int> intList = new List<int>();
for (int j = 1; j <= m; j++)
{
for (int x = 0; x < j; x++)
{
intList.Add(j);
}
}
return initList.ToArray();
}
```
[Answer]
# J, 23 \* 0.5 = 11.5
```
f=.-;@(<@|.@i."0@>:@i.)
f 5
5 4 5 3 4 5 2 3 4 5 1 2 3 4 5
```
# J, 11
```
f=.#~@i.@>:
f 5
1 2 2 3 3 3 4 4 4 4 5 5 5 5 5
```
] |
[Question]
[
Given a string that contains only lowercase letters, encode that string with the alphabet cipher.
To encode with the alphabet cipher (I will be using the example `hello`):
1. First, convert each letter in the string to a number depending on its position in the alphabet (`a` = `1`, `b` = `2`, etc.) Example: `8` `5` `12` `12` `15`
2. Pad each number to two characters with `0`s. Example: `08` `05` `12` `12` `15`
3. Join. Example: `0805121215`
## Test cases
```
helloworld -> 08051212152315181204
codegolf -> 0315040507151206
alphabetcipher -> 0112160801020520030916080518
johncena -> 1015081403051401
```
Remember, this is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the code with the fewest number of bytes wins.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), ~~11~~ 6 bytes
**Code:**
```
Ç4+€¦J
```
**Explanation:**
First, we convert the string to their ASCII values. `codegolf` would become:
```
[99, 111, 100, 101, 103, 111, 108, 102]
```
To get to the indices of the alphabet, you subtract `96`:
```
[3, 15, 4, 5, 7, 15, 12, 6]
```
To pad with zeros, add `100` to each element and remove the first character of each int. For the above example, `+100` would be:
```
[103, 115, 104, 105, 107, 115, 112, 106]
```
And removing the first character of each would lead to:
```
[03, 15, 04, 05, 07, 15, 12, 06]
```
We can merge both steps above (the `-96` and the `+100`) part to just `+4`. For the code:
```
Ç # Convert to an array of ASCII code points
4+ # Add four to each element in the array
€¦ # Remove the first character of each element
J # Join to a single string
```
[Try it online!](http://05ab1e.tryitonline.net/#code=w4c0K-KCrMKmSg&input=Y29kZWdvbGY)
[Answer]
# Python 2, 42 bytes
```
f=lambda s:s and`ord(s[0])+4`[1:]+f(s[1:])
```
Test it on [Ideone](http://ideone.com/p7RFlo).
[Answer]
# C, ~~55~~ 43 bytes
```
f(char*c){for(;*c;)printf("%02d",*c++-96);}
```
[ideone](http://ideone.com/SZPzoT)
[Answer]
# Pyth, ~~11~~ 10 bytes
```
FNwpt`+4CN
```
[Try it!](https://pyth.herokuapp.com/?code=%23FNwpt%60%2B4CN%29%22&input=helloworld%0Acodegolf%0Aalphabetcipher%0Ajohncena&debug=0) My first go at Pyth.
```
FNwpt`+4CN
FNw # For N in w (w is input, N will be single char)
p # Print without newline
CN # Int with code point `N`
+4CN # Add 4 to int with code point N
`+4CN # representation of above (basically to string)
t`+4CN # Tail (All but first character)
```
Python equivalent:
```
for N in input():
print(repr(ord(N) + 4)[1:], end='')
```
[Answer]
# Python, 46 bytes
```
lambda x:"".join("%02i"%(ord(j)-96)for j in x)
```
Pretty straightforward. [**Try it on repl.it!**](https://repl.it/EIwU/0)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~9~~ 7 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
O+4ṾḊ$€
```
**[TryItOnline](http://jelly.tryitonline.net/#code=Tys04bm-4biKJOKCrA&input=&args=aGVsbG8)**
### How?
```
O+4ṾḊ$€ - Main link: s e.g. hello
O - cast to ordinals e.g. [ 104, 101, 108, 108, 111]
+4 - add 4 e.g. [ 108, 109, 112, 112, 115]
$€ - last two links as a monad for €ach
Ṿ - uneval, effectively converts to strings e.g. ["108","109","112","112","115"]
Ḋ - dequeue, remove the leading '1' e.g. [ "08", "09", "12", "12", "15"]
- implicit print e.g. "0809121215"
```
[Answer]
# Haskell, ~~fortyfour 30~~ 28 bytes
```
(>>=tail.show.(+4).fromEnum)
```
Using the `+4` approach from [Adnan's answer](https://codegolf.stackexchange.com/a/97864/56433) saves 14 bytes.
[Try it on Ideone.](http://ideone.com/RzY4ET) Usage:
```
> (>>=tail.show.(+4).fromEnum)"codegolf"
"0315040507151206"
```
Two bytes off thanks to [xnor](https://codegolf.stackexchange.com/users/20260/xnor). Old version:
```
f a=['0'|a<'k']++(show$fromEnum a-96)
(f=<<)
```
[Answer]
## Perl, 29 bytes
28 bytes of code + `-n` flag.
```
printf"%02s",-96+ord for/./g
```
Run with :
```
perl -ne 'printf"%02s",-96+ord for/./g' <<< "helloworld"
```
[Answer]
# JavaScript (ES6), ~~52~~ 49 bytes
```
f=s=>s&&(s.charCodeAt()+4+f(s.slice(1))).slice(1)
```
Recursion turned out to be 3 bytes shorter than `.replace`:
```
s=>s.replace(/./g,s=>(s.charCodeAt()+4+"").slice(1))
```
`parseInt(s,36)` is slightly longer for each approach, because you have to change `4` to `91`:
```
s=>s.replace(/./g,s=>(parseInt(s,36)+91+"").slice(1))
f=s=>s&&(parseInt(s[0],36)+91+f(s.slice(1))).slice(1)
```
[Answer]
# Japt, 10 bytes
```
¡4+Xc)s s1
```
Probably doesn't get shorter than this...
[**Test it online!**](http://ethproductions.github.io/japt/?v=master&code=oTQrWGMpcyBzMQ==&input=ImhlbGxvd29ybGQi)
## Explanation
```
¡ // Map each char X in the input by this function:
4+Xc) // Take 4 + the char code of X.
s s1 // Convert to a string, then remove the first char.
// Implicit: output last expression
```
[Answer]
# Java 7,60 bytes
```
void f(char[]s){for(int i:s)System.out.printf("%02d",i-96);}
```
[Answer]
# MATL, ~~12~~ 11 bytes
*1 byte saved thanks to @Luis*
```
4+!V4LZ)!le
```
[**Try it Online**](http://matl.tryitonline.net/#code=NCshVjRMWikhbGU&input=J2hlbGxvd29ybGQn)
[Answer]
# [Hexagony](https://github.com/m-ender/hexagony), 33 bytes
```
10}{'a({=!{{\.@29$\,<.-":!\>Oct\%
```
[Try it Online!](http://hexagony.tryitonline.net/#code=MTB9eydhKHs9IXt7XC5AMjkkXCw8Li0iOiFcPk9jdFwl&input=aGVsbG93b3JsZA)
Mm.. got a few no-ops in the Hexagon so I put today's date in.
## Expanded Form with date replaced by no-ops
```
1 0 } {
' a ( { =
! { { \ . @
. . $ \ , < .
- " : ! \ >
. . . \ %
. . . .
```
1. Initialise a `10` and move Memory Pointer to somewhere...
2. `$` skips the mirror and `,` reads a byte. `<` branches:
3. If end of string (`-1` which is non-positive) it goes to `@` and terminates the program.
4. Otherwise it subtracts `95` (decremented `a`), and then we print `result / 10` (integer division) and `result % 10` and loop again.
[Answer]
# [Stax](https://github.com/tomtheisen/stax), 5 [bytes](https://github.com/tomtheisen/stax/blob/master/docs/packed.md#packed-stax)
```
öÇIªÆ
```
[Run and debug it](https://staxlang.xyz/#p=948049a692&i=%22helloworld%22%0A%22codegolf%22%0A%22alphabetcipher%22%0A%22johncena%22&a=1&m=2)
For each character
* add 4 to the codepoint e.g. `108`
* convert to string e.g. `"108"`
* drop the first character e.g. `"08"`
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~19~~ 12 bytes [SBCS](https://en.wikipedia.org/wiki/SBCS)
```
⎕UCS ⍝ Convert the argument (string) into an array of codepoints.
4+ ⍝ and add 4 to each of those codepoints.
¨ ⍝ Now, for each of those numbers
⍕ ⍝ turn it into a string
∘ ⍝ and
1↓ ⍝ drop its first character.
∊ ⍝ Finally enlist the strings into a single string (as in, join them together)
```
Thanks @Bubbler for saving 7 bytes
## my original 19 bytes
```
{,/{1↓⍕⍵}¨4+⎕UCS ⍵}
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///v1pHv9rwUdvkR71TH/VurT20wkT7Ud/UUOdgBRD3f2pecn5K6qO2CY96@x51NT/qXfOod8uh9caP2iYClQUHOQPJEA/PYKhCBfXEpOSU1LT0jMys7JzcvPyCwqLiktKy8orKKnUA "APL (Dyalog Unicode) – Try It Online")
```
{ } ⍝ Define a function taking a string as argument.
⎕UCS ⍵ ⍝ Convert the argument (string) into an array of codepoints.
4+ ⍝ and add 4 to each of those codepoints.
{ }¨ ⍝ For each number in the array,
⍕⍵ ⍝ convert it to a string
1↓ ⍝ and drop the first character (the 1).
,/ ⍝ Finally join everything and return.
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 6 bytes
```
C4+ƛSḢ
```
*-1 byte thanks to [@Steffan](https://codegolf.stackexchange.com/users/92689/steffan)*
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiQzQrxptT4biiIiwiIiwiaGVsbG93b3JsZCJd)
Explanation:
```
C # Convert to ASCII codes
4+ # Add 4
ƛ # On each number:
S # Stringify
Ḣ # Remove first char
```
[Answer]
# Vim, 60 keystrokes
```
:s/./\=char2nr(submatch(0))-96."\r"/g
:%s/\<\d\n/0&
V{gJ
```
An *almost* entirely regex based solution. As usual, using the eval register makes it obscenely long.
[Answer]
# PHP, 58 Bytes
```
foreach(str_split($argv[1])as$c)printf("%02d",ord($c)%32);
```
[Answer]
## PowerShell v2+, 44 bytes
```
-join([char[]]$args[0]|%{"{0:D2}"-f($_%32)})
```
Takes input `$args[0]`, casts it as a `char`-array, feeds into a loop. Each iteration, we take the current character `$_` modulo `32`, which implicitly casts as the ASCII value. Conveniently ;-), this lines up so `a = 1, b = 2`, etc. That fed into the `-f`ormat operator, operating on string `"{0:D2}"`, which specifies a two digit minimum (i.e., it prepends a leading zero if required). Those strings of digits are encapsulated in parens, `-join`ed together into one string, and left on the pipeline. Output via implicit `Write-Output` happens at program conclusion.
```
PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'hello'
0805121215
PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'helloworld'
08051212152315181204
PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'codegolf'
0315040507151206
PS C:\Tools\Scripts\golfing> .\encode-alphabet-cipher.ps1 'johncena'
1015081403051401
```
[Answer]
# Perl, 24 bytes
Includes +1 for `-p`
Give input on STDIN:
```
encode.pl <<< hello
```
`encode.pl`
```
#!/usr/bin/perl -p
s/./substr 4+ord$&,1/eg
```
[Answer]
# [DASH](https://github.com/molarmanful/DASH), 27 bytes
```
@><""(->@rstr["."""]+4#0)#0
```
Example usage:
```
(@><""(->@rstr["."""]+4#0)#0)"helloworld"
```
# Explanation
```
@ ( #. take input through a lambda
join "" ( #. join with newlines the following:
(map #. result of mapping
@ ( #. this lambda
rstr ["." ; ""] ( #. replace first char w/ empty string:
+ 4 #0 #. mapped item's codepoint + 4
)
)
) #0 #. over the argument
)
)
```
[Answer]
## Batch, ~~256~~ ~~239~~ 237 bytes
```
@echo off
set/ps=
set r=
set a=abcdefghijklmnopqrstuvwxyz
:g
set c=%a%
for /l %%i in (101,1,126)do call:l %%i
set s=%s:~1%
if not "%s%"=="" goto g
echo %r%
exit/b
:l
set i=%1
if %c:~,1%==%s:~,1% set r=%r%%i:~1%
set c=%c:~1%
```
Takes input on STDIN.
[Answer]
# IBM PC DOS 8088 Assembly, ~~33~~ ~~28~~ 27 bytes
Assembled binary:
```
00000000: be82 00ac 2c60 7812 d40a 0530 3092 86f2 ....,`x....00...
00000010: b402 cd21 86f2 cd21 ebe9 c3 ...!...!...
```
Unassembled:
```
BE 0082 MOV SI, 82H ; point SI to command line string
CH_LOOP:
AC LODSB ; load next char into AL
2C 60 SUB AL, 'a'-1 ; convert ASCII to a=1,b=2...z=26
78 12 JS DONE ; if char is terminator or not valid, exit
D4 0A AAM ; convert binary to BCD
05 3030 ADD AX, '00' ; convert BCD to ASCII
92 XCHG DX, AX ; save AX to DX for display
86 F2 XCHG DH, DL ; reverse bytes
B4 02 MOV AH, 2 ; DOS display char function
CD 21 INT 21H ; write first digit
86 F2 XCHG DH, DL ; reverse bytes back
CD 21 INT 21H ; write second digit
EB E9 JMP CH_LOOP ; restart loop
DONE:
C3 RET ; return to DOS
```
Standalone PC DOS executable. Input string from command line, output to console.
I/O:
[](https://i.stack.imgur.com/wi57R.png)
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/), 16 bytes
```
∾·(1↓•Fmt)¨4+-⟜@
```
[Try it at BQN online!](https://mlochbaum.github.io/BQN/try.html#code=RiDihpAg4oi+wrcoMeKGk+KAokZtdCnCqDQrLeKfnEAKCkYgImFoZWxsbyI=)
### Explanation
Same approach, independently derived, as [RGS's APL answer](https://codegolf.stackexchange.com/a/201756/16766) and [tybocopperkettle's Vyxal `s` answer](https://codegolf.stackexchange.com/a/250415/16766).
```
∾·(1↓•Fmt)¨4+-⟜@
-⟜@ Subtract null byte from each character, giving its ASCII value
4+ Add 4 (a = 101, z = 126)
( )¨ Map this function to each number:
•Fmt Format as string
1↓ Drop first character
∾· Join together into a single string
```
[Answer]
# [K (ngn/k)](https://codeberg.org/ngn/k), 8 bytes
```
,/1_'$4+
```
[Try it online!](https://ngn.codeberg.page/k#eJwdjMEKAjEMRO/7GUXwoOAk26zVn5Haba0StssiePPbTSUwEObNK9fjiW77nT8Mg0OAENsJjyQUiOHdt7iaVdunbTo7g6yCh+BsCGPqQGpzfjQtvSbbT2YiMISBEZf/b76ORl1rvOd3eq41bzYgmC+QN1AsqUOvVpeUl+h++NUoXQ==)
`4+` add 4 to (the ASCII codes of) the argument - this turns `a` into 101, `b` into 102, etc
`$` format numbers as strings
`1_'` drop one digit from each
`,/` concatenate
[Answer]
# [J](http://jsoftware.com/), 25 22 15 bytes
```
[:,4}.@":@+3&u:
```
[Try it online!](https://tio.run/##dcq9CsIwFAXgvU9xzeC1tA03aVLbC0JRcBIHVxGH/lgkEBDEQXz2GBRHOZzlnO8amhmrUzXjBjEREkdYMSDkQMCxhYTNYbcNR87NS7aC26yc3zmkyX4tIa5nvXhKwanIzOdJhm7yMAJOg3P@4W@ux@@GVJNVOsbqUllVK00GoeA/OhoyZGkZrabqJzvfDxfvRgxv "J – Try It Online")
*-7 bytes thanks to [ngn's K approach](https://codegolf.stackexchange.com/a/250555/15469)*
[Answer]
# [Knight](https://github.com/knight-lang/knight-lang), ~~45~~ 41 bytes
*-4 thanks Aiden*
```
;=xP W<1Lx;O++*'0'-2L=a-Ax 96a'\'=xSxF1""
```
[Try it online!](https://tio.run/##rVltV9vKEf5s/4rFOVhaWU5kQXtubWQOyYUcTgnkQtJ8ADcIWcY6V5ZdSealhP71dGb2RSvbpE17@WBZu8/Mzjw7OzNrou5tFH1/lWRRuhzHe0U5Tuavp8OmOZImN7WhqHxcxCugPMlua0NlMhOYcTxJspilKUvn2S19NPXop9PPH1iver34dM786vVvB@dst3o9On3Hfqlezz@zXgU@OrkwsKefTwzo59MPBxd/tQvObPxos3/1/sT17MEFLCsmo2mYM4dXAiYKbNUqhkO2W82dHn7ByQwmyaNvDL/v7a1gcBnCoJuASVOOwBrm7dnZCYHwY5@c7KNvhiHn7wUA5A1b78J0GXN@mY14s0l@wK5cjoLz1uHZkf19EDx8ZF/2eicPg7NOx7E8q@ufBGH34IH95c@hdWUFDxcPR71W6zsHfGsgVDigIw5nLEBlg2YTVlyEeRHbnD01G0lWsmTQbMAore4yZ7LMIhgh4Qjey9nCLRbZpT8KnjzXewYdjQTUER6eHg68eYPqkwW7nyZlXCzCKG424Hsa2zAO4rYww2Wtq/Iqu5pc5ezp@XJk8/6rFidTGsmE2dragFmvLM6ECjW6BaNXGQx3OmIE7GzEaRGbA8/CnGgaR7@zyTxn2XJ2E@eFtIfZSTFObpNSaYXV0Z2eqz0ST4f1PNZhjrS80@Gsy4B0WAItTTjL43KZZ0zFixCjkBms2nAX5kl4k8bKCjAind/HuR3BesoQ9u0bU8ZF9BYREV8tLulJNrieBD0X9ijQwyvW4QmUkQqQbLxc2LilTHLaZfC2brDIB4XQJsy4sqzKppYlNg2EwQNtFAMlkD/gO1i2CIuSldMYlIV5CWC5AY5iFDc04uiJMtY4Vi8aC589ThvdqMgg8zF0y2SegdkYsd4ITIsUI8VysUDCuYoqNWLSb8Yf0G6QjTpUKC8yiGPIZRi50nLByidLH3gxcIQDmNf6mM/QTBVklAqFqzbajaaGaTqP7F3P7XF0EIe1E@RgtkzTMH80Ha3259zYno@WtowWlPLLbEWalujhEjIpbPL04PDtu@vftk5@PTMcNtXeJBv1@ut6t2qK3x9fvKCxjHNSGWZj9o9lqF5R7Z25xM76EoKA95bm4ngDFyS8WxeuY54pVebLDHdoIPOxU84LW@VKOgAQ2mUSMZq9WU4u/d2RtENsdJvSgzagWMCxKic2QMH/7TQdt1TeoXrkopJVBXAotAJR6cT6Ndwe6@3U/UTnMRb3WavMl3ELYlCPY0jC@CSEDIITLYysVkUC@om@y5JEdHx9O5@nMHNTZ@BFXyu3fuSQ8/MemWberJmZoo3ZH2ojBG05T1PbNNVlngsV4n8wOVszGavwh4OPpy7WYhFo8Hp82fM8D8IJXIFX9VYk/4y/lgwfAyNGDW@RAXhz8cOnz52gp0o6Zjis6vigT188dgBwdHxy6LAJJMdBQ4e2XA/TcBQu3DTOqAMwuFIdk@AMzt1LZKwKYm3C0oYFx06ol4BavEdcDKCoJDip80Y0W6zsAJGUjKoUgjQlI1ymuE/KaGo7wMxagwUcMfkXYZ2yDqw@w1UEIEBCsUWDLMzb5JRUL5vEWsjyAVXhCkGdaJlj6aJm9HLEn6owgwaKcrtY@BwWruvOIePZvO09TPCvQn4EJGgVHN3GZQp9pN2mvWzjDmGJHCcZHyQT26b9xIYgmuZoiwtxyrnY5sAbbLQVHpzaALHeoVhPdI6YDSQhA2UvkiRzZ2Xl28ofgdcz76oZlDQp1phrwGA0QPwFi/kizmxjYbeVt6hVAKuCmaiUEI@B7@3@QuOyubBFRzIB08foFLRwELIu9ncAh96B3nANWFqFlw2DrBNQK4QnFpBc0g16aC2iGjU4AfPNnqWisfLkN/AkfoA2Dk/7mp9btV2n68IWZrI14MlaeMAqaZ0XA/6r1Zd94oZA1plPVqDWKbXFNtYgrorQcLjLq8ZyLR0q0QtqDu3tAgXrh2FdGOiE1sdcFzIpb1VQNYHlJQ4zqfalEiZrlrkDMrdIFs4qFvBgiIsPkib2s0Yda7fpjtXtInQk2twrarcbyqzt104B9tjwxpk6arlh/rIs1O7rmBC9njCoow2iPAn5ElMyhpaxPaKbbtR3W1xYEQ19P1Ox5Is9x/6XDoPYAELhMJ7yQHnp882hGoWlesius9epaOLqO@ri0I269CxljpB@ddei04h2bNXr9gohp9qdDSyslucNPDhrPIh93cTCbINrDmECUwkJQA2yKUMG1hVc8hA06HZJnySKSubqRgtGy9rpf/NDYt5sJmb7h0Lbm4X@TmzWHBJXBxrzTS8HknbBesC6Pc0yYYH6Hpyzbg/OWM8E@z@J3oP0WMMGAUJp3b4a8RTlRLQ/9CTXPqd2xQmI/@bqgaBJcgXuCJRgscTAd7wyTOM8tgqWzaGHTtIyydh9@Ai8sfEc7qRlfBvnILOYZ3FWJiHeIuAkz9l9zKbhXQxAqQjhJZuF2RLC5/E1jqJ3N8g4UEFMFMu0xB8NaHGd8BSka2LUkiuUmXIasqIe9b2M9F42RMP2aiiP7udhirXxEbzOxmk8ZteV2ddayxN@E42ZsUjlzBCVdbvqnRO8IaGOYfqzzoN7FKwrhQ@TXi0vBvWsuM/Mw79nHgMU7cuf4tpMAPZZrVGkQZcZ2RB1eEJSlVxf1AHEbgVQbYwuaAiHEkNrPp732SyeRQsMs4wNr/f/X1eGf4ArQ@XK1gZfAumLdGX/ZfbFqhtMxul9VgP4GuGrArq1yc7qRbunMo@pQJvXrtIf@rKpNuybkjKVaPlv/428zEGGGi0/sPomutbmrmKDKuvWp3/6IqN62@omg7hG7TajUyFhUOMoqEkbaRIlENHpaDFh8hdwT/zqZTaaNe@Y2btIseN6145QQ37f7@8YtLwXV4bA6LA6ZgFavyNl8uLh6rOwU2toLwTRK0oHqyXP31TydrjuA3wtvUuD/6EhQsPwiVsR6eZft0Nmb@SDh7hqp4dNEjUIIv7FJD0I0ZEnAVYfx5MQkiR4pjrMJIPJZEw/IoVRCWXK2o4s7DlxhLMXbrGoTNdA6AblDwmzMMmwWWVhfhu5pNRx4Psdx5@r6H6J/9mxPbKmfo17/j6NweH7eZ6O/w0 "C (gcc) – Try It Online")
[Answer]
# [Piet](https://www.dangermouse.net/esoteric/piet.html) + [ascii-piet](https://github.com/dloscutoff/ascii-piet), 44 bytes (2×22=44 codels)
```
tuuuumknnfbkqmkcalrmu_sajs?daltdddbfckkkkk ?
```
[Try Piet online!](https://piet.bubbler.one/#eJw1TtsKgzAM_Zc8RzBOnforKtLVuDq6tqhjD2P_vlRnTiDnwin9gPYjQ9O2KRZ_EGGNVwFdkHLh-WGRRCWWmEUpvOqxvUSrQjkVUnbk6c6OzfdHCmmfoDo2e4SVAzSQJAkg2PkpnNI4InnV0EzKrowwu_DaJDRsrX_7xY5D56TVufjzu7fTqZUNRt1403MwvJzuwxun2akBvj97yj8B)
Input the string with the [sentinel value](https://codegolf.meta.stackexchange.com/questions/2447/default-for-code-golf-input-output-methods/24639#24639) `_`.
### Pseudocode
```
while true:
S = character input
n = (codepoint of S) - 96
if n+1 == 0:
exit
else:
print(floor(n/10))
print(n modulo 10)
```
[Answer]
# [MATL](http://github.com/lmendo/MATL), 11 bytes
```
96-OH&YA!1e
```
[Try it online!](http://matl.tryitonline.net/#code=OTYtT0gmWUEhMWU&input=J2hlbGxvd29ybGQn)
```
% Implicit input
96- % Subtract 96. So 'a' becomes 1, 'b' becomes 2 etc
OH&YA % Convert each number to 2 decimal digits. Gives a 2-column matrix
!1e % Transpose and linearize into a row
% Implicit display
```
[Answer]
## Ruby, ~~53~~ 46 bytes
~~`->s{s.chars.map{|c|(c.ord-96).to_s.rjust(2,?0)}.join}`~~
`->s{s.chars.map{|c|(c.ord+4).to_s[1..2]}.join}`
] |
[Question]
[
### Introduction
Let's observe the following string:
```
ABCDEFGHIJKLMNOP
```
If we swap the **ends of the string**, which are these:
```
ABCDEFGHIJKLMNOP
^^ ^^
```
We get the following result:
```
BACDEFGHIJKLMNPO
```
After that, we delete the ends of the string, which in this case are `B` and `O`. The result is:
```
ACDEFGHIJKLMNP
```
If we repeat the process, we get the following list:
```
N Result
2 ADEFGHIJKLMP
3 AEFGHIJKLP
4 AFGHIJKP
5 AGHIJP
6 AHIP
7 AP
```
You can see that for **N = 5**, the result is `AGHIJP`. At **N = 7**, the length of the string is smaller than **3**, so N > 7 is considered *invalid* in this case.
### The Task
Given a string **S** with *at least* length 4 and the number of repetitions **N** > 0, output the final result. You can assume that N is always *valid*.
### Test cases
```
Input > Output
N = 3, S = ABCDEFGHIJKLMNOP > AEFGHIJKLP
N = 1, S = Hello > Hlo
N = 2, S = 123321 > 11
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the least amount of bytes wins! For the simplicity, you can assume that the string will only contain **alphanumeric** characters.
[Answer]
# [Retina](https://github.com/mbuettner/retina), ~~44~~ 20 bytes
[Crossed out 44 is still regular 44 :(](https://codegolf.stackexchange.com/questions/62732/implement-a-truth-machine/63380#63380)
```
+`'(\w).(.*).\B
$1$2
```
Assumes input in following format (in unary - counting character: `'`):
`{number of repeats}{string}`
For example: `'''''''ABCDEFGHIJKLMNOP`
There is no space between number of repeats and the string.
Thanks [@MartinBüttner](https://codegolf.stackexchange.com/users/8478/martin-b%C3%BCttner) for shaving off 24 bytes!
[Try it online!](http://retina.tryitonline.net/#code=K2AnKFx3KS4oLiopLlxCCiQxJDI&input=JycnJycnJ0FCQ0RFRkdISUpLTE1OT1A)
[Answer]
## Python 2, 31 bytes
```
lambda s,n:s[0]+s[n+1:~n]+s[-1]
```
I think this works?
[Answer]
## [Labyrinth](https://github.com/mbuettner/labyrinth), 40 bytes
```
<
,,}:?
.
;(" {(={}{".
,",;=};} }) "{@
```
Input is `N` followed by the string, separated by any non-numeric character.
[Try it online!](http://labyrinth.tryitonline.net/#code=PAosLH06PwouCjsoIiAgIHsoPXt9eyIuCiwiLDs9fTt9IH0pICJ7QA&input=NSBBQkNERUZHSElKS0xNTk9Q)
This was written in collaboration with Sp3000 (which means I couldn't be bothered to figure out an algorithm, so he started working on it, came up with 118 byte solution but couldn't be bothered golfing it, so I did the golfing... yay for teamwork).
### Explanation
Sp's usual primer (as usual slightly modified):
* Labyrinth is a stack-based 2D language with two stacks, main and auxiliary. Pretty much everything happens on the main stack, but you can shift values over to the other one, e.g. to reverse them or save them for later.
* The stacks are bottomless and filled with zeroes, so popping from an empty stack is not an error.
* Execution starts from the first valid character (here the top left). At each junction, where there are two or more possible paths for the instruction pointer (IP) 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. While this was *meant* to make the code look like winding, twisty passages, there's nothing stopping you from making "rooms" where these conditions are checked in every cell. Those can yield quite unpredictable behaviour, but are great for golfing.
* The source code (and therefore the layout of the labyrinth) can be modified at runtime using `<>^v` which cyclically shifts a row or column or the grid.
* `"` are no-ops.
Here we go.
The code starts on the `<`, which is a golfing trick I've used a few times when starting with a long piece of linear code. It shifts the first row cyclically to the left, *with the IP on it*, so the source then looks like this:
```
<
,,}:?
.
;(" {(={}{".
,",;=};} }) "{@
```
But now the IP can't move anywhere, so it executes the `<` again. This continues until we reach this state:
```
<
,,}:?
.
;(" {(={}{".
,",;=};} }) "{@
```
At this point, the IP can leave the cell and begin executing the second line starting from the `?`. So here's the linear code broken down:
```
? # Read the first integer on STDIN, i.e. N.
:} # Duplicate it and move one copy over to the auxiliary stack.
, # Read the separator character.
,. # Read the first character of the input string and directly print it.
```
The IP now enters this 3x2 room, which is actually two tightly-compressed (overlapping) 2x2 clockwise loops. The first loop reads and discards `N-1` characters from STDIN.
```
; # Discard the top of the stack. On the first iteration, this is the
# separator we've already read. On subsequent iterations this will be
# one of the N-1 characters from the input string.
( # Decrement N. If this hits zero, we leave the loop, otherwise we continue.
, # Read the next character from STDIN to be discarded.
```
Now we enter the second loop which reads the remainder of the input string. We can detect EOF because `,` will return `-1` in that case, making the IP turn left.
```
, # Read a character. Exit the loop if EOF.
( # Decrement it.
```
That decrement isn't actually useful, but we can undo it later for free and here it allows us to overlap the two loops.
If we take the `5 ABCDEFGHIJKLMNOP` input as an example, the stack looks like this:
```
Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' 'O' -1 | 5 ... ] Auxiliary
```
Note that these actually correspond to the input characters `FGHIJKLMNOP` (because we decremented them), and that we don't actually want to print the first of those (we've only discarded `N-1` characters, but want to skip `N`).
Now there's a short linear bit that prepares the stack for the next loop:
```
; # Discard the -1.
= # Swap the tops of the stacks, i.e. N with the last character.
# By putting the last character on the auxiliary stack, we ensure that
# it doesn't get discarded in the next loop.
} # Move N over to the auxiliary stack as well.
```
The stacks now look like:
```
Main [ ... 'E' 'F' 'G' 'H' 'I' 'J' 'K' 'L' 'M' 'N' | 5 'O' ... ] Auxiliary
```
We enter another 2x2 clockwise loop. This discards the top `N` characters from the main stack:
```
; # Discard the top of the main stack.
{ # Pull N over from the auxiliary stack.
( # Decrement it. It it's 0 we leave the loop.
} # Push N back to the auxiliary stack.
```
When we exit the loop `=` swaps that `0` and the last character of the input string again. Now the stacks look like this:
```
Main [ ... 'E' 'F' 'G' 'H' 'I' 'O' | ... ] Auxiliary
```
We want to print the contents of the main stack (except the bottom element and all incremented by 1), *from the left*. That means we need to get it over to the auxiliary stack. That's what the next 2x2 (clockwise) loop does:
```
{ # Pull an element over from the auxiliary stack. This is necessary so we
# have a 0 on top of the stack when entering the loop, to prevent the IP
# from turning right immediately.
} # Move the top of the main stack back to the auxiliary stack. If this was the
# bottom of the stack, exit the loop.
) # Increment the current character.
} # Move it over to the auxiliary stack.
```
Stacks now:
```
Main [ ... | 'F' 'G' 'H' 'I' 'J' 'P] ... ] Auxiliary
```
We move the first of those (the one we don't want to print) back to the main stack with `{`. And now we enter final 2x2 (*counterclockwise*) loop, which prints the rest:
```
{ # Pull another character over from the auxiliary stack. Exit the loop
# if that's the zero at the bottom of the stack.
. # Print the character.
```
Finally we terminate the program with `@`.
[Answer]
# Mathematica, 29 bytes
My first answer!
```
#~Delete~{{2},{-2}}&~Nest~##&
```
The crux of bracketless Mathematica!
Function inputs are a list (of characters, or whatever) and a number.
[Answer]
## JavaScript (ES6), 39 bytes
```
(s,n)=>s[0]+s.slice(++n,-n)+s.slice(-1)
```
Turns out I just reinvented @Sp3000's answer.
[Answer]
# Jelly, 8 bytes
```
Ḣ1¦UðḤ}¡
```
[Try it online!](http://jelly.tryitonline.net/#code=4biiMcKmVcOw4bikfcKh&input=&args=IkFCQ0RFRkdISUpLTE1OT1Ai+Nw)
### How it works
```
Ḣ1¦UðḤ}¡ Main link. Left input: S (string). Right input: N (deletions)
Ḣ Pop the first element of S.
This return the element and modifies S.
1¦ Apply the result to the first index.
This replaces the first character of the popped S with the popped char.
U Upend/reverse the resulting string.
ð Convert the preceding chain into a (dyadic) link.
Ḥ} Apply double to the right input.
This yields 2N.
¡ Repeat the link 2N times.
```
[Answer]
# [MATL](https://esolangs.org/wiki/MATL), 8 ~~9~~ ~~12~~ ~~13~~ bytes
```
th"P[]2(
```
Inputs are: first `N` as a unary string with quotes (allowed by the challenge); second `S` as a string with quotes (quotes in strings are allowed by default); separated by a linebreak.
This works by flipping the string, removing its second element, and repeating for a total of `2*N` times.
[**Try it online!**](http://matl.tryitonline.net/#code=dGgiUFtdMig&input=JzExMScKJ0FCQ0RFRkdISUpLTE1OT1An)
```
th % implicitly take first input (N) as a unary string. Concatenate horizontally
% with itself: gives a string of 2*N ones
" % for each (i.e., repeat 2*N times)
P % flip string. Take S implicitly as input the first time
[] % empty array (used as new contents)
2 % 2 (used as index)
( % assign [] to position 2 of string; that is, remove second element
% implicitly end for each
% implicitly display
```
[Answer]
## [Jelly](https://github.com/DennisMitchell/jelly), 10 [bytes](https://github.com/DennisMitchell/jelly/blob/master/docs/code-page.md)
```
Ḣ;ṪjḊṖ$Ɠ¡F
```
Input [the number via STDIN, and the string via command line args](http://meta.codegolf.stackexchange.com/a/5415/21487). Thanks to @Dennis for a lot of hints/help getting this to work (Jelly still eludes me).
[Try it online!](http://jelly.tryitonline.net/#code=4biiO-G5qmrhuIrhuZYkxpPCoUY&input=Mg&args=IjEyMzMyMSI)
```
Ḣ;Ṫ Pop first and last chars of string and concatenate
j Join by...
Ɠ¡ Execute n times...
ḊṖ$ Drop first, drop last of string ($ combines the two monadically)
F Flatten to filter out empty lists, since Jelly's j is weird
```
[Answer]
## Pyth, 13 bytes
```
++hz:zhQ_hQez
```
Explanation:
```
- autoassign z = input()
- autoassign Q = eval(input())
:zhQ_hQ - z[Q+1:-(Q+1)]
++hz ez - z[0]+^+z[-1]
```
[Try it here](http://pyth.herokuapp.com/?code=%2B%2Bhz%3AzhQ_hQez&input=Swap+delete+and+repeat%0A8&debug=0)
[Answer]
## Ruby, 29 bytes
```
->s,n{s[0]+s[n+1...~n]+s[-1]}
```
Very straightforward.
`~` trick stolen from [Sp's answer](https://codegolf.stackexchange.com/a/73583/3808), which saves a byte over `s[n+1..-2-n]`. (It works because `~n` is `-1-n` in two's-complement, and then `...` is an exclusive range.)
[Answer]
# Vitsy, ~~12~~ 9 (code) + 1 (newline for function declaration) = 10 bytes
\o/
Expects input on the stack as the string followed by the number.
```
2*\[vXvr]
2* Multiply by 2.
\[ ] Do the stuff in the brackets that many times. (input num * 2)
v Take the top item off the stack and save it as a local variable.
X Remove the top item of the stack.
v Push the temporary variable back onto the stack.
r Reverse the stack.
```
Which you can call with:
```
'String' r <number> 1m Z
2*\[vXvr]
```
This is a function that leaves the resultant string on the stack. I have provided it as a program in the TryItOnline link.
[TryItOnline!](http://vitsy.tryitonline.net/#code=J0FCQ0RFRkdISUpLTE1OT1AnIHIgMyAxbSBaCjIqXFt2WHZyXQ&input=)
[Answer]
## Perl, ~~36~~ 32 + 1 = 33 bytes
```
for$i(1..<>){s;\B.(.+).(.);$1$2;}
```
Requires `-p` flag and takes input on two lines, with numbers of iterations at the end:
```
$ perl -pe'for$i(1..<>){s;\B.(.+).(.);$1$2;}' <<< $'ABCDEFGHIJKLMNOP\n4'
AFGHIJKP
```
Ungolfed?
```
for $i ( 1..<> ) {
s;
\B.(.+).(.);$1$2;x
}
```
[Answer]
# Python 2, ~~49~~ 48 bytes
```
g=lambda s,n:n and g(s[0]+s[2:-2]+s[-1],n-1)or s
```
[Try it here with testcases!](https://repl.it/BoVJ/1)
Simple recursive solution. Removes the second and last second element from the input string and calls itself with this and `n-1` until `n=0`.
**edit:** Feeling kinda stupid, looking at [the other python solution](https://codegolf.stackexchange.com/a/73583/49110). Guess I just like recursion too much...
[Answer]
# C, 96 bytes
```
i;main(c,v,p)char**v,*p;{i=atoi(v[2])+1;c=strlen(p=v[1]);printf("%c%.*s%s",*p,c-2*i,p+i,p+c-1);}
```
## Ungolfed
```
i; /* Param 2, the number of chars to remove */
main(c,v,p)char**v,*p;
{
i=atoi(v[2])+1; /* convert param 2 to integer */
c=strlen(p=v[1]); /* Length of the input */
printf("%c%.*s%s",*p, /* Print the first char... */
c-2*i, /* a number of characters equal to the length minus twice the input... */
p+i, /* skip the "removed" chars... */
p+c-1); /* Print the last character of the string */
}
```
[Answer]
## Rust, 135 bytes
Well, that's a pretty terrible length.
```
fn f(s:&str,n:usize)->String{let s=s.as_bytes();s[..1].iter().chain(&s[n+1..s.len()-n-1]).chain(s.last()).map(|d|*d as char).collect()}
```
Pretty-printed:
```
fn f(s: &str, n: usize) -> String {
let s = s.as_bytes();
s[..1].iter()
.chain(&s[n+1..s.len()-n-1])
.chain(s.last())
.map(|d| *d as char)
.collect()
}
```
You can get it down to **104** bytes if we allow bytestrings instead of proper strings.
```
fn f(s:&[u8],n:usize)->Vec<u8>{let mut r=vec![s[0]];r.extend(&s[n+1..s.len()-n-1]);r.extend(s.last());r}
```
Pretty-printed:
```
fn f(s: &[u8], n: usize) -> Vec<u8> {
let mut r = vec![s[0]];
r.extend(&s[n+1..s.len()-n-1]);
r.extend(s.last());
r
}
```
Curious if anyone can do better.
[Answer]
# CJam, 12 bytes
```
q~{VW@)t(t}*
```
[Try it online!](http://cjam.tryitonline.net/#code=cX57VldAKXQodH0q&input=IkFCQ0RFRkdISUpLTE1OT1AiIDc)
### How it works
```
q~ Read and evaluate all input. This pushes S (string) and N (integer).
{ }* Do the following N times:
VW Push 0 and -1.
@ Rotate S on top of them.
) Pop the last character of S.
t Set the item at index -1 to that character.
( Pop the first character of S.
t Set the item at index 0 to that character.
```
[Answer]
# Octave, 28 bytes
```
@(S,N)S([1,N+2:end-N-1,end])
```
Index the string, omitting `S(2:N+1)` and `S(end-N:end-1)`.
Sample run on [ideone](http://ideone.com/CcR75J).
[Answer]
# Vim, 27 bytes
```
o0lxehx <ESC>"ay0ddA@a<ESC>B"bdWx@b
```
Input is expected to be in the form `STRING N` on the first line with no other characters.
Explanation:
```
#Write a macro to do one round of the swap and delete and save to register a
o0lxehx <ESC>"ay0dd
#Append register a to N and save in register B so it will run @a N times.
A@a<ESC>B"bdWx
# Actually run the macro
@b
```
[Answer]
# mSL - 137 bytes
```
c {
%l = $len($1)
return $mid($+($mid($1,2,1),$left($1,1),$right($left($1,-2),-2),$right($1,1),$mid($1,$calc(%l -1),1)),2,$calc(%l -2))
}
```
## Explanation:
`%l = $len($1)` will get the length of the input string and saves it in variable called l
`$right(<input>,<length>)` and `$left(<input>,<length>` can be used to return the left or right most part of the original string respectably. $left always return text starting from the very left side while $right always return text starting from the right side. If the length specified is a negative number, $left and $right return the entire text minus that many characters from their respective sides.
`$mid(<string>,<start>,[length])` is used to get a substring from the middle of the string. Start is the start of the substring from the left. A negative value indicates a start from the right. In both case, an optional length can be specified. A negative length can be used to remove that many characters from the end. So I used it to retrieve the second character and the second last character by using the length of the input string.
`$calc(<input>)` is used to perform mathematical calculations
[Answer]
## Brainfuck, 130 bytes
My first PPCG entry!
Obviously not gonna win but hey.
Takes input like: 4ABCDEFGHIJKL, with the first character being N.
```
,>+++++++[<------->-]<+>>+[>,]<[<]>-<<[>>>[<+>-]>[<+>-]<<[>>+<<-]>[>]<[>+<-]<[>+<-]>>[<<+>>-]<[-]<[<]>[-]>[[<+>-]>]<<[<]<<-]>>>[.>]
```
Test it on [this](https://fatiherikli.github.io/brainfuck-visualizer/#LD4rKysrKysrWzwtLS0tLS0tPi1dCjwrPj4rWz4sXTxbPF0+LTw8Cls+Pj5bPCs+LV0+WzwrPi1dPDxbPj4rPDwtXT5bPl08Wz4rPC1dPFs+KzwtXT4+Wzw8Kz4+LV0KPFstXTxbPF0+Wy1dPltbPCs+LV0+XTw8WzxdPDwtXQo+Pj5bLj5dCgohM0FCQ0RFRkc= "this") wonderful site.
Limited to N less than or equal to 9, because two-digit numbers are a pain in the butt.
EDIT: I sucked it up and added support for two-digit numbers. Pad with a zero for single digits.
```
,>+++++++[<------->-]<+ [>++++++++++<-]>[<+>-],>+++++++[<------->-]<+ [<+>-]>+[>,]<[<]>-<<[>>>[<+>-]>[<+>-]<<[>>+<<-]>[>]<[>+<-]<[>+<-]>>[<<+>>-]<[-]<[<]>[-]>[[<+>-]>]<<[<]<<-]>>>[.>]
```
[Answer]
## As of yet untitled language (so new noncompetitive), 9 bytes
```
hD_RQ:Q|J
```
You can find the source code [here](https://github.com/muddyfish/PYKE), language is completely unstable (first test challenge for it) so don't expect it to work in the future (commit 7)
This is a stack based language with functions that add and remove objects from the stack. There are currently 2 stack manipulation commands: `D`(duplicate the top of the stack N times) and `R`(rotate the top N items on the stack)
Explanation:
```
- autoassign Q = eval_or_not(input()) (string)
h - imp_eval_input()+1
D - duplicate(^)
_ - neg(^)
R - rotate(^)
Q: - Q[^:^]
Q| - Q[0], Q[-1]
J - "".join(all)
```
[Answer]
## CJam, 14 bytes
```
l(o)\l~_W*@<>o
```
[Test it here.](http://cjam.aditsu.net/#code=l(o)%5Cl~_W*%40%3C%3Eo&input=ABCDEFGHIJKLMNOP%0A5)
### Explanation
```
l e# Read the input string.
(o e# Pull off the first character and print it.
)\ e# Pull off the last character and swap with the rest of the string.
l~ e# Read the second line of the input and evaluate it (N).
_ e# Duplicate.
W* e# Multiply by -1 to get -N.
@ e# Pull up the string.
< e# Discard the last N characters.
> e# Discard the first N characters.
o e# Output what's left. The last character of the input is now still on the
e# stack and is automatically printed at the end of the program.
```
[Answer]
# Perl, 27 bytes
Include +1 for `-p`
Run as `perl -p sdr.pl`
Input given on STDIN, first line the string, second line the count
Assumes the string contains only "word" characters
`sdr.pl`:
```
eval's%\B.(.*).\B%$1%;'x<>
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `Ṫ`, 8 bytes
```
f÷?d($_^
```
[Try it online!](https://vyxal.pythonanywhere.com/#WyLhuaoiLCIiLCJmw7c/ZCgkX14iLCIiLCJcIjEyMzMyMVwiXG4yIl0=)
Explanation:
```
f # Get the list of characters
÷ # and push each one to the stack.
d # Double
? # the input
( # times:
$ # swap the top two items
_ # pop the stack
^ # then reverse the stack.
# Sum the whole stack and print
```
[Answer]
# [Factor](https://factorcode.org/), 47 bytes
```
[ 1 cut pick tail 1 cut* swap roll head* glue ]
```
[Try it online!](https://tio.run/##RY5LC4JAGEX3/oqLSxeBuisIeqo9LIhW0WKYPlOc1OZBhPjbJ8Ogu7vn3MXNGNe1tOdTkkZjMKVqrtBI0vrdyKLSUPQ0VHFSKElWJKByk2WCMHGc1kGfFiHc2XyxXK2jONlsd/v0cHTR/aQPNyYh6j8J4PpBGAb@F3X20k@40WgKXkKzQgzdg3qxBrIWAjmxm4e7MISrzYab00dvR/YD "Factor – Try It Online")
```
! 5 "ABCDEFGHIJKLMNOP"
1 ! 5 "ABCDEFGHIJKLMNOP" 1
cut ! 5 "A" "BCDEFGHIJKLMNOP"
pick ! 5 "A" "BCDEFGHIJKLMNOP" 5
tail ! 5 "A" "GHIJKLMNOP"
1 ! 5 "A" "GHIJKLMNOP" 1
cut* ! 5 "A" "GHIJKLMNO" "P"
swap ! 5 "A" "P" "GHIJKLMNO"
roll ! "A" "P" "GHIJKLMNO" 5
head* ! "A" "P" "GHIJ"
glue ! "AGHIJP"
```
[Answer]
# PHP, 60 bytes
This solution iteratively sets characters from the input string to an empty string by index. I'm manipulating the input string directly to prevent a long `return`.
```
function(&$w,$i){for(;$i;)$w[$i--]=$w[strlen($w)-$i-2]="";};
```
Basically in memory `$w` looks like this when done:
```
Addr 0 1 2 3 4
H l o
^ ^ ^
>Result: Hlo
```
Run like this:
```
php -r '$f = function(&$w,$i){for(;$i;)$w[$i--]=$w[strlen($w)-$i-2]="";}; $f($argv[1],$argv[2]);echo"$argv[1]\n";' Hello 1
```
[Answer]
# [Pylons](https://github.com/morganthrapp/Pylons-lang), 16 Bytes.
```
i:At,{\,v\,v,A}c
```
How it works:
```
i # Get command line input.
:At # Set A equal to the top of the stack.
, # Pop the stack.
{ # Start a for loop.
\ # Swap the top two elements of the stack.
, # Pop the stack.
v # Reverse the stack.
\ # Swap the top two elements of the stack.
, # Pop the stack.
v # Reverse the stack.
, # Switch to loop iterations.
A # Iterate A times.
} # End the for loop.
c # Print the stack as a string
```
[Answer]
# CJam, 15 bytes
```
r(\)\{(;);}ri*\
```
I'm sure it's possible to golf this further...
[Answer]
# Jolf, 13 bytes
```
ΆFi liγhj_γgi
```
A tranpilation of the JavaScript answer.
Explanation:
```
ΆFi liγhj_γgi
Ά ternary add
Fi i[0],
`li i sliced
γhj γ = j + 1
_γ to -γ
gi and the last of i
```
[Try it here!](http://conorobrien-foxx.github.io/Jolf/#code=zoZGaSBsac6zaGpfzrNnaQ)
A more interesting post-question version:
```
ΆFi]ihjYgi
```
[Answer]
## Seriously, 17 bytes
```
,#,`p@pXod@dXq`nΣ
```
Takes input as `s \n n`.
[Try it online!](http://seriously.tryitonline.net/#code=LCMsYHBAcFhvZEBkWHFgbs6j&input=J0FCQ0RFRkdISUpLTE1OT1AnCjY)
Explanation:
```
,#,`p@pXod@dXq`nΣ
,# push a list of characters in s
,` `n do the following n times:
p@pXo pop 2 characters off the front, discard the second, put the first back
d@dXq pop 2 characters off the back, discard the second, put the first back
Σ join
```
] |
[Question]
[
Code golf: Print an image of the source code.
**Requirements**
1. Must output the image of the source code itself, not a version stored elsewhere and retrieved at run time.
2. Code must be legible enough to copy out by hand and reproduce the results.
Any image format is applicable.
**Bonuses**
* -10% of your score if you allow more than one output format.
* -15% if your code is *also* a 'true' quine. i.e. it does not read its source code but the source code is embedded (see [here](https://codegolf.stackexchange.com/a/23231/9534) for an example)
* -30% if your code is a strict quine - i.e the image of the code is embedded in the program (Piet solutions, I'm looking at you.).
[Answer]
# shell
By "Print an image of the source code", I assume that actually printing an image on paper would be acceptable.
```
#!/bin/sh
lpr $0
```
[Answer]
## Piet, 24399.76

[This was not made by me.](http://mamememo.blogspot.com/2009/10/piet-quine.html)
[Answer]
# PHP - 487 × 0.9 × 0.85 = 372.555 (2000×99px)
```
<?php $y="imagecolorallocate";$l=[
'<?php $y="imagecolorallocate";$l=[',
'];$i=imagecreate(2e3,99);$y($i,99,99,99);$w=$y($i,$j=0,0,0);$z=function($_)use(&$j,$i,$w){imagestring($i,4,9,$j+=15,$_,$w);};$z($l[0]);foreach($l as$m)$z(chr(39).$m.chr(39).",");$z($l[1]);$argv[1]($i,"o");',
];$i=imagecreate(2e3,99);$y($i,99,99,99);$w=$y($i,$j=0,0,0);$z=function($_)use(&$j,$i,$w){imagestring($i,4,9,$j+=15,$_,$w);};$z($l[0]);foreach($l as$m)$z(chr(39).$m.chr(39).",");$z($l[1]);$argv[1]($i,"o");
```
# If warnings are fine: PHP - 479 × 0.9 × 0.85 = 366.435
```
<?php $y=imagecolorallocate;$l=[
'<?php $y=imagecolorallocate;$l=[',
'];$i=imagecreate(2e3,99);$y($i,99,99,99);$w=$y($i,$j=0,0,0);$z=function($_)use(&$j,$i,$w){imagestring($i,4,9,$j+=15,$_,$w);};$z($l[0]);foreach($l as$m)$z(chr(39).$m.chr(39).",");$z($l[1]);$argv[1]($i,o);',
];$i=imagecreate(2e3,99);$y($i,99,99,99);$w=$y($i,$j=0,0,0);$z=function($_)use(&$j,$i,$w){imagestring($i,4,9,$j+=15,$_,$w);};$z($l[0]);foreach($l as$m)$z(chr(39).$m.chr(39).",");$z($l[1]);$argv[1]($i,o);
```
You provide the output function to use as the first command line argument:
```
php timwolla.php imagepng
```
Solution with warnings:
[](https://i.stack.imgur.com/7tH6D.png)
[Answer]
**Whitespace, 125**
```
```
Outputs an image file in the [pbm](http://netpbm.sourceforge.net/doc/pbm.html) format.
If you're testing this code, please copy it by clicking on "Edit", and copying everything between the `<pre>` tags.
**Output:**
```
P1 1 1 0
```
[Answer]
# Mathematica, ~~37~~ 31 chars
```
(#2[#1[#0[#1,#2]]]&)[Defer,Rasterize]
```
```
(Rasterize[#1[#0[#1]]]&)[Defer]
```

Inspired by [an answer in mathematica.stackexchange.com](https://mathematica.stackexchange.com/questions/6104/mathematica-quine/6107#6107).
[Answer]
## AppleScript, 68 37
Alright, if you can call ImageMagick in zsh then this too is valid. I'm still hacking at something more elegant and of-the-quine-spirit for my own satisfaction, but for pure golfiness, here we are:
**New version**
```
do shell script "screencapture q.jpg"
```
**Old version**
```
tell application "System Events" to keystroke "#" using command down
```
I imagine this will still be beaten, but verbose old AppleScript does an admirable imitation of succinctness for this one.

```
do shell script "screencapture -c"
```
[Answer]
## Mathematica, 83
```
SelectionMove[InputNotebook[],Previous,Cell];Rasterize@NotebookRead@SelectedCells[]
```

[Answer]
# Sh, X & ImageMagick 18.9:
```
import -window root a.jpg
```
This should work in any shell that has ImageMagick.
To print only the code prepend `clear &&` this comes out at 26.1
```
clear && import -window root a.jpg
```
Sample output:

[Answer]
**HTML5/Javascript : 615**
```
<canvas id='i' width=500 height=5000></canvas><script>function d(){var e=document.getElementById("i");var t=e.getContext("2d");t.font="20px Arial";var n=400;var r=25;var i=(e.width-n)/2;var s=60;str="<canvas id='i' width=5000 height=500></canvas>\n<script>"+d+"d();"+wrapText+"<\/script>";wrapText(t,str,i,s,n,r)}function wrapText(e,t,n,r,i,s){var o=t.split(" ");var u="";for(var a=0;a<o.length;a++){var f=u+o[a]+" ";var l=e.measureText(f);var c=l.width;if(c>i&&a>0){e.lineWidth=1;e.strokeStyle="blue";e.strokeText(u,n,r);u=o[a]+" ";r+=s}else{u=f}}e.lineWidth=1;e.strokeStyle="blue";e.strokeText(u,n,r)}d()</script>
```
Demo : <http://jsfiddle.net/E2738/2/>
One can right click on the image and save its as a PNG
[Answer]
# Java, 570 - 10% - 15% = 427.5
("filepath" included), 554 - 10% - 15% = 415.5 ("filepath" not included)
Thanks to Andreas for removing `BufferedImage` in `java.awt.image.BufferedImage`
```
import java.awt.image.*;class Q{public static void main(String[]a)throws Exception{BufferedImage i=new BufferedImage(3500,12,1);String s="import java.awt.image.*;class Q{public static void main(String[]a)throws Exception{BufferedImage i=new BufferedImage(3500,12,1);String s=%s%s%s;char q=34;i.getGraphics().drawString(String.format(s,q,s,q,q,q,q,q),0,9);javax.imageio.ImageIO.write(i,%spng%s,new java.io.File(%sfilepath%s));}}";char q=34;i.getGraphics().drawString(String.format(s,q,s,q,q,q,q,q),0,9);javax.imageio.ImageIO.write(i,"png",new java.io.File("filepath"));}}
```
Output:
To view properly, see this link: <https://i.stack.imgur.com/RRSDw.png>
This works just like a regular quine, except it outputs to an image. The current format is `png`, but the format can easily be changed by replacing all instances of `png` in the program with whatever format you want.
Unlike a few answers here, this is a true quine; no reading of the program file.
[Answer]
## Javascript + JQuery 153 148
Regular
```
(function f(){
c=$('<canvas/>')[0];
a=c.getContext('2d');
l=('('+f+')()').split('\n');
for(i=0;i<l.length;i++)
a.fillText(l[i],5,12*(i+1));
$('body').append('<img src="'
+c.toDataURL("image/png")+'"/>')
})()
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
```
Golfed
```
function f(){c=$('<canvas>')[0];c.width=750;a=c.getContext('2d');a.fillText(f+'f()',5,9);$('body').append('<img src="'+c.toDataURL("png")+'"/>')}f()
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
```
[Answer]
## zsh, 57 × 0.9 = 51.3
Pass it the output filename as an argument.
```
convert -annotate +0+10 "$(<$0)" -size 320x14 xc:white $1
```
Produces:
>
> 
>
>
>
[Answer]
## C99 (using SDL & SDL\_ttf), ~~414~~ ~~354~~ 346 - 15% = 294.1
```
#include<SDL_ttf.h>
#define Q(P)char*q=#P;P
Q(
i=5;main(){for(SDL_Surface*s=SDL_SetVideoMode(2048,80,SDL_Init(SDL_INIT_VIDEO),TTF_Init());i--;SDL_SaveBMP(s,"q.bmp"))SDL_BlitSurface(TTF_RenderText_Blended(TTF_OpenFont("q.ttf",9),(char*[]){"#include<SDL_ttf.h>","#define Q(P)char*q=#P;P","Q(",q,")"}[i],(SDL_Color){~0}),0,s,&(SDL_Rect){0,16*i});}
)
```
This is pretty ugly without more line breaks, but unfortunately they need to be absent. The text-rendering function doesn't grok control characters at all, so any line breaks in the code have to be rendered manually in the output.
Here's the same code but with some extra line breaks thrown in for legibility:
```
#include<SDL_ttf.h>
#define Q(P)char*q=#P;P
Q(
i=5;main(){for(SDL_Surface*s=SDL_SetVideoMode(2048,80,
SDL_Init(SDL_INIT_VIDEO),TTF_Init());i--;SDL_SaveBMP(s,"q.bmp"))
SDL_BlitSurface(TTF_RenderText_Blended(TTF_OpenFont("q.ttf",9),
(char*[]){"#include<SDL_ttf.h>","#define Q(P)char*q=#P;P","Q(",q,")"}[i],
(SDL_Color){~0}),0,s,&(SDL_Rect){0,16*i});}
)
```
Sadly, this doesn't also add line breaks to the graphical output:

The output is still legible, though with 9-point output and the red font color, it's a bit squinty. You can improve it at the cost of a character by replacing the `9` with `12`. (Note that the dimension of the resulting image is hardcoded to 2048x80. To accommodate the differences in various fonts, a fair bit of excess has been added to the right margin and the leading, enough so that a size-12 font should still fit comfortably. If you wish to increase it further, however, the dimensions will probably need to be altered as well.)
The command to build the program is:
```
gcc -Wall -o imgquine imgquine.c -lSDL_ttf `sdl-config --cflags --libs`
```
The program assumes that there is a font file called `q.ttf` in the current directory when run. I took care of this beforehand by running the following command (which should work on most modern Linuxes):
```
ln -s `fc-match --format='%{file}' sans` ./q.ttf
```
(Feel free to import your own favorite TrueType font instead.)
After running the program, the image output will be created in the current directory, in a file named `q.bmp`. Unfortunately Windows bitmap files are the only output format that this program provides. Adding more output formats would require linking in more libraries.
Note that this program takes advantage of C99's syntax for introducing non-simple literal values, thus significantly reducing the number of variables that need to be defined. This is something that more C golfers should take advantage of.
[Answer]
# C# - 498 - 15% = 423.3
This can probably be golfed more. I've never done quines or this kind of graphics in C# before:
```
using System;using System.Drawing;class Q{static void Main(){var b = new Bitmap(3050, 20);var g=Graphics.FromImage(b);string f="using System;using System.Drawing;class Q{{static void Main(){{var b = new Bitmap(3050, 20);var g=Graphics.FromImage(b);string f={0}{1}{0},e={3}{0}{2}{0};g.DrawString(String.Format(f,(char)34,f,e,'@'),SystemFonts.MenuFont,Brushes.Black,0,0);b.Save(e);}}}}",e=@"D:\p.png";g.DrawString(String.Format(f,(char)34,f,e,'@'),SystemFonts.MenuFont,Brushes.Black,0,0);b.Save(e);}}
```
Output:

Adding a different format support would be easy. Not sure if it's worth it, though.
[Answer]
## Ruby, 104 characters
```
require "RMagick"
include Magick
Draw.new.annotate(i=Image.new(999,99),0,0,0,9,File.read($0))
i.display
```
Example output, per request: [i.imgur.com/jMC594C.png](https://i.stack.imgur.com/M2Uvp.png)
[Answer]
# Python: ~~255~~ 238 -10% -15% = ~~195.075~~ 182.07
```
import sys,PIL.ImageDraw as D;i=D.Image.new('L',(2000,20));r="import sys,PIL.ImageDraw as D;i=D.Image.new('L',(2000,20));r=%r;D.Draw(i).text((0,0),r%%r,fill=255);i.save(sys.argv[1])";D.Draw(i).text((0,0),r%r,fill=255);i.save(sys.argv[1])
```
Usage:
```
python imgquine.py quine.jpg
```
This is a true quine that draws the output to the file specified on the commandline. The file format is set simply by changing the filename extension (e.g. `quine.jpg` for a JPEG and `quine.png` for a PNG).
Example output (2000x20 image):

] |
[Question]
[
Inspired by [this StackOverflow post](https://stackoverflow.com/q/70508442/7742131)
Given a list where each element appears a maximum of 2 times, we can define it's "sortedness" as the sum of the distances between equal elements. For example, consider
```
[1,1,2,3,3] (array)
0 1 2 3 4 (indices)
```
The sortedness of this array is \$2\$. The distance between the `1`s is \$1 - 0 = 1\$, the distance between the `2`s is \$2 - 2 = 0\$ (as there's only one `2`) and this distance between the `3`s is \$4 - 3 = 1\$. Summing these distances, we get the sortedness as \$1 + 0 + 1 = 2\$.
Now, consider
```
[1,3,2,1,3] (array)
0 1 2 3 4 (indices)
```
The sortedness of this array is \$6\$:
* `1`s: \$3 - 0 = 3\$
* `2`s: \$2 - 2 = 0\$
* `3`s: \$4 - 1 = 3\$
* \$3 + 0 + 3 = 6\$
In fact, \$6\$ is the maximal sortedness of the permutations of this particular array, and there are 16 permutations of `[1,1,2,3,3]` with a sortedness of \$6\$.
```
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[1, 3, 2, 1, 3]
[1, 3, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
[3, 1, 2, 1, 3]
[3, 1, 2, 3, 1]
```
---
Given a list of positive integers, where each integer appears either once or twice, output a permutation of this list where the sortedness is maximal. You may input and output in any [convenient manner](https://codegolf.meta.stackexchange.com/q/2447/66833), and you may output any number of the permutations with maximal sortedness.
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the shortest code in bytes wins.
## Test cases
```
input -> output
[1] -> [1]
[8, 7] -> [8, 7]
[1, 1, 2] -> [1, 2, 1]
[9, 7, 4] -> [9, 7, 4]
[2, 9, 3, 10] -> [2, 9, 3, 10]
[4, 4, 10, 10] -> [4, 10, 4, 10]
[1, 1, 2, 3, 3] -> [1, 3, 2, 1, 3]
[2, 8, 5, 6, 5] -> [5, 2, 8, 6, 5]
[5, 2, 6, 1, 9] -> [5, 2, 6, 1, 9]
[7, 1, 1, 4, 5, 5, 8] -> [1, 5, 7, 4, 8, 1, 5]
[3, 1, 2, 8, 3, 10, 8] -> [3, 8, 1, 2, 10, 3, 8]
[1, 1, 2, 2, 3, 3, 4, 4] -> [1, 2, 3, 4, 1, 2, 3, 4]
[4, 4, 3, 3, 2, 2, 1, 1] -> [4, 3, 2, 1, 4, 3, 2, 1]
```
[Answer]
# [Python 3](https://docs.python.org/3/), 47 bytes
```
lambda l:(sorted({*l},key=l.count)*2)[-len(l):]
```
[Try it online!](https://tio.run/##PU7dDoIgFL7vKbgERy3E/80nMS8scboInWHNtZ6djkCyM873c84H06r7UXHTlRcjm8e1bZAs8HOctWjxJ5BfehdrKU@3cVGaBCGpjlIoLElRm3c/SIFYMc2D0rjD4tVIPKhp0ZjAMRWrD1VGUQqNUQQVAspBoCgCFFIEhINzBhaBuEFP/YL1uRuGqJiiBG7gsTUTO5UDTy1iNiS2lYHK/ymZf8jJe7jPt1vR/gknOXsbrX8 "Python 3 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 57 bytes
```
lambda l:[x for c in 1,2,1for x in set(l)if l.count(x)-c]
```
[Try it online!](https://tio.run/##PY7bDoMgEETf@xX7KAltCt5N@iXWB2slklA0FlP79XS51ITAnJllYPmaadbcitvdqv71ePagmnYHMa8wgNTAKKfM0e7oPZpEESlAXYZ50ybZyXno7GeSagTWLKvUBkQi9bKZhBDbsu7UVhRKPBjFMuCoajQoZKg4BYQUkytShqaTEeMFn6dhGKtyCgXuyLkPCz9VI5deMV@S@1Whm/5bqvhQsI/y2O9vZccnghViN9r9AA "Python 2 – Try It Online")
Iterates through the distinct elements of `l` 3 times, first outputting those that appear twice in `l`, then those that appear once, then twice again.
*-1 byte by att*
# [Python 3.8](https://docs.python.org/3.8/), 47 bytes
```
def f(l):*map(l.remove,s:={*l}),;l+=[*s-{*l}]+l
```
[Try it online!](https://tio.run/##PU7dCoMgFL7fU3ip5cbM/qMniS6CGQVWUq01xp7dndQFB/3@zqfqvXbTyFM1a/0QLWqxJLk3NArL2yyGaRN0ycuPJ7@EFtIvK2@5Hqz2pX51vRSI5XsptkbiflTPFRNStHgnhZr7cQWgK1ZfqpSiBC5GEUwAKAOBohBQQBEQDs4dWAjiAR11C8bnNgxVEUUxnMAjY8YmlQFPDGKmJDKTgsr/Lal7yMpnues3W@H5CStZ@4jWPw "Python 3.8 (pre-release) – Try It Online")
*-3 bytes by pxeger with modifying the list in place*
[Answer]
# [J](http://jsoftware.com/), 10 bytes
```
/:~:*1#.e.
```
[Try it online!](https://tio.run/##y/qvpKegnqZga6WgrqNgoGAFxLp6Cs5BPm7/9a3qrLQMlfVS9f5r/k9TMFKwUDBVMFMw5UpTMFcwBLJNgNhQwQLINwSyjRSMoaQhAA "J – Try It Online")
I had this first, hoping J might tie caird's Jelly, but I couldn't find any actual 9-byter.
### How it works
```
/:~:*1#.e. Monadic train, input: X, a numeric vector
1#.e. Count occurrences of each number of X in X
~:* Multiply with nub sieve (1 if a number appears first, 0 otherwise)
First occurrence of a double becomes 2, second becomes 0
A single becomes 1
/: Sort X by the above
```
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 35 bytes
```
ReverseSort@Gather@#~Flatten~{2,1}&
```
[Try it online!](https://tio.run/##NY0xD4IwFIR3/gYJ05lYaKEMGiZdjYzGoSElkggmtXEh8Nfre0Wn3t13vTca/7Cj8UNnQn8IV/ux7m3bl/PNmZFr0vX0NN7baZ1ziCULFzdM/pbujn2T3rO17QyhZBYLklmj4kdAIGdRo4JkkaNGAbFnLSFJ/UysEiq2loZCCcVGUV4SrdlU4KIkqqA5KOI/HUe3ZFuKW1SU/0tsOSa8JEv4Ag "Wolfram Language (Mathematica) – Try It Online")
```
# {1,1,2,3,3}
Gather@ {{1,1},{2},{3,3}}
ReverseSort@ {{3,3},{1,1},{2}}
~Flatten~{2 } {{3,1,2},{3,1}}
,1 {3,1,2,3,1}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
```
ẹⱮ_"JỤị
```
[Try it online!](https://tio.run/##y0rNyan8///hrp2PNq6LV/J6uHvJw93d/w@3P2pa4/7/f7RhrI5CtIWOgjmINtRRACIjJKaOgjEQgQSMYQIWYDFDAyALRSFUrY6CCRDFAgA "Jelly – Try It Online")
### How it works
```
ẹⱮ_"JỤị Monadic link. Input: X, a numeric vector
ẹⱮ For each element n of X, get all indices of n in X
_"J For each list of indices, subtract the original index
If n appears twice, the first becomes [0, positive],
and the second becomes [negative, 0].
If n appears only once, it becomes [0].
Ụị Sort X by the above
All [negative, 0]s come first, then [0]s, then [0, positive]s
```
I really hope Jelly were a proper derivative of J/K, in which case we wouldn't need the `"`.
[Answer]
# [Factor](https://factorcode.org/), ~~94~~ 62 bytes
```
[ [ ] collect-by values [ length ] inv-sort-with round-robin ]
```
Have a screenshot of running this in Factor's REPL because `collect-by` postdates the build on TIO.
[](https://i.stack.imgur.com/n0UX6.png)
## Explanation
I finally found a use for `round-robin`! It's sort of like if `flip` (matrix transposition) worked for non-rectangular matrices and it also flattens the results.
```
! { 1 1 2 3 3 }
[ ] collect-by ! H{ { 1 V{ 1 1 } } { 2 V{ 2 } } { 3 V{ 3 3 } } }
values ! { V{ 1 1 } V{ 2 } V{ 3 3 } }
[ length ] inv-sort-with ! { V{ 1 1 } V{ 3 3 } V{ 2 } }
round-robin ! { 1 3 2 1 3 }
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ĠEÞZFị
```
A monadic Link accepting and returning a list of positive integers as specified.
**[Try it online!](https://tio.run/##y0rNyan8///IAtfD86LcHu7u/n90z@H2R01rjk56uHMGkAaiLBDVMEdB107hUcPcyP//o6MNY3UUoi10FMxBtKGOAhAZITF1FIyBCCRgDBOwAIsZGgBZsbEA "Jelly – Try It Online")**
### How?
Produces a list of the form `a+b+a` where `a` is a list of the elements that are present twice and `b` is a list of the elements that only appear once. (`a` and `b` are also each sorted by value as a side effect of the method employed.)
```
ĠEÞZFị - Link: list of integers with at most two of each, A
e.g. [3, 3, 1, 1, 2]
Ġ - group indices of A by their values [[3, 4], [5], [1, 2]]
Þ - sort the result using: v v v
E - all equal? 0 1 0
-> [[3, 4], [1, 2], [5]]
Z - transpose [[3, 1, 5], [4, 2]]
F - flatten [3, 1, 5, 4, 2]
ị - index back into A [1, 3, 2, 1, 3]
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jellylanguage), 8 bytes
```
Œ!ĠISƊÐṀ
```
[Try It Online!](https://jht.hyper-neutrino.xyz/tio#WyIiLCLFkiHEoElTxorDkOG5gCIsIiIsIiIsWyIxLCAxLCAyLCAyLCAzLCAzIl1d)
[Answer]
# Haskell + [hgl](https://gitlab.com/WheatWizard/haskell-golfing-library), 17 bytes
```
cx<tx<rsB l<gr<sr
```
## Explanation
This one is pretty simple, it composes 5 functions:
* `sr` sorts a list.
* `gr` groups a list into contiguous sublists of equal elements.
* `rsB l` sorts a list of lists in descending order of length.
* `tx` transposes a list of lists.
* `cx` concats a list of lists.
## Worked example
We take the original list:
```
1 2 9 9 3 1
```
... sort it
```
1 1 2 3 9 9
```
... group it
```
1 1
2
3
9 9
```
... sort by length
```
1 1
9 9
2
3
```
... transpose it
```
1 9 2 3
1 9
```
.. and concat it
```
1 9 2 3 1 9
```
## Reflections
This score seems pretty weak despite how straightforward the answer is. However I think there could be some improvements.
* `rsB l` and `sB l` could probably be their own functions. Sorting lists by length is likely to come up again so it would be nice to have these.
* `gr<sr` could probably be rolled into one function. It's not uncommon to want to get all the groups irrespective of the initial order and 5 bytes is a big price for that. Since the final order is arbitrary why not sort the output by size. It's the order we want here so that shows it's at least useful once.
As of [e7ce5325](https://gitlab.com/WheatWizard/haskell-golfing-library/-/commit/e7ce53255b667b951b99dc5899cdfa9dd9375b00) these changes have been implemented saving 9 bytes:
```
cx<tx<bg
```
Obviously this is non-competing, but these changes should be helpful in the future.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 7 bytes
```
ÙΣ¢}RI∍
```
[Try it online!](https://tio.run/##yy9OTMpM/f//8Mxziw8tqg3yfNTR@/9/tLGOgqGOgpGOgoWOAohtAGTFAgA "05AB1E – Try It Online")
-4 thanks to @ovs
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~14~~ ~~12~~ 9 bytes
```
9B#u1>&)y
```
The input is a column vector. The output contains each entry on a line (not necessarily right-aligned). [Try it online!](https://tio.run/##y00syfn/39JJudTQTk2z8v//aENrBSAyslYwBqJYAA) Or [verify all test cases](https://tio.run/##y00syfmf8N/SSbnU0E5Ns/K/QXKES8j/aMNYrmgLawVzIGVorQBERkCWJVDAWsEEyDKyVgByjIEyBkCeCVAQxIRyoRrA8sYQxUCjTK0VzIAkkG8KljQDq7IE8s3BLEOwIaZgZAEUNYaZYgG1CCIMNxxqPliXCdwRECGINEhpLAA).
### Explanation
This outputs the duplicated numbers in their original order, then the non-duplicated numbers, then the duplicated numbers in their original order again.
```
9B % Push 9, convert to binary. Gives [1 0 0 1]
# % Use as output specification for the next function
u % Implicit input. "Unique" function, first and fourth outputs. This
% pushes the unique numbers in their orignal order, and their count
1> % Greater than 1? (element-wise). Gives a mask for duplicated numbers
& % Use alternative output specification for the next function
) % Indexing, two outputs. This pushes the duplicated numbers, then the
% non-duplicated numbers
y % Duplicate from below. Implicit display
```
[Answer]
# Python3, ~~139~~ ~~131~~ ~~116~~ 106 bytes
```
def f(x):
l,m=[],[]
while x:
i=x.pop()
if x.count(i):l+=[i];x.remove(i)
else:m+=[i]
return l+m+l
```
[Try it online](https://tio.run/##bZJRj4MgDMff/RR9lEjMOXRzXvgkxqcbZiQoBt3O@/Reqajb5RIC7b@/ltIw/Ex324tycMtyUy208cyqCAzvZN3wuong@66NghlF0HJOBzvEzNstzOmXffRTrFllElnr5nNOnersU6GEiDKjqjqKRODU9HA9mKRLzDKpcRpBQo0UQFxnDQfcGA9@yeHiJTp3NeOA60QsnugdsSuSHHIf28w9hiRqAvkPH391dybHDK9sUHDydyp0QNki9CHWVrzweiO2XnA44@65gqAyCDu3ymdKvx7cJuzchYSM@iloleH2Yn0s1c7eaout1zI8NiSJjT2tovf/eWF4JNXOj5GvwmH/naDYBrLOJAuz3Id02A2LmihqrQPNwYLugX5FReUGp/FjKagk/kjNEOBg9DjFTj2VG9UtVoyBlGDZ8gs)
## Alternative with lambda, 103 bytes
With non-deterministic ordering of elements. I'm not sure, whether that counts:
```
lambda x:(l:=[e for e in set(x)if x.count(e)>1])+[e for e in set(x)if x.count(e)<2]+l
```
[Try it online](https://tio.run/##hVLLboMwELz7K/ZoKzQqIQ@CSn4k5UCDUS0ZjMBU9OvT9dpAUlUqQrZ3dvap6b7tp2mTtOvvdf5@12XzUZUwZVxn@VVCbXqQoFoYpOWTUDVM25sZW8uluMSF2PzDedsVG32ve9PAzWgtb1aZdgDVdKa3UMm6HLWt1M0yZuVgB8jhygA/fo2LCPAQUbDTCE4OontB4wjw3xEXb7RW3xmZEeydb34uPmQiliD/1fkfzYWzxwiHzKRg7J9ZoQOKTkIfiW/FAY8VsfVDBEc8He9ApDQAC8/DRwo/r7wZWHgnAmLq50B/Gqof/LCUO37Kncy9pmHYEJTM3J0Hnf3HhGFIyr1fV@6B9f17g8m8EL@TOOxyWdL6LgQrGENZQKXqmmuRUaIKZfGgFa7VYAV5nPZU5OUn27GRfWnlEkexV1lsy66TbcWVD6Kjl3bsUbNjw5tywpCXRrV4UUrt8lXbr1KPcuACUNNakvcCsWCMhbrG8Ui4vmDXKyd7yHKosRoSIj@JFOFhhLj/AA)
[Answer]
# [Python 3](https://docs.python.org/3/), 69 bytes
```
def f(l):x={z for z in l if l.count(z)<2};y=[*{*l}-x];return y+[*x]+y
```
[Try it online!](https://tio.run/##HczBCoQgGEXhV7nLtBqYmlXlk4irKRnhR0MM1OjZHQu@5eHsKfycHQsJ@elQjY/h8a5UWTcN3RCbojgztPPIMBYEo0GvrztsaDJbhmtOQvKT09VHNfstHN4itZJH1aaye1O7@8PKHw "Python 3 – Try It Online")
No, @xnor has better version of this idea, heck @tsh has even better
[Answer]
# [J](http://jsoftware.com/), 19 bytes
```
/:~:]`(I.@[)`[}1#.=
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/9a3qrGITNDz1HKI1E6JrDZX1bP9rcvk56SnoW0Vbaes7aGiZ1GjrxygZatpqgWS5uFKTM/IV0hSMFAyB0FjBGCZgCGNYKJjDxYAKQAqN/wMA "J – Try It Online")
The idea is to create a mask for sorting, such that unique elements are pushed into the middle, and the first and second instances of repeat elements are pushed right and left, like a solution of water, oil, and mercury.
Consider `2 1 1 3 3`:
* `=` Creates boolean masks for each unique element:
```
1 0 0 0 0
0 1 1 0 0
0 0 0 1 1
```
* `1#.` Sums the rows:
```
1 2 2
```
* `~:` Nub sieve of input: ones at the first occurrence of each element:
```
1 1 0 1 0
```
* `]`(I.@[)`[}` Update the nub sieve `[` at the indices of those ones `(I.@[)` using the row-sum values `]` (ie, `1 2 2`):
```
1 2 0 2 0
```
* `/:` Sort the original input according to that:
```
1 3 2 1 3
```
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 21 bytes
```
W⁻θυ⊞υ⊟ιF³IΦυ¬﹪⁻ι№θκ²
```
[Try it online!](https://tio.run/##LYyxCsJAEER7v2LLXVhBTSOkDNhF0ocUR4zc4pE1d7f6@ecFnOox85jZuzirC6V8vYQFsJfVEm4MRgSDJY/GMOgbhag9PDUCNnWIsmbsXMp4k5CXuFt3zdjrw4L@X4ShU6tivXsRMVxoT1vKODYM51owXBl2PlWapnL8hB8 "Charcoal – Try It Online") Link is to verbose version of code. Explanation: Since each element is guaranteed to occur no more than twice, the exercise reduces to printing the elements that are duplicated, then the ones that only appear once, then the ones that are duplicated again.
```
W⁻θυ⊞υ⊟ι
```
Create a (reversed) deduplicated list of elements.
```
F³IΦυ¬﹪⁻ι№θκ²
```
Output the elements three times, but alternately filtered on whether the element was originally duplicated or not.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
ĠvḢf?Ġ'₃;fȮJJ
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLEoHbhuKJmP8SgJ+KCgztmyK5KSiIsIiIsIlsxLDEsMiwzLDNdIl0=)
Wow this is a mess.
```
Ṗµ ;t # Maximal permutation by...
Uv=∩ # For each unique element, indices of equal elements?
ƛ ;∑ # Apply to each, taking the sum
T # Truthy indices
¯h # Cumulative differences
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 7 bytes
```
ΣT↔ÖLk=
```
[Try it online!](https://tio.run/##yygtzv7//9zikEdtUw5P88m2/f//f7S5jiEQmuiYAqFFLAA "Husk – Try It Online")
Output is concatenation of:
1. List of all elements present, with those appearing twice coming first
2. List of elements that appear twice, in the same order as 1
```
k= # group list elements by equality
ÖL # and sort the groups by length
↔ # and reverse this order
# (so now 2-element groups are first,
# then 1-element groups),
T # now transpose
Σ # and flatten the resulting list of 2 lists
```
[Answer]
# [R](https://www.r-project.org/), ~~55~~ 54 bytes
*Edit: -1 byte thanks to Giuseppe*
```
function(x)names(y<-table(x))[c(order(-y),which(y>1))]
```
[Try it online!](https://tio.run/##bc5NCsIwEAXgfU8xYBcJpIuKogvrRcRFjGkbiIlMJmpOX2P9BcvbDAPz5sMhuuCRmqGNTpHxjt24kycdWNpUJA9W5wXfKebxqJFViYtrb1TP0rbmfP86Z4qtRJ2zEMucNecAM/CRzpFABpCIMoFvIRAa14XHSL0Gj6YzTlrQVp@0o1AUz8J5U3xBIjWYHeOjjOGpvPyASvshlXZEvTsmVJOoP8VwBw "R – Try It Online")
Output as strings of the original elements. Add +3 bytes to output as the original elements themselves (see TIO link).
Output is: one of each element that appears twice, then elements that appear once, and finally one more of each element that appears twice.
[Answer]
# [BQN](https://mlochbaum.github.io/BQN/index.html), 13 bytes
```
(⍷⍒∘⊒⊸⊏˜)∾⊒⊸/
```
[Try it at BQN online REPL](https://mlochbaum.github.io/BQN/try.html#code=VW5zb3J0IOKGkCAo4o234o2S4oiY4oqS4oq44oqPy5wp4oi+4oqS4oq4LwoKVW5zb3J0IDfigL8x4oC/MeKAvzTigL814oC/NeKAvzg=)
```
∾ # join together:
(⍷⍒∘⊒⊸⊏˜) # L: unique set of elements, with those present twice first
⊒ # occurrence count of each element
⍒∘ # reverse order (so those twice first)
⊸⊏˜ # use this to index original elements
⍷ # and deduplicate them;
⊒⊸/ # R: just the elements that are present twice
⊒ # occurrence count of each element
⊸/ # use this to select original elements
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 13 bytes
```
Ṗµv=UvTv¯f∑;h
```
[Try It Online!](https://vyxapedia.hyper-neutrino.xyz/tio#WyIiLCLhuZbCtXY9VXZUdsKvZuKIkTtoIiwiIiwiIiwiWzEsMSwyLDJdIl0=)
Vyxal's deltas is negative for whatever reason, but no worries, we just get the minimum value then.
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~53~~ 44 bytes
```
O$`(\d+)((?<=\b\1,.*))?((?!.*,\1\b))?
$#2$#3
```
[Try it online!](https://tio.run/##JYy9DsIwEIP3ewvUICXFqrj8NIkE6sjIC2QoFR1YGBDvHy5hOvuzz5/9@3o/6lHf1npXqy7Pk9F6uVzLVhjTaMwi9jCNKFw2caQGqwZXK1NCJAbDUkaEJ4sMBz6Th5fTVI8FOgkTAmYECkJm4ZkiWu6FByRyvZv6hNj/a3@Wiu@jTTcm2Q8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation: Saved 9 bytes by using @Bubbler's idea of encoding both whether the elements need to be sorted to the start or the end in the same sort key.
```
(\d+)
```
Matching each entry...
```
((?<=\b\1,.*))?
```
... check whether this is the second entry of a duplicate, and...
```
((?!.*,\1\b))?
```
... check whether this is a unique entry or the second entry of a duplicate.
```
O$`
$#2$#3
```
Sort by a combination of the two checks. The first entry of a duplicate has a sort key of `00`. Unique elements have a sort key of `01`. The second entry of a duplicate has a sort key of `11`. This means that the unique elements sort between the two sets of duplicate elements.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 7 bytes
A port of [tsh's Python answer](https://codegolf.stackexchange.com/a/240372/64121).
```
Qċ@Þ¹Uṁ
```
[Try it online!](https://tio.run/##y0rNyan8/z/wSLfD4XmHdoY@3Nn4/3D7o6Y17v//RxvG6ihEW@gomINoQx0FIDJCYuooGAMRSMAYJmABFjM0ALJQFELV6iiYAFEsAA "Jelly – Try It Online")
```
Q -- the unique elements of the list
Þ -- sort by ...
ċ@ ¹ -- the number of occurences in the full list
U -- reverse
ṁ -- mold; reshape the list to the length of input by reusing from the front
```
[Answer]
# python3, ~~121~~ 101 bytes
```
def u(l):
x=[]
y=set()
for i in l:x.append(i)if l.count(i)%2else y.add(i)
y=list(y)
return y+x+y
```
[Try it online!](https://tio.run/##PU7baoQwEH33K@alkLAi9bbrWvwS8UFqZAMhBk3a5OvtMdqFYXIuM2dign0tutz3SczkmOJtQr7rh4RCtwnLeELzspIkqUm1PhuNEXpiksuZVPa9OG1BPgqhNkEhG6fDO5aV3CwLgKuwbtUUbv4W9t@XVILy1nfiZ1RMauNwg3@ZVSLIMc/53udD0jcpPfDkKaEKoCeElCqgIiWQEs4nWAXxgBe9FqJfnsOIqlO6o4PX0bzHqSf4I6I8htSxGqjlf0pzHTrld/iVH7eq9ydO6bSP0eEP)
Thanks to caird coinheringaahing
[Answer]
# [Perl 5](https://www.perl.org/), 67 bytes
```
sub f{pop=~s/(.*)(\b\d+ )(.*)(\2)(.*)/my$x=$2;$x.f("$1$3$5").$x/er}
```
[Try it online!](https://tio.run/##dZRbb9owFMef609xlLl1srlJQwilQdl4X9W@bE8FRXQNVTZyWRwkKsS@OjvYuTgplQI5/vt3Lj74UMTlxj8exfYZ1vsiL8J/wjHtz5a5eF68fAFL2SP5dtI3ugvpaEZ39to0qEs96huWTXdOXB5kDJGXVfySxULAHtI3uCxy4c6Anl57Gj3RaHlwnJBGsM5LuLFt@imagdimZroqaHTdA7nat@BAkDYJwBPgx11C@FW@YMkbccrhVunK0vdcDviMaje0cN0n7tCHw1gR7UIn0Ad1Dz1vFNUTdHKMvie1Q@vl@D1bVybjeG19nipRSoMa8HA@hwl@K9qX6LSRdFptTWSgO51uJZ2@laIrq/TlM23r8VVDZB73XR6vOcO0bkfr6jUeIyV7cufs@esWyCxj/YdSUmef67XXtEx1zW273jays2t/a48hAG@oSZOs2FacrqJ0tSviMrXCOY1m9TbQWITdpTbnGtcxr3nVqCEOBsxVUDA6Zq4zotgkFQPGdU8tXD@lxtTxijLJqrVxeT0RuMJcQZsSAPGglw61GI1fGDDq4ganoym8r76KRWZwcoEGhKGkrq7gd55kJuOMn1izzmZZEP8dbunlWvANWP6HQQDs4fEHPH5nM3JBDmQrYrhPRBUEP6tkAwz/AdgRR5qo8SXtzJJ2HElv5Eh/zshglMhgWMjg7pOzF56cv8zko3tKPrqA/wE "Perl 5 – Try It Online")
[Answer]
# [R](https://www.r-project.org/), 48 bytes
```
function(x)c(d<-x[duplicated(x)],setdiff(x,d),d)
```
[Try it online!](https://tio.run/##K/pfmlecX1SiYKP7P600L7kkMz9Po0IzWSPFRrciOqW0ICczObEkNQUoFqtTnFqSkpmWplGhk6IJRFCtGska5jqGQGiiYwqEFpqa/wE "R – Try It Online")
[Answer]
# [Ruby](https://www.ruby-lang.org/), 43 bytes
```
->l{(l&l-z=l.select{|x|l.count(x)<2})+z|=l}
```
[Try it online!](https://tio.run/##KypNqvyfZvtf1y6nWiNHLUe3yjZHrzg1JzW5pLqmoiZHLzm/NK9Eo0LTxqhWU7uqxjan9n@BQlp0tKGOkY6xjqGOcWwsF1jAREcBiIzByAiMDIEoNvY/AA "Ruby – Try It Online")
[Answer]
# [Julia 1.0](http://julialang.org/), 46 bytes
```
~a=(!x=a∩a[a.|>i->sum(i.==a)==x];[!2;!1;!2])
```
[Try it online!](https://tio.run/##TVBJboQwELz7Fc2cQAIUs8wwQuaeQ15gcehoSOSIOAgYiUM053wl38pHSGObBVm4qrrscvfHvVXIp3l@oPC9SeDfzy9KjL8rFVXD/dNXsRAYCDHVpfSS0uOll9TB/PbVgwKloW/w1irdDH7AgD4MX0HA0LVq9FV4iqqT00l91qN8aUaMO@yHxscgxv59KGtj6Hqlx1b7ZKzggQFr9G2WvIaoAtqYLEK4WGYQkzwEWolzECJO8pWqIWRWXgmTVCWSkufJlo4Ckxm5FrjXHc2cwaWZE@mWmdrYRTIR9LQ8hDP9rSU39cJJzPGzOXI9WlaJyYtB3CTnZhVbXG7bMTdye2O6vqtwzWz@dLUlVl74sRHXi7kvO07RSjvexpOuDdue@TaobQw7rv8B "Julia 1.0 – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~119~~ \$\cdots\$ ~~103~~ 97 bytes
```
*b;*p;f(a,e)int*a,*e;{for(b=a;a<e;++a)for(p=a;++p<e;)*a==*p?*p^=*--e^(*e=*p),*a^=*b^(*b++=*a):0;}
```
[Try it online!](https://tio.run/##rVVbb5swFH7fr7AiVeIWDWOudVkfpv2KNJ0IdTq6jaCAtGgVf33ZwRdsk3Tqw6IEH5/vO1f7kHr9XNfns7ejXkf3ThUwt2kHrwo8Rl/3h6OzKyta3THq@5U77TvY@34HGterytLr7r3usfTWa/boeAz2buBVoNjBduf7pVe5tyEdz@AV/aya1nHR6wcEn0kxsH7Amy0q0Sse6ayKhCoPUGZoiSQGCL6RAcQCKIAeoNgAEgFEAQKMgF1ogKkAYzCZkAWaWcG4NTHgfPYMSSYBSuFpwIWAE26ach@FAeNQ4BlHMM9A@DGdYNkZonLIZREgmbRokarMlns1u4GJWbGgCPpkOlJ1Kh5n94LMDQNxKmIhYonFkoglFUsmllwsRSCrlav0g6UjTHRMrmhFyL75zQ57h1Pcj3LniW2ADDSy0chGiY0SG41tNLbRxEYTG01tNLXRzEYzG81tNLfRwkYLG8Xhoh3hAl@2a9EvvGgYXnQML1oGe@OE2Klj9cCeFvOq1JczqxA9txG/ZxZ4dXYV@Ob8KoKe4emSxVcYeo6JuupkQcnNYc2tWVaUf8zz3JZwjpSIYrgzfOnMmOtczeyUPtFzPVMjs3dipLW8JOv5nmvVsjnfykLwZ/tAH6YWiRZjLSZaTLWYaTHXYhEYTTJkIx42As6vhfrQ9gOqv1VHD56s/s6OIuHVw@lL9HAqPsMvWQXI3JOVtIb/KuRM7WnaJ3YCs5BK8U7deRVR3/pZQ5Hvc7bLnYl/LP1@BHfiHck5W2rCqJVoe4F2R8D3zmqzcrVSJyqThARbHt814prmN/3NE5Td3E@1367gOWyareFyvIi4RetPyA7rDGCHfNS61K6OQR7zDblWYH84AtSyvv/KeM5voYONvr/SmfkCzAaSxBREyX5ZsnnkPXIYdAGVkPzmZeteMKaPlblfgs81auhVZ4N0NrzH2fCGs/H/nd9N/9ACUw2CfQallYxyNX4Yz3/q/Y/quT@vf/0F "C (gcc) – Try It Online")
*Saved 3 bytes thanks to [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat)!!!*
Inputs a pointer to an array of integers and a pointer one past the end of the array (because pointers in C carry no length info).
Unsorts the array in place.
### Commented
```
*b;*p;f(a,e)int*a,*e;{ // declare pointers and f
for( ;a<e;++a) // main loop a to the end
b=a // init b to the beginning
for(p=a;++p<e;) // inner loop of p from
// a + 1 to the end
*a==*p? // is current int equal to
// another int in a?
*p^=* e^(*e=*p), // then swap second int with
// one before the end
-- // move end back one
*a^=*b^(*b =*a) // and swap current int with
// the beginning which
// has already been seen
// so is single or is the
// same as what a points to
++ // bump up the beginning one
:0; // or do nothing
} //
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 56 [bitsv2](https://github.com/Vyxal/Vyncode/blob/main/README.md), 7 bytes
```
Þzµ≈;∩fİ
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=2#WyI9IiwiIiwiw556wrXiiYg74oipZsSwIiwiIiwiWzEsMSwyLDMsM10iXQ==)
Jelly porting ftw
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 60 bytes [by tsh](https://codegolf.stackexchange.com/a/250292/76323)
```
a=>(p=a.filter(y=c=>!(y[c]^=1))).concat(a.filter(c=>y[c]),p)
```
[Try it online!](https://tio.run/##PU5LboMwEN33FO6Kseo6IUBCFJllL9AlopHljCMqC4ghkTg9HQxFsuz3mzf@1S/dG193w2fT3nCyatKqgE5paWs3oIdRGVW8w1ia6kfFnHNp2sboAbYE@bPLRceni8fHs/YIke0jLj3q21ft8HtsDOxF9BxsHuTOaYOwkx@7u7iqgir71qF07R0s4Es7uNIqPpVx9Vbmgp3oiQWjcyB0JkGwlNBBMCIJOXtiKYkzXOk6EPxkCVNVJtiRbuJZMI8hdSZ@CigOJVk4OanJf0u@LlrkrXztD1Pp9olFWuw5Wv0B "JavaScript (Node.js) – Try It Online")
# [JavaScript (Node.js)](https://nodejs.org), 61 bytes
```
x=>x.map(r=t=>r[t]=[r[t]?~++r[t][0]:4,t]).sort().map(t=>t[1])
```
[Try it online!](https://tio.run/##PU7NjoMgEL7vU3ATIku1amvbYG/7AnskpCEWGzdULNKmveyruyO6JRNmvp/54Ec91FC7tvefnT3rseHjk1dPdlU9dtzzygkvuZju428cT10kcp9TLwkbrPOYBC84vUglGQ9O3@6t0zhqhogwp9X5qzX6@9XVOKHR3TdloHujao1XLF5d6IlXte0GazQz9oIbrB/K4BOBM0Lohygp2kJLKYJaw7QDgqIcpjVFADJQEkA5kNO4wGUh6NlshqiCog3cgIsgboJrB3gbpjSEFKFKYLP/lHJ5aKbf4Ut@2Mrfn5ipWZ6s8g8 "JavaScript (Node.js) – Try It Online")
] |
[Question]
[
Since today marks the occasion of the 26th [leap second](https://en.wikipedia.org/wiki/Leap_second) ever to occur, your challenge will be to output the date and time of every leap second in GMT or UTC that has occurred so far, as well as the one to occur today.
### Input
There is no input.
### Output
```
1972-06-30 23:59:60
1972-12-31 23:59:60
1973-12-31 23:59:60
1974-12-31 23:59:60
1975-12-31 23:59:60
1976-12-31 23:59:60
1977-12-31 23:59:60
1978-12-31 23:59:60
1979-12-31 23:59:60
1981-06-30 23:59:60
1982-06-30 23:59:60
1983-06-30 23:59:60
1985-06-30 23:59:60
1987-12-31 23:59:60
1989-12-31 23:59:60
1990-12-31 23:59:60
1992-06-30 23:59:60
1993-06-30 23:59:60
1994-06-30 23:59:60
1995-12-31 23:59:60
1997-06-30 23:59:60
1998-12-31 23:59:60
2005-12-31 23:59:60
2008-12-31 23:59:60
2012-06-30 23:59:60
2015-06-30 23:59:60
```
### Rules
Since I doubt there are many built-ins that allow leap-seconds, I'll allow them.
Standard loopholes are disallowed.
Shortest code wins.
Date format must have a zero-padded month and a 4-digit year, as well as military time and a space separating the time from the date. Putting `UTC` at the end is optional. Your choice of dashes or slashes.
EDIT: Yep as predicted, this became an encoding challenge. If only encoding could fix the leap second problem, ...then all our code would be much more practical. Maybe we need some ideas for more fun challenges with practical uses?
[Answer]
# R, ~~78~~ 75 bytes
Built-ins, you say? Well...
```
message(paste(as.Date(.leap.seconds)-1,"23:59:60\n"),"2015-06-30 23:59:60")
```
R has an automatic variable `.leap.seconds` which contains the date and time of each leap second insertion, given in the system's local time. As of R version 3.2.0, this does not include today, so I've added that manually.
Ungolfed + explanation:
```
# Convert the datetime values to UTC dates. These will be a day past the
# expected output, so we can subtract 1 to get what we want.
dates <- as.Date(.leap.second) - 1
# Paste the UTC time and a newline onto the end of each date
datetimes <- paste(dates, "23:59:60\n")
# Print each time, including today, on its own line
message(datetimes, "2015-06-30 23:59:60")
```
You can [try it online](http://www.r-fiddle.org/#/fiddle?id=KmbJDJDY)!
[Answer]
# CJam, ~~72~~ ~~70~~ ~~69~~ 64 bytes
```
26,"~g¼K&Béx¸¦Ø"240bFbf{<1b2md\1972+'-@6X$4*-'-Z3$" 23:59:60"N}
```
Try it online in the [CJam interpreter](http://cjam.aditsu.net/#code=26%2C%22~g%C2%BCK%26B%C3%A9x%C2%B8%C2%A6%C2%AD%C3%98%22240bFbf%7B%3C1b2md%5C1972%2B'-%406X%244*-'-Z3%24%22%2023%3A59%3A60%22N%7D).
### Idea
We start by encoding each leap second as **2 \* (Y - 1972) + D**, where **D** is **1** if it occurs in December and **0** otherwise.
The array of all encoded leap seconds is:
```
[0 1 3 5 7 9 11 13 15 18 20 22 26 31 35 37 40 42 44 47 50 53 67 73 80 86]
```
Let's call this array **L**.
Since the array is in ascending order, we can store the consecutive differences instead of the actual numbers:
```
[1 2 2 2 2 2 2 2 3 2 2 4 5 4 2 3 2 2 3 3 3 14 6 7 6]
```
Treating this array as the digits of a base 15 number, we obtain the integer
```
19238985373462115979359619336
```
which digits in base 240 (cast to characters) are
```
~g¼K&Béx¸¦Ø
```
### Code
```
26, e# Push I := [0 ... 25].
"~g¼K&Béx¸¦Ø" e# Push the string from above.
240bFb e# Convert from base 250 to base 15 to push L.
f{ e# For each J in I:
e# Push L.
< e# Replace L with L[:J].
1b e# Push the sum S of the integers in L[:J].
2md e# Push (S / 2) and (S % 2).
\1972+ e# Add 1972 to (S / 2).
'-@ e# Push '-' and rotate (S % 2) on top.
6X$4*- e# Compute (6 - 4 * (S % 2)).
'-Z e# Push '-' and 3.
3$ e# Push a copy of (S % 2).
" 23:59:60" e# Push that string.
N e# Push a linefeed.
}
```
[Answer]
# HTML, 594 bytes
```
1972-06-30 23:59:60<br>1972-12-31 23:59:60<br>1973-12-31 23:59:60<br>1974-12-31 23:59:60<br>1975-12-31 23:59:60<br>1976-12-31 23:59:60<br>1977-12-31 23:59:60<br>1978-12-31 23:59:60<br>1979-12-31 23:59:60<br>1981-06-30 23:59:60<br>1982-06-30 23:59:60<br>1983-06-30 23:59:60<br>1985-06-30 23:59:60<br>1987-12-31 23:59:60<br>1989-12-31 23:59:60<br>1990-12-31 23:59:60<br>1992-06-30 23:59:60<br>1993-06-30 23:59:60<br>1994-06-30 23:59:60<br>1995-12-31 23:59:60<br>1997-06-30 23:59:60<br>1998-12-31 23:59:60<br>2005-12-31 23:59:60<br>2008-12-31 23:59:60<br>2012-06-30 23:59:60<br>2015-06-30 23:59:60
```
¯\\_(ツ)\_/¯
[Answer]
# C, ~~160~~ ~~146~~ ~~141~~ 140 bytes
First time posting, not sure what "standard loopholes" are. I have printf warnings of course.
**160 bytes:**
The original idea is to encode leap seconds using two bits per year: one for June and one for December. The encoding is consumed one bit at a time by the inner while loop. Without a 128-bit integer, the outer while loop is necessary. The rest is all bookkeeping and math. :-)
```
int main(){long long X=0x2495288454AAAB,Y=1972,Z=1;while(Y<2000){while(X){if(X&1)printf("%d-%02d-%d 23:59:60\n",Y,6*(2-Z),31-Z);Y+=Z^=1;X>>=1;}X=0x104082000;}}
```
**141 bytes:**
Applying the suggested tips gets it down to 146 bytes. Then I found a way to simplify the outer while condition (from Y<2000 to just Z), bringing it down to 141 bytes. So close to a tweet!
```
main(Z){long long X=0x2495288454AAAB,Y=1972;while(Z){while(X)X&1?printf("%d-%02d-%d 23:59:60\n",Y,12-6*Z,31-Z):1,Y+=Z^=1,X/=2;X=4362608640;}}
```
**140 bytes:**
I noticed the dash in the date could be eliminated by making the day negative. Can't do it with the month as well due to leading zero in June. But at least it fits in a tweet now!
```
main(Z){long long X=0x2495288454AAAB,Y=1972;while(Z){while(X)X&1?printf("%d-%02d%d 23:59:60\n",Y,12-6*Z,Z-31):1,Y+=Z^=1,X/=2;X=4362608640;}}
```
**Pretty version:**
```
main(Z) {
long long X = 0x2495288454AAAB, Y = 1972;
while (Z) {
while (X)
X&1 ? printf("%d-%02d%d 23:59:60\n", Y, 12-6*Z, Z-31) : 1,
Y += Z ^= 1,
X /= 2;
X = 4362608640;
}
}
```
**Bonus version:**
I eliminated the outer loop by bit-shifting one 64-bit integer into another, but it's 150 bytes, due to the rather long "unsigned long long"; if I could use something like "uint64" it would be 138 bytes.
```
main(Z) {
unsigned long long Y = 1972, X = 0x2495288454AAAB, W = 8520720;
while (X)
X&1 ? printf("%d-%02d-%d 23:59:60\n", Y, 12-6*Z, 31-Z) : 1,
Y += Z^= 1,
X = X/2 | (W>>=1)<<63;
}
```
[Answer]
## Python 3, 91
Uses the encoding and string formatting [by Sp3000](https://codegolf.stackexchange.com/a/52462/20260), but stores the values in a [Python 3 bytes object](https://codegolf.stackexchange.com/a/51622/20260) rather than a magic number.
```
for n in b'()+-/1357:<>BGKMPRTWZ]kqx~':print('%d-%02d-3%d 23:59:60'%(1952+n/2,n%2*6+6,n%2))
```
The encoding only needs 86 of the 256 possible values of a bytes, so a range of printable characters is used to make it look nicer.
[Answer]
# Brainfuck, 806
```
++++++++[>++++++>+++++++>+++++++>++++++>++++++>++++++>+++++++>++++++>++++++>++++++>++++>++++++>++++++>+++++++>+++++++>+++++++>+++++++>+++++++>++++++>+<<<<<<<<<<<<<<<<<<<<-]>+>+>->++>--->>-->--->+++>>>++>+++>++>--->+>++>-->>++[<]>[.>]<[<]>>>>>>+>---->>>+[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>+>-------->>->++++>>>-[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>++[<]>[.>]<[<]>>>>++>>+>---->>>+[<]>[.>]<[<]>>>>++[<]>[.>]<[<]>>>+>---------[<]>[.>]<[<]>>>>++>>->++++>>>-[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>+[<]>[.>]<[<]>>>>+>>+>---->>>+[<]>[.>]<[<]>>>>++>>->++++>>>-[<]>[.>]<[<]>>>>+>>+>---->>>+[<]>[.>]<[<]>+>--------->--------->---[<]>[.>]<[<]>>>>+++[<]>[.>]<[<]>>>+>------>>->++++>>>-[<]>[.>]<[<]>>>>+++[<]>[.>]
```
You can [run it on this online interpreter.](http://copy.sh/brainfuck/)
[Answer]
# Python 2, ~~111~~ 104 bytes
```
n=0x6697f252225354422533333330;y=1972
while n:print'%d-%02d-3%d 23:59:60'%(y,n%2*6+6,n%2);y+=n/2%8;n/=16
```
Base encoding and more base encoding.
[Answer]
# GNU sed+date: 112
Common Linux distributions have the leap seconds built-in, too. Using GNU sed and date:
```
sed -n 's/^\([0-9]\+\).*/1899-12-31 \1sec/p' /usr/share/zoneinfo/leap-seconds.list|date -f- +"%Y-%m-%d 23:59:60"
```
# GNU sed+date: 90
Safing a few characters by cutting the path:
```
sed -n 's/^\([0-9]\+\).*/1899-12-31 \1sec/p' /u*/s*/z*/leap*|date -f- +'%Y-%m-%d 23:59:60'
```
# GNU sed+date tuned by Toby Speight: 84
Deeply golfed version proposed in the comments:
```
sed -nr 's/^([0-9]+).*/date -d "1899-12-31 \1sec" "+%F 23:59:60"/ep' /u*/s*/z*/leap*
```
[Answer]
# JavaScript (*ES6*) 125
The newline inside `` is significant and counted.
To test, run the snippet below (being EcmaScript 6, Firefox only)
```
alert([..."09:;=DEFIX[01234567?ABGJQS"].map((c,i)=>c.charCodeAt()+1924+(i>10?'-12-31':'-06-30')+' 23:59:60').sort().join`
`)
```
[Answer]
# PHP, 198 bytes
```
foreach([.5,1,2,3,4,5,6,7,8,9.5,10.5,11.5,13.5,16,18,19,20.5,21.5,22.5,24,25.5,27,34,37,40.5,43.5] as$d){$h=(int)$d-ceil($d);echo date("Y-m-d 23:59:60",mktime(0,0,0,-6*$h,31+$h,(int)$d+1972))."\n";}
```
Unfortunately, I don't know if I can insert `\n` in the date function. If so, this is 3 bytes less because of `.""`.
[Answer]
# 8086 machine code + DOS, 92 bytes
Hexdump of the code:
```
BE 3A 01 B1 57 D1 E0 75 03 AD EB F9 72 09 50 BA
47 01 B4 09 CD 21 58 BB 50 01 81 77 FC 01 04 80
37 01 80 3F 31 74 10 83 EB 05 4B FE 07 80 3F 3A
75 05 C6 07 30 EB F3 E2 CC C3 AA 2A 77 B5 6A DD
DF B6 BE FF 7D BF 31 39 37 32 2D 30 36 2D 33 30
20 32 33 3A 35 39 3A 36 30 0D 0A 24
```
To run, write the 92 bytes into a `com`-file and run under 32-bit Windows or DOSBox.
The code uses a bitmap with 87 bits, one per half a year. The bits are arranged into groups of 16, starting from MSB.
Decoding the bitmap:
```
; when the program starts, ax=0 (tested on DOSBox)
myloop:
shl ax, 1 ; shift the MSB left into the carry flag
jnz mywork ; if some bits are left in the register, work normally
lodsw ; if all bits were shifted out, load the next 16 bits
jmp myloop ; and check the MSB again
```
Because of the code's structure, some bits are lost during decoding, so I had to repeat them. This repeating doesn't bloat the bitmap because I had to pad 87 bits to 96 bits anyway.
After printing (or not printing) the leap second, the code increases the date by half a year, using manipulations on the ASCII codes of the output message.
Source code (can be assembled with [`tasm`](http://www.phatcode.net/downloads.php?id=280)):
```
mov si, offset mydata
mov cl, 57h ; number of iterations
myloop:
shl ax, 1 ; shift the MSB left into the carry flag
jnz mywork ; if some bits are left in the register, work normally
lodsw ; if all bits were shifted out, load the next 16 bits
jmp myloop ; and check the MSB again
mywork:
jc myinc_date ; shifted bit 1? - skip printing the message
push ax
mov dx, offset mymsg
mov ah, 9
int 21h ; print the message
pop ax
myinc_date:
mov bx, offset mymsg + 9 ; pointer to the middle of the message
xor word ptr [bx - 4], 401h ; change month 06<->12
xor byte ptr [bx], 1 ; change day 30<->31
cmp byte ptr [bx], '1'
je myloop_end ; if 31 December, no need to increase the year
sub bx, 5 ; pointer beyond the last digit of the year
myinc_year:
dec bx
inc byte ptr [bx] ; increase the digit
cmp byte ptr [bx], '0' + 10
jne myloop_end ; if the digit was less than 9, done
mov byte ptr [bx], '0' ; set the digit to 0
jmp myinc_year ; continue increasing other digits
myloop_end:
loop myloop
ret ; terminate the program
; In the following bitmap, the spaces before some LSBs
; show that the least significant 1-bit and all
; following 0-bits are lost during decoding.
mydata:
dw 02aaah ; 00101010101010 10
dw 0b577h ; 101101010111011 1
dw 0dd6ah ; 11011101011010 10
dw 0b6dfh ; 101101101101111 1
dw 0ffbeh ; 11111111101111 10
dw 0bf7dh ; 101111110111110 1
mymsg:
db '1972-06-30 23:59:60',13,10,'$'
```
[Answer]
# Pyth - 88 84 bytes
Converts to char to compress the data and saves the `06-30` versus `12-31` data as binary number.
```
jbm++-2047ed?"-06-30"hd"-12-31"" 23:59:60"C,j33678243 2CM"KKJIHGFEDBA@><:9765421*'#
```
(there is a space there at the end)
[Try it here online](http://pyth.herokuapp.com/?code=jbm%2B%2B-2047ed%3F%22-06-30%22hd%22-12-31%22%22+23%3A59%3A60%22C%2Cj33678243+2CM%22KKJIHGFEDBA%40%3E%3C%3A9765421*%27%23+&debug=1).
[Answer]
# Python 2, ~~123~~ ~~121~~ ~~116~~ ~~114~~ 111
I've managed to get it pretty short, but I'm not sure how much shorter it can get. I tried using `exec`, but the formatting gets to be too costly.
I used a base 16 encoding of the table from the linked Wikipedia page.
Edit: Using hex encoding is shorter than base 36 (see the less golfed version.)
[**Try it here**](http://ideone.com/AGUrW8)
```
n=0x410208002495288454aaab
for i in range(88):
if n%2:print"%d-%02d-3%d 23:59:60"%(1972+i/2,i%2*6+6,i%2)
n/=2
```
Less golfed:
```
s=bin(int('WELD24ZDGIMBWWLFM',36))[2:]
for i in range(44):
t,s=int(s[0]),s[1:]
if t:print"%d-06-30 23:59:60"%(i+1972)
t,s=int(s[0]),s[1:]
if t:print"%d-12-31 23:59:60"%(i+1972)
```
[Answer]
# C, ~~155~~ ~~149~~ 147 bytes
Here's another approach in C, using strings and run length encoding. Not quite as terse as my other C solution, but maybe it can be improved?
**155 bytes:**
Using a string to hold the month/day.
```
main(Y){Y=1972;char*M="06-3012-31",*B="#@DGCDF7D3daTdS#!",b,c;while(b=*B++-33){c=b>>1&7;while(c--)printf("%d-%.5s 23:59:60\n",Y++,M+b%2*5);Y+=(b>>4&7)-1;}}
```
**149 bytes:**
Eliminating the month/day string.
```
main(Y){Y=1972;char*B="#@DGCDF7D3daTdS#!",b,c;while(b=*B++-33){c=b>>1&7;while(c--)printf("%d-%02d-%d 23:59:60\n",Y++,6+b%2*6,30+b%2);Y+=(b>>4&7)-1;}}
```
**147 bytes:**
Eliminating the year initialization.
```
main(Y){char*B="#@DGCDF7D3daTdS#!",b,c;while(b=*B++-33){c=b>>1&7;while(c--)printf("%d-%02d-%d 23:59:60\n",1971+Y++,6+b%2*6,30+b%2);Y+=(b>>4&7)-1;}}
```
**144 bytes:**
If I reencoded the buffer to make the skip count apply before (not after) the run, then I could reorder the statements in the outer while loop, use the comma operator, and eliminate the braces, saving 2 bytes.
I can save another byte by making the day negative (as in my other solution).
**Pretty:**
```
main(Y) {
char *B = "#@DGCDF7D3daTdS#!", // buffer of bytes encoding runs
b, // current byte
c; // current count
while (b = *B++-33) { // get byte
c = b>>1&7; // get count
while (c--) printf("%d-%02d-%d 23:59:60\n", 1971+Y++, 6+b%2*6, 30+b%2); // run
Y += (b>>4&7)-1; // skip years
}
}
```
**Explanation:**
Runs are encoded in bytes. Each byte has one bit to say whether it's June or December, 3 bits for a length count, 3 bits for a skip count, and 1 unused high bit.
The skip count is the number of years to skip after a run; it's offset by -1 to allow for two leap seconds in 1972. The length is how many years in a run; it probably could be offset by +1 but it isn't currently.
So a byte means: "Do LENGTH years of JUNE (or DECEMBER) years of leap seconds, then skip SKIP-1 years" before moving to the next byte.
The bytes are offset by 33 to make them readable and avoid fancy encoding.
This means although we have enough skip bits to cover 1998-2005, we're out of ASCII range, so we have an extra zero length run. Also, 1979 appears on its own because the length 1972-1979 is one too long.
There's enough bits in the bytes, so those issues might be fixable ultimately.
[Answer]
# q/kdb+, ~~95~~ ~~94~~ 93 bytes
```
asc 1_" "0:([]raze("DEFGHIJKSUV[^eh";"DMNOQXYZ]lo"){("d"$"m"$-12*95-6h$x)-y}'1 185;`23:59:60)
```
**Explanation**
For each year **+ 1**, encode for years since 1905 as an ASCII character, e.g.:
```
1972 -> 1973 -> 68 -> D
```
`6h$x` turns `"D"` back to `68`. Since `q`'s date epoch is `2000.01.01`, we subtract `95` and perform the integers-to-date conversion `"d"$"m"$-12*95-6h$x`.
The reason we **+ 1** above is to subtract the number of days from the start of **next year** to get the *actual year's* 31st December or 30th June, namely 1 or 185 days. Therefore, `"DEFGHIJKSUV[^eh"` represents the years with a leap second in December, and `"DMNOQXYZ]lo"` for those in June. The pairing-subtraction is done via `(a;b){x-y}'(c;d)`, where `a` and `b` are years that will be subtracted by `c` and `d` number of days respectively.
`" "0:([]...)` prepares the results to give us the correct formatting, with a small caveat that a column header will be generated. `1_` drops that header and finally apply `asc` to get the ordering correct.
**edit**: 're-base' to subtracting 95 years instead of 100 (saving 1 character).
**edit 2**: re-ordering the operands' positioning inside the integers-to-date conversion function.
[Answer]
# PHP, 164 bytes
```
foreach([.5,1,2,3,4,5,6,7,8,9.5,10.5,11.5,13.5,16,18,19,20.5,21.5,22.5,24,25.5,27,34,37,40.5,43.5]as$d){echo(ceil($d)+1971).($d%2?'-12-31':'-06-30')." 23:59:60\n";}
```
This is just a few modification on @Voitcus's idea
[Answer]
# Python, 204 201
```
e,g,h=0,1972,0
for i in range(1,27):e,g,h={2:1,9:2,10:1,12:2,15:1,16:2,17:1,20:2,21:1,22:7,23:3,24:4,25:3}.get(i,e),g+e,(h,1-h)[i in[2,10,14,17,20,21,22,25]];print`g`+("-06-30","-12-31")[h]+" 23:59:60"
```
You can play with it on [repl.it](https://repl.it/utN).
Edit: Thoroughly beaten! The compression answers are amazingly short.
[Answer]
# Python, 221 217
```
def d(x):
q=x%10
if x%2==0:
p,r=q/2,"06-30"
else:
p,r=(q-1)/2,"12-31"
return"%d%d-%s 23:59:60"%(p+197,x/10,r)
for x in [20,21,31,41,51,61,71,81,91,12,22,32,52,73,93,5,24,34,44,55,74,85,57,87,28,58]:print(d(x))
```
# Some Insights
Basically, `d(x)` decompresses a vector of 3 integers from a single 2-digit integer. `d(x)` is constructed as the inverse function (over the 26 leap seconds datetimes) of `c(v)`, which in turn is a compression function that turns a 3-uple such as (1998,12,31) into a number like 85. To derive the list [20,21...28,58] I designed another algorithm to verify that the compression function is bijective over the domain. That is, I made sure that the following program doesn't produce duplicates, and I used its output as the list of the program above.
```
dates = [(1972,06,30),
(1972,12,31),
(1973,12,31),
(1974,12,31),
(1975,12,31),
(1976,12,31),
(1977,12,31),
(1978,12,31),
(1979,12,31),
(1981,06,30),
(1982,06,30),
(1983,06,30),
(1985,06,30),
(1987,12,31),
(1989,12,31),
(1990,12,31),
(1992,06,30),
(1993,06,30),
(1994,06,30),
(1995,12,31),
(1997,06,30),
(1998,12,31),
(2005,12,31),
(2008,12,31),
(2012,06,30),
(2015,06,30)]
def c(v):
x = (v[0] % 10) * 10
x += v[2] % 30
x += 2 * (int(v[0] / 10) - 197)
return x
for v in dates:
print(c(v))
```
The compression function `c(v)` was designed to be bijective by using a very simple scheme. Let's take as an example (1998,12,31).
* The expression (v[0] % 10) \* 10 selects the units of the year (e.g. 1 9 9 **8** --> 8) and makes it the tenths digit of the output (now x=80).
* There are only two month-day combination in which the leap second thing happens, so I decided to use the day component to distinguish between the 06,30 case and the 12,31 case. The expression v[2] % 30 is 0 if the day is 30, and is 1 if the day is 31. In our example, we add 1 to x (hence, now x=81).
* Finally, I observed that this puzzle involves only 5 decades; hence if I map the first decade (the seventies) to 0 and the last decade (the 2010s) to 4 I can do cool stuff. More specifically, if instead of mapping to 0,1,2,3,4 I map to 0,2,4,6,8 I can add this value to the units of x, which due to the previous rule is either 0 or 1. So in the end we have that also this last step doesn't screw the bijection, and we get that the units of a 06,30 case are one of 0,2,4,6,8 and that the units of a 12,31 case are one of 1,3,5,7,9. Hence the bijection is obvious. In our example, 1998 is in the third decade (70s->0, 80s->1, 90s->2) so we add 2\*2=4. So we get x=85.
I wrote the program to verify that this is true, and then I defined `d(x)` as the inverse of `c(v)`. In our example, c((1998,12,31)) is 85 and d(85) correctly prints `1998-12-31 23:59:60`.
[Answer]
**gzip, 114 bytes**
Hexdump:
1f8b080853f9975502006c006dd04b0a80300c84e1bde01dbc40218fa6697aff8309e2a6fa6f3f86cc10adb426a3b95ce62b6a0d398f07d59aeb8e4ed80983701026e1242cc0a9307e1aa11306615211b59710527b3961270cba9994fc7fc944829092faeedc313e7803993cfafb20020000
Create a file with the bytes described above.
Extract using gunzip or another decompression program to get a new file named "l". This file contains the desired output.
] |
[Question]
[
Output the numbers 1-16 (or any other set of 16 distinct items). Then, repeatedly, output a random value chosen uniformly from the last 16 items outputted.
After the same item is printed 16 times in a row, halt.
If a number appears multiple times in the last 16 values, it should have proportionally more chance to be chosen as the next number. If a number did *not* appear in the last 16 elements, it can't be chosen ever again.
0 bonus points to whoever can provide the probability distribution of each number becoming the last one standing.
[Answer]
# [Python](https://www.python.org), ~~102 88 86 85~~ 84 bytes
```
from random import*;*t,=range(16)
while~-len({*(x:=t[-16:])}):t+=choice(x),
print(t)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3Q9KK8nMVihLzUoBUZm5BflGJlrVWiY4tUCg9VcPQTJOrPCMzJ7VONyc1T6NaS6PCyrYkWtfQzCpWs1bTqkTbNjkjPzM5VaNCU4eroCgzr0SjRBNiNtQKmFUA)
* -14 thanks to mousetail
* -1 thanks to loopy walt
Prints a list of numbers from 0 to 15.
#### Commented
```
from random import*; # Import the random module for later
*t,=range(16) # Set t equal to [0, 1, ..., 15]
# ([* ... ] unpacks it into a list)
while~-len( # Loop while the number of unique items
{*(x:=t[-16:])}): # in the last 16 elements of t is not 1
# (setting x to the last 16 elements of t)
t+=choice(x), # Append a random element of x to t
print(t) # At the end, output t
```
[Answer]
# [Ruby](https://www.ruby-lang.org/), ~~55 51~~ 48 bytes
```
puts x=[*1..16];_,*x=x<<p(x.sample)while(x|x)[1]
```
[Try it online!](https://tio.run/##KypNqvz/v6C0pFihwjZay1BPz9As1jpeR6vCtsLGpkCjQq84MbcgJ1WzPCMzJ1WjoqZCM9ow9v9/AA "Ruby – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~66~~ 61 bytes
```
x=Map(show,L<-1:16)
while(sd(L))L=c(L[-1],print(sample(L,1)))
```
[Try it online!](https://tio.run/##K/r/v8LWN7FAozgjv1zHx0bX0MrQTJOrPCMzJ1WjOEXDR1PTxzZZwyda1zBWp6AoM69EozgxtwAo6aNjqKmp@f8/AA "R – Try It Online")
### Explanation outline:
1. `Map` the `show` function over `1:16` (and save the vector to variable `L`).
2. We assign the result of the `Map` to `x` to avoid outputting its value (ugly list of nulls).
3. Then we `sample` one element from `L` and append to `L[-1]` (`L` without the first element).
4. Loop until `sd(L)==0` (this means that the last 16 numbers are all the same).
[Answer]
# [R](https://www.r-project.org/), 52 bytes
```
a=b=16:1;while(sd(a[b]))a=c(sample(a[b],1),a);rev(a)
```
[Try it online!](https://tio.run/##K/r/P9E2ydbQzMrQujwjMydVozhFIzE6KVZTM9E2WaM4MbcAKAYS0DHU1EnUtC5KLdNI1Pz/HwA "R – Try It Online")
Full program that yields an [R](https://www.r-project.org/) vector containing the sequence of values.
[R](https://www.r-project.org/) displays this by default with index numbers (in square brackets) at the start of each line. If this is annoying, add 5 bytes more to wrap the output into a call to `cat()` [like this](https://tio.run/##K/r/P9E2ydbQzMrQujwjMydVozhFIzE6KVZTM9E2WaM4MbcAKAYS0DHU1EnUtE5OLNEoSi3TSNTU/P8fAA).
[Answer]
# JavaScript (ES7), 74 bytes
Same algorithm as the other version, but using the weirder set `"5368709124,false"`.
```
f=(s=2**29+[4,k=!1])=>/(.)\1{15}/.test(s)?s:f(s+s[Math.random()*16+k++|0])
```
[Try it online!](https://tio.run/##BcFLDoIwEADQs7ib6WCxBE00KZzAEyCLBlo/xY5hGjfq2et7D/d2Mq33V94mnn0pwYLYRqnmSENbRbsxI9quBo0X8zH7X62zlwyCvZwCCMlwdvmmV5dmfgIqc6BI9N2NWCZOwovXC18hAGL5Aw "JavaScript (Node.js) – Try It Online")
### How?
\$2^{29}=536870912\$ contains all digits from \$0\$ to \$9\$ exactly once, except \$4\$. Adding `[4,!1]` forces a coercion to a string and appends `"4"`, followed by a comma, followed by `"false"`.
---
# JavaScript (ES6), 83 bytes
Uses the hexadecimal characters `0-9` and `A-F`.
```
f=(s=(k=0)+'123456789ABCDEF')=>/(.)\1{15}/.test(s)?s:f(s+s[Math.random()*16+k++|0])
```
[Try it online!](https://tio.run/##BcFJDsIwDADA59TGIm2AlkUKiPXGC4BD1CYsLTGqIy7A28PMw76t1P39FYeBG5eSNyAGWlMgZXo0npTVdDZfb7a7/SFDs8xB4Vl/dPnLVXQSQXAlCw9CcjraeFO9DQ0/AQe6opboW1ww1RyEO6c6voIHxPQH "JavaScript (Node.js) – Try It Online")
### Commented
```
f = ( // f is a recursive function taking:
s = (k = 0) + // s = output string
'123456789ABCDEF' // k = counter
) => //
/(.)\1{15}/.test(s) // if s contains the same character repeated
? // 16 times in a row:
s // stop and return s
: // else:
f( // do a recursive call:
s + // append to s
s[ // the character from s
Math.random() // whose index is randomly chosen in
* 16 + k++ | 0 // [k .. k+15] (increment k afterwards)
] // i.e. one of the last 16 characters
) // end of recursive call
```
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), ~~15~~ ~~13~~ ~~12~~ 9 bytes
```
k6≬℅+Ḣ↔ƒ⋎
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJrNuKJrOKEhSvhuKLihpTGkuKLjiIsIiIsIiJd)
Outputs characters from the string `"0123456789abcdef"`
*-3 thanks to emanresu*
## Explained (old)
```
k6≬℅+Ḣ↔ḣvt∑+
k6 # The string "0123456789abcdef"
≬ ↔ # apply the following and collect results while invariant:
℅+ # append a random item of the string to the string
Ḣ # remove the first character
ḣvt # separate the first item from that list and get the tail of each remaining item
∑+ # join that into a single string and append to the previously separated head
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 18 bytes
```
15⟦ẉ₂ᵐ{=|ṛRẉ&b,R↰}
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/39D00fxlD3d1Pmpqerh1QrVtzcOds4OAfLUknaBHbRtq////DwA "Brachylog – Try It Online")
```
15⟦ The list [0, …, 15]
ẉ₂ᵐ Map writeln
{ } If
= All elements of the list are equal, then stop
| Else
ṛR R is a random element of the list
Rẉ writeln R
&b Remove the first element of the list
,R Append R to the list
↰ Recursive call on this list
```
[Answer]
# [C (gcc)](https://gcc.gnu.org/), 105 bytes
```
j,k;a[16];f(i){for(k=i=16;a[--i]=i;);for(;k;j-(a[i++%16]=a[rand()%16])?k=16:--k)printf("%d ",j=a[i%16]);}
```
[Try it online!](https://tio.run/##TY29CoMwFIX3PIVYhBs0BReHpmlfQLp1EofUaHuNf2jsIj67TaTQnunej@9wCvYsim2rI81lFic5rwDpUvUjaIEiTixlDHOBnHJHueY1A5lhGAZWFzIbZaeAuodetW2cGNN0GLEzFfiB8vyothbuAl@3A3ZFM6vSO09GNfg4vi7kxwy2pSPE1kkrsYN3j4qShXg2077lHLjd05RSvuMKvscwmwl8/x@v2wc "C (gcc) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~20~~ 19 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
Far too long but seeing as Japt has no infinite loops and can't loop until invariant, it'll have to do for now.
```
Go
@òÎÌʨG}a@pUsX ö
```
[Test it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=R28KQPLOzMqoR31hQHBVc1gg9g)
```
Go\n@òÎÌʨG}a@pUsX ö
G :16
o :Range [0,G)
\n :Assign to variable U
@ :Left function
ò : Partition U between elements where
Î : Sign of difference is truthy (non-zero)
Ì : Last element
Ê : Length
¨G : >=16
} :End function
a :Run right function until left function returns true and return final result
@ :Right function, taking 0-based iteration index X as argument
p : Push to U
UsX : Slice U from index X
ö : Random element
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E) `--no-lazy`, ~~15~~ 14 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
16L€=[DΩ=ª¦DË#
```
[Try it online!](https://tio.run/##yy9OTMpM/f/f0MznUdMa22iXcyttD606tMzlcLfy////dXXz8nVzEqsqAQ "05AB1E – Try It Online")
* -1 thanks to Kevin Cruijssen
### Alternative 15 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage) solution (thanks to Kevin Cruijssen)
```
16L[D16.£©Ωª®Ë#
```
[Try it Online!](https://tio.run/##AR8A4P9vc2FiaWX//zE2TFtEMTYuwqPCqc6pwqrCrsOLI///)
#### Explanation
```
16L # Push [1..16]
€= # Print each item
[ # Start an infinite loop:
DΩ # Duplicate and push a random element of the list
=ª # Print and append to the list
¦ # Remove the first item
DË# # If all items are equal, break
```
[Answer]
# [Python](https://www.python.org), 77 bytes
```
from random import*
t=range(16)
while t:T,*s=*t,choice(t);t=s[t==s:];print(T)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m72soLIkIz9vwYKlpSVpuhY3fdOK8nMVihLzUoBUZm5BflGJFleJLVAgPVXD0EyTqzwjMydVocQqREer2FarRCc5Iz8zOVWjRNO6xLY4usTWttgq1rqgKDOvRCNEE2Io1GyYHQA)
Prints one number per line.
### How?
The two mildly clever bits are
1. the rolling tail end of the sequence is all equal if and only if it's equal to its next iteration
2. for the winding down it doesn't matter whether we truncate from the right (more logical) or the left (shorter) since all elements are equal
[Answer]
# [Nibbles](http://golfscript.com/nibbles/index.html), 10 bytes (20 nibbles)\*
```
/`.,16>>:$=`#$16$:/
```
\*[Nibbles](http://golfscript.com/nibbles/index.html) is a pure functional language and has no random number capability.
So, this program uses the hash-modulo-16 of the last 16 values after each pick to select the next index. This is pseudo-random, but obviously will be the same on each run of the program.
To more-closely mimic PRNGs from other programming languages, we can select a 'salt' value for the hash, to act as a 'seed': this needs to be appended to the program, and, additionally, the otherwise-implicit variables of the program then need to be explicitly specified, costing +3 nibbles (+1.5 bytes, so [11.5 bytes](https://i.stack.imgur.com/9UZue.png) not including the 'seed' itself).
```
/`.,16>>:$=`#$16$:/
`. # iterate while unique
,16 # starting with 1..16:
:$ # join the last list to
= $ # its element at index
`#$ # itself hashed
16 # modulo-16
/ # now, fold over this list from the right:
: # joining
/ # the (implicit) first element of the (implicit) left argument
# to the (implicit) right argument
```
[](https://i.stack.imgur.com/G62N0.png)
[Answer]
# [J](http://jsoftware.com/), 31 bytes
```
(,1}._1{"1(}.,?@#{])^:a:)@i.@16
```
[Try it online!](https://tio.run/##TcvBCoJAGATgu08xKrEr2a9LZbgUSUWn6NDdxEJrOyikdRF9dVs9dRiYgW9efWhKEQemDBkzdJ@vYh8JdAyLWI6NBIOrt9SZEfaX07HnrmgpEY0leEvuNrKb2LnKVDqRokgEvWOcdwS/0eQfcLG2o450Swa4GNVBVfVb3T61Kguo4ptVtXqkw5LI7s8SnNsedZjAduBJ6D9yawpFIlsao8jBWP8D "J – Try It Online")
>
> 0 bonus points to whoever can provide the probability distribution of each number becoming the last one standing.
>
>
>
```
┌──┬──────┐
│0 │1/136 │
├──┼──────┤
│1 │2/136 │
├──┼──────┤
│2 │3/136 │
├──┼──────┤
│3 │4/136 │
├──┼──────┤
│4 │5/136 │
├──┼──────┤
│5 │6/136 │
├──┼──────┤
│6 │7/136 │
├──┼──────┤
│7 │8/136 │
├──┼──────┤
│8 │9/136 │
├──┼──────┤
│9 │10/136│
├──┼──────┤
│10│11/136│
├──┼──────┤
│11│12/136│
├──┼──────┤
│12│13/136│
├──┼──────┤
│13│14/136│
├──┼──────┤
│14│15/136│
├──┼──────┤
│15│16/136│
└──┴──────┘
```
Proof: For example, the system of equations you'd solve for the n=3 case is:
$$
\begin{align}
x\_1 &= \frac{x\_3}{3} \\
x\_2 &= x\_1 + \frac{x\_3}{3} \\
x\_3 &= x\_2 + \frac{x\_3}{3} \\
x\_1 + x\_2 + x\_3 &= 1
\end{align}
$$
where \$x\_1\$ is the chance that number in positon 1 wins, etc -- where 1, if it is not picked the first round, vanishes forever.
The first equation represents that 1/3 of the time \$x\_1\$ will be picked and move into position 3, and the rest of the time of vanish. Thus its "value" is 1/3 of \$x\_3\$'s.
Similarly, \$x\_2\$ will always move into slot 1, where it has \$x\_1\$ chance of winning, and 1/3 of the time will also move into slot 3, giving it \$x\_3\$ chance of winning. And so on...
[Answer]
# Excel (ms365), 109 bytes
I do hope that this could get OP's approval. Since volatility would stand in the way of using a list of elements, the only way I could think about a repetitive function that would auto-stop when last 16 elements are exactly the same is to use a custom function made with the name-manager. In this case my function is called 'Z':
```
=LAMBDA(x,LET(y,RIGHT(x,16),IF(y=REPT(RIGHT(y),16),x,Z(x&MID(y,RANDBETWEEN(1,16),1)))))
```
[](https://i.stack.imgur.com/zpfLX.png)
Formula in `A1`:
```
=Z("ABCDEFGHIJKLMNOP")
```
This would make for a combined total of 87 + 22 = 109 bytes.
[Answer]
# TI-Basic, 54 bytes
```
For(I,1,16
Disp I
End
cumSum(1 or rand(16
While max(Ans≠max(Ans
augment(ΔList(cumSum(Ans)),{Ans(randInt(1,16
Disp Ans(16
End
```
`max(abs(ΔList(Ans` can be used instead of `max(Ans≠max(Ans` alternatively.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~16~~ 15 bytes
```
pK<TGWt{=t+KpOK
```
[Try it online!](https://tio.run/##K6gsyfj/v8DbJsQ9vKTatkTbu8Df@/9/AA)
Thanks @isaacg for -1 byte
### Explanation
```
K<TG # K = "abcdefghijklmnop" (all but the last ten elements of the alphabet)
p # print(K)
Wt{ # while deduplicated K has more than one element
pOK # print a random element of K
+K # append this to K
=t # remove the first element of K
```
[Answer]
# [Retina](https://github.com/m-ender/retina/wiki/The-Language), 43 bytes
```
16*.
Y`.`L
/(.)\1{15}$/^+-16,@v`(.).*
$&$1
```
[Try it online!](https://tio.run/##K0otycxLNPz/n8vQTEuPKzJBL8GHS19DTzPGsNrQtFZFP05b19BMx6EsASimp8WloqYCVAwA "Retina – Try It Online") Uses `ABCDEFGHIJKLMNOP`. Explanation:
```
16*.
```
Insert 16 `.`s.
```
Y`.`L
```
Transliterate them to uppercase letters using a different letter each time.
```
/(.)\1{15}$/^+
```
Repeat until the last 16 letters are identical.
```
-16,@v`
```
Randomly choose between one of the last 16 overlapping matches.
```
(.).*
```
Match any character and the rest of the string.
```
$&$1
```
Append the initial character to the match, i.e. append it to the string.
[Answer]
# [Go](https://go.dev), 177 bytes
```
import."math/rand"
func f(){N,M,l:=[]int{},1,16;for i:=1;i<17;i++{N=append(N,i);println(i)}
for M<16{k:=Intn(16)
x:=N[k]
println(x)
N=append(N[1:],x)
if x!=l{l=x;M=1}else{M++}}}
```
[Attempt This Online!](https://ato.pxeger.com/run?1=VU-xTsMwFNz9FSaTrThFXgJy6gEJBoZkoIUlymC1TvuUxImCKyJZ_hKWCIkPYOVP-BtSSEGd3tPdvXt3r2-7dvzs1KZSO40bBQZB07W9XQQWGh28H2wZXX99nMBG2f1lr8w2QOXBbHBJqMtYymoh8wKMdZ5xxuOkbHsMQvIElvwqgTB0mVRdp82WZAxo0vWTuDYEqEdHbbrksauEvDfWEB5TNAiZ5VWBTsKBon-HnIuCTQiUeLiQtavlkKSSe10_a5eGofd-Dv70k_LYi1Ds0Err6bx9IXTxaGAglP49CKIowqv1zcMaT1tA0VTtnLzLbmdqdh_H3_kN)
[Answer]
## Zsh, 73 bytes
```
set {a..p};<<<${(F)@};while 17=$@[RANDOM%16+1];shift;<<<$16;((${#@:#$1}))
```
[Try it online!](https://tio.run/##qyrO@P@/OLVEoTpRT6@g1trGxkalWsNN06HWujwjMydVwdDcVsUhOsjRz8XfV9XQTNsw1ro4IzOtBKzS0MxaQ0OlWtnBSlnFsFZT8/9/AA "Zsh – Try It Online")
I use single letters instead of up-to-two-digit numbers as the “16 distinct items”, which saves a byte. (It also gives extra flexibility, which I took advantage of in [an earlier version of this answer](https://codegolf.stackexchange.com/revisions/257440/1) with a more complex termination condition.)
Expanded and commented:
```
set {a..p} # set positional arguments 1=a, 2=b, ...
<<<${(F)@} # join arguments with newline, call implicit cat
while
17=$@[RANDOM%16+1]; # append a random element
shift; # remove the first element
<<<$16; # print the last element
((${#@:#$1})) # termination condition (see below)
# no loop body = empty loop body
```
For those unfamiliar with zsh: the positional arguments can be accessed through `$1`, `$2`, … like in other shells, and also through the variable `@` which mostly behaves like an array. Zsh array indexes start at 1. `RANDOM` is a special variable that returns a random number each time it's accessed; fortunately the range 0..32767 is dividible by 16 so all values are equally likely modulo 16.
Now for the termination condition. It's the arithmetic expression `${#@:#$1}`: the command is true if the integer expression has a nonzero value. The expression uses several parameter expansion features. From the outside in, first, we have `${#*spec*}` to count the number of elements in the parameter expansion of `*spec*`. Inside, we have `${*name*:#*pattern*}` which, when `*name*` is an array, removes the elements that match `*pattern*`. The `*name*` is `@`, i.e. the positional parameters. The `*pattern*` is `$1`. Thus we count the number of positional parameters that are not equal to the first one: this is 0 if and only if all the positional parameters are equal.
[Answer]
# [Julia](https://julialang.org), ~~73~~ ~~70~~ 69 bytes
```
^,~=last,rand
s=[1:16;]
while s∩s^16!=s^1
push!(s,~s^16)end
show(s)
```
[Attempt This Online!](https://ato.pxeger.com/run?1=m700qzQnM3HBgqWlJWm6Fjdd43TqbHMSi0t0ihLzUriKbaMNrQzNrGO5yjMyc1IVih91rCyOMzRTtAWSXAWlxRmKGsU6dSAhzVSQ-oz8co1iTYhhUDNhZgMA)
* -1 byte thanks to MarcMush: reassign operators on the same line
+ (Otherwise, a space is needed between `^` and `=`)
* -2 bytes thanks to MarcMush: replace `!allequal(s^16)` with `s∩s^16!=s^1`
+ (`!allequal(last(s,16))` with `s∩last(s,16)!=last(s,1)`)
* -1 byte thanks to MarcMush: remove the newline before `end`
* Thanks also to MarcMush for spotting an error or two!
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 24 bytes
```
≔…α¹⁶θθW∧⁻θ⌊θ‽θ«ι≔⁺Φθλιθ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/9@xuDgzPU/DuTI5J9U5I79AI1FHwdBMU0ehUNOaK6AoM69EA8Qqz8jMSVXQcMxL0fDNzCst1ijUUQAyMnNLc4HyQOVBiXkp@WC2pkI1FydEZyZQJyfUhoAcoC63zJyS1CKQ5hygnkyoNbX////XLcsBAA "Charcoal – Try It Online") Link is to verbose version of code. Uses `ABCDEFGHIJKLMNOP`. Explanation:
```
≔…α¹⁶θθ
```
Get and print the first `16` uppercase letters.
```
W∧⁻θ⌊θ‽θ«ι
```
While there is a choice of at least two different letters, pick and output a random letter from those remaining.
```
≔⁺Φθλιθ
```
Update the string of available letters.
23 bytes if the last letter does not need to be printed (it will be the same as the preceding 15):
```
≔…α¹⁶θW⁻θ⌊θ«→Pθ≔⁺Φθλ‽θθ
```
[Try it online!](https://tio.run/##Lc29CsIwFAXgOX2KjDcQhy4OOknBrVD6BiGG5sJtYv4qIj57TNXtDOd8R1sVtVdU6yUlXBwMT01msP4OSvL@KCQP4tw9LJLhMKIrCYLkLeBaVghCCP7q2Og3A6cZF5tbm42FMk4RXYZ9zf72RG19Rcom7gg1fFbu5r/O7@hdaz1s9AE "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 21 bytes
```
P*Y,16T$=yY SyAE PRCy
```
Uses 0 to 15. [Attempt This Online!](https://ato.pxeger.com/run?1=m724ILNgwYKlpSVpuhZbA7QidQzNQlRsKyMVgisdXRUCgpwrIXJQJTClAA)
### Explanation
```
P*Y,16T$=yY SyAE PRCy
,16 ; Range(16)
Y ; Yank, storing in y variable
P* ; Print each
T ; Loop till
$=y ; all elements of y are equal:
RCy ; Choose a random element of y
P ; Print it
AE ; Append that element to
Sy ; y without its first element
Y ; Yank that list as the new value of y
```
[Answer]
# [Factor](https://factorcode.org/), 69 bytes
```
16 iota [ dup 16 tail* dup all-eq? ] [ random suffix ] until drop ...
```
[Try it online!](https://tio.run/##LYyxCgIxEAV/5dWCARsLLSzFxkas5Ipw2RyLcZPbbEC/PgaxnBmY6GfL2u@3y/V8QKW1kcxUoV5CfmHR3ArLgqJk9inKYniSCiUc@24PzubxQGgFg8xz2vzAp7Sl9YRpxP@rthj5PUwT44SgucA51/sX "Factor – Try It Online")
[Answer]
# [Raku](https://raku.org/), 56 bytes
```
|(1..16),{@_.tail(16).pick}...{~@_~~/(\d+)[' '$0]**15$/}
```
[Try it online!](https://tio.run/##K0gtyjH7X5xYqZCVn5mnoK6grqOg8b9Gw1BPz9BMU6faIV6vJDEzRwPI0SvITM6u1dPTq65ziK@r09eISdHWjAbqUDGI1dIyNNWv/a/5HwA "Perl 6 – Try It Online")
This is a sequence of the form `initial-elements, { generator } ... { termination-check }`.
* The initial elements are from the range `1..16`, flattened with `|`.
* The generator takes the entire sequence generated so far in `@_`, then randomly picks an element from the last sixteen of them.
* The termination check stringifies the sequence, then checks that the string satisfies a regex: a space-separate sequence of digits that repeats sixteen times before the end of the string.
[Answer]
# [CJam](http://sourceforge.net/projects/cjam/), ~~24~~ 23 bytes
```
G,_:p;{_mR_p+(;__|,(}g;
```
[Try it online!](http://cjam.aditsu.net/#code=G%2C_%3Ap%3B%7B_mR_p%2B%28%3B__%7C%2C%28%7Dg%3B)
**Explanation**
```
G,_:p; create and print an array [0-16)
{ }g do...
_mR pick a random number from the last 16
_p+(; print, add to the list, and remove the oldest number
__|,( ...while the number of unique numbers in the last 16 != 1
; cleanup
```
**(-1 byte)** *replacing `1-` with `(`, courtesy of my bestie*
[Answer]
# [Arturo](https://arturo-lang.io), ~~74~~ ~~70~~ 67 bytes
```
a:@0..15prints a until[prints->a\0[]=a--a\0][a:@[sample a]++chop a]
```
[Try it](http://arturo-lang.io/playground?KKyOQc)
[Answer]
# Swift 5.6+, 107 bytes
```
var a=[_](1...16),i=0
a.map{print($0)}
while Set(a).count>1{a[i]=a.randomElement()!
print(a[i])
i=(i+1)%16}
```
Uses `a` as a circular buffer, overwriting a different position each run through the loop. For lack of a builtin "all elements are the same" operation, the loop condition converts it to a Set to count the number of unique elements.
[SwiftFiddle link](https://swiftfiddle.com/p2epgkuqwzeknjbvjvxhd6qgj4)
Ungolfed:
```
var arr = Array(1...16)
for el in arr {
print(el)
}
var i = 0
while Set(arr).count > 1 {
let x = arr.randomElement()!
print(x)
arr[i] = x
i = (i + 1) % arr.count
}
```
[Answer]
# PHP 8, 110 bytes
```
$o=range(1,16);do$o[]=$o[count($o)-rand(1,16)];while(count(array_unique(array_slice($o,-16)))>1);print_r($o);
```
I wish PHP's array syntax was a little less verbose...
Works by building up an array by appending a random element from the last 16 elements, then printing it all at once, when the last 16 elements are all the same.
[Answer]
# [Zsh](https://www.zsh.org/), 101 bytes
```
seq 16|tee a;set `shuf a`
while shift;16=`shuf -n1 a`;<<<$16;s=(${(n)@});((s[1]<s[16]))&&<<<${(F)@}>a
```
[Try it online!](https://tio.run/##qyrO@P@/OLVQwdCspiQ1VSHRuji1RCGhOKM0TSExgas8IzMnVaE4IzOtxNrQzBYirptnCJSztrGxUTE0sy621VCp1sjTdKjVtNbQKI42jLUBEmaxmppqaiAl1RpuQDm7xP//AQ)
~~[114 bytes](https://tio.run/##JcmxDoMgEADQ3a@4geFucGBh6EHjfzQmMmAhMaT1qG0qfjs16fKW95XYmoQnaFNLCODZr/fN4STxNYOfqHvHtAS48C4xzYW1cf/rsz6frbVKm04cqh0zDQcxotz0aE/MSFRr@KTCjzXlAv0Carj6o7Uf)~~
~~[117b](https://tio.run/##JcuxDsIgEIDhvU9xQwcYHG5h8MD0PaRJGa5CYkjsYTWWPjvWuPzLl/8jsTXhB6CphRkCheW2OjVJfM4QJt29YroznGmTmOZCaNzfThkPJ2ttj6YTp/pNZT3smpSSK472iBm1rpXfqVBZwAN4n3/DcAl7a18 "Zsh – Try It Online")~~
Writes/reads from file `a`. Uses the shell `$argv` array to randomise and pick new values, and a sorted array `$s` to check equality.
Whoops, the initial version incorrectly ran forever. And then the second version was not uniformly random. Fixed now. Thanks to @Gillies for -13 bytes.
[Answer]
# Java 8, 135 bytes
```
()->{int a,m=16,i=0,c=1,t[]=new int[m];for(;c<m;c=a==t[(i+++15)%m]?c+1:1)System.out.println(t[i%m]=a=i<m?i:t[(int)(Math.random()*m)]);}
```
[Try it online!](https://tio.run/##TY@xcsIwEETr@CuuyYwUG09UJAVC4QegotSouMg2EZFkxjrIZDz@dkeAi2y5d29n94RXXJ2a7/l8@fTOgvWYEuzRRRiLArJcpHbo0LawyxYsuvaugY5xeXemx2sipJyxAw9qZnz1MWYYsApKvFdOvVZWiYq0UbH9ueXqYGTXD0zaTZBWoVKkmSvLUrzx52C2thRrwQ@/idpQ9xeqz0OmfGSkXb5nwG3C1q1vVCTO9khf9YCx6QPjL4EbLqf50XCZtzS8tw95JDtQjjxqAzgcEx@LJ1//XzXNfw "Java (JDK) – Try It Online")
Even if Java always loses by far, it was still a fun challenge to code!
] |
[Question]
[
### Introduction
For this example, let's take the string `Hello, World!` and the array `[3, 2, 3]`. To find the substring chain, we go through the following process:
The first number of the array is `3`, so we get the substring `[0 - 3]`, which is `Hel`. After that, we remove the first `3` characters from the initial string, which leaves us with `lo, World!`.
The second number of the array is `2`, so we get the substring `[0 - 2]` from our new string, which gives us `lo`. The leftover string becomes `, World!`.
The last number is a `3`, which gives us `, W`. The **substring chain** is all of the substrings combined, which gives us:
```
['Hel', 'lo', ', W']
```
For a more visual example:
```
[3, 2, 3], 'Hello, World!'
3 -> Hel
2 -> lo
3 -> , W
```
### The task
Given **a *non-empty* string** and **a *non-empty* array** only consisting of **positive integers** (`> 0`), output the **substring chain**. You may assume that the sum of all integers in the array does not exceed the length of the string.
You can also assume that the strings will never contain any newlines.
### Test cases
```
Input: abcdefghijk, [2, 1, 3]
Output: ['ab', 'c', 'def']
Input: Code Golf, [4, 1]
Output: ['Code', ' ']
Input: Ayyy, [3]
Output: ['Ayy']
Input: lexicographically, [2, 2, 2, 7, 4]
Output: ['le', 'xi', 'co', 'graphic', 'ally']
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the smallest number of bytes wins!
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 1 byte
```
£
```
This is the substring(0,N) command.
Applied on a list this works repeatedly on the remainder on the string.
[Try it online!](http://05ab1e.tryitonline.net/#code=wqM&input=WzIsIDIsIDIsIDcsIDRdCmxleGljb2dyYXBoaWNhbGx5)
[Answer]
## Python 2, 42 bytes
```
s,a=input()
for n in a:print s[:n];s=s[n:]
```
Sometimes you just do it the boring way.
[Answer]
# [Brachylog](http://github.com/JCumin/Brachylog), ~~20~~ 13 bytes
```
h@[~c.:la~t?,
```
[Try it online!](http://brachylog.tryitonline.net/#code=aEBbfmMuOmxhfnQ_LA&input=WyJhYmNkZWZnaGlqayI6WzI6MTozXV0&args=Wg)
This is extremely inefficient and times out on TIO for the last test case.
### Explanation
```
Input = [String, List of integers]
h@[ Take a prefix of the string
~c. Take a possible list of strings which when concatenated results in that prefix
:la Take the lengths of each element of that list
~t?, This list of lengths is equal to the list of integers of the Input
```
### A slightly more efficient version, 15 bytes
[```
t:{~l}a.,?h@[~c
```](http://brachylog.tryitonline.net/#code=dDp7fmx9YS4sP2hAW35j&input=WyJsZXhpY29ncmFwaGljYWxseSI6WzI6MjoyOjc6NF1d&args=Wg)
[Answer]
# Python 3, 45 bytes
```
f=lambda s,a:f(s[a[0]:print(s[:a.pop(0)])],a)
```
This prints one substring per line and terminates with an error when **a** is exhausted.
Test it on [repl.it](https://repl.it/Ddza).
[Answer]
# Python, ~~52~~, 46 bytes
```
f=lambda a,s:a and[s[:a[0]]]+f(a[1:],s[a[0]:])
```
A recursive lambda function.
*Thanks to Dennis for shaving off 6 bytes!*
[Answer]
# [Jelly](http://github.com/DennisMitchell/jelly), 6 bytes
```
Jx$ĠịY
```
[Try it online!](http://jelly.tryitonline.net/#code=SngkxKDhu4tZ&input=&args=WzMsIDIsIDNd+J0hlbGxvLCBXb3JsZCEn)
```
The implicit working value is the first argument.
Jx$ Given a list L, repeat (x) an element of [1..len(n)] (J)
as many times as the corresponding value in L.
Ġ Group indices by values. This turns [1, 1, 1, 2, 2, 3, 3]
into [[1, 2, 3], [4, 5], [6, 7]].
ị Index into the second argument.
Y Join by newlines.
```
[Answer]
## Haskell, 34 bytes
```
s#(a:b)=take a s:drop a s#b
_#_=[]
```
Usage example: `"lexicographically" # [2,2,2,7,4]` -> `["le","xi","co","graphic","ally"]`
Simple recursion.
Or the boring **29 bytes** solution via built-in:
```
import Data.Lists
splitPlaces
```
[Answer]
# Ruby, 26 bytes
```
->w,a{a.map{|n|w.shift n}}
```
Strings are represented as arrays of characters.
[Answer]
## PowerShell v2+, 46 bytes
```
param($a,$b)$b|%{-join$a[$i..($i+=$_-1)];$i++}
```
Takes input string `$a` and array `$b`, loops over `$b`. Each iteration, does an array slice of `$a` based on `$i` (defaults to `$null`, or `0`) and the current number. Needs to do the `-1` and `$i++` because strings in PowerShell are zero-indexed.
### Examples
(The output here is space-separated, because that's the default stringification method for arrays)
```
PS C:\Tools\Scripts\golfing> @('abcdefghijk',@(2,1,3)),@('Code Golf',@(4,1)),@('Ayyy',@(3)),@('lexicographically',@(2,2,2,7,4))|%{""+$_[0]+" -> "+(.\substring-chainification.ps1 $_[0] $_[1])}
abcdefghijk -> ab c def
Code Golf -> Code
Ayyy -> Ayy
lexicographically -> le xi co graphic ally
```
[Answer]
# Perl, 28 bytes
Includes +1 for `-n`
Run with the input string on STDIN followed by each number on a separate line:
```
(echo "Hello, World!"; echo 3; echo 2; echo 3) | perl -nE 'say for/(??{"."x<>||"^"})/g'
```
Just the code:
```
say for/(??{"."x<>||"^"})/g
```
The 23 bytes version without `||"^"` also sort of works, but prints spurious trailing newlines
`"^"` can be replaced by `$_` if the string does not contain regex meta characters
[Answer]
# [MATL](http://github.com/lmendo/MATL), 8 bytes
```
ys:)1bY{
```
[Try it online!](http://matl.tryitonline.net/#code=eXM6KTFiWXs&input=WzIsIDEsIDNdCidhYmNkZWZnaGlqaycK)
### Explanation
```
y % Implicitly take the two inputs: numerical array, string. Duplicate the array
s % Sum of the array, say n
: % Range from 1 to n
) % Take first n characters of the string
1 % Push 1
b % Bubble up the original copy of the string to the top
Y{ % Split into pieces of lengths given by the numerical array. The pieces are
% stored in a cell array, which is implicitly displayed, one cell per line
```
[Answer]
## JavaScript (ES6), ~~39~~ ~~38~~ 35 bytes
Saved 3 bytes thanks to ETHproductions:
```
s=>a=>a.map(v=>s.slice(t,t+=v),t=0)
```
Example:
```
//Definition
f=
s=>a=>a.map(v=>s.slice(t,t+=v),t=0)
//Call
f('lexicographically')([2, 2, 2, 7, 4]);
//Output
Array [ "le", "xi", "co", "graphic", "ally" ]
```
---
Previous solution:
38 bytes thanks to Huntro:
```
s=>a=>a.map(v=>s.substr(t,v,t+=v),t=0)
```
39 bytes:
```
(s,a)=>a.map(v=>s.substr(t,v,t+=v),t=0)
```
[Answer]
## Batch, 74 bytes
```
@set/ps=
@for %%i in (%*)do @call echo %%s:~0,%%i%%&call set s=%%s:~%%i%%
```
I'm beating C? This can't be right! Takes the string on STDIN and the array as command-line arguments.
[Answer]
# Java, 119 Bytes
```
String[] substringChainification(String s, int[] i) {
String[] r = new String[i.length];
int j = 0, f = 0;
for (int t : i)
r[j++] = s.substring(f, f += t);
return r;
}
```
**Golfed:**
```
String[]s(String s,int[]i){String[]r=new String[i.length];int j=0,f=0;for(int t:i)r[j++]=s.substring(f,f+=t);return r;}
```
I modified Roman Gräf's answer(<https://codegolf.stackexchange.com/a/93992/59935>), but i don't have enough rep to comment.
I changed the loop implementation and instead of setting the source string to another substring in every iteration, i just change the indices with which i get the substring.
[Answer]
## Pyke, 10 bytes
```
FQR<
Ki?>Q
```
[Try it here!](http://pyke.catbus.co.uk/?code=FQR%3C%0AKi%3F%3EQ&input=abcdefghijk%0A%5B2%2C+1%2C+3%5D)
[Answer]
# sed (82 + 2 for -rn) 84
```
s,^,\n,;:l;N;s,\n\n,\n,;:
s,^([^\n]*)\n(.)([^\n]*\n)1,\1\2\n\3,
t;P;s,^[^\n]*,,;tl
```
The first line of input is the string. Then each line after that is the size of a substring in [unary](http://meta.codegolf.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary?answertab=votes#tab-top).
Example:
```
$ cat test.txt:
lexicographically
11
11
11
1111111
1111
$ cat hold | sed -rnf sed.txt
le
xi
co
graphic
ally
```
[Answer]
## [CJam](http://sourceforge.net/projects/cjam/), 11 bytes
```
lq~{/(ns}/;
```
[Try it online!](http://cjam.tryitonline.net/#code=bHF-ey8obnN9Lzs&input=bGV4aWNvZ3JhcGhpY2FsbHkKWzIgMiAyIDddCg)
### Explanation
```
l e# Read input string.
q~ e# Read array of lengths and eval.
{ e# For each length...
/ e# Split the string into chunks of the given size.
( e# Pull off the first chunk.
n e# Print with linefeed.
s e# Flatten the remaining chunks into a single string again.
}/
; e# Discard any remainder of the input string.
```
[Answer]
# C, 81 bytes
```
i,j;f(s,l,k)char*s;int*l;{for(i=j=0;i<k;){write(1,s+j,l[i]);puts("");j+=l[i++];}}
```
Because `write()` output is not buffered any online compiler will have a hard time outputting this.
**test.c**:
```
i,j;f(s,l,k)char*s;int*l;{for(i=j=0;i<k;){write(1,s+j,l[i]);puts("");j+=l[i++];}}
main(){
int l[]={3,2,3};
f("Hello, World!",l,3);
int ll[]={2,1,3};
f("abcdefghijk",ll,3);
int lll[]={4,1};
f("Code Golf",lll,2);
int llll[]={3};
f("Ayyy",llll,1);
int lllll[]={2,2,2,7,4};
f("lexicographically",lllll,5);
}
```
Output without piping:
```
Hel
lo
, W
ab
c
def
Code
Ayy
le
xi
co
graphic
ally
```
[Answer]
# PHP, 98 Bytes
```
<?php
$b=$argv[1];foreach(explode(',',$argv[2])as$a){echo(substr($b,0,$a).' ');$b=substr($b,$a);}
```
**Usage:**
```
php chainification.php lexicographically 2,2,2,7,4
```
**Output:**
```
le xi co graphic ally
```
There's probably a better solution with PHP.
[Answer]
# PHP, 82 Bytes
```
<?php for($s=$argv[++$i],$j=-1;$n=$argv[++$i];){for(;$n--;)echo$s[++$j];echo"
";}
```
Takes input as a string and then a list of numbers, output is separated by new lines. e.g.
```
php chainify.php lexicographically 2 2 2 7 4
```
If you're one of those people able to use $argv with -r you can save the 6 bytes used for the opening tag.
[Answer]
# PHP, 63 Bytes
```
<?foreach($_GET[a]as$p){echo" ".substr($_GET[s],$s,$p);$s+=$p;}
```
Output as Array 85 Bytes
```
<?foreach($_GET["a"]as$p){$o[]=substr($_GET["s"],$s,$p);$s+=$p;}echo json_encode($o);
```
[Answer]
# Rebol, 38 bytes
```
func[s b][map-each n b[take/part s n]]
```
[Answer]
# Pyth, 7 bytes
```
PcwsM._
```
Takes input separated by newline, with the string unescaped and coming after the array.
[Try it Online!](http://pyth.herokuapp.com/?code=PcwsM._&input=%5B3%2C2%2C3%5D%0AHello%2C+World%21&debug=0)
Explanation:
```
._ Get all prefixes of Q
sM Map sum across each of these prefixes (to get the total indices)
cw Split the string at these locations
P Remove the last "remainder" of the string
```
[Answer]
# Octave / MATLAB, 31 bytes
```
@(s,a)mat2cell(s(1:sum(a)),1,a)
```
This is an anonymous function with inputs `s`: string; `a`: numerical array.
[Try it at Ideone](http://ideone.com/PL4hZs).
### Explanation
This is a port of my MATL answer.
```
s(1:sum(a)) % Take first n characters of string s, where n is the sum of array a
mat2cell(...,1,a) % Split into pieces of lengths given by a and store in a cell array
```
[Answer]
# Java 142 bytes
```
public static String[]substringChain(String s,int[]i){
String[]r=new String[i.length];
for(int j=-1;++j<i.length;){
r[j]=s.substring(0,i[j]);
s=s.substring(i[j]);
}
return b;
}
```
Golfed:
```
String[]s(String s,int[]i){String[]r=new String[i.length];for(int j=-1;++j<i.length;){r[j]=s.substring(0,i[j]);s=s.substring(i[j]);}return b;}
```
[Answer]
# Awk, 36 characters
```
{FIELDWIDTHS=$0;OFS=RS;getline}$1=$1
```
Sample run:
```
bash-4.3$ awk '{FIELDWIDTHS=$0;OFS=RS;getline}$1=$1' <<< $'3 2 3\nHello, World!'
Hel
lo
, W
```
In real life I would use it like this, just no idea how to calculate its score:
```
bash-4.3$ awk -vFIELDWIDTHS='3 2 3' -vOFS='\n' '$1=$1' <<< 'Hello, World!'
Hel
lo
, W
```
[Answer]
# [Dyalog APL](http://goo.gl/9KrKoM) 16.0, 15 [characters](http://meta.codegolf.stackexchange.com/a/9429/43319) (non-competing); 15.0, 17 [bytes](http://meta.codegolf.stackexchange.com/a/9429/43319)
### 16.0 solution
```
{⍵⊆⍨(⍴⍵)↑⍺/+\⍺}
```
Dyalog APL 16.0 adds APL2's [partition](http://help.dyalog.com/15.0/Content/Language/Primitive%20Functions/Partition.htm) primitive, `⊂`, with the glyph `⊆`.
### 15.0 solution:
```
{(-⍺)↑¨(+\⍺)↑¨⊂⍵}
```
[TryAPL online!](http://tryapl.org/?a=3%202%203%20%7B%28-%u237A%29%u2191%A8%28+%5C%u237A%29%u2191%A8%u2282%u2375%7D%20%27Hello%2C%20World%21%27&run)
[Answer]
## GNU sed, 55 + 2(rn flags) = 57 bytes
```
1H;1d;G;:;s=.(\n.*)\n(.)=\1\2\n=;t;s=.==;P;s=[^\n]*==;h
```
**[Try it online!](http://sed.tryitonline.net/#code=MUg7MWQ7Rzs6O3M9Lihcbi4qKVxuKC4pPVwxXDJcbj07dDtzPS49PTtQO3M9W15cbl0qPT07aA&input=YWJjZGVmZ2hpamsKMDAKMAowMDAK&args=LXJu)** (thanks to @Dennis for adding sed)
**Explanation:** The input string should be on the first line and the numbers, [in unary](https://codegolf.meta.stackexchange.com/questions/5343/can-numeric-input-output-be-in-unary?answertab=votes#tab-top "consensus"), on separate lines after that. A new line is read implicitly at the start of a cycle, running the script each time.
```
1H;1d # once: append string to hold space and start new cycle
#Initially, the hold space contains an useful '\n'.
G # append hold space to pattern space. The pattern space
#format will be: 'UNARY\n\nSTRING'.
:;s=.(\n.*)\n(.)=\1\2\n=;t # iteratively remove a char from the string, as many
#times as unary chars, and store it on 2nd pattern line
s=.==;P # remove '\n', then print the new top line
s=[^\n]*==;h # delete up to '\n' and update hold space
```
**Test run:** using a here-document with EOF as the end marker
```
sed -rnf program.sed << EOF
> abcdefghijk
> 00
> 0
> 000
> EOF
```
**Output:**
```
ab
c
def
```
[Answer]
## Ruby, 28 bytes
```
->a,w{a.map{|e|w.slice!0,e}}
```
In case arguments are an array of positive integers and one string.
[Answer]
# Vimscript, ~~79~~ 78 bytes
not very pretty, I'm sure it can be improved...
Takes a vim buffer, then call `echom string(A([2,3]))` to see the output
```
fu A(l)
let r=[]
for i in a:l
exe "norm d".i."l"
let r+=[@"]
endfo
retu r
endf
```
I actually thought of cheating and outputing the *string* `["abc", "def"]`... But I resisted :P
Explanation: Delete (puts in default register) each array items amounts of characters and adds it to the array `r`... A boring answer indeed.
] |
[Question]
[
[Sandbox](https://codegolf.meta.stackexchange.com/a/18337/78850)
*A spin-off of a [rip-off](https://codegolf.stackexchange.com/questions/193315/i-reverse-the-source-code-you-reverse-the-input/193317#193317) of a [rip-off](https://codegolf.stackexchange.com/questions/193021/i-reverse-the-source-code-you-negate-the-input) of a [rip-off](https://codegolf.stackexchange.com/q/192979/43319) of a [rip-off](https://codegolf.stackexchange.com/q/132558/43319). Go upvote those!*
Your task, if you accept it, is to write a program/function that outputs/returns its input/argument. The tricky part is that if I left shift your source code, the output must be left shifted too. Likewise, if I right shift your source code, the output must be right shifted too.
Source code will only be shifted once in each direction (in other words, only one shift will be applied, meaning that there are only three possible programs that need to be run). Consequently, the minimum source length should be 3.
## Examples
Let's say your source code is `ABC` and the input is `xyz`. If I run `ABC`, the output must be `xyz`. But if I run `BCA` instead, the output must be `yzx`. And if I run `CAB`, the output must be `zyx`.
Let's say your source code is `EFG` and the input is `Hello`. If I run `EFG`, the output must be `Hello`. If I run `GEF`, the output must be `oHell`. And if I run `FGE`, the output must be `elloH`.
Let's say your source code is `abcde` and the input is `2019`. If I run `abcde`, the output must be `2019`. But if I run `eabcd` instead, the output must be `9201`. And if I run `bcdea`, the output must be `0192`.
# Rules
* The program must print the entire output shifted in the specified direction
* Input can be taken in any convenient format.
* Output can be in any convenient format as well.
* Standard Loopholes are forbidden.
* Source length should be at least 3 characters long, as to allow for unique shifted programs.
## Scoring
This is code-golf so the answer with the fewest amount of bytes wins.
## Leaderboards
Here is a Stack Snippet to generate both a regular leaderboard and an overview of winners by language.
To make sure that your answer shows up, please start your answer with a headline, using the following Markdown template:
```
# Language Name, N bytes
```
where `N` is the size of your submission. If you improve your score, you *can* keep old scores in the headline, by striking them through. For instance:
```
# Ruby, <s>104</s> <s>101</s> 96 bytes
```
If there you want to include multiple numbers in your header (e.g. because your score is the sum of two files or you want to list interpreter flag penalties separately), make sure that the actual score is the *last* number in the header:
```
# Perl, 43 + 2 (-p flag) = 45 bytes
```
You can also make the language name a link which will then show up in the leaderboard snippet:
```
# [><>](http://esolangs.org/wiki/Fish), 121 bytes
```
```
var QUESTION_ID=196864;
var OVERRIDE_USER=78850;
var ANSWER_FILTER="!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe",COMMENT_FILTER="!)Q2B_A2kjfAiU78X(md6BoYk",answers=[],answers_hash,answer_ids,answer_page=1,more_answers=!0,comment_page;function answersUrl(d){return"https://api.stackexchange.com/2.2/questions/"+QUESTION_ID+"/answers?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+ANSWER_FILTER}function commentUrl(d,e){return"https://api.stackexchange.com/2.2/answers/"+e.join(";")+"/comments?page="+d+"&pagesize=100&order=desc&sort=creation&site=codegolf&filter="+COMMENT_FILTER}function getAnswers(){jQuery.ajax({url:answersUrl(answer_page++),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){answers.push.apply(answers,d.items),answers_hash=[],answer_ids=[],d.items.forEach(function(e){e.comments=[];var f=+e.share_link.match(/\d+/);answer_ids.push(f),answers_hash[f]=e}),d.has_more||(more_answers=!1),comment_page=1,getComments()}})}function getComments(){jQuery.ajax({url:commentUrl(comment_page++,answer_ids),method:"get",dataType:"jsonp",crossDomain:!0,success:function(d){d.items.forEach(function(e){e.owner.user_id===OVERRIDE_USER&&answers_hash[e.post_id].comments.push(e)}),d.has_more?getComments():more_answers?getAnswers():process()}})}getAnswers();var SCORE_REG=function(){var d=String.raw`h\d`,e=String.raw`\-?\d+\.?\d*`,f=String.raw`[^\n<>]*`,g=String.raw`<s>${f}</s>|<strike>${f}</strike>|<del>${f}</del>`,h=String.raw`[^\n\d<>]*`,j=String.raw`<[^\n<>]+>`;return new RegExp(String.raw`<${d}>`+String.raw`\s*([^\n,]*[^\s,]),.*?`+String.raw`(${e})`+String.raw`(?=`+String.raw`${h}`+String.raw`(?:(?:${g}|${j})${h})*`+String.raw`</${d}>`+String.raw`)`)}(),OVERRIDE_REG=/^Override\s*header:\s*/i;function getAuthorName(d){return d.owner.display_name}function process(){var d=[];answers.forEach(function(n){var o=n.body;n.comments.forEach(function(q){OVERRIDE_REG.test(q.body)&&(o="<h1>"+q.body.replace(OVERRIDE_REG,"")+"</h1>")});var p=o.match(SCORE_REG);p&&d.push({user:getAuthorName(n),size:+p[2],language:p[1],link:n.share_link})}),d.sort(function(n,o){var p=n.size,q=o.size;return p-q});var e={},f=1,g=null,h=1;d.forEach(function(n){n.size!=g&&(h=f),g=n.size,++f;var o=jQuery("#answer-template").html();o=o.replace("{{PLACE}}",h+".").replace("{{NAME}}",n.user).replace("{{LANGUAGE}}",n.language).replace("{{SIZE}}",n.size).replace("{{LINK}}",n.link),o=jQuery(o),jQuery("#answers").append(o);var p=n.language;p=jQuery("<i>"+n.language+"</i>").text().toLowerCase(),e[p]=e[p]||{lang:n.language,user:n.user,size:n.size,link:n.link,uniq:p}});var j=[];for(var k in e)e.hasOwnProperty(k)&&j.push(e[k]);j.sort(function(n,o){return n.uniq>o.uniq?1:n.uniq<o.uniq?-1:0});for(var l=0;l<j.length;++l){var m=jQuery("#language-template").html(),k=j[l];m=m.replace("{{LANGUAGE}}",k.lang).replace("{{NAME}}",k.user).replace("{{SIZE}}",k.size).replace("{{LINK}}",k.link),m=jQuery(m),jQuery("#languages").append(m)}}
```
```
body{text-align:left!important}#answer-list{padding:10px;float:left}#language-list{padding:10px;float:left}table thead{font-weight:700}table td{padding:5px}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/codegolf/primary.css?v=f52df912b654"> <div id="language-list"> <h2>Winners by Language</h2> <table class="language-list"> <thead> <tr><td>Language</td><td>User</td><td>Score</td></tr></thead> <tbody id="languages"> </tbody> </table> </div><div id="answer-list"> <h2>Leaderboard</h2> <table class="answer-list"> <thead> <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr></thead> <tbody id="answers"> </tbody> </table> </div><table style="display: none"> <tbody id="answer-template"> <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table> <table style="display: none"> <tbody id="language-template"> <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr></tbody> </table>
```
[Answer]
# [Haskell](https://www.haskell.org/), 51 bytes
```
midm(a:b)=b++[a]
i=(:).last<*>init
main=interact id
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/PzczJVcj0SpJ0zZJWzs6MZYr01bDSlMvJ7G4xEbLLjMvs4QrNzEzzzYzryS1KDG5RCEz5f9/RydnAA "Haskell – Try It Online")
## Explanation
Our `main` function is just `interact` of a another function. By default it is `id` which just returns the input, but if we shift we either add an `m` to make `idm` or remove the `d` to make `i`. Both of which we have defined to be roll left and roll right.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), 4 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
À\Á\
```
[Try it online](https://tio.run/##yy9OTMpM/f//cEPM4caY//89UnNy8gE)
[ry it shifted towards the leftT](https://tio.run/##yy9OTMpM/f8/5nBjzOGG//89UnNy8gE)
[tTry it shifted towards the righ](https://tio.run/##yy9OTMpM/f8/5nBDzOHG//89UnNy8gE)
**Explanation:**
```
À # Shift the (implicit) input once towards the left
\ # Discard it from the stack
Á # Shift the (implicit) input once towards the right
\ # Discard it from the stack
# (output the implicit input implicitly as result)
\ # Discard (no-op, since the stack is already empty)
À # Shift the (implicit) input once towards the left
\ # Discard it from the stack
Á # Shift the (implicit) input once towards the right
# (and output this right-shifted input at the top of the stack implicitly as result)
\ # Discard (no-op, since the stack is already empty)
Á # Shift the (implicit) input once towards the right
\ # Discard it from the stack
À # Shift the (implicit) input once towards the left
# (and output this left-shifted input at the top of the stack implicitly as result)
```
[Answer]
# [R](https://www.r-project.org/), ~~82~~ ~~75~~ ~~67~~ 62 bytes
-4 bytes thanks to Giuseppe.
```
!-1->i
c(tail(s<-el(strsplit(scan(,""),"")),1/i),head(s,-i))#!
```
[Try it online!](https://tio.run/##K/r/X1HXUNcu0zpZoyQxM0ej2EY3FUiWFBUX5GSWaBQnJ@Zp6CgpaYKwpo6hfqamTkZqYopGsY5upqamsuJ/j9ScnPz/AA "R – Try It Online")
[ry it online!T](https://tio.run/##K/r/X9dQ1y7TOlmjJDEzR6PYRjcVSJYUFRfkZJZoFCcn5mnoKClpgrCmjqF@pqZORmpiikaxjm6mpqayouJ/j9ScnPz/AA)
[!Try it online](https://tio.run/##K/r/X1FR11DXLtM6WaMkMTNHo9hGNxVIlhQVF@RklmgUJyfmaegoKWmCsKaOoX6mpk5GamKKRrGObqampvJ/j9ScnPz/AA)
Uses rightwards assignment `->` (this is [only the 2nd time](https://codegolf.stackexchange.com/a/191416/86301) I have ever used rightwards assignment). The value of `i` is either 0, 1 or -1 depending on the shift. This is used to give the correct output:
* when `i=1`, `tail(s, 1)` gives the last element and `head(s, -1)` gives all elements but the last
* when `i=-1`, `tail(s, -1)` gives all elements but the first and `head(s, 1)` gives the first element
* when `i=0`, `tail(s, Inf)` gives `s` and `head(s, 0)` gives the empty vector.
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), 18 bytes
```
?.<Q1 Q ;*.>Q1qk"
```
[Try it online!](https://tio.run/##K6gsyfj/317PJtBQIVDBWkvPLtCwMFtJ4f9/pcy8gtISJQA "Pyth – Try It Online"), [Right-shift](https://tio.run/##K6gsyfj/X8FezybQUCFQQVNLzy7QsDBb6f9/pcy8gtISJQA "Pyth – Try It Online"), [Left-shift](https://tio.run/##K6gsyfj/X88m0FAhUEFTS88u0LAwW0nB/v9/pcy8gtISJQA "Pyth – Try It Online")
Pretty proud of this one. Has a trailing newline except on right shift. Makes use of the fact that a space before a pyth expression suppresses the output. Note the last byte is a space.
## How it works
```
?.<Q1 Q ;*.>Q1qk" - Unshifted
?.<Q1 - If the input left-shifted is truthy
Q ; - Print the input, end if statement
*.>Q1 - Right shifted input, multiplied by...
qk" - whether k (an empty string) is equal to the string at the end.
Since there is a space at the end, y(Q) is multiplied by zero.
.<Q1 Q ;*.>Q1qk" ? - Left Shifted
.<Q1 - Left shift the input and print it.
Q - This input is preceded by a space and as such does not print
" ? - Obviously is not equal to an empty string (Pyth
closes strings implicitly)
?.<Q1 Q ;*.>Q1qk" - Right Shifted
?.<Q1 Q ; - The space before the if statement suppresses the printing
" - Since the space has been removed from the end, the
terminating string is now an empty string, and y(Q) is printed
```
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~15~~ 11 [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")
-4 thanks to inspiration from [Luis Mendo's solution](https://codegolf.stackexchange.com/a/196871/43319).
Full program, prompting for input via stdin.
---
```
1⊢⍞⌽⍨¯2+≢1⍬
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qKO94L/ho65Fj3rnPerZ@6h3xaH1RtqPOhcZPupdA5L9rwAGBVwZqTk5@QA "APL (Dyalog Unicode) – Try It Online")
`1⍬` the list `[1,[]]`
`≢` tally the elements in that; `2`
`¯2+` add negative two to that; `0`
…`⌽⍨` cyclically rotate the following by that number of steps:
`⍞` stdin
`1⊢` yield that, ignoring the `1`
---
```
⊢⍞⌽⍨¯2+≢1⍬1
```
[ry it online!T](https://tio.run/##SyzI0U2pTMzJT///qKO94P@jrkWPeuc96tn7qHfFofVG2o86Fxk@6l1jCJL9rwAGBVwZqTk5@QA "APL (Dyalog Unicode) – Try It Online")
`1⍬1` the list `[1,[],1]`
`≢` tally the elements in that; `3`
`¯2+` add negative two to that; `1`
…`⌽⍨` cyclically rotate the following by that number of steps:
`⍞` stdin
`⊢` yield that
---
```
⍬1⊢⍞⌽⍨¯2+≢1
```
[!Try it online](https://tio.run/##SyzI0U2pTMzJT///qKO94P@j3jWGj7oWPeqd96hn76PeFYfWG2k/6lxkCJL9rwAGBVwZqTk5@QA "APL (Dyalog Unicode) – Try It Online")
`1` the number `1`
`≢` tally the elements in that; `1`
`¯2+` add negative two to that; `-1`
…`⌽⍨` cyclically rotate the following by that number of steps:
`⍞` stdin
`⍬1⊢` yield that, ignoring the list `[[],1]`
[Answer]
# JavaScript (Browsers), ~~81~~ ~~68~~ 66 bytes
```
xx=1;var x,xxx;w=prompt();alert(w.slice(a=x|-xxx)+w.slice(0,a))//x
```
## Original solution (81 bytes)
```
tob=-1;try{ob;atob=1}catch(e){}w=prompt();alert(w.slice(atob)+w.slice(0,atob))//a
```
No TIO link because it works only in browsers ~~with `atob` function defined~~.
In order to show the output in a more friendly way, `prompt` and `alert` are overridden in the screenshot below.
[](https://i.stack.imgur.com/ANx5U.png)
## Explanation
The declarations of `x` and `xxx` are hoisted to the beginning automatically, so the declarations won't clear the values assigned beforehand.
### No rotation
```
xx=1;var x,xxx;w=prompt();alert(w.slice(a=x|-xxx)+w.slice(0,a))//x
// xx = 1, so a = 0, so we have alert(w.slice(0)+w.slice(0,0))
```
### Left rotation
```
x=1;var x,xxx;w=prompt();alert(w.slice(a=x|-xxx)+w.slice(0,a))//xx
// x = 1, so a = 1, so we have alert(w.slice(1)+w.slice(0,1))
```
### Right rotation
```
xxx=1;var x,xxx;w=prompt();alert(w.slice(a=x|-xxx)+w.slice(0,a))//
// xxx = 1, so a = -1, so we have alert(w.slice(-1)+w.slice(0,-1))
```
[Answer]
# [Python 2](https://docs.python.org/2/), 64 bytes
```
bc=k=input()
print[k,k[1:]+k[0],k,k[-1]+k[:-1]][len(dir()[5])]#a
```
[Try it online!](https://tio.run/##K6gsycjPM/r/PynZNts2M6@gtERDk6ugKDOvJDpbJzva0CpWOzvaIFYHxNE1BHGsgFRsdE5qnkZKZpGGZrRprGascuL//0oeqTk5@UoA "Python 2 – Try It Online"), [!Try it online](https://tio.run/##K6gsycjPM/r/PzEp2TbbNjOvoLREQ5OroCgzryQ6Wyc72tAqVjs72iBWB8TRNQRxrIBUbHROap5GSmaRhma0aaxmrPL//0oeqTk5@UoA "Python 2 – Try It Online") and [ry it online!T](https://tio.run/##K6gsycjPM/r/P9k22zYzr6C0REOTq6AoM68kOlsnO9rQKlY7O9ogVgfE0TUEcayAVGx0TmqeRkpmkYZmtGmsZqxyYtL//0oeqTk5@UoA "Python 2 – Try It Online")
`dir` is a builtin function that returns a list of all variable names. The length of the first variable name is used to choose the right output.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 4 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ÉUé0
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yVXpMA&input=ImFiY2RlZiI)
---
[0ÉUé](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MMlV6Q&input=ImFiY2RlZiI)
[Ué0É](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VekwyQ&input=ImFiY2RlZiI)
---
Works with arrays too.
[ÉUé0](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=yVXpMA&input=WzEsMiwzLDRd)
[Ué0É](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=VekwyQ&input=WzEsMiwzLDRd)
[0ÉUé](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=MMlV6Q&input=WzEsMiwzLDRd)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~109~~ ~~86~~ 83 bytes
-20 bytes thanks to [xibu](https://codegolf.stackexchange.com/users/90181/xibu)
Takes the text to display is a command line argument. The active code is bookended by newlines, having the result of changing what `__LINE__` evaluates to when shifting the code. This means `2-__LINE__` will be +1 for shifting left, 0 for no shift, and -1 for shifting right.
## No shift
```
K;main(L,s)char**s;{for(L=strlen(s[1]);K<L;)putchar(s[1][(K+++2-__LINE__+L)%L]);}
```
[Try it online!](https://tio.run/##S9ZNT07@/5/L2zo3MTNPw0enWDM5I7FIS6vYujotv0jDx7a4pCgnNU@jONowVtPa28bHWrOgtASkBiwUreGtra1tpBsf7@Pp5xofr@2jqeoDVFjL9f///8Sk5BQA "C (gcc) – Try It Online")
## Left shift
```
K;main(L,s)char**s;{for(L=strlen(s[1]);K<L;)putchar(s[1][(K+++2-__LINE__+L)%L]);}
```
[Try it online!](https://tio.run/##S9ZNT07@/9/bOjcxM0/DR6dYMzkjsUhLq9i6Oi2/SMPHtrikKCc1T6M42jBW09rbxsdas6C0BKQGLBSt4a2trW2kGx/v4@nnGh@v7aOp6gNUWMvF9f///8Sk5BQA "C (gcc) – Try It Online")
## Right shift
```
K;main(L,s)char**s;{for(L=strlen(s[1]);K<L;)putchar(s[1][(K+++2-__LINE__+L)%L]);}
```
[Try it online!](https://tio.run/##S9ZNT07@/5@Ly9s6NzEzT8NHp1gzOSOxSEur2Lo6Lb9Iw8e2uKQoJzVPozjaMFbT2tvGx1qzoLQEpAYsFK3hra2tbaQbH@/j6ecaH6/to6nqA1RY@////8Sk5BQA "C (gcc) – Try It Online")
[Answer]
# [Python 3](https://docs.python.org/3/), ~~52~~ 48 bytes
## Base code:
```
"i=1#";i=0#';i=-1
a=input()
print(a[i:]+a[:i])#'
```
[Try it online!](https://tio.run/##K6gsycjPM/7/XynT1lBZyTrT1kBZHUjqGnIl2mbmFZSWaGhyFRRl5pVoJEZnWsVqJ0ZbZcZqKqv//@@RmpOTrxCeX5SToggA "Python 3 – Try It Online")
## Left shift:
```
i=1#";i=0#';i=-1
a=input()
print(a[i:]+a[:i])#'"
```
[ry it online!T](https://tio.run/##K6gsycjPM/7/P9PWUFnJOtPWQFkdSOoaciXaZuYVlJZoaHIVFGXmlWgkRmdaxWonRltlxmoqqyv9/@@RmpOTrxCeX5SToggA "Python 3 – Try It Online")
## Right shift:
```
'"i=1#";i=0#';i=-1
a=input()
print(a[i:]+a[:i])#
```
[!Try it online](https://tio.run/##K6gsycjPM/7/X10p09ZQWck609ZAWR1I6hpyJdpm5hWUlmhochUUZeaVaCRGZ1rFaidGW2XGair//@@RmpOTrxCeX5SToggA "Python 3 – Try It Online")
Comments in code are useful :)
[Answer]
# [MATL](https://github.com/lmendo/MATL), ~~9~~ 8 bytes
```
TFsqYS%T
```
[Try it online!](https://tio.run/##y00syfn/P8StuDAyWDXk/391j9ScnHx1AA) See also [right-shifted](https://tio.run/##y00syfn/PyTErbgwMlj1/391j9ScnHx1AA) and [left-shifted](https://tio.run/##y00syfn/3624MDJYNSTk/391j9ScnHx1AA) versions.
# How it works
**Normal version:**
```
TF % Push array [true, false]
sq % Sum; subtract 1. Gives 0
YS % Implicit input. Circular shift by that amount. Implicit display
%T % Comment. Ignore rest of line
```
**Right-shifted version:**
```
TTF % Push array [true, true, false]
sq % Sum; subtract 1. Gives 1
YS % Implicit input. Circular shift by that amount. Implicit display
% % Comment. Ignore rest of line
```
**Left-shifted version:**
```
F % Push array [false]
sq % Sum; subtract 1. Gives -1
YS % Implicit input. Circular shift by that amount. Implicit display
%TT % Comment. Ignore rest of line
```
[Answer]
# [Runic Enchantments](https://github.com/Draco18s/RunicEnchantments/tree/Console), 7 bytes
```
@{͍{͍
```
[Try it online!](https://tio.run/##KyrNy0z@b5dpYOh0tve/Q/XZXiD6/7@isgoA "Runic Enchantments – Try It Online")
Input is limited to a single string (spaces need to be escaped).
This is the best I can come up with. It is not a full program, but instead [a function](https://codegolf.stackexchange.com/a/187842/47990) (see the header on TIO for the entry, stdin handling, and `B`ranch).
This also relies on treating each *cell* of the function as a single object.
Alternatively [this](https://tio.run/##KyrNy0z@b2cQnZkTa6BpomVfZGDodLb3f3W1w///FQqVClUA) works on space separated inputs and doesn't require modifier characters, but outputs them all with no separator.
Without those concessions, the challenge would be impossible in Runic, due to having explicit input and output, as well as a termination command (eg. sample program `i@}`, if it was rotated two to the right to `@}i`, the program would terminate without reading or outputting anything; with an explicit entry point, the program could not distinguish its own rotation).
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~96~~ 94 bytes
-2 bytes thanks to gastropner
```
BC=1;C;ABC;S,K;main(N,c)char**c;{K=S=strlen(c[1]);for(N=C-ABC+S;K--;)putchar(c[1][N++%S]);}//A
```
[Try it online!](https://tio.run/##S9ZNT07@/9/J2dbQ2tna0cnZOljH2zo3MTNPw08nWTM5I7FISyvZutrbNti2uKQoJzVPIznaMFbTOi2/SMPP1lkXqEU72NpbV9das6C0BKQerCDaT1tbNRiorlZf3/H///@GRsYmpgA "C (gcc) – Try It Online")
explanation:
```
BC=1; // declare and set variable ABC, BC or C (depending on shift)
C;ABC; // declare possible variable names
// existing variables are not changed, newly declared variables are set to 0
int main(int NumArgs,char** c)
{
char* input = c[1];
int S = strlen(input); // string length used for modulo
int K = S; // string length used to count characters
int I = C - ABC + S; // set start of output
for(;K--;) // display K characters
putchar(input[I++%S]); // display character and move read position
}
//A // A used to create valid variable name in first line
```
[Answer]
# Javascript, ~~63~~ ~~40~~ 39 bytes
Thanks to @Shaggy and @l4m2, it's now 39 bytes.
`0;f=x=>x.slice(o)+x.slice(0,o);o=~-0b01`
**Explanation**
The last line of this snippet assigns the variable o to either `-1+0b0`, `-1+0b01`, or `-1+0b010`. The 0b prefix is used to define a binary literal, causing those to evaluate to -1, 0, or 1, which then gets used inside the function.
Here are try-it-now versions:
**Not Shifted**
```
<html>
<body>
<script>
0;f=x=>x.slice(o)+x.slice(0,o);o=~-0b01
console.log(f(prompt()))
</script>
</body>
</html>
```
**Left Shifted**
```
<html>
<body>
<script>
;f=x=>x.slice(o)+x.slice(0,o);o=~-0b010
console.log(f(prompt()))
</script>
</body>
</html>
```
**Right Shifted**
```
<html>
<body>
<script>
10;f=x=>x.slice(o)+x.slice(0,o);o=~-0b0
console.log(f(prompt()))
</script>
</body>
</html>
```
## History
**Original version**
`0;x=prompt();onload=_=>alert(x.slice(o)+x.slice(0,o));o=-1+0b01`
A value gets assigned to o on the last line, but we need it in the middle of the code, so we called a function with a delay (by attaching it to the onload event) in order to do so.
**After @Shaggy suggestion to accept I/O from a function**
`0;f=x=>x.slice(o)+x.slice(0,o);o=-1+0b01`
**After @l4m2's suggestion to use `~-` to subtract 1, instead of `-1+` (the current solution).**
`0;f=x=>x.slice(o)+x.slice(0,o);o=~-0b01`
[Answer]
# [Ruby](https://www.ruby-lang.org/), 72 bytes
```
aa,a,aaa,g=0,-1,1,gets
f=->s,a{(g*3)[s+a..-s+a-1]}
puts f.call g.size,aa
```
[Try it online!](https://tio.run/##KypNqvz/PzFRBwiBZLqtgY6uoY6hTnpqSTFXmq2uXbFOYrVGupaxZnSxdqKeni6Q1DWMreUqKC0pVkjTS07MyVFI1yvOrEoFGvD/f0ZqTk4@AA "Ruby – Try It Online")
```
a,a,aaa,g=0,-1,1,gets
f=->s,a{(g*3)[s+a..-s+a-1]}
puts f.call g.size,aaa
```
[Try it online!](https://tio.run/##KypNqvz/P1EHCBMTddJtDXR0DXUMddJTS4q50mx17Yp1Eqs10rWMNaOLtRP19HSBpK5hbC1XQWlJsUKaXnJiTo5Cul5xZlUqyID//zNSc3LyAQ "Ruby – Try It Online")
```
aaa,a,aaa,g=0,-1,1,gets
f=->s,a{(g*3)[s+a..-s+a-1]}
puts f.call g.size,a
```
[Try it online!](https://tio.run/##KypNqvz/PzExUQcIgWS6rYGOrqGOoU56akkxV5qtrl2xTmK1RrqWsWZ0sXainp4ukNQ1jK3lKigtKVZI00tOzMlRSNcrzqxK1Un8/z8jNScnHwA "Ruby – Try It Online")
Triplicates the input then takes a middle substring, shifted according to whether the source code was shifted. Doesn't take kindly to empty input, unfortunately.
Ruby actually has a built-in `rotate` function, there might be a way to use this but it only works on arrays and not strings.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 8 bytes
```
←→Fθ§θⅈ←
```
[Try it online!](https://tio.run/##S85ILErOT8z5/983vyxVw8onNa1E05oLwgnKTM8A8dLyixQ0CjUVAooy80o0HEs881JSKzQKdRQiNDQ14aohWv//DymqVMgsUcjPy8nMS1Xk@q9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
← Move cursor left (decrement X-position)
→ Move cursor right (increment X-position)
F For each character of
θ Input string
§ Implicitly print cyclically indexed character
θ Input string
ⅈ Current X-position
← Move cursor left (no-op)
```
Rotating the code simply causes the X-position to start at `1` or `-1` appropriately thus causing the characters of string to be output cyclically offset, however Charcoal does not include the cursor movement in the output.
```
→Fθ§θⅈ←←
```
[ry it online!T](https://tio.run/##S85ILErOT8z5/983vyxVwyooMz2jRNOaKy2/SEGjUFMhoCgzr0TDscQzLyW1QqNQRyFCQ1MTKA9R7ZOaVoLG@f8/pKhSIbNEIT8vJzMvVZHrv25ZDgA "Charcoal – Try It Online") Link is to verbose version of code.
```
←←→Fθ§θⅈ
```
[!Try it online](https://tio.run/##S85ILErOT8z5/983vyxVw8onNa1E05oLCycoMz0DxEvLL1LQKNRUCCjKzCvRcCzxzEtJrdAo1FGI0NDU1LT@/z@kqFIhs0QhPy8nMy9Vkeu/blkOAA "Charcoal – Try It Online") Link is to verbose version of code.
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 33 bytes
```
0+#~RotateLeft~Log10[.1$]&/.$->10
```
[Try it online!](https://tio.run/##VY8xa8MwFIR3/YqghNJQO7KHDB1stGQozVBc00VoUJMXSRBJRVIgISR/3ZVsQul0fHf3Dp4RUYERUe/E8C0CNHioXub3zkURYQuHeN86WVdsVS/4E1ktyrauBkzIZ/Tayt5rg46p1Uz8d0bzGPJaqv9Zl50ptMJAaK4I54EZLtusBcI5zJg14biRcFR0Qx9pLBI6Xk/A@MPslQexZ@9wCWws8LJNnjtJxZ57tzn/eAhBO0volzie4NFa0s1OOTrn6UeKZp2we2febAQJnr0W13WxvvHhFw "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [Klein](https://github.com/Wheatwizard/Klein) 000, ~~[59](https://codegolf.stackexchange.com/revisions/215152/1)~~ 53 bytes
## Original
```
@>:?!\)>):?!\?@
\( / \$
/( \ /) \
>$:?!/?>:?!/?@/
```
[Try it online!](https://tio.run/##y85Jzcz7/9/BzspeMUbTThNE2TtwxWgoKOgrxKhw6QMZCjEK@ppAkstOBSitb28HJh30////r5v838DA4H9icTYA "Klein – Try It Online")
## Left-Shifted
```
>:?!\)>):?!\?@
\( / \$
/( \ /) \
>$:?!/?>:?!/?@/@
```
[Try it online!](https://tio.run/##y85Jzcz7/9/Oyl4xRtNOE0TZO3DFaCgo6CvEqHDpAxkKMQr6mkCSy04FKK1vbwcmHfQd/v//r5v838DA4H9icTYA "Klein – Try It Online")
## Right-Shifted
```
/@>:?!\)>):?!\?@
\( / \$
/( \ /) \
>$:?!/?>:?!/?@
```
[Try it online!](https://tio.run/##y85Jzcz7/1/fwc7KXjFG004TRNk7cMVoKCjoK8SocOkDGQoxCvqaQJLLTgUorW9vByYd/v//r5v838DA4H9icTYA "Klein – Try It Online")
---
This requires topology 000 for some small byte saving measures. For a version that works on any topology see the 59 byte version in the history.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 9 bytes
```
10%3Cṙ@ḷ4
```
[Try it online!](https://tio.run/##y0rNyan8/9/QQNXY@eHOmQ4Pd2w3@f//f0VlVWJSMgA "Jelly – Try It Online")
A monadic link taking a Jelly string and returning the processed Jelly string.
[All three variations](https://tio.run/##y0rNyan8b6Bq7Pxw50yHhzu2mxj@N0Tm/jdB5nIZHdmvY3hk/8Odax2Mj@yP/P@/orIqMSkZAA)
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, 37 bytes
```
's/(.)(.*)/\2\1/;';";s/(.*)(.)/\2\1/"
```
[Try it online!](https://tio.run/##K0gtyjH9/1@9WF9DT1NDT0tTP8YoxlDfWt1ayRokpgUUhIop/f@fmJSckvovv6AkMz@v@L9uAQA "Perl 5 – Try It Online")
### Left shift
```
s/(.)(.*)/\2\1/;';";s/(.*)(.)/\2\1/"'
```
[Try it online!](https://tio.run/##K0gtyjH9/79YX0NPU0NPS1M/xijGUN9a3VrJGiSmBRSEiimp//@fmJSckvovv6AkMz@v@L9uAQA "Perl 5 – Try It Online")
### Right shift
```
"'s/(.)(.*)/\2\1/;';";s/(.*)(.)/\2\1/
```
[Try it online!](https://tio.run/##K0gtyjH9/19JvVhfQ09TQ09LUz/GKMZQ31rdWskaJKYFFISK/f@fmJSckvovv6AkMz@v@L9uAQA "Perl 5 – Try It Online")
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 12 bytes
```
0&~Rotate??~
```
[Try it online!](https://tio.run/##SywpSUzOSP2fZmX730CtLii/JLEk1d6@7n9AUWZeSXRatJKjk7OLq5tSbOx/AA "Attache – Try It Online")
Returns a function.
## Explanation
`Rotate` is a function which does string rotation. `~Rotate` reverses the argument order. `x&` binds the `x` to the left argument of the given function. `??~` is a comment (`??` marking the start of it). So, this returns a function which, given y, returns `Rotate[y, x]`—rotating `y` by `x` degree.
For the case of no rotation, this rotates the string by 0.
When rotated once right, this becomes:
```
~0&~Rotate??
```
Which is the same as the above, except this time it's `Rotate[y, -1]`, which performs the desired transformation.
If instead we rotate left once, it becomes:
```
&~Rotate??~0
```
`&`, when used in a unary context such as this, will, if given an array as input, apply the each element of the array as an argument for the function. However, the argument is a string, and this is effectively a no-op. Thus, `Rotate[y, x]` has no right argument; by default, it is `1`, so this performs the desired transformation.
[Answer]
# [Crystal](https://crystal-lang.org/), 52 bytes
**Unshifted**
```
25.tap{|n|puts gets.to_s.chars.rotate(n%3-1).join}#2
```
[Try it online!](https://tio.run/##Sy6qLC5JzPn/38hUrySxQKG6Jq@moLSkWCE9taRYryQ/vlgvOSOxqFivKL8ksSRVI0/VWNdQUy8rPzOvVtno//@M1JycfAA "Crystal – Try It Online")
**Left-Shifted**
```
5.tap{|n|puts gets.to_s.chars.rotate(n%3-1).join}#22
```
[Try it online!](https://tio.run/##Sy6qLC5JzPn/31SvJLFAobomr6agtKRYIT21pFivJD@@WC85I7GoWK8ovySxJFUjT9VY11BTLys/M69W2cjo//@M1JycfAA "Crystal – Try It Online")
**Right-Shifted**
```
225.tap{|n|puts gets.to_s.chars.rotate(n%3-1).join}#
```
[Try it online!](https://tio.run/##Sy6qLC5JzPn/38jIVK8ksUChuiavpqC0pFghPbWkWK8kP75YLzkjsahYryi/JLEkVSNP1VjXUFMvKz8zr1b5//@M1JycfAA "Crystal – Try It Online")
Crystal's `Object#tap` passes the object into the following block. Then we get the input, guarantee it's a string, get an array of that string's characters, and then rotate. We rotate by the number at the beginning, modded by three and then subtracted by 1 (with the number at the beginning "chosen" based on convenient modulo properties).
[Answer]
# [Pxem](https://esolangs.org/wiki/Pxem), Content: 0 bytes + Filename: 75 bytes.
* Filename (escaped): `X.c.Z.w.i.c\001.+.a.s.v.t.p.m.o.d.A.c.Z.w.o.i.c\001.+.a.d.A.w.i.c\001.+.a.s.t.v.m.pX`
[Try it online!](https://tio.run/##jVhtV9rKFv7eXzGkkUzI6yAqEqNS8FrOUarWuqyArpAEDYbAIUHRwPnrvXsmQSD0dt2u1TLz7GfP3rNfJjN9Dp9@ff5sW5a9a7vdvV5xv0gsq@duW3Z52@6VSFEn9k5Z33N3i73ip9CNkOJOjMnACp@RrheLhjsdDccROqs9VM/OzJqBo7eRix7dyB4GvXyezezhYGAFjnioOe6LFkx8HxUP8ySfT5UvqtdfTY7HKQ8po8UCTCTyMf2RKvNkoMy5hdkfzcbtw/frulnU9e0FePHte@P27OdD7dvV1Unt2iRGC3F8/KX6/evDzcnV98a3ZkV6m3PIRG@ok8@zXQ3RaBh602QmfUlU7v6HhjuY@FbkovCJ8YejCIavw7ETjnwvyuct37NCpDwigY@JxPHH3FwwBfor5PPNH2dntfO6WWE2MLXnGOGT14sMNkaUlwKu/TRE/GeRWibUcg4MFYe@c5iH0L9YPuJyqGf5ocvNZqsytjTTns5C10FCqE21N80I4Z93TWALvqMOVWIs4CxUbSziISShGiDlJZqQWTRGSi1E7Zau7HeQ0GoHhY4wexy7I6Qmi2v3pV1eiytVg@8aTUNrB2x@AebuVbUdaJrRrRrzZNq6p@sQUuS1kWZEq2BZ38QIIbw2zIB7@5sYIaAdZInlTYzoO7zmZYnbm9g@8B6yGFi2M9ju3iZGCCiH2f1tb2KEgIsvWeLuJkZ0iFgv67a@iREdIuZmfdzfxAgp8do4a7q4iREC2q9Z4t4mBucFD4WWIZY3MVIEH9@yxP1NjBTBn/dsEvTfYOCOld30ziZGCMQ2yloubWJEB3cG2XjvbWJEB3ecrOnyJlaC9EtZDFxUMtg28HJZDLzmsxg4s0WxuTDDtpUeF46YNiXrVy0@pU05NRzov1Oq3cZqW2zjdkD/VQttkdfa2@1im2jACjW1AN06Xe/vim/wuVhrvU7f3i2no@XiptH1YcG58QbNriHN0Fr3qZSWOK8hR1tbQwmQkJpv3R/LHbALHuBWMgQXiseIuvCUchIcqQUQMc8S67CfEXOT12SKdsEFSHEMs1wcwqiqjYzuJaAJTT6GBT6IzgfR0eoL4hptIUnjUBkbfJyYO0Z0aTjiGBtVF0hUZaHlc02QtIMWUt47BYeuFo1XENgSi08n2azGRBbQRiynyeasRGsO3lYuP5ZUmW/RZebMTePxFSJTr0JcpmlyWWSXcUvic5quxP4mriSepFn/naKAFp@OlYRoXg/7Vtf1TZNrE06M2U5wazQMvAc7fOm542gg5fgtpUPZbYJFQ3tMOLQe2zGR23MqusBtksqsVZfCSRdzNCGcTLWPYMxVuGNOZmbFeWpwnf8ncp3XumPXemYTyFsVc/5wOELBMEIDK7KfvOCRA6qw2K6ERa2LiUj5ChsrySTHJjob8zD@Jx1vsTFwoA9ZDwq94TgNEzhjGGIsGB8NKswFUfz1n2b1/MQUblVbvVNfVU@127pOVEm11FB9USN1pA7Uoeqo1ZQxXONQPKsVgd5AHd0Kn2rfmtcnzWtTEH6FY9sUvpycNpoxpE4KXdcRwzFcszAbznuTwI68YYAucF2Mv7ee5b@x2DHrBgw7krSUn2AxHrvRZBygnAScpeSvpQTwQ7KU/L2U0OWWgus1ATWpkBXxLb4S4ysTWMwNRTFS8tWSM8E1MR6NvSBCtSV6iq/ku4@14Rrpe4F7qB/xekVZcexrYoAnBiufe1abElQRx4lrEEqgTfM/qPlJYK7YruLzhUfnMw7yDdcpelX1IrRiegRbf33yfBfnIKTicDWSMIkBnM0m@BZkS0GAG/KNXJd9kWaRKcY3JnAM3/Td4DF6wjeiQauuAffdxoHpG@IE47oJewmjMb6RG5IkE1H8l2P74o7qUqlcKe2I86URD6xf4NM1ww/4XK7Jd/JPMT43OfWhgprQNhZyXNsbwP0TNus@umP4HU0izqiZoG7cgQ/UF1r44G5p76CWz9cOdsoia0QDsNq/3H2ptb3T4eEMuTNLJaWWKie9ChRcTtRICQJSM83tohgnFHgaRF4wcec04pRaOyiVgXO4sydSKDG@NJusLP408U8R1ZRS2aDZMy7wXeHnyl7tRfQv8PVaEMKF4HY1WS@Qk758I8YNU2cW@yarYwh/n5at3FeUjnlDE0VnjQ4DIQ8dNu93VkI/XpqGiGLWn2KB1sCKwddl02x6M8WXMrOVg3akEc7B7JKVyI15eUC5qe7NUuntj0qHv1d6/3CDajE3lDVXosVmnqB3zTXRAETPUCwIXk4XmMpXhF1sQUCTEv@LVvgFto5AXbJoJCq3aUSM5YlRMIlSLGDrQBcLNGfwuxLUf7Lr9dOOuU03i/sFX4SKATOcugUfDhWqkaugO3cM9yjvxQthGY4WCk2KddQ/9I/6W37F3@pX2FhjY8jRPDlhwTNT70A5wGMPs5OgBw8xdtRzM1vkhKVzPYjEGis9s7nZ5uPrD28vM/loJTcFuIjBR4y@gZVx8Exm9gRGjoAEpPSKi68bXGwucF6kj8AVd1xWzMlXM4bCZQX9LEmGJPUPMD2EadFCyJPw99MpDETj99ug23Vc34V3MuQZWiE9nqBBJKlxAOoSSVqCfWkabEWJQJ8kh76UzDtzwaBfKvofBHCVshH7T4QJ7ZDhgD6JARxvgMsYOiWkNEtrhNkMj@B5XoU3v@fIbuQNXHlkjybyS/huOPCwF1dzUPrzAxhFlufD9ba0EmB6xY7L9JrDLlPCzHp9hrWQZSpFUtorlbd3S2UkxJZk8vr8pFlPvxoW3Ay4T/93/tNV0@jQHw4SAB98jokEXoc7GvzhUJikB3NbQ07mdVGYTa3xI8SgMUVp5qbo06@iTvb/Cw)
[!Try it online](https://tio.run/##jVhtV9rKFv7eXzGkkUzI6yAqEqNS8FrOUarWuqyArpAEDYbAIUHRwPnrvXsmQSD0dt2u1TLz7GfP3rNfJjN9Dp9@ff5sW5a9a7vdvV5xv0gsq@duW3Z52@6VSFEn9k5Z33N3i73ip9CNkOJOjMnACp@RrheLhjsdDccROqs9VM/OzJqBo7eRix7dyB4GvXyezezhYGAFjnioOe6LFkx8HxUP8ySfT5UvqtdfTY7HKQ8po8UCTCTyMf2RKvNkoMy5hdkfzcbtw/frulnU9e0FePHte@P27OdD7dvV1Unt2iRGC3F8/KX6/evDzcnV98a3ZkV6m3PIRG@ok8@zXQ3RaBh602QmfUlU7v6HhjuY@FbkovCJ8YejCIavw7ETjnwvyuct37NCpDwigY@JxPHH3FwwBfor5PPNH2dntfO6WWE2MLXnGOGT14sMNkaUlwKu/TRE/GeRWibUcg4MFYe@c5iH0L9YPuJyqGf5ocvNZqsytjTTns5C10FCqE21N80I4Z93TWALvqMOVWIs4CxUbSziISShGiDlJZqQWTRGSi1E7Zau7HeQ0GoHhY4wexy7I6Qmi2v3pV1eiytVg@8aTUNrB2x@AebuVbUdaJrRrRrzZNq6p@sQUuS1kWZEq2BZ38QIIbw2zIB7@5sYIaAdZInlTYzoO7zmZYnbm9g@8B6yGFi2M9ju3iZGCCiH2f1tb2KEgIsvWeLuJkZ0iFgv67a@iREdIuZmfdzfxAgp8do4a7q4iREC2q9Z4t4mBucFD4WWIZY3MVIEH9@yxP1NjBTBn/dsEvTfYOCOld30ziZGCMQ2yloubWJEB3cG2XjvbWJEB3ecrOnyJlaC9EtZDFxUMtg28HJZDLzmsxg4s0WxuTDDtpUeF46YNiXrVy0@pU05NRzov1Oq3cZqW2zjdkD/VQttkdfa2@1im2jACjW1AN06Xe/vim/wuVhrvU7f3i2no@XiptH1YcG58QbNriHN0Fr3qZSWOK8hR1tbQwmQkJpv3R/LHbALHuBWMgQXiseIuvCUchIcqQUQMc8S67CfEXOT12SKdsEFSHEMs1wcwqiqjYzuJaAJTT6GBT6IzgfR0eoL4hptIUnjUBkbfJyYO0Z0aTjiGBtVF0hUZaHlc02QtIMWUt47BYeuFo1XENgSi08n2azGRBbQRiynyeasRGsO3lYuP5ZUmW/RZebMTePxFSJTr0JcpmlyWWSXcUvic5quxP4mriSepFn/naKAFp@OlYRoXg/7Vtf1TZNrE06M2U5wazQMvAc7fOm542gg5fgtpUPZbYJFQ3tMOLQe2zGR23MqusBtksqsVZfCSRdzNCGcTLWPYMxVuGNOZmbFeWpwnf8ncp3XumPXemYTyFsVc/5wOELBMEIDK7KfvOCRA6qw2K6ERa2LiUj5ChsrySTHJjob8zD@Jx1vsTFwoA9ZDwq94TgNEzhjGGIsGB8NKswFUfz1n2b1/MQUbm9VW71TX1VPtdu6TlRJtdRQfVEjdaQO1KHqqNWUMVzjUDyrFYHeQB0Jn2rfmtcnzWtTEH6FY9sUvpycNpoxpE4KXdcRwzFcszAbznuTwI68YYAucF2Mv7ee5b@x2DHrBgw7krSUn2AxHrvRZBygnAScpeSvpQTwQ7KU/L2U0OWWgus1ATWpkBXxLb4S4ysTWMwNRTFS8tWSM8E1MR6NvSBCtSV6iq/ku4@14Rrpe4F7qB/xekVZcexrYoAnBiufe1abElQRx4lrEEqgTfM/qPlJYK7YruLzhUfnMw7yDdcpelX1IrRiegRbf33yfBfnIKTicDWSMIkBnM0m@BZkS0GAG/KNXJd9kWaRKcY3JnAM3/Td4DF6wjeiQauuAffdxoHpG@IE47oJewmjMb6RG5IkE1H8l2P74o7qUqlcKe2I86URD6xf4NM1ww/4XK7Jd/JPMT43OfWhgprQNhZyXNsbwP0TNus@umP4HU0izqiZoG7cgQ/UF1r44G5p76CWz9cOdsoia0QDsNq/3H2ptb3T4eEMuTNLJaWWKie9ChRcTtRICQJSM83tohgnFHgaRF4wcec04pRaOyiVgXO4sydSKDG@NJusLP408U8R1ZRS2aDZMy7wXeHnyl7tRfQv8PVaEMKF4HY1WS@Qk758I8YNU2cW@yarYwh/n5at3FeUjnlDE0VnjQ4DIQ8dNu93VkI/XpqGiGLWn2KB1sCKwddl02x6M8WXMrOVg3akEc7B7JKVyI15eUC5qe7NUuntj0qHv1d6/3CDajE3lDVXosVmnqB3zTXRAETPUCwIXk4XmMpXhF1sQUCTEv@LVvgFto5AXbJoJCq3aUSM5YlRMIlSLGDrQBcLNGfwuxLUf7Lr9dOOuU03i/sFX4SKATOcugUfDhWqkaugO3cM9yjvxQthGY4WCk2KddQ/9I/6W37F3@pX2FhjY8jRPDlhwTNT70A5wGMPs5OgBw8xdtRzM1vkhKVzPYjEGis9s7nZ5uPrD28vM/loJTcFuIjBR4y@gZVx8Exm9gRGjoAEpPSKi68bXGwucF6kj8AVd1xWzMlXM4bCZQX9LEmGJPUPMD2EadFCyJPw99MpDETj99ug23Vc34V3MuQZWiE9nqBBJKlxAOoSSVqCfWkabEWJQJ8kh76UzDtzwaBfKvofBHCVshH7T4QJ7ZDhgD6JARxvgMsYOiWkNEtrhNkMj@B5XoU3v@fIbuQNXHlkjybyS/huOPCwF1dzUPrzAxhFlufD9ba0EmB6xY7L9JrDLlPCzHp9hrWQZSpFUtorlbd3S2UkxJZk8vr8pFlPvxoW3Ay4T/93/tNV0@jQHw4SAB98jokEXoc7GvzhUJikB3NbQ07mdVGYTa3xI8SgMUVp5qbo06@iTvb/Cw)
[ry it online!T](https://tio.run/##jVhtV9rKFv7eXzGkkUzI6yAqEqNS8FrOUarWuqyArpAEDYbAIUHRwPnrvXsmQSD0dt2u1TLz7GfP3rNfJjN9Dp9@ff5sW5a9a7vdvV5xv0gsq@duW3Z52@6VSFEn9k5Z33N3i73ip9CNkOJOjMnACp@RrheLhjsdDccROqs9VM/OzJqBo7eRix7dyB4GvXyezezhYGAFjnioOe6LFkx8HxUP8ySfT5UvqtdfTY7HKQ8po8UCTCTyMf2RKvNkoMy5hdkfzcbtw/frulnU9e0FePHte@P27OdD7dvV1Unt2iRGC3F8/KX6/evDzcnV98a3ZkV6m3PIRG@ok8@zXQ3RaBh602QmfUlU7v6HhjuY@FbkovCJ8YejCIavw7ETjnwvyuct37NCpDwigY@JxPHH3FwwBfor5PPNH2dntfO6WWE2MLXnGOGT14sMNkaUlwKu/TRE/GeRWibUcg4MFYe@c5iH0L9YPuJyqGf5ocvNZqsytjTTns5C10FCqE21N80I4Z93TWALvqMOVWIs4CxUbSziISShGiDlJZqQWTRGSi1E7Zau7HeQ0GoHhY4wexy7I6Qmi2v3pV1eiytVg@8aTUNrB2x@AebuVbUdaJrRrRrzZNq6p@sQUuS1kWZEq2BZ38QIIbw2zIB7@5sYIaAdZInlTYzoO7zmZYnbm9g@8B6yGFi2M9ju3iZGCCiH2f1tb2KEgIsvWeLuJkZ0iFgv67a@iREdIuZmfdzfxAgp8do4a7q4iREC2q9Z4t4mBucFD4WWIZY3MVIEH9@yxP1NjBTBn/dsEvTfYOCOld30ziZGCMQ2yloubWJEB3cG2XjvbWJEB3ecrOnyJlaC9EtZDFxUMtg28HJZDLzmsxg4s0WxuTDDtpUeF46YNiXrVy0@pU05NRzov1Oq3cZqW2zjdkD/VQttkdfa2@1im2jACjW1AN06Xe/vim/wuVhrvU7f3i2no@XiptH1YcG58QbNriHN0Fr3qZSWOK8hR1tbQwmQkJpv3R/LHbALHuBWMgQXiseIuvCUchIcqQUQMc8S67CfEXOT12SKdsEFSHEMs1wcwqiqjYzuJaAJTT6GBT6IzgfR0eoL4hptIUnjUBkbfJyYO0Z0aTjiGBtVF0hUZaHlc02QtIMWUt47BYeuFo1XENgSi08n2azGRBbQRiynyeasRGsO3lYuP5ZUmW/RZebMTePxFSJTr0JcpmlyWWSXcUvic5quxP4mriSepFn/naKAFp@OlYRoXg/7Vtf1TZNrE06M2U5wazQMvAc7fOm542gg5fgtpUPZbYJFQ3tMOLQe2zGR23MqusBtksqsVZfCSRdzNCGcTLWPYMxVuGNOZmbFeWpwnf8ncp3XumPXemYTyFsVc/5wOELBMEIDK7KfvOCRA6qw2K6ERa2LiUj5ChsrySTHJjob8zD@Jx1vsTFwoA9ZDwq94TgNEzhjGGIsGB8NKswFUfz1n2b1/MQUVFu9U19VT7Xbuk5USbXUUH1RI3WkDtSh6qjVlDFc41A8qxWB3kAd3d4Kn2rfmtcnzWtTEH6FY9sUvpycNpoxpE4KXdcRwzFcszAbznuTwI68YYAucF2Mv7ee5b@x2DHrBgw7krSUn2AxHrvRZBygnAScpeSvpQTwQ7KU/L2U0OWWgus1ATWpkBXxLb4S4ysTWMwNRTFS8tWSM8E1MR6NvSBCtSV6iq/ku4@14Rrpe4F7qB/xekVZcexrYoAnBiufe1abElQRx4lrEEqgTfM/qPlJYK7YruLzhUfnMw7yDdcpelX1IrRiegRbf33yfBfnIKTicDWSMIkBnM0m@BZkS0GAG/KNXJd9kWaRKcY3JnAM3/Td4DF6wjeiQauuAffdxoHpG@IE47oJewmjMb6RG5IkE1H8l2P74o7qUqlcKe2I86URD6xf4NM1ww/4XK7Jd/JPMT43OfWhgprQNhZyXNsbwP0TNus@umP4HU0izqiZoG7cgQ/UF1r44G5p76CWz9cOdsoia0QDsNq/3H2ptb3T4eEMuTNLJaWWKie9ChRcTtRICQJSM83tohgnFHgaRF4wcec04pRaOyiVgXO4sydSKDG@NJusLP408U8R1ZRS2aDZMy7wXeHnyl7tRfQv8PVaEMKF4HY1WS@Qk758I8YNU2cW@yarYwh/n5at3FeUjnlDE0VnjQ4DIQ8dNu93VkI/XpqGiGLWn2KB1sCKwddl02x6M8WXMrOVg3akEc7B7JKVyI15eUC5qe7NUuntj0qHv1d6/3CDajE3lDVXosVmnqB3zTXRAETPUCwIXk4XmMpXhF1sQUCTEv@LVvgFto5AXbJoJCq3aUSM5YlRMIlSLGDrQBcLNGfwuxLUf7Lr9dOOuU03i/sFX4SKATOcugUfDhWqkaugO3cM9yjvxQthGY4WCk2KddQ/9I/6W37F3@pX2FhjY8jRPDlhwTNT70A5wGMPs5OgBw8xdtRzM1vkhKVzPYjEGis9s7nZ5uPrD28vM/loJTcFuIjBR4y@gZVx8Exm9gRGjoAEpPSKi68bXGwucF6kj8AVd1xWzMlXM4bCZQX9LEmGJPUPMD2EadFCyJPw99MpDETj99ug23Vc34V3MuQZWiE9nqBBJKlxAOoSSVqCfWkabEWJQJ8kh76UzDtzwaBfKvofBHCVshH7T4QJ7ZDhgD6JARxvgMsYOiWkNEtrhNkMj@B5XoU3v@fIbuQNXHlkjybyS/huOPCwF1dzUPrzAxhFlufD9ba0EmB6xY7L9JrDLlPCzHp9hrWQZSpFUtorlbd3S2UkxJZk8vr8pFlPvxoW3Ay4T/93/tNV0@jQHw4SAB98jokEXoc7GvzhUJikB3NbQ07mdVGYTa3xI8SgMUVp5qbo06@iTvb/Cw)
## With comments
```
??.z
# number of X's, as literals branches
.a??X.z
# if not empty; then pop; else enter here
.a.c.Z??.z
# push while EOF
.a.w.i.c\001.+.a??.z
# pop; reverse; pop to heap; pop all to print; push heap; pop to print; exit
.as.v.t.p.m.o.d??.a
.a.A??.z
# if not empty; then pop; else enter here
.a.c.Z??.z
# cat; as in my previous post
.a.w.o.i.c\001.+.a.d??.z
.a.A??.z
# and finally
.a.w.i.c\001.+.a.s.t.v.m.pX
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~112~~ 75 bytes
```
+<,[>[>+<-],]+>[-[<<.[-]<[<]>[.[-]>]]<[-<<[<]>[.>]]>]<[-<[<]>>[.>]<[<]>.<]+
```
[Try it online!](https://tio.run/##LchLCoAwDEXRreg4TVfwyNgdOAgZ@AWxWCi4/tgWZ/fctSzXc77b7U4IKioEtmAkygpEZYPCRFuJVTD@USXdjd29IozcpyOlPMy5pH38AA "brainfuck – Try It Online")
[!Try it online](https://tio.run/##LchLCoAwDEXRreg4TVfwyNgdOAgZ@AWxWCi4/tgWZ/fctSzXc77b7U6EoKJCYAtGoqxAVDYoTLSVWAXjH1XS3djdK8LcpyOlPMy5pH38AA "brainfuck – Try It Online")
[ry it online!T](https://tio.run/##LchLCoAwDEXRreg4TVfwyNgdOAgZ@AWxWCi4/tgWZ/fctSzXc77b7Y6gokJgC0airEBUNihMtJVYBeMfVdLd2N0rwojcpyOlPMy5pH38AA "brainfuck – Try It Online")
] |
[Question]
[
Banknotes in many countries come in denominations of 1,2,5,10,20,50,100,200,500,1000, etc. That is, one of \$ \{ 1,2,5\} \$ times a power of \$10\$. This is OEIS [A051109](https://oeis.org/A051109), except we'll extend the sequence to bigger values.
Given a positive integer as the input, the program should output the largest bank note that is less than or equal to the input. The input will be less than \$2^{63}\$.
Examples:
```
1 => 1
2 => 2
3 => 2
5 => 5
9 => 5
42 => 20
49 => 20
50 => 50
99 => 50
100 => 100
729871 => 500000
3789345345234 => 2000000000000
999999999999999999 => 500000000000000000
```
[Answer]
# [Python 2](https://docs.python.org/2/), 39 bytes
```
f=lambda n:n>9and 10*f(n/10)or 5>>5/-~n
```
[Try it online!](https://tio.run/##NYyxCoMwGAZ3n@IbTRoxfyFQA@ZFSocUGxXaTwkuXXz1NEu3u@Fu/x7LxmspaXzHz3OKoGcYIieI1allL1ZtGS4E13cnS6pCrESOnF@tGLGicMHd6RpouXVi8OeHb7DnlQdoUGeq/AA "Python 2 – Try It Online")
[Answer]
# [Perl 5](https://www.perl.org/) `-p`, ~~24~~ ~~20~~ 19 bytes
*Credit to @DomHastings for shortening this entry.*
```
s/\B./0/g;y;3-9;225
```
[Try it online!](https://tio.run/##K0gtyjH9/79YP8ZJT99AP9260tpY19LayAgoaGZu8S@/oCQzP6/4v26BGwA "Perl 5 – Try It Online")
[Answer]
# [Python 2](https://docs.python.org/2/), 38 bytes
```
lambda a,*b:`5>>5/-~int(a)`+"0"*len(b)
```
[Try it online!](https://tio.run/##ZY3NbsMgEITv@xQrn2zXTfEPcoiEn6SH4BorSBgjoFJyyau7@Kdqq46QvmWGHewj3GZTLSN/X7SY@kGgKPL@cqVdR99en8qEVGTXl4QkuZYm7bNFTXZ2Af3DA4yzQ62MRGVW4@TDoMwF0BQo71Z@BDkgx0nY1AcXU6dssS2cvNUqpAnvkiwDdNJ/6hCfjmlu4t26@PHhcv5dVRzOUiLvsIRqRQX1DrqCAtvR7CGBhh0DJVtCgLFjKMlmRUBbsXNb7v4qqNszqxsaT1U3e8MvxY5/@ln@oy8 "Python 2 – Try It Online")
A function that takes in the number as characters, and returns a numeric string.
Use [xnor's formula](https://codegolf.stackexchange.com/a/210684/92237) to get from a digit to 1, 2, or 5.
[Answer]
# [Raku](https://github.com/nxadm/rakudo-pkg), 30 bytes
```
{first /^(1|2|5)0*$/,($_...1)}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/Oi2zqLhEQT9Ow7DGqMZU00BLRV9HQyVeT0/PULP2f2FpZmpJTqVCcWKlgh5QQ1p@kUJOZl5q8X9DLiMuYy5TLksuEyMuE0suUwMuS0suQwMDAA "Perl 6 – Try It Online")
Counts down from the input, finding the first number that is a 1,2 or a 5 followed by only zeroes
[Answer]
# [J](http://jsoftware.com/), 26 bytes
```
(>:{:@#])1 2 5*<.&.(10&^.)
```
[Try it online!](https://tio.run/##ZYvNCoMwEITvPsVgQZNil/wSE9oiCD315F2PCr5CHz7d7bXLfPAx7Jy1pX7Ho6DHAIPC3Ajz8n5V9SyfMl1WbeEQr3fqSFnTbaSrrods1LDr5oBlHOOZyGQmSBHEopFKzBrR5PKYZOLTmH2IHOfD7@fvvg "J – Try It Online")
### How it works
```
(>:{:@#])1 2 5*<.&.(10&^.) 250
(10&^.) logarithm to base 10 3.x
<.&. and floor 3
(10&^.) and reverse the logarithm: 100
1 2 5* 1 2 5 times that: 100 200 500
(>: ) input greater-equal list? 1 1 0
#] take from list: 100 200
{:@ last element 200
```
[Answer]
# [R](https://www.r-project.org/), ~~51~~ 47 bytes
Golfed down 4 bytes by Giuseppe.
```
function(x,z=c(5,2,1)*10^nchar(x)/10)z[z<=x][1]
```
[Try it online!](https://tio.run/##Zc7hCoMgEAfw73uKg33REczTpIT5JNGggjYZKIhB9PKtqWPF/gjyO@8O/dp39gV6HSc7BOMsmYtFD0QWvEB6QXa3w7PzZKZXZHRplpue2wbbOEaQgtaApwgewRPEHjJCJqg9yjzEMtWBkqXeTKUORJaetzsVKq7qCnPPJ/krVa1EKbfDRZn37/Ld/RcK5@Ac9OYBo/PQWTA2wG/7Iesb "R – Try It Online")
[Answer]
# [Rockstar](https://codewithrockstar.com/online), 187 bytes
```
Listen to B
cast B at 0 into C
D is 5
E is 2
F is 1
let G be F
if C is as strong as E
let G be E
if C is as strong as D
let G be D
while B is as strong as 10
let B be B over 10
let G be G of 10
say G
```
Ungolfed and a bit more Rockstarish (yes this is valid syntax)
```
sunset was spellbound
god was a roundabout
Listen to the devil
cast the devil at sunset into the storm
(The kids are young don't let em grow up too fast)
Tommy is 5
Jimmy is 2
Alice is 1
(My kids are my heroes)
let my Hero be Alice
if the storm is as strong as Jimmy
let my Hero be Jimmy
if the storm is as strong as Tommy
let my Hero be Tommy
while the devil is as strong as god
let the devil be the devil over god
let my hero be my hero of god
say my hero
```
First time ever using this language, just having a bit of fun
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 12 bytes
```
⭆S∧¬κ÷⁵⊕÷⁵⊕ι
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRCO4BEil@yYWaHjmFZSWQLgamjoKjnkpGn75JRrZQLZnXolLZllmSqqGKYiTXJSam5pXkpqigVMiUxMCrP//Nza3sDQ2MQUiI2OT/7plOQA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
S Convert input to a string
⭆ Map over digits and join
κ Current index
¬ Is zero
∧ Boolean AND
ι Current digit
⊕ Incremented
⁵ Literal 5
÷ Integer divide
⊕ Incremented
⁵ Literal 5
÷ Integer divide
Implicitly print
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), ~~6~~ 5 bytes
```
Ω£İ₅←
```
[Try it online!](https://tio.run/##yygtzv7//9zKQ4uPbHjU1PqobcL///9NLM3NAA "Husk – Try It Online")
## Explanation
It's basically a built-in.
```
Ω£İ₅← Implicit input.
← Decrement
Ω until
£ is an element of
İ₅ Infinite list of powers of 10 and multiples by 2 or 5:
[1,2,5,10,20,50,100,200,500,..]
```
Here's a more interesting 10-byte solution that avoids `İ₅`:
```
Ωö€Ḋ10d↔d←
```
[Try it online!](https://tio.run/##yygtzv7//9zKw9seNa15uKPL0CDlUdsUIJ7w//9/E0tzMwA) Explained:
```
Ωö€Ḋ10d↔d← Implicit input.
← Decrement
Ω until
ö composition of 4 functions:
d number to digits,
↔ reverse,
d back to number,
€ is an element of
Ḋ list of divisors of
10 10 (so 1, 2, 5 or 10, and the last one is impossible).
```
[Answer]
# [JavaScript](https://v8.dev/), 34 bytes
```
f=n=>n<2?1:n<5?2:n<10?5:10*f(n/10)
```
[Try it online!](https://tio.run/##bY7dCsIwDEbvfZJmoCb9oe3Y7LOMYUUZrTjZ69fdjs8QcnE4HPKatmmdP8/397yF1vJYxlsZdJK@DC7p/Qon1wt3WZWrMLW5lrUu98tSHyorITodiQZigDggEYjFkEXLMabQEkbN6xg8vm98iMa6fbWxf9owRO0H "JavaScript (V8) – Try It Online")
A recursive function that checks each denomination, otherwise divides by 10 and tries again.
Note that the last test case fails because it exceeds the maximum safe integer.
-6 bytes don't need to check `<1`
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), 17 [bytes](https://github.com/abrudz/SBCS)
```
10⊥≢↑'125'(⍎⍸⊃⊣)⊃
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///qG@qW9CjtgmGRhbmXEBOQACQY2zy39DgUdfSR52LHrVNVDc0MlXXeNTb96h3x6Ou5kddizWB1P80oEKQYFfzofXGQGVAzcFBzkAyxMMz@H/aoRUKj3qnAklDBSMFYwVTBUsFQ0sFEyMFE0sFUwMFSyDXwEBB49B6Q21DAy1DC00FDQgNAA "APL (Dyalog Unicode) – Try It Online")
A tacit function that takes input as a string, and returns an integer. `⎕FR←1287` is needed to get exact results for high numbers.
### How it works
```
10⊥≢↑'125'(⍎⍸⊃⊣)⊃ ⍝ Input: a string of digits without leading zeros
⊃ ⍝ First char
'125'( ⍸ ) ⍝ Interval index into '125'; 1→1; 2-4→2; 5-9→3
⊃⊣ ⍝ The char at the above index of '125'
⍎ ⍝ Eval it, so it becomes numeric
≢↑ ⍝ Pad with zeros to the length of the input
10⊥ ⍝ Convert from base 10 digits to integer
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~12~~ 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I/O as an integer.
```
@AvXìw}aaU
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=QEF2WOx3fWFhVQ&input=NzI5ODcx)
---
## Alternative (w/ [`-m` flag](https://codegolf.meta.stackexchange.com/a/14339/)), 10 bytes
I/O as a string or an array of digits. Credit, again, to xnor for the formula to find the first digit.
```
V?T:5Á5/°U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LW0&code=Vj9UOjXBNS%2bwVQ&input=IjcyOTg3MSI)
---
## Original (with `-h` flag), 12 bytes
I/O as integer strings.
```
#}ì úTUl)f§U
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&flags=LWg&code=I33sIPpUVWwpZqdV&input=IjcyOTg3MSI)
```
#}ì úTUl)f§U :Implicit input of integer string U
#} :125
ì :To digit array
ú :Right pad each
T : With 0
Ul : To the length of U
) :End padding
f :Filter
§U : Less than or equal to U
:Implicit output of last element
```
[Answer]
# [Pyth](https://github.com/isaacg1/pyth), ~~26 bytes~~ 21 bytes
```
efgQTm*d^Ttl+Qk[1 2 5
```
[Try it online!](https://tio.run/##K6gsyfj/PzUtPTAkVyslLqQkRzswO9pQwUjB9P9/E0tLAA "Pyth – Try It Online")
*Old Solution:*
```
V60 aY*h^%N3 2^T/N3;efgQTY
```
Explanation:
Using `((n % 3) ** 2 + 1) * 10**int(n/3)` To calculate a the banknote for n in the series.
```
V60 aY*h^%N3 2^T/N3;efgQTY
V60 Looping 60 times.
*h^%N3 2^T/N3 Calculate the current iterations banknote value
aY Append it to list Y
fgQTY Filter the list for all values less than or equal to input
e Grab the last value in the list.
```
[Try it online!](https://tio.run/##K6gsyfj/P8zMQCExUisjTtXPWMEoLkTfz9g6NS09MCTy/38TS0sA "Pyth – Try It Online")
[Answer]
# [Husk](https://github.com/barbuz/Husk), 14 bytes
```
:ḟ≤←¹s521mK'0t
```
[Try it online!](https://tio.run/##yygtzv7/3@rhjvmPOpc8aptwaGexqZFhrre6Qcn///@VTA2VAA "Husk – Try It Online")
This is my first Husk answer.
In Haskell this would look like
```
\x -> (find (<= head x) (show 521)) : (map (const '0') (tail x))
```
[Answer]
# [JavaScript (V8)](https://v8.dev/), 62 bytes
```
n=>(e=Math.log10(n)|0,x=n/(y=10**e),y*((x>=5)*5||(x>=2)*2||1))
```
[Try it online!](https://tio.run/##TcxNCoMwFATgfU/yXrBtfkmyeN7AQ4SiraWkokEUcvdUF4XALL6ZxbzDGpbHPE7puroyUInUQk9dSK/b5/sUHCJm3mwU77CT4Iz12OwMYGvJIDM5n5LIZM4CsUzzGBMMoBAvf5vKvrKWVbHSOyuqQVnnlTZHpNLH8w8 "JavaScript (V8) – Try It Online")
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), 15 bytes
```
T`3-9`225
\B.
0
```
[Try it online!](https://tio.run/##ZckrEoAwEARRP3eB2uynkrGcAYlIBAKDoLj/Ek/Xc/2c73WPzL3bwq4aOLYVklmgMAQIVzgRAhJFBFXZaoHVRvOY1Hy@Xx8 "Retina 0.8.2 – Try It Online") Link includes test cases. Explanation:
```
T`3-9`225
```
Change `3` and `4` to `2`, and higher digits to `5`.
```
\B.
0
```
Change all digits after the first to `0`.
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~13~~ ~~12~~ ~~10~~ 9 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
LR.ΔRTÑQO
```
-2 bytes by porting [*@JoKing*'s Raku answer](https://codegolf.stackexchange.com/a/210687/52210), so make sure to upvote him as well!
-1 byte by taking inspiration from [*@Zgarb*'s second Husk answer](https://codegolf.stackexchange.com/a/210713/52210).
[Try it online](https://tio.run/##yy9OTMpM/f/fJ0jv3JSgkMMTA/3//zexBAA) or [verify almost all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfaXLoZX/fYL0zk0JCjk8MdD/f63O/2hDHSMdYx1THUsdEyMdE0sdUwMdS0sdQwMDHTNzCx1zI0sL81gA) (times out for the larger test cases).
**Explanation:**
```
L # Push a list in the range [1, (implicit) input-integer]
R # Reverse it
.Δ # Find the first value which is truthy for:
R # Reverse the integer
# i.e. 200 → "002"
T # Push 10
Ñ # Pop 10 and push its divisors: [1,2,5,10]
Q # Check for each if it's equal to the reversed integer
# "002" → [0,1,0,0]
O # Take the sum of those checks (only 0 or 1 will be truthy at a time,
# and 10 is never truthy because no integer had leading 0s)
# (after which the result is output implicitly)
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/brainfuck), ~~78 69~~ 66 bytes
```
-[<+>>+>+<<-----],++<[->-<]>[-[-[-[>+++<[-]]]]>+<]>--.>--->,[<.>,]
```
[Try it online!](https://tio.run/##HYpBCoAwEAMftE0PtqLCko8se1BBEMGD4PvX2knmErI963kf735FwFRIoajix5OIGgh1GnooffJGuzmB3ASTaWbyiDLNS6lj61DqBw "brainfuck – Try It Online")
-9 bytes by rearranging the variables and adding the output directly to the ASCII value.
-3 bytes by calculating and triplicating the constants in a single loop
```
[tape: 51, input (of first digit), output + 51, 51, input (of other digits)]
-[<+>>+>+<<-----] 51 0 51 51
,++<[->-<] input minus 49("1")
>[ if not input = 1
-[-[-[ if not input between 2 and 4
>+++ add 3 to output (will add another 1 later)
<[-] set input = 0
]]] exit if
>+< inc output ("4" if input between "2" and "4" | "7" if input not between "1" and "4")
]
>--. decrement output by 2 and print it
>--- set third 51 to 48("0")
>,[ while more characters in input
<.> print "0"
, read next input char
]
```
[Answer]
# [Rockstar](https://codewithrockstar.com/), ~~163~~ ... ~~119~~ ~~117~~ 97 bytes
```
listen to N
cut N
roll N in D
X's 5
until X's as low as D
let X be/2
turn down X
say X*10*N or X
```
[Try it](https://codewithrockstar.com/online) (Code will need to be pasted in)
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 45 bytes
```
Max@Select[{1,2,5}10^⌊Log10[s=#]⌋,#<=s&]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n2773zexwiE4NSc1uSS62lDHSMe01tAg7lFPl09@uqFBdLGtcuyjnm4dZRvbYrVYtf8BRZl5JQr6Dun6DmDVxjqmOpY6JkY6JpY6pgY6lpY6hgYGOuZGlhbmhjrG5haWxiamQGRkbAKUQwe1//8DAA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~40 39~~ 32 bytes
```
f(n){n=n>9?10*f(n/10):5>>5/-~n;}
```
[Try it online!](https://tio.run/##dVHNboMwDL7zFBZSJaBBhJ@IMgY7THuKwaGC0CFtoSIc0BB7dWYCbam6WXGSz/4cO3Zhn4pimipDmINIRBq9uNRC5LjUfGJpyhz7R8TjVIsOvo61MExt0ABlNnRcdvI9hwQGl4BHwCfACEQEAgQBnowixNOleAm96BC6YwyOBV3TwGcjTlA1rXoLg8ND5AcMl@cHc9iDYKjlXLPz/syLjpfbAjxVAC6PLspWVQUwOgv5pwLkb@TCvpNbAcXHsbWgXXLrWf/mZX30isp0Alvs62OsqZA5jzEnqkXJe4yj8Xp9Bll/86YyVENNZ0XWAmPY7xXPhKX1lwYIfGMZgXLn8Z2Xo/faor8IEgnz3G/Wc4v2ytB3Jdgp4L6TmcD/CAKS4GdlkvB85Y/aOP0C "C (gcc) – Try It Online")
Recursively calls itself, multiplying the returned value by \$10\$ and chopping the last digit off \$n\$ until \$n\$ is \$9\$ or less. Then returns one of \$\{1,2,5\}\$, whichever lays just below or equal to \$n\$ using [xnor](https://codegolf.stackexchange.com/users/20260/xnor)'s [formula](https://codegolf.stackexchange.com/a/210684/9481).
[Answer]
# [sed 4.2.2](https://www.gnu.org/software/sed/), 25
* Thanks to @David258 for suggesting the use of `2g` to start replacing at the 2nd match and saving a byte.
Pretty much the same as the [perl answer](https://codegolf.stackexchange.com/a/210701/11259). Sadly the sed `y` command is not as flexible.
```
s/./0/2g
y/346789/225555/
```
[Try it online!](https://tio.run/##XYqxEYAwDMT6HwY7b5vE@8AxQCqmN67RqZP2fVVtOUSFD14xP@dKIaORqgHCEEg44YlQZGKoYjLXHLDezaOlebc/Hw "sed 4.2.2 – Try It Online")
[Answer]
# [Brain-Flak](https://github.com/Flakheads/BrainHack), 116 bytes
```
({}<<>(((((()()()){}){}){}){})<>{{}<>(({}))<>}>)({}<>[({})<((((((((({}<>())())))()()())))))>[]]){({}()<{}>)}{}({}<>)
```
[Try it online!](https://tio.run/##RUy7CoAwDPwXp94gVJ2EEPA7SofqoggOrqHfHpOieMlwxz3WuxzXXrZTNUgl4tAAP0j9n1jMN9u4icrwPCfXFD60CLwLvCMOTjlDzA0gsWo15lGoar9oNw/jFGPsHg "Brain-Flak (BrainHack) – Try It Online")
This uses string IO. Meaning input is expected as a string and output is produced as a string. This works by replacing all the digits other than the lead with zeros and then mapping the lead to the three results.
Rather predictably for Brain-Flak the two biggest sinks are
1. Producing the ascii code for `0`
2. Mapping 9 different values to arbitrary outputs.
The first part which replaces everything with zeros is:
```
({}<<>(((((()()()){}){}){}){})<>{{}<>(({}))<>}>)
```
With most of it being the code for point 1:
```
(((((()()()){}){}){}){})
```
[Answer]
# [Pip](https://github.com/dloscutoff/pip), 25 bytes
```
@(_<=aFI[5 2o]*t**(#a-1))
```
A simple solution with filtering.
## Explanation
```
@(_<=aFI[5 2o]*t**(#a-1))
t**(#a-1) ten to the power (length of input - 1)
[5 2o]* times the list [5,2,1]
_<=aFI Filtered by lambda: element <= input?
@( ) first element of filtered list
```
[Try it online!](https://tio.run/##K8gs@P/fQSPexjbRzTPaVMEoP1arREtLQzlR11BT8////5aYAAA "Pip – Try It Online")
[Answer]
# [Octave](https://www.gnu.org/software/octave/), 43 bytes
```
@(x)y((y=[5 2 1]*10^floor(log10(x)))<=x)(1)
```
[Try it online!](https://tio.run/##dVBNS8QwEL37K@YiNOKWpB@kAQv@AI/eRCHtTrZZY1PaZN3@@tqkHgqrQ3iZzLx5b4htnbzgouo0TZfn5ErmJJnrtxIyYO8PjH4oY@2YGHtidO0S8lRfScLIola4U0kWIA9QBhABilgsYl7SWI45o/HBM1HxOJzzSuRFuZ4sLyKPUs6EyMqCF3S9CdzDixxPODno/VeDI7hOOhjRaNmYGb7t@DnBAY4ewVkYRmz1pG0PVsHR@sZgGu33UVa5@E9Yts5LsxM@@5XRyWHAfgoODYL8Vd4mNmKvWzTzrVeI4PXa6QmU1Ga6XfUA@z/@Y57UG4Hx9LZZM/4IjXeAF2m8dBjXZNXyAw "Octave – Try It Online")
This converts the number to the highest power of 10 less than the number, then multiplies by 5, 2, and 1 to get the possible notes that could be involved. It then finds the largest note still less than the number.
---
It should be noted that Octave is very doubley and not really friends with 64bit integers. As a result numbers larger than 2^53 don't reliably work due to double precision issues. This may invalidate the answer.
---
---
The below answer is valid only if it is allowed to take the input as a string, and return a string, overcoming the double precision issues.
# [Octave](https://www.gnu.org/software/octave/), 41 bytes
```
@(x,y='521')[y(x(1)>=y)(1) 48+x(2:end)*0]
```
[Try it online!](https://tio.run/##y08uSSxL/Z9mq6en999Bo0Kn0lbd1MhQXTO6UqNCw1DTzrZSE0gpmFhoV2gYWaXmpWhqGcT@T9NQB6rhAlJGEMoYQplCKEsIZQKVNIHyTQ2g0lC@oQFUwNzI0sIcaqCxuYWlsYkpEBkZm8DUowN1zf8A "Octave – Try It Online")
[Answer]
# JavaScript, ~~30~~ 29 bytes
I/O as an array of digits.
Uses xnor's formula for the first digit so please be sure to upvote him if you're upvoting this.
```
a=>a.map((x,y)=>y?0:5>>5/-~x)
```
[Try it online!](https://tio.run/##ZY5LCoMwFAD3PYVkldBnGvNBU0h6EBEM0hTFGtEicePVU@m2w@xnBre5tVv6@ZNvVfImOWMdfbsZ4wg7MXZ/sLuyVt3yI5Lkw4JjFnxWF8BBgAINkoPUoBhoDQVjUHJdlQWIstJCqlMuJCD9B2rIpQvTGsYnHcMLe1xTSuMVoeY3EI09ziahQ@intiXpCw)
[Answer]
# [Bash](https://www.gnu.org/software/bash/), ~~39~~ 36 bytes
Saved 3 bytes thanks to [Digital Trauma](https://codegolf.stackexchange.com/users/11259/digital-trauma)!!!
```
echo $[(5>>5/-~${1::1})*10**~-${#1}]
```
[Try it online!](https://tio.run/##bY7haoMwFIX/@xRnWQYqyJJosGlR9h7WH5tGFErsGgcDsa/uoq6sYztcws13Lufet1fbzo0fYJx11faghS/zXD5HVzry/Z5PQchZGF4jOj7yqZwnb9B2sJnPIRBDQiERSBQkg1LgjCEVapdyxOlOxYl0JeLEeX8UePrzrKtB11uacGkSgi0l11rSJFvk2J2@4S8FXtNf0KEzIHR8WK8sXsqJHFD3HpxMRscN066cVqQduh3xQ21G/QbUBOvvfOnM0IA81YhyuJc4C9SuZtegKNxCTRDpd9dYgrI8DK02q38fcPwQKY@PhmyrT1b/O5JUt5Gm8@re6PkL "Bash – Try It Online")
Port of my [C answer](https://codegolf.stackexchange.com/a/210689/9481).
### Explanation:
```
echo $[(5>>5/-~${1::1})*10**~-${#1}]
$[ ] # Evaluate what's inside as an
# arithmetic expression
(5>> # Shift 5 to the right by
5/ # 5 integally divided by
-~ # 1 plus
${1 # the first argument's
::1}) # substring starting at 0 of length 1
* # Times
10** # 10 to the power of
${#1} # the length of the first agument
~- # minus 1
```
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 25 bytes
```
{≥.~×Ċ{~^h10}ᵗh∈125∧≜}ᵘot
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/pfXa6koGunoFRu/6htw6Ompoe7Omsfbp3wv/pR51K9usPTj3RV18VlGBoABadnPOroMDQyfdSx/FHnHKDAjPyS//@jDXWMdIx1THUsdUyMdEwsdUwNdCwtdQwNDGIB "Brachylog – Try It Online")
### How it works
```
{≥.~×Ċ{~^h10}ᵗh∈125∧≜}ᵘot
{ }ᵘ find all unique outputs of …
≥. the output is less-equal the input,
~×Ċ and two numbers which product is the output, where
{~^h10}ᵗ the 2. number can be obtained by 10^k,
h∈125 the 1. number is one of 1, 2, 5
∧≜ return the output with the constrains solved
ot order all possible banknotes and take the largest
```
[Answer]
# x86-16 machine code, IBM PC DOS, ~~34~~ ~~31~~ 30 bytes
```
00000000: d1ee ad8a c849 b830 0acd 10ac 3c35 7c04 .....I.0....<5|.
00000010: b035 eb07 3c32 b032 7d01 48cd 29c3 .5..<2.2}.H.).
```
Listing:
```
D1 EE SHR SI, 1 ; SI to DOS PSP
AD LODSW ; AL = input length
8A C8 MOV CL, AL ; input length into CL
49 DEC CX ; remove leading space from length
B8 0A30 MOV AX, 0A30H ; AH = 0AH, AL = '0'
CD 10 INT 10H ; display '0' CX number of times
AC LODSB ; AL = first digit
3C 35 CMP AL, '5' ; is it less than five?
7C 04 JL LT_FIVE ; if so, check two
B0 35 MOV AL, '5' ; otherwise it's a 5 spot
EB 07 JMP DONE ; jump to display
LT_FIVE:
3C 32 CMP AL, '2' ; is it less than two?
B0 32 MOV AL, '2' ; if not, it's a 2
7D 01 JGE DONE ; jump to display
48 DEC AX ; otherwise it's a '1'
DONE:
CD 29 INT 29H ; display first digit of denomination
C3 RET ; return to DOS
```
[Try it online!](http://twt86.co/?c=0e6tishJuDAKzRCsPDV8BLA16wc8MrAyfQFIzSnD) (type `ASM 1`, `ASM 9`, etc)
Looks at the first digit and determines if it's less than `5` or `2` and resets it to the appropriate note digit. Then displays the remaining length of the input string as `0`'s.
Standalone PC DOS executable COM program. Input via command line, output to console.
[](https://i.stack.imgur.com/rzzf9.png)
[Answer]
# [Thunno 2](https://github.com/Thunno/Thunno2) `t`, 5 [bytes](https://github.com/Thunno/Thunno2/blob/main/docs/codepage.md)
```
ærTFƇ
```
[Try it online!](https://Not-Thonnu.github.io/run#aGVhZGVyPSZjb2RlPSVDMyVBNnJURiVDNiU4NyZmb290ZXI9JmlucHV0PTcyOTg3MSZmbGFncz10)
Note: this is pretty slow (the 729871 case takes ~5s on my computer and ~10s on the online interpreter) because it checks every number in the range \$[1 .. \text{input}]\$.
#### Explanation
```
ærTFƇ # Implicit input
æ # Filter [1..input] by:
r # Reverse it
TF # Push the factors of 10
# -> [1, 2, 5, 10]
Ƈ # And check if the reversed
# integer is in this list
# Implicit output of last
# (largest) integer
```
] |
[Question]
[
In a single file, write a program that requires no input and produces no output. When run it should reverse the name of the file it is contained in, **regardless of what the name is**, without altering the code or producing other lasting side effects.
Any way of achieving this is fine. It only matters that once the program is run the only lasting change is that its file name has been reversed. e.g. no new files should be in the directory.
Running the program again should reverse the name back. Indeed, the program should be able to be run arbitrarily many times.
For the purposes of this challenge:
* You may assume filenames are always strings of lowercase letters (a-z) between 1 and 127 characters long. (If your language requires files to have extensions to run then just reverse the part before the extension, e.g. `mycode.bat` → `edocym.bat`.)
* You may assume the code file is in a directory by itself so it will not have naming conflicts (except with itself).
* You may **not** assume the filename is not a palindrome, i.e. the same when reversed. Filenames that are palindromes should work just as well as those that aren't.
* You may read your file's contents or metadata. There are no [quine](/questions/tagged/quine "show questions tagged 'quine'") restrictions here.
* You may assume your program will be run on a particular, modern, commonplace operating system (e.g. Windows/Linux), since not all shells have the same command set.
>
> As a concrete example, say you have a Python program in a file called
> `mycode` in its own directory. Running
>
>
>
> ```
> python mycode
>
> ```
>
> in the terminal should result in the filename being reversed to
> `edocym`. The file `edocym` should be alone in its directory - no file
> named `mycode` should exist anymore. Running
>
>
>
> ```
> python edocym
>
> ```
>
> will reverse the name back to `mycode`, at which point the process can
> be repeated indefinitely.
>
>
> If the same Python file was renamed `racecar` (without changing the code) and then run
>
>
>
> ```
> python racecar
>
> ```
>
> nothing should visibly change since "racecar" is a palindrome.
> That same goes if the filename were, say, `a` or `xx`.
>
>
>
**The shortest code in bytes wins. Tiebreaker is higher voted answer.**
[Answer]
# Bash + common linux utils, 13 bytes
My method is similar to @DigitalTrauma's but a bit shorter due to the pipe with `ls`:
```
mv * `ls|rev`
```
[Answer]
## C#, 153 bytes
```
void f(){var x=System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name;File.Move(x,new string(x.Reverse().ToArray()).Substring(4)+".exe");}
```
OO is cool and all untill you have a variable defined:
**System.Reflection.Assembly.GetExecutingAssembly().ManifestModule.Name**
thats just mean
[Answer]
# Bash + common linux utils, 15
* 1 byte saved thanks to @Dennis
Assumes that the script is in a directory by itself.
```
mv * `rev<<<$0`
```
[Answer]
# Julia, 51 bytes
```
d,f=splitdir(@__FILE__)
cd(d)do
mv(f,reverse(f))end
```
This program should be operating system agnostic, though it was only tested on OS X.
Ungolfed:
```
# Get the directory and file name of the current source file
d, f = splitdir(@__FILE__)
# Change the working directory temporarily to d
cd(d) do
# Overwrite the file with the reverse of its name
mv(f, reverse(f))
end
```
[Answer]
# MATLAB, ~~50~~ 46 bytes
```
e='.m';x=mfilename;movefile([x e],[flip(x) e])
```
*Thanks to @Suever for removing 4 bytes and for the testing!*
Tested on OS X El Capitan and Debian Jessie, both with Matlab version R2014a.
On Windows a flag `'f'` is needed ( `e='.m';x=mfilename;movefile([x e],[flip(x) e]),'f'`) to change file name while the file is being used.
### How it works
```
e='.m'; % Store file extension '.m' in variable `e`
x=mfilename; % Get name of file being run, without the extension
movefile([x e],[flip(x) e]) % Move (rename) file. `flip` is used for reversing the
% name without extension. [...] is (string) concatenation
```
[Answer]
## Batch, 109 bytes
```
@echo off
set f=%0
set r=
:l
set r=%f:~0,1%%r%
set f=%f:~1%
if not .%f%==. goto l
ren %0.bat %r%.bat
```
Note 1: Batch files must end in `.bat`; it is assumed that the batch file is executed by its name without extension, and that the `.bat` is not to be reversed. For example, `reverse` would attempt to rename `reverse.bat` to `esrever.bat`.
Note 2: `CMD.EXE` errors out after renaming the batch file. (`COMMAND.COM` wouldn't, except that it's incapable of string manipulation in the first place.)
Edit: Saved 2 bytes by using the guarantee that the file name is alphabetic (based on @CᴏɴᴏʀO'Bʀɪᴇɴ's comment).
[Answer]
# C, 102 bytes
```
main(c,v)char**v;{char*b=strdup(*v),*n=strrchr(*v,47),*t=strchr(b,0);for(;*++n;*--t=*n);rename(*v,b);}
```
Breakdown:
```
// No #include lines required (for GCC at least)
main(c,v)char**v;{ // K&R style function to save 2 bytes
char*b=strdup(*v), // Duplicate args[0] (script path)
*n=strrchr(*v,47), // Find last "/" in input
*t=strchr(b,0); // Go to end of output string
for(;*++n;*--t=*n); // Reverse input into output character-by-character
rename(*v,b); // Rename the file
} // Implicit return 0
```
Finally a challenge where C isn't (quite so hopelessly) uncompetitive!
---
If we take "You can assume the working directory of the shell will be the folder the file is in" to mean that the program will always be invoked as `./myexecutable`, we can simplify `*n=strrchr(*v,47)` to `*n=*v+1` to save 10 characters, but this isn't entirely valid (it could be invoked as `././myexecutable`, for example).
---
Also if you want to keep a file extension (e.g. ".out") in-tact, you can change `*t=strchr(b,0)` to `*t=strrchr(b,46)`, costing 2 bytes. Not required though.
[Answer]
## Ruby, 24 bytes
```
File.rename$0,$0.reverse
```
Fairly self-explanatory. (`$0` is the name of the file being executed.)
Run with `ruby whatever` with a working directory of the directory that contains the file.
[Answer]
# [Vitsy](http://esolangs.org/wiki/Vitsy) + \*sh, 15 bytes
```
iG:`?r.iG' mr',
```
### Explanation
```
iG:`?r.iG' mr',
i Push -1 to the stack. (this assumes that no arguments are passed)
G Get the use name of the class specified by the top item of the
stack. (-1 refers to the origin class, so this class)
: Duplicate stack and jump to it.
` Read a file with the current stack as its name, replacing the stack
with the file's contents.
? Shift one stack to the right.
r Reverse the current stack.
. Write a file with the name specified by the top stack and the
contents as the second-to-top stack.
iG Get the name of the current class again.
' mr' Push 'rm ' to the stack.
, Execute the current stack as a command.
```
Note that this submission must use the non-safe version of Vitsy (cannot be done on Try It Online!)
[Answer]
# Perl 5, 18 bytes
A bit like the Ruby one (run `perl nameofscript`):
```
rename$0,reverse$0
```
Taking a possible path into account is uglier (47 bytes)
```
($a,$b)=$0=~/(.*\/)?(.*)/;rename$0,$a.reverse$b
```
[Answer]
# [V](https://github.com/DJMcMayhem/V), ~~29~~ 26 bytes
```
:se ri
izyw:!mv z "
dd
```
Since this contains unprintables, here is a hex dump:
```
00000000: 3a73 6520 7269 0a69 127a 1b79 773a 216d :se ri.i.z.yw:!m
00000010: 7620 127a 2012 220a 6464 v .z .".dd
```
*Note:* this will not run on [v.tryitonline.net](http://v.tryitonline.net/) since TIO does not allow file access.
Explanation:
```
:se ri "Turn on 'reverse mode' (all text is inserted backwards)
i<C-r>z<esc> "Enter the path to the file in reverse
yw "Yank a word. This first word is the name we will save the new file as
"Run an "mv" in the terminal with the contents of register 'z' (the path to the file)
"And the contents of register '"' (the word we yanked)
:!mv <C-r>z <C-r>"
dd "Delete a line so that we don't have any text printed.
```
[Answer]
## Python 3, 105 bytes
```
import os;a=__file__.split('\\')[::-1][0].split('.');os.rename('.'.join(a),'.'.join([a[0][::-1],a[1]]))
```
-Alex.A removed 1 byte.
-Digital Trauma showed me os.rename() which took away 62 bytes.
-muddyfish removed 7 bytes.
[Answer]
# PHP, ~~84~~, ~~70~~, 54 bytes
```
rename($f=__FILE__,strrev(basename($f,$e='.php')).$e);
```
---
**EDIT:** removed 14 bytes thanks to `insertusernamehere` in the comments
---
**EDIT:** removed 16 bytes thanks to `Martijn` in the comments
[Answer]
## PowerShell, 39 bytes
```
mi *(-join((ls).name)[-5..-999]+'.ps1')
```
[Answer]
# [Python 2](https://docs.python.org/2/), 41 bytes
```
import os;s=__file__;os.rename(s,s[::-1])
```
[Demo on Bash.](https://tio.run/##S0oszvifnFiiYKdQUJSfXpSYy5VTzFVQWZKRn4dFJDexKD2/qAAo8v///8zcgvyiEoX8Yuti2/j4tMyc1Ph46/xivaLUvMTcVI1ineJoKytdw1hNAA "Bash – Try It Online")
Python really doesn't care the file extension, so we can just flip the entire file name.
[Answer]
# PHP, 31 bytes
Nothing much to explain I guess:
```
rename($x=$argv[0],strrev($x));
```
[Answer]
# [Perl 6](http://perl6.org), ~~70~~ 27 bytes
If it needed to work in a different working directory you would need something like this:
```
$_=$*PROGRAM;.rename: .basename.flip.IO.absolute: .absolute.IO.dirname
```
Since the working directory will be the same directory as the program it can be simplified to just:
```
$_=$*PROGRAM;.rename: .flip
```
### Explanation:
```
$_ = $*PROGRAM; # IO::Path object
$_.rename:
$_.basename
.flip # reverse characters
.IO # turn into an IO object (IO::Path)
.absolute: # turn it into an absolute path Str in the following dir
$_.absolute.IO.dirname
```
[Answer]
# JavaScript (Node), ~~108~~ ~~104~~ 68 bytes
36 bytes saved, thanks to Downgoat!
Windows version:
```
require("fs").rename(F=__filename,F.split(/.*\\|/).reverse().join``)
```
Other version:
```
require("fs").rename(F=__filename,F.split(/.*\/|/).reverse().join``)
```
[Answer]
# JavaScript ES6 (Node.js) 70 Bytes
No Regex Yay!
```
require("fs").rename(a=__filename,[...a].reverse().join``.split`/`[0])
```
Any help is appreciated
[Answer]
## PowerShell v4+, 68 bytes
```
$a,$b=($c=(ls).Name)-split'\.';mv $c "$(-join($a[$a.length..0])).$b"
```
Only works because the script is guaranteed to be in a directory all by itself. Performs an `ls` (alias for `Get-ChildItem`) and takes the `.Name` of the resultant object(s). We store that in `$c` and then `-split` it on literal period to get the filename and extension, and store those in `$a` and `$b`, respectively.
Next is the `mv` (alias for `Move-Item`) command, where we're moving `$c` to `$a`(reversed)`.$b`.
### Example
```
PS C:\Tools\Scripts\golfing\reverse> ls
Directory: C:\Tools\Scripts\golfing\reverse
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 6/13/2016 7:58 AM 88 reverse.ps1
PS C:\Tools\Scripts\golfing\reverse> .\reverse.ps1
PS C:\Tools\Scripts\golfing\reverse> ls
Directory: C:\Tools\Scripts\golfing\reverse
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 6/13/2016 7:58 AM 88 esrever.ps1
```
[Answer]
# Python (2.7 or 3.4+), 61 49 bytes
I believe this is close to the optimal Python solution:
```
import os;a=__file__;os.rename(a,a[-4::-1]+".py")
```
Inspired by `s4b3r6`'s answer, but uses list slicing instead of reverse, and saves `__file__` to a variable to save bytes when using it twice.
**Note:** This assumes that the filename is always `*.py`. A slightly more generic solution that can handle any two-character file extension would be to use `a[-3:]` to replace `".py"`, at the cost of 1 extra byte.
**Update:** Saved 12 bytes by using the list slicing trick `a[-4::-1]` to remove the file extension, instead of splitting and then reversing with `a.split(".")[0][::-1]`.
[Answer]
## Powershell, 112 bytes
I'm not going to beat the unix cmds, just adding my two pence for fun :-)
```
gci * | % { $n=($_.basename[-1..-(($_.basename).length)] -join “”)+$_.Extension; mv -Path $_.Fullname -Dest $n }
```
[Answer]
## PowerShell, 50 bytes
```
mv *(-join($f=(ls).BaseName)[$f.Length..0]+'.ps1')
```
There is only one file, so `mv *` shell wildcard will only have one result. The destination name is `(ls).basename` which lists all the files (alias for 'dir'), calls for the BaseName property - and since there's only one file, PowerShell will unpack the 1-item array into a string. Store that filename in `$f`, then index it with a countdown and `-join` the reversed characters back up into a string. Add the mandatory `.ps1` suffix.
[Answer]
# AutoIt, 45 bytes
```
$a=@ScriptName
FileMove($a,StringReverse($a))
```
[Answer]
# Python 2.7, 68 bytes
```
import os;a=__file__;os.rename(a,a.split("\\")[-1][:-3][::-1]+".py")
```
This is probably the best I can get it.
I just proved myself wrong.
[Answer]
# Python (2 & 3), 88 78 bytes
```
import os;os.rename(__file__,''.join(reversed(__file__.split(".")[0]))+".py"))
```
Exploits the fact that the filename is given by sys.argv (as the working directory is the folder the file is in), and makes use of os.rename. Annoyingly, reversed returns an iterator, so we have to use join.
Edit: Saved 10 bytes by using \_\_file\_\_ instead of sys.argv[0], as suggested by @muddyfish to @DigitalTrauma.
[Answer]
# tcl, 42
```
file rename $argv0 [string reverse $argv0]
```
[Answer]
# Visual Basic Script, 44 Bytes
```
WScript.Echo(StrReverse(WScript.ScriptName))
```
Example output for file called `reverse.vbs` (Run with cscript):
```
sbv.esrever
```
[Answer]
# [sfk](http://stahlworks.com/dev/swiss-file-knife.html), 83 bytes
```
list -maxfiles=1 . +setvar n +getvar n +swap +setvar m +ren -var . /#(n)/#(m)/ -yes
```
[Try it online!](https://tio.run/##K07L/v8/J7O4REE3N7EiLTMntdjWUEFPQbs4taQssUghT0E7Hc4qLk8sgMvkKmgXpeYp6ILYegr6yhp5mkAiV1NfQbcytfj/fwA "sfk – Try It Online")
[Answer]
# SmileBASIC 60 bytes
```
P$=PRGNAME$()FOR I=1-LEN(P$)TO.Q$=Q$+P$[-I]NEXT
RENAME P$,Q$
```
Alternative:
```
P$=PRGNAME$()T$=P$*1WHILE""<T$Q$=Q$+POP(T$)WEND
RENAME P$,Q$
```
] |
[Question]
[
What general tips do you have for golfing in Scala? I'm looking for ideas that can be applied to code golf problems in general that are at least somewhat specific to Scala (e.g. "remove comments" is not an answer). Please post one tip per answer.
[(This is a shameless copy of ... in Python)](https://codegolf.stackexchange.com/questions/54/tips-for-golfing-in-python)
[Answer]
The shortest way of repeating something is with `Seq.fill`.
```
1 to 10 map(_=>println("hi!")) // Wrong!
for(i<-1 to 10)println("hi!") // Wrong!
Seq.fill(10)(println("hi!")) // Right!
```
[Answer]
### suspicious identifier: ?
You can use ? as identifier:
```
val l=List(1,2,3)
val? =List(1,2,3)
```
Here it doesn't save you anything, because you can't stick it to the equal sign:
```
val ?=List(1,2,3) // illegal
```
But later on, it often saves one character, since you don't need a delimiter:
```
print(?size) // l.size needs a dot
def a(? :Int*)=(?,?tail).zipped.map(_-_)
```
However, it is often tricky to use:
```
print(?size)
3
print(?size-5)
<console>:12: error: Int does not take parameters
print(?size-5)
^
```
[Answer]
## Collections
The first choice for a random collection is often *List*. In many cases you can replace it with *Seq*, which saves one character instantan. :)
Instead of
```
val l=List(1,2,3)
val s=Seq(1,2,3)
```
and, while s.head and s.tail is more elegant in usual code, `s(0)` is again one character shorter than `s.head`.
Even shorter in some cases - depending on needed functionality is a tuple:
```
val s=Seq(1,2,3)
val t=(1,2,3)
```
saving 3 characters immediately, and for accessing:
```
s(0)
t._1
```
it is the same for direct index access. But for elaborated concepts, tuples fail:
```
scala> s.map(_*2)
res55: Seq[Int] = List(2, 4, 6)
scala> t.map(_*2)
<console>:9: error: value map is not a member of (Int, Int, Int)
t.map(_*2)
^
```
### update
```
def foo(s:Seq[Int])
def foo(s:Int*)
```
In parameter declaration, Int\* saves 4 characters over Seq[Int]. It is not equivalent, but sometimes, Int\* will do.
[Answer]
*disclaimer: parts of this answers are generalizations of other answers found here.*
## Use lambdas without specifying their argument types
It's allowed to submit something like this: `a=>a.size` instead of `(a:String)=>a.size`.
## Use ascii-symbols as identifiers.
These include `!%&/?+*~'-^<>|`. Because they arent't letters, they get parsed separately when they're next to letters.
Examples:
```
a=>b //ok
%=>% //error, parsed as one token
% => % //ok
val% =3 //ok
&contains+ //ok
if(x)&else* //ok
```
## Use Set instead of contains
```
if (Seq(1,2,3,'A')contains x)... //wrong
if (Set(1,2,3,'A')(x))... //right
```
This is possible because `Set[A] extends (A => Boolean)`.
## Use a curried function when you need two arguments.
```
(a,b)=>... //wrong
a=>b=>... //right
```
## Use the `_`-syntax when possible
The rules for this are somewhat obscure, you have to play a little bit around sometimes to find the shortest way.
```
a=>a.map(b=>b.size)) //wrong
a=>a.map(_.size) //better
_.map(_.size) //right
```
## Use partial application
```
a=>a+1 //wrong
_+1 //better, see above
1+ //right; this treats the method + of 1 as a function
```
## Use `""+` instead of `toString`
```
a=>a.toString //wrong
a=>a+"" //right
```
## Use strings as sequences
`""` is sometimes the shortest way to create an empty sequence if you don't care about the actual type
## Use BigInt to convert numbers to and from strings
The shortest way to convert a number to a string in a base other than base 10 is through BigInt's `toString(base: Int)`method
```
Integer.toString(n,b) //wrong
BigInt(n)toString b //right
```
If you want to convert a string to a number, use `BigInt.apply(s: String, base: Int)`
```
Integer.parseInt(n,b) //wrong
BigInt(n,b) //right
```
Be aware that this returns a BigInt, which is useable like a number most of the times, but can't be used as an index for a sequence, for example.
## Use Seq to create sequences
```
a::b::Nil //wrong
List(...) //also wrong
Vector(...) //even more wrong
Seq(...) //right
Array(...) //also wrong, except if you need a mutable sequence
```
Use Strings for Seqences of chars:
```
Seq('a','z') //wrong
"az" //right
```
## Make use of Stream for infinite sequences
Some challenges ask for the n-th element of an infinite sequence. Stream is the perfect candidate for this. Remember that `Stream[A] extends (Int => A)`, that is, a stream is a function from an index to the element at that index.
```
Stream.iterate(start)(x=>calculateNextElement(x))
```
## Use symbolic operators instead of their wordy counterparts
`:\` and `:/` instead of `foldRight` and `foldLeft`
```
a.foldLeft(z)(f) //wrong
(z/:a)(f) //right
a.foldRight(z)(f) //wrong
(a:\z)(f) //right
```
`hashCode` -> `##`
`throw new Error()` -> `???`
Use `->` for creating and unpacking tuples
```
(a,b) //wrong
a->b //right
```
## Use `&` and `|` instead of `&&` and `||`
They work the same for booleans, but will always evaluate both operands
## Alias long method as functions
```
def r(x:Double)=math.sqrt(x) //wrong
var r=math.sqrt _ //right; r is of type (Double=>Double)
```
## Know the functions in the standard library
This especially applies to the methods of collections.
Very useful methods are:
```
map
flatMap
filter
:/ and :\ (folds)
scanLeft and scanRight
sliding
grouped (only for iterators)
inits
headOption
drop and take
collect
find
zip
zipWithIndex3
distinct and/or toSet
startsWith
```
[Answer]
Use infix syntax to remove the need for `.` characters. You don't need spaces unless adjacent items are both in alphanumeric or both in operator characters (see [here](https://stackoverflow.com/questions/7656937/valid-identifier-characters-in-scala)), and not separated by reserved characters (brackets, commas etc).
E.g.
```
List(1,2,3,4).filter(_ % 2 == 0) // change to:
List(1,2,3,4)filter(_%2==0)
```
[Answer]
You can usually use `map` instead of `foreach`:
```
List("a","b","c") foreach println
```
can be replaced with
```
List("a","b","c") map println
```
The only difference is the return type (`Unit` vs `List[Unit]`), which you aren't interested in anyway when using `foreach`.
[Answer]
The `true` and `false` literals are shorter to write as `2>1` for true and `1>2` for false
[Answer]
Call two times the same function for initialization:
```
val n,k=readInt
```
(Seen somewhere else, but can't find it now).
[Answer]
define shorter Types:
If you have multiple declarations of a type, like
```
def f(a:String,b:String,c:String)
```
it is shorter to define a type alias, and use it instead:
```
type S=String;def f(a:S,b:S,c:S)
```
Original length is 3\*6=18
Replacement-code is 8(type S=;)+6+3\*1(=new length)=17
if (n\*length < 8+length+n), then it is an advantage.
For classes which are instantiated via a factory, we can set a shorter variable name to point to that object. Instead of:
```
val a=Array(Array(1,2),Array(3,4))
```
we can write
```
val A=Array;val a=A(A(1,2),A(3,4))
```
[Answer]
Rename Methods, if their name is long, and if they're used multiple times - real world example:
```
x.replaceAll(y,z)
type S=String; def r(x:S,y:S,z:S)=x.replaceAll(y,z)
```
Depending on the possibility to save 'S=String' at different places too, this will only be economical, if you replace at least replaceAll 3 times.
[Answer]
Initialize several variables at once using a tuple:
```
var(a,b,c)=("One","Two","Three") //32 characters
```
vs.
```
var a="One";var b="Two";var c="Three" //37 characters
```
[Answer]
# Use `lazyZip` or `zipped` (and `_`) instead of `zip` when combining lists
Using `a.zip(b)` is shorter than `a.lazyZip(b)` or `(a,b).zipped`, but if you're using `map` on it later, the latter will be shorter, since with `zip`, `map` requires function taking a single `Tuple2`, but with `lazyZip`/`zipped`, you can use a function of two parameters with underscores.
Here's an example adding together two lists:
```
val list1 = List(1, 2, 3, 4)
val list2 = List(5, 6, 7, 8)
list1.zip(list2).map(t=>t._1+t._2) //Not good
list1.lazyZip(list2).map((a,b)=>a+b) //Okay, this is worse
list1.lazyZip(list2).map(_+_) //But underscores make it all better
(list1,list2).zipped.map((a,b)=>a+b) //Same as with lazyZip
(list1,list2).zipped.map(_+_) //Same as with lazyZip
```
Since `zipped` is deprecated, I'd recommend `lazyZip`, as you can also use infix syntax with it. However, in some situations, such as when you're zipping more than 2 lists, `zipped` may still be better (and it's not available on TIO, which uses an older version of Scala - you'll need Scastie).
[Answer]
# Treat a String as a Sequence
## Use `filter` instead of `replace` or `replaceAll`
If you need to erase characters from a String use instead of `replace` / `replaceAll`
```
x replaceAll(y,"") // 18 bytes
x replace(y,"") // 15 bytes
```
the `filter` method:
```
x filter(y!=) // 13 bytes
```
## Do not use `charAt`
If you need a character from a specific index from a String, do not use `charAt`:
```
x charAt 7 // 10 bytes
```
Treat the String as a sequence:
```
x(7) // 4 bytes
```
## Use `drop` / `slice` instead of `substring`
```
x substring y // 13 bytes
x drop y // 8 bytes
x substring(a,b) // 16 bytes
x slice(a,b) // 12 bytes
```
**Thanks to [user](https://codegolf.stackexchange.com/users/95792/user) for extending the answer!**
[Answer]
0. Use syntactic sugar and built-in functions to save bytes.
syntactic sugar, e.g. use `/: operator (fold left)`
```
val sum = numbers.foldLeft(0) { (accumulator, element) => accumulator + element }
val sum = (0 /: numbers) { (accumulator, element) => accumulator + element }
```
1. Type conversion. `231+.0` instead of `231.toDouble`. `231+""` instead of `231.toString`
2. Use `Seq` instead of `Array` or `List`
3. Rewrite type name and method name.
Rewrite the type name if the type appears **very many times**.
Use generic parameter instead of external type definition to save more bytes.
```
/*42 bytes*/
def f(a:String,b:String,c:String,d:String)
/*36 bytes*/
type S=String
def f(a:S,b:S,c:S,d:S)
/*33 bytes*/
def f[S<:String](a:S,b:S,c:S,d:S)
```
If the method appears **very many times**, please rewrite the method name.
```
implicit class V[A](val x:A)extends AnyVal{def Q=x.toSet}
```
4. Avoid `def` return type if possible. Use `def` instead of lambda function `val f=`. e.g.
use `def f(a:Int)=a+1` instead of `val f:(Int=>Int)={a:Int=>a+1}` to save bytes.
5. Avoid unnecessary braces `{} ()`
6. Simultaneously initialize multiple variables `val r,c=new StringBuilder;`
7. use `0 to x-1` instead of `0 until x`
[Answer]
# If you need to reuse a function, make a `def` instead of a `val`
If you absolutely need to define a function in your answer to reuse multiple times, it's usually better to define it like a method rather than using a lambda.
Consider these two pairs of functions:
```
//Recursive
def f(i:Int):Int=if(i>0)i*f(i-1)else 1
val f:Int=>Int=i=>if(i>0)i*f(i-1)else 1
//Not recursive is also shorter with def
def f(i:Int)=i+1
val g=(i:Int)=>i+1
```
# Except when using pattern matching
However, if you're pattern matching, you can use Scala's special syntax and omit `match` when assigning an anonymous function to a `val`. As you can see, it's a lot shorter:
```
//Highly efficient way to sum a list
val g:List[Int]=>Int={case h::t=>h+f(t)case _=>0}
def f(l:List[Int]):Int=l match{case h::t=>h+f(t)case _=>0}
```
[Answer]
You can also use `⇒` instead of using `=>` for function definitions.
] |
[Question]
[
# Problem:
Your task is to decide if in a sequence of numbers, every number contains at least one of the digits of the number that preceded it.
For example, the following should return truthy:
```
[1, 12, 203, 0, 30]
^ ^ Contains a 0
^ Contains a 2
^ Contains a 1
```
The following should return falsey:
```
[1, 32, 23, 34]
^ Doesn't contain a 1, therefore false
```
Your submission can be a function or full program.
# Input:
Input can be any reasonable type of sequence. An array of numbers, an array of strings, a delimited string of numbers, etc.
Order matters however, so whatever structure you choose to accept as input obviously must have a definite ordering.
Input can be taken via the stdin or as an argument.
You can assume:
* all numbers will be non-negative integers
* input will always contain at least 2 numbers
* input numbers will not start with a 0
# Output:
Output will be a truthy or falsey value (as defined by your language), representing whether or not the above specification is met.
Truthy/falsey values don't need to be consistent between tests.
It can either be output to the stdout or returned.
# Test Cases:
```
True cases:
[1, 1, 1, 11, 111, 11, 1]
[12, 23, 34, 45, 56]
[65, 54, 43, 32, 21]
[123, 29, 9, 59, 55, 52, 2017, 2]
[1234567890, 19, 95, 5012, 23]
False cases:
[1, 2, 3, 4, 5, 1, 11] (2 doesn't contain a 1)
[12, 23, 33, 45] (45 doesn't contain a 3)
[98, 87, 76, 11, 12, 23] (11 doesn't contain a 7 or 6)
```
This is code-golf, so the least number of bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 48 bytes
```
lambda x:reduce(lambda a,b:set(a)&set(b)and b,x)
```
[Try it online!](https://tio.run/nexus/python2#bY9NboMwEIX3nMKrGkuuxJ@BIGXbE3RHUWPAViylTgRGysWzJniGJEjp5o3H8z7NG73/mU/yr@0luVaD6qdOhWsveVuNyoWSffjSMml70vIrm92vU6PjGsre2MvkQhZcBmMdod/DpIgfjDTQ54EYYixBogoImgw/6NCww4P5kqfxHdL/Q3Nd1zSmnGxl1W1DG774Ev9OUq9p5jUTXkUO4xwbHKAJgQcNf8nOK4hARQytUVxABSJakEzkRQm@GEF0R88szeJcT4AvWAIZxPait/zpmt8PdqVvSlhd5JuzX0ua@WbPn53sjuoO "Python 2 – TIO Nexus")
Print a empty set for `False` and the last element for `True`
[Answer]
# [Retina](https://github.com/m-ender/retina), ~~25~~ 20 bytes
```
(.).*¶(?=.*\1)
^.+$
```
[Try it online!](https://tio.run/nexus/retina#NY1bCgIxDEX/sw6FzngpTdv08THMIvwVcZUuwI3V24okJOEcuLm6@wvD@c3vn7c7D78/dBN5@ttlDMWq2b8lGhETUkY2WJHCyZuEfNqE2NFhbCrCoBVRAk22UluH0lOFlSSKiIQMW3/@8SQmvaFV1LIeT/4F "Retina – TIO Nexus")
Whenever we find a digit that also occurs in the next number, we remove the separator between those numbers (along with the digits in the former number, starting from the shared one, but that's irrelevant). The input is valid, if all separators have been remove in the process, which we check by making sure that the string can be matched as a single line.
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 9 bytes
```
{⊇ᵐ=∧?t}ˡ
```
[Try it online!](https://tio.run/nexus/brachylog2#@1/9qKv94dYJto86ltuX1J5e@P9/tKGOoZGOkYGxjoGOsUHs/695@brJickZqQA "Brachylog – TIO Nexus")
Note that this not only works with a list of integers, but also with a list of strings or a list of lists.
### Explanation
```
{ }ˡ Left fold on the input:
⊇ᵐ= It is possible to find a number which is a subset of both input numbers
∧ (and)
?t The output is the second number (to continue the fold)
```
[Answer]
# JavaScript (ES6), ~~47~~ ~~44\*~~ 43 bytes
*Saved a byte thanks to @Neil*
```
x=>x.every(y=>y.match(`[${p}]`,p=y),p=1/19)
```
Takes input as a list of strings.
### Test snippet
```
let f =
x=>x.every(y=>y.match(`[${p}]`,p=y),p=1/19)
let g = x => console.log("f([%s]): %s", x.join(", "), f(x.map(String)))
g([1, 1, 1, 11, 111, 11, 1])
g([12, 23, 34, 45, 56])
g([65, 54, 43, 32, 21])
g([123, 29, 9, 59, 55, 52, 2017, 2])
g([123456789, 19, 95, 5012, 23])
g([1, 2, 3, 4, 5, 1, 11])
g([12, 23, 33, 45])
g([98, 87, 76, 11, 12, 23])
```
\**([crossed out 44 is still regular 44](https://codegolf.meta.stackexchange.com/a/7427/42963))*
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), ~~5~~ 4 bytes
```
f2\Ạ
```
Input is an array of strings.
[Try it online!](https://tio.run/nexus/jelly#XU45DsJADOx5xTzAQknI5qgpeERIgdByFCQosZDoEA2foOAB9BwFDS8JHwk2WSiQ7LV3ZuSZdhaMm/upbW6P1/7cFZ4Ht4zQXC@v3RHDstjYisElaq6WxbwmrCZrlIKCFxZsa8Z0Ulsh1pVl3spYFtxv2yzLfIKrT3@XnHpA5geEYEAYhITQEEzU4ZHuiimnmp9egCAlSBlt1Snv@bG8P1FoojhJPfFRrYq8zioXSQ@fVPKXY2JiXLy/SEqaDksTQiIGceTSu1v5Gw "Jelly – TIO Nexus")
### How it works
```
f2\Ạ Main link. Argument: A (array of strings)
2\ Pairwise reduce by:
f Filter, yielding all chars in the left string that appear in the right one.
Ạ All; yield 1 if all strings are non-empty, 0 if not.
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 10 bytes
```
ü‚vy`Så1åP
```
[Try it online!](https://tio.run/nexus/05ab1e#@394z6OGWWWVCcGHlxoeXhrw/3@0oY4CFIExjBELAA "05AB1E – TIO Nexus")
or as a [Test suite](https://tio.run/nexus/05ab1e#TY5NCsIwEIX3nmKI2xGaNH/1FIIIhVDwFIWCgudw31sIXeQmXiS@MRGEmWTy3sfL3OZFpYnVYX8ZS369H895uZ7zqvN6KvdR5e1IeVNckmZq9e3fMO2SNkymZ@otk3VMzkP0MogghgCVxMsMTCgnLZCYnQ44QXRArPMhwtUCCtHVHyQAN/IQC7lt87@BOA7CEJkiIoNva9aADw)
**Explanation**
```
ü‚ # map pairing over each pair in input
v # for each pair
y` # push as 2 separate elements on stack
Så # check each digit in 2nd number for membership in first
1å # check if any 1 exists in the resulting list
P # product of stack
```
[Answer]
# [CJam](https://sourceforge.net/p/cjam), ~~18~~ ~~15~~ 14 bytes
*Saved 4 bytes thanks to Martin Ender*
```
l~Afb_1>.&:,:*
```
[Try it online!](https://tio.run/nexus/cjam#@59T55iWFG9op6dmpWOl9f9/tKGRgpGxgrGJgomxqYKpWSwA "CJam – TIO Nexus")
**Explanation**
```
l~ e# Read and eval the input
Afb e# Convert each number to a list of digits
_ e# Duplicate the array
1> e# Slice it after the first element
.& e# Vectorized set intersection; take the set intersection of corresponding
e# elements of the two arrays
:, e# Get the length of each intersection
:* e# Take the product of the whole array.
e# Will be 0 if any intersection was empty.
```
[Answer]
# Haskell, ~~51~~ ~~48~~ 35 Bytes
-3 bytes thanks to @NickHansen! I really need to get better with those monad operators
-4 and -9 bytes thanks to @Laikoni and @nimi respectively!
```
and.(zipWith(any.flip elem)=<<tail)
```
This version takes the input as an array of strings, eliminating the need for `show`, but as far as I can see it works in largely the same way as the older version:
```
all(\(x,y)->any(`elem`x)y).(zip=<<tail).map show
```
(I'm fairly certain I'm allowed to submit an anonymous function like this, but I'll fix it if necessary)
First the numbers are converted to strings. Then the monad magic `zip=<<tail` creates a function that zips the list with itself which pairs each entry with its neighbor(s). Then `all` maps a lambda to each pair that checks whether one string contains any chars from the other and finally checks that they all come out `True`.
Old version that works basically the same way:
```
f a=and$zipWith(\b->any(`elem`show b).show)a$tail a
```
[Answer]
# Ruby, ~~49~~ 48 bytes
```
->x{x.each_cons(2){|z|x&&=z*' '=~/(.).* .*\1/};x}
```
Output is `nil` for false and a "random" integer for true.
[Answer]
# Mathematica ~~62 47~~ 35 bytes
With 12 bytes saved thanks to MartinE.
```
FreeQ[#⋂#2&@@@Partition[#,2,1],{}]&
```
---
```
FreeQ[#⋂#2&@@@Partition[#,2,1],{}]&[{{1},{1,2},{2,0,3},{0},{3,1}}]
```
>
> False
>
>
>
```
FreeQ[#⋂#2&@@@Partition[#,2,1],{}]&[{{1},{1,2},{2,0,3},{0},{3,0}}]
```
>
> True
>
>
>
[Answer]
# Java 8, ~~94~~ ~~90~~ 87 bytes
Input is an array of strings representing the numbers. Starting with the second string, it performs a regular expression comparison against each previous string to see if it contains any of its characters: `.*[previous string].*`.
Golfed:
```
a->{int r=1,i=0;while(++i<a.length)r*=a[i].matches(".*["+a[i-1]+"].*")?1:0;return r>0;}
```
Ungolfed:
```
public class NumberChainingPredicate {
public static void main(String[] args) {
System.out.println("Expect true:");
for (String[] input : new String[][] { { "1", "1", "1", "11", "111", "11", "1" }, { "12", "23", "34", "45", "56" },
{ "65", "54", "43", "32", "21" }, { "123", "29", "9", "59", "55", "52", "2017", "2" },
{ "1234567890", "19", "95", "5012", "23" } }) {
System.out.println(java.util.Arrays.toString(input) + " = " + exec(f(), input));
}
System.out.println();
System.out.println("Expect false:");
for (String[] input : new String[][] { { "1", "2", "3", "4", "5", "1", "11" }, { "12", "23", "33", "45" },
{ "98", "87", "76", "11", "12", "23" } }) {
System.out.println(java.util.Arrays.toString(input) + " = " + exec(f(), input));
}
}
private static java.util.function.Function<String[], Boolean> f() {
return a -> {
int r = 1, i = 0;
while (++i < a.length) {
r *= a[i].matches(".*[" + a[i - 1] + "].*") ? 1 : 0;
}
return r > 0;
};
}
private static boolean exec(java.util.function.Function<String[], Boolean> function, String[] input) {
return function.apply(input);
}
}
```
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
Dµf"ḊẠ
```
[Try it online!](https://tio.run/nexus/jelly#@@9yaGua0sMdXQ93Lfj//3@0oZGxjpGxiY6pgYmOgY6JgamZjqmZuY65gY5BLAA "Jelly – TIO Nexus")
## Explanation
```
Dµf"ḊẠ
Dµ Treat the first (i.e. only) input as a list of decimal digits
" For each pair of corresponding elements in {the input digits} and
Ḋ {the input digits} with the first element removed
f take all elements common to both sides
Ạ then return true if the result has no empty lists, false otherwise
```
It's most obvious to try to use `2/` here, but that runs a unary function on all slices of size 2. `"Ḋ` effectively runs a *binary* function on all pairs of adjacent elements, which means we can use `f` directly (rather than needing to convert it to a unary function as `f/`). This does end up leaving the last element of the input in place, but luckily not even an input of 0 becomes an empty list when converted to decimal, so it has no effect on the `Ạ`.
[Answer]
# [Python 3](https://docs.python.org/3/), 48 bytes
```
f=lambda x:x==x[:1]or{*x[0]}&{*x[1]}and f(x[1:])
```
[Try it online!](https://tio.run/nexus/python3#XU/LCoNADDzrV@RUXMnBVdcX@B/Cdg8WEYT6wHpYKH67TerWQyHZTTJDZnL09bMdH10LtrJ1bXUlzby@Q6sjs9/4l2Zvpw76gMrKiKOfV2hgmODug9ZaIrj45q8w6ANoGSPECUKSIqQKQWXnPOOaZ4wx5@LTIC4RKBQn8xiPZE7vRUpVlhdlRDrMZVJ0ShmisC2yQD0tIxHl7P1ZYlCds7JAKEggz5x7t8tUvsfnWj63ocZb1mHagj7Q4dguwWtb0QojhO8AcXwA "Python 3 – TIO Nexus")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 8 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
Dœ&L¥2\Ạ
```
**[Try it online!](https://tio.run/nexus/jelly#@@9ydLKaz6GlRjEPdy34//9/tKGOgrGRjoKRMZA2iQUA "Jelly – TIO Nexus")**
### How?
```
Dœ&L¥2\Ạ - Main link: the list of integers e.g. [3, 13, 351, 73, 82]
D - convert all the integers to decimal lists [[3],[1,3],[3,5,1],[7,3],[8,2]]
2\ - 2-slice cumulative reduce with:
¥ - last two links as a dyad:
œ& - multiset intersection [[3],[1,3],[3],[]]
- length [1,2,1,0]
Ạ - all truthy? 0
```
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 5 bytes
Code:
```
üÃõå_
```
Uses the **CP-1252** encoding. [Try it online!](https://tio.run/nexus/05ab1e#@394z@Hmw1sPL43//z/a0EhHwchYR8EYiE1MYwE "05AB1E – TIO Nexus") or [Verify all test cases!](https://tio.run/nexus/05ab1e#TY7LEcMgDETvqUIF6AAY8SnAacKTSSU5uRaX4JtvFEZ2A57JjARi982i8pS1t6vt7WzHu6t8@uZVZv36Hl6PzQeVsKgsUSWaiiWIiQMFGgQGiVeoKihjE6LpfMY5iGgpl@qQTZCEGz/Qxo08xEKe2/xvQMcg1KJSEJnTXHMEfAE).
Explanation:
```
üà # Intersection on each pair
õå # Check if the empty string exists
_ # Boolean negate
```
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 87 bytes
```
param($n)(1..($a=$n.length-1)|?{[char[]]$n[($i=$_)-1]|?{$n[$i]-like"*$_*"}}).count-eq$a
```
[Try it online!](https://tio.run/nexus/powershell#FcjRCoMgGIbhe4kP1JiC1Q6jCxGJn5Alq39L6qi6dudOHnjf/KVEqwQraY2RoB5slsCvfdZWXcPpppmS8x7sJGKPUWnryy@N6PUS36GqMdbVfSszfQ7eddhAOWdhG/EQTVto/3RP8QM "PowerShell – TIO Nexus")
Not the shortest by any measure, but a slightly different approach than others are using, and shows off the nifty `|?{}` functionality.
This takes the input as an array of strings into `$n`, then loops from `1` up to the `length-1`. We use `Where-Object` (the `|?{...}`) to pull out those indices that are truthy for a particular condition. You can think of this like a combination `for` loop with an `if` clause.
The clause here is `[char[]]$n[($i=$_)-1]|?{$n[$i]-like"*$_*"}`. That is, we're taking the current index `$_`, setting it to `$i`, and subtracting `1`, and using that to index into `$n` (i.e., so we get the previous element in our input array). That is then cast as a `char`-array and sent through another `Where-Object` procedure.
The inner clause `$n[$i]-like"*$_*"` specifies that the string at the current index `$i` is `-like` the current character `$_` from the previous index. This will therefore output any characters that are in common between the two array elements. Thus, the outer clause will only be truthy if there is a character in common (since an empty array is falsey in PowerShell), and so the index will only be selected if there are characters in common.
Then, we gather up all of the indices that matched the criteria, and verify that the `.count` thereof is `-eq`ual to the length of the input array. That Boolean result is left on the pipeline, and output is implicit.
[Answer]
# [Perl 5](https://www.perl.org/), 31 bytes
A port of Martin Ender's beautiful [answer](https://codegolf.stackexchange.com/a/112950/55508).
30 bytes of code + `-p` flag.
```
s/(\S)\S* (?=\S*\1)//g;$_=!/ /
```
[Try it online!](https://tio.run/nexus/perl5#NY3RCoMwDEXf/Yo79UE3ttpqW4vIPsJXQWSUjc1N0fr9LnWMhNxwDiTRYbLzgPO0LSxpm7RtjkiuNUXLU8buVdzVBwa2@SXJTnGXXsL2E1aI8FwXBzfi3b8s3MNiXN20OtwG28923jj28v2LgAuIHHmBQkKqQNGknQhxb3MIAwNJTYpgxjWEF4VUujQZOHlS2X4p4BDIUUDuf/7nicigNCg1tNofe/4F "Perl 5 – TIO Nexus")
[Answer]
# [APL (Dyalog APL)](https://www.dyalog.com/), 9 bytes
```
∧/×≢¨2∩/⎕
```
[Try it online!](https://tio.run/nexus/apl-dyalog#rZI7DgIxDER7TpHO5eb/udBeZUNDh@hpgGvATXKRBduAEgmQyG6KiRLJfvFkSp7GueTTcDuU7fF61iVfhrLbP@6mWYzi37URAhS08tT6AG1NJ0djL21QjUW1DtV5@FLTx/HclQlMY7Jal6N4FJ1QSRwr85kpVaAdFnGs8yEmSX/BOGbIytPl87weCjQX@efaWIjVc2DeOfhR08dJEXtH8j/4Ks0fPMN1Bw "APL (Dyalog APL) – TIO Nexus")
`∧/` are all ones in the list of
`×` the signs
`≢` of the tally of
`¨` each of
`2∩/` the pair-wise intersections of
`⎕` the input?
[Answer]
# PHP, 65 68
```
for(;null!==$a=$argv[++$i+1];)$r+=$a==strtr($a,$argv[$i],_);echo!$r;
```
iterate over all numbers and remove all digits that appeared in the previous. Count how often it equals the number itself (no digit removed). If at least one equaled we didn't have a match in one of the pairs.
---
Fixed a mistake using `trim` insted of `strtr`. Thanks to @JörgHülsermann
[Answer]
# PHP, 75 bytes
```
for($b=3**39;--$argc;)preg_replace("#[$b]#","",$b=$argv[$argc])<$b?:die(1);
```
takes numbers from command line arguments; exits with `1` for falsy, with `0` for truthy.
Run with `-r` or [test it online](http://sandbox.onlinephpfunctions.com/code/d20de231cb3e127654740d81b4deb46b56b27ee2).
* start with `$b` = a number containing all digits
* loop down through the arguments
+ remove all digits of `$b` from the argument
+ copy argument to `$b`
+ if no digit was removed, exit with `1`
* implicit: exit with `0`
[Answer]
# PHP, 77 Bytes
```
for($i=$t=1;++$i<$argc;)$t*=preg_match("#[{$argv[$i-1]}]#",$argv[$i]);echo$t;
```
[Answer]
# [MATL](https://github.com/lmendo/MATL), 14 bytes
```
1&)"V@VX&nv@]x
```
[Try it online!](https://tio.run/nexus/matl#@2@oGeau5BAWoZZX5hAWW/HfXr2kqLQko1K9Vj0tMae4Uv1/tKGRsY6xiamOghGIMI4FAA "MATL – TIO Nexus")
Thanks @LuisMendo for saving a byte. Explanation:
```
1&) % 'Pop' the first item from the input and push it on the stack.
" ] % Main 'for' loop, to loop over the rest of the input.
V % Stringify previous (or first) iten from the input.
@V % Push current number, convert to string
X& % Intersect with stringified number already on the stack.
nv % Count the size of the intersection, and add it to the existing list of sizes.
@ % Push the current number again for the intersection in the next loop.
x % Remove the number pushed by the last loop.
% Else the program would end with the result on the second instead of the first position in the stack
```
[Answer]
# Clojure, 71 bytes
```
(fn[n](every?(fn[[q w]](some q w))(partition 2 1(map #(set(str %))n))))
```
An anonymous function that accepts a sequence of numbers. Returns `true`/`false`.
I like how it reads. There's definitely a few areas that can be improved upon here. My function being passed to `map` can't easily be changed so that it doesn't require the function macro, which means the entire function can't make use of the macro, which likely added some bytes. It would also be nice if I could figure out a better way of unpacking the values in the `every?` predicate.
```
(defn number-chain? [nums]
(let [; Turn each number into a set of characters
set-nums (map #(set (str %)) nums)
; Partition the sets into lists of neighbors
; [1 2 3 4] -> [[1 2] [2 3] [3 4]]
partitioned (partition 2 1 set-nums)]
; Does every second neighbor contain some element of the first?
(every?
(fn [[l1 l2]]
(some l1 l2))
partitioned)))
```
[Answer]
# SimpleTemplate, 124 bytes
Wow, this was a workout!
```
{@eachargv asA keyK}{@ifK}{@setR"/[",O,"]/"}{@calljoin intoR"",R}{@ifA is notmatchesR}{@return}{@/}{@/}{@setO A}{@/}{@echo1}
```
This "simply" makes a regex using the old element, showing `1` as a truthy value, or nothing otherwise.
---
**Ungolfed:**
```
{@each argv as number key K}
{@if K}
{@set regex "/[", old, "]/"}
{@call join into regex "", regex}
{@if number is not matches regex}
{@return false}
{@/}
{@/}
{@set old number}
{@/}
{@echo 1}
```
[Answer]
## JavaScript (ES6), 37 bytes
```
s=>/^(.*(.).*\n(?=.*\2))+.+$/.test(s)
```
Accepts input as a string of newline-separated numbers. Based on @MartinEnder♦'s excellent Retina answer, but doing the entire test in a single regexp because it's shorter in JavaScript that way.
[Answer]
# [Pip](https://github.com/dloscutoff/pip), ~~12~~ 10 bytes
```
$&B@X^_MPg
```
Takes input as a series of command-line arguments. Output is a nonempty list for truthy and an empty list for falsey. [Try it online](https://tio.run/nexus/pip#@6@i5uQQERfvG5D@//9/w/@GRv@NDIz/A6EBAA) or [verify all test cases](https://tio.run/nexus/pip#TY7LCsIwEEX3/Yq7kKK7ZJLJYyfuC6UgCKW69CPEb4830y4kA8mcM8nNMp8/7TTero/na5rf7Tvdh3XA6mGr175tHQokIEREhaZOEg9sCamOmQCpqFAWLbnzGXK4qCmX6uA5QuvsSTqLFAREqAX/5RFqb2tBycjJ/rPf2y7tBw "Pip – TIO Nexus").
### Explanation
```
g List of all cmdline args
MP Map this function to consecutive pairs of items from that list:
^_ Split 1st item of pair into list of characters
X Convert to regex that matches any of those characters
B@ Find all matches in 2nd item of pair
$& Fold on logical AND--truthy if all items are truthy, falsey if one is falsey
Print (implicit)
```
[Answer]
# [Röda](https://github.com/fergusq/roda), ~~45~~ 35 bytes
```
{[_=~`(\S*(\S)\S* (?=\S*\2))+\S+`]}
```
[Try it online!](https://tio.run/nexus/roda#VY3dCoJAEEav3af46MpNA3d1/Qmkh/DSFZVU8iKNtCuzV7fRKIidnW84B2auZdthQoNjDL1MaR6/ClMne/qcAuYpptCSc0snVpHNi9H0d4z1MObncqhR9cwwbve2G3F7DBfzZ9LjQWQcTzQmt7HT487Gv2RG1Xc1mxeB7a31CSYkpAvXg6egfOZTp5kI8dW6kBEiKCpSBB0RQK7CU34QRg4EeVLOtokJSLjwoLY73/VEFAsjhAECfzu88jc "Röda – TIO Nexus")
This is similar to the Perl 5 solution, which is a port of the Retina solution by Martin Ender. -10 bytes thanks to @Neil.
Here's a different solution (~~73~~ 72 bytes):
```
{[_/""]|{|x|{x|[0]()unless[not(_ in y)]else[1]}if tryPeek y}_|sum|[_=0]}
```
It's an anonymous function that pulls strings from the stream and checks that the consecutive strings contain same characters. Explanation:
```
{
[_/""]| /* split strings -> creates arrays of characters */
{|x| /* begin for loop over character arrays */
{ /* begin if tryPeek(y) -> peeks the second item from the stream */
/* x and y are now two consecutive character arrays */
x| /* push characters in x to the stream */
[0]()unless[not(_ in y)]else[1] /* pushes 0 to the stream */
/* if y contains the character */
/* in the stream, otherwise 1 */
}if tryPeek y
}_| /* end for loop */
sum| /* sum all numbers in the stream */
[_=0] /* return true if the sum is zero */
}
```
It could possibly be golfed more...
[Answer]
# [Bash](https://www.gnu.org/software/bash/) + Unix utilities, ~~71~~ 69 bytes
```
sed "s/\(.*\)/<<<\1 \&\&grepx[\1]/;1s/.*g/g/;\$s/ .*//"|tr 'x
' \ |sh
```
[Try it online!](https://tio.run/nexus/bash#BcE9CoAwDAbQPacIIlY79CMK/mBvYtyUOopxcOjd63vFzoMrg7bBa4cYowpro016zvvbVHasYgg@IWHV2sDBA1V@H3YfOVbOdpWyzDRPNI0kQtJTP9AP "Bash – TIO Nexus")
Input is on stdin, one number per line.
Output is in the exit code: 0 for truthy, 1 for falsey.
This can probably be golfed more.
For the code above to work, there cannot be any file in the current directory whose name is a single digit. If this isn't acceptable, replace `[\1]` in the program with `'[\1]'` (at a cost of 2 additional bytes).
Sample run (the last test case provided in the challenge):
```
$ echo '98
> 87
> 76
> 11
> 12
> 23' | ./digittest > /dev/null; echo $?
1
```
(1 here is falsey.)
---
How it works:
I'll demonstrate on the sample run above.
The sed command converts the input into:
```
grepx[98]
<<<87 &&grepx[87]
<<<76 &&grepx[76]
<<<11 &&grepx[11]
<<<12 &&grepx[12]
<<<23
```
The tr command then converts this to the string:
```
grep [98] <<<87 &&grep [87] <<<76 &&grep [76] <<<11 &&grep [11] <<<12 &&grep [12] <<<23
```
This string is a shell command for doing the desired operation, so I pipe that into sh and I'm done.
[Answer]
## Q, 57 bytes
```
{r::();({r,::any(last x)in y;x,enlist y}\)($)0,x;all 1_r}
```
1. Initialises global r.
2. Converts input to array of strings.
3. Scans array checking that some character in last string is in current string.
4. Appends each result to r.
5. Returns 1 if all strings satisfy step 3 else returns 0.
Note: 0 appended to start of input array within function. This was done so that the comparison of the first element would be done enlisted. Otherwise, the last character of the first element is grabbed for comparison. Could do a type check however that adds 7 bytes over the current count.
] |
[Question]
[
**NOTE: Some terminology used in this challenge is fake.**
For two integers `n` and `k` both greater than or equal to 2 with `n > k`, `n` is *semidivisible* by `k` if and only if `n/k = r/10` for some integer `r`. However, `n` may not be divisible by `k`. Put more simply, the base 10 representation of `n/k` has exactly one digit after the decimal place. For example, 6 is semidivisible by 4 because 6/4=15/10, but 8 is not semidivisible by 4 because `8 % 4 == 0`.
Your task is to write a program which takes in two integers as input, in any convenient format, and outputs a truthy (respectively falsy) value if the first input is semidivisible by the second, and a falsey (respectively truthy) value otherwise. Standard loopholes are forbidden. You may assume that `n > k` and that both `n` and `k` are at least 2.
Test cases:
```
[8, 4] -> falsey
[8, 5] -> truthy
[9, 5] -> truthy
[7, 3] -> falsey
```
This question is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'") therefore shortest answer in bytes wins.
[Answer]
# [Python 2](https://docs.python.org/2/), 24 bytes
```
lambda n,k:n*10%k==0<n%k
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ9sqT8vQQDXb1tbAJk81@395RmZOqoKhFRcnUE7BViEzr6C0REOTi7OgKDOvRCFNAyis@T/aQkfBJJYLRJkCKUsIZa6jYBwLAA "Python 2 – Try It Online")
Checks that \$10n\$ is a multiple of \$k\$, but \$n\$ itself is not.
**24 bytes**
```
lambda n,k:n%k>>n*10%k*n
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ9sqTzXbzi5Py9BANVsr7395RmZOqoKhFRcnUE7BViEzr6C0REOTi7OgKDOvRCFNAyis@T/aQkfBJJYLRJkCKUsIZa6jYAykDC0NDAx1FAwNgCAWAA "Python 2 – Try It Online")
The `*n` at the end can't be omitted, say for `n=19001, k=10000`.
[Answer]
# [R](https://www.r-project.org/), 31 bytes
```
function(x,y)nchar((x/y)%%1)==3
```
[Try it online!](https://tio.run/##K/qfoJpZHF@cmpuZklmWWZyZlJMan1SpmmD7P600L7kkMz9Po0KnUjMvOSOxSEOjQr9SU1XVUNPW1vi/mQJWnQomCsoKJUWlqVwWeBSkJeYU41ZhCjPCkpACcxwKjOF2/AcA "R – Try It Online")
Fractional part (`%%1`) of `x/y` must be 3 characters: so, `0.1`, `0.2` ... `0.9`, but not `0` or `0.3333`.
[Answer]
# [Python 2](https://docs.python.org/2/), 23 bytes
Saves 1 byte from [xnor's answer](https://codegolf.stackexchange.com/a/220283/88546) *(for the [bounty](https://codegolf.meta.stackexchange.com/a/18334/88546))*. Notice that the chained comparison forces `n*10%k = 0` and `n%k > 0` to both be true.
```
lambda n,k:1>n*10%k<n%k
```
[Try it online!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPJ9vK0C5Py9BANdsmTzX7f3lGZk6qgqEVFydQSsFWITOvoLREQ5OLs6AoM69EIU0DKKz5P9pCR8EklgtEmQIpSwhlrqNgHAsA "Python 2 – Try It Online")
[Answer]
# [APL (Dyalog Unicode)](https://www.dyalog.com/), ~~12~~ 9 bytes
```
3=∘≢∘⍕1|÷
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wRj20cdMx51LgKRvVMNaw5v//@obypQwkIhTcFE4VHvXAVdO4W0xJziSi6EhClMoqSotCQDJmOJU8YcKGOMYth/AA "APL (Dyalog Unicode) – Try It Online")
The previous, obvious method.
```
'.'=∘⊃¯2↑∘⍕÷
```
[Try it online!](https://tio.run/##SyzI0U2pTMzJT///P@1R2wR1PXXbRx0zHnU1H1pv9KhtIojdO/Xw9v@P@qYCpS0U0hRMFB71zlXQtVNIS8wpruRCSJjCJEqKSksyYDKWOGXMgTLGKIb9BwA "APL (Dyalog Unicode) – Try It Online")
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 10 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
I think this is right; I'm quite drunk!
```
*A vV «UvV
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=KkEgdlYgq1V2Vg&input=NyAz)
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~25~~ ~~24~~ 23 bytes
Saved a byte thanks to [AZTECCO](https://codegolf.stackexchange.com/users/84844/aztecco)!!!
Thanks to [dingledooper](https://codegolf.stackexchange.com/users/88546/dingledooper) who found and fixed a bug!!!
```
f(n,k){n=n%k>0>10*n%k;}
```
[Try it online!](https://tio.run/##bVDhaoMwEP7vU1wFQe3JdG3ZitM/Y08xZUiMnWRLixEmE1997mqi1LFwOS73fXeX@1hwYmwcK1ei8HqZSEekYRqFPgXxMH4WtXQ9q7eATi1baLlq3@RrDgn0jwhkR4QH7Yd4TROatkc4TLZDiEKE/Q2PdxfOWl5qJoHRZDoIDZG9F41PnjPBG820s@7lPuuOz3QPNsLte2ebuurcgHudUsuSd1QWxiZ8AlV/83PlzvO9O5Pwl0wM2@3E9kCvP/9ZUicjw4Tn8QoWMyz@hRXBWu11nlN@UeNv4aUhSuXaTonglBCkV@@oTNLqEkEgKFwE2mxUkvDc9B@sYfxh1UdxUmPw9Qs "C (gcc) – Try It Online")
Inputs integers \$n\$ and \$k\$ and returns a truthy iff \$10n\$ is divisible by \$k\$ and \$n\$ isn't divisible by \$k\$.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 8 bytes
```
€tḊ10/¹⌉
```
[Try it online!](https://tio.run/##yygtzv6fG6zhpaSga6eglKqpUez2qKkxt6hc89C2/4@a1pQ83NFlaKB/aOejns7///@bKZhwWSiYclkCsbmCMZBtwmVoYKhgaGAAAA "Husk – Try It Online")
Uses a different approach from what I have seen in other answers, could be even shorter if I found a better way to check if a number is in [2,5,10]. (Any golfing language with a single-byte builtin for 10 could probably do it)
### Explanation
Taking 2 numbers \$a\$ and \$b\$, we compute: $$\frac{lcm(a,b)}{a}$$
This value will be equal to the smallest number you have to multiply \$a\$ by to make it divisible by \$b\$. Since we don't want \$a\$ to be divisible by \$b\$ we'll need this to be greater than 1, and since we want \$10\*a\$ to be divisible by \$b\$ we'll need this to be a divisor of 10. In the end we want the result to be one of [2,5,10].
```
€tḊ10/¹⌉
⌉ Least common multiplier of the two numbers
/¹ divided by the first number
€ Find its position in the list: (returns 0 if missing)
Ḋ10 divisors of ten: [1,2,5,10]
t except the first: [2,5,10]
```
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes
```
n#k=(10*n`mod`k<1)>(n`mod`k<1)
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P08521bD0EArLyE3PyUh28ZQ004Dwf6fm5iZp2CrUFCUmVeiEA1UXBOdp5Mda6MbHW2ho2ASqwOiTIGUJYQy11Ewjo2N/Q8A "Haskell – Try It Online")
* inspired by @xnor [answer](https://codegolf.stackexchange.com/a/220283/84844)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 bytes
```
×⁵ọ¹ȧ%
```
[Try it online!](https://tio.run/##y0rNyan8///w9EeNWx/u7j2088Ry1f@H2/UfNa35/z862kLHJFYHSJoCSXMwaaljDCQNDQx0zGNjAQ "Jelly – Try It Online")
[Answer]
# [JavaScript (Node.js)](https://nodejs.org), 18 bytes
```
n=>k=>n%k>0>10*n%k
```
[Try it online!](https://tio.run/##y0osSyxOLsosKNHNy09J/Z9m@z/P1i7b1i5PNdvOwM7QQAvI@J@cn1ecn5Oql5OfrpGmYaGpYaKpaa2gr6@ga6eQlphTXMmFocIUoaKkqLQkA12JJWEl5poaxmj2/AcA "JavaScript (Node.js) – Try It Online")
-2 bytes thanks to [iota](https://codegolf.stackexchange.com/users/99986/iota)
-1 byte indirectly from Neil or Noodle9 or dingledooper
[Answer]
# [J](http://jsoftware.com/), 11 bytes
```
3=[#@":@%~|
```
[Try it online!](https://tio.run/##y/qvpKeepmBrpaCuoKNgoGAFxLp6Cs5BPm7/jW2jlR2UrBxU62r@a3KlJmfkK6inJeYUVyokJxanFqtDhEwU0hQsIExjINOcC6qypKi0JANVqSlCKYhpqfAfAA "J – Try It Online")
Looks like I stumbled on almost exactly the same method as the APL answer.
* `[...%~|` The left input `[` floating point divided into `%~` the remainder when the left input is divided into the right input `|`.
* `#@":@` Format that result as a string and take its length.
* `3=` Does that equal 3? This will only be true for numbers of the form `0.n` where n is an element of the digits `1-9`.
[Answer]
# [PowerShell](https://github.com/TryItOnline/TioSetup/wiki/Powershell), 36 bytes
```
param($n,$k)!((10*$n)%$k)-and($n%$k)
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/vyCxKDFXQyVPRyVbU1FDw9BASyVPUxXI0U3MSwGKg5j///@3@G8CAA "PowerShell – Try It Online")
Inspired by @xnor method of checking if 10n is multiple of k but n itself not
[Answer]
# [GolfScript](http://www.golfscript.com/golfscript/), 15 bytes
```
.~@~%!!@10*@%!&
```
[Try it online!](https://tio.run/##S8/PSStOLsosKPn/X6/OoU5VUdHB0EDLQVVR7f9/CwVTAA "GolfScript – Try It Online")
Unfortunately, as GolfScript lacks support for floating-point values, I couldn't use the strategy of looking for the decimal place. The program just checks if n % k is truthy and 10n % k is falsy.
Also of note is that I found it easier to take the input as a string containing two space-separated integers instead of taking it as two integers directly.
```
.~@~ prepare two sets of n and k
%!! check if n % k > 0
@10* multiply n by 10
@%! check if 10n % k = 0
& AND both values
```
[Answer]
# [R](https://www.r-project.org/), 28 bytes
```
function(x,y)!(x*10)%%y&x%%y
```
[Try it online!](https://tio.run/##K/qfoJpZHF@cmpuZklmWWZyZlJMan1SpmmD7P600L7kkMz9Po0KnUlNRo0LL0EBTVbVSrQJI/DdTwKpNwURBWaGkqDSVywKPgrTEnGLcKkxhRlgSUmCOQ4Ex3A5DSwMDQxyqDA2AAK7yPwA "R – Try It Online")
Test harness taken from [Dominic's answer](https://codegolf.stackexchange.com/a/220284/55372).
[Answer]
# Excel, ~~31~~ ~~29~~ 20 bytes
```
=LEN(MOD(A1/B1,1))=3
```
*-2 bytes thanks to @Dominic van Essen*
*-9 bytes porting [Dominic's Answer](https://codegolf.stackexchange.com/questions/220281/semidivisibility/220284#220284)*
Previous Answer
```
=MOD(A1,B1)*(MOD(A1*10,B1)=0)
```
[Answer]
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~41~~ ~~40~~ 35 bytes
```
$
0
\d+
$*
^(1+),(?!(\1{10})+$)\1+$
```
[Try it online!](https://tio.run/##K0otycxL/K@q4a8SlxCTos31X4XLgAvEUNHiitMw1NbU0bBX1IgxrDY0qNXUVtGMMdRW@f/fQseEy0LHlMsSiM11jAE "Retina 0.8.2 – Try It Online") Takes inputs in reverse order, but header in link reverses the test suite for convenience. Explanation:
```
$
0
```
Multiply `n` by `10`.
```
\d+
$*
```
Convert `k` and `10n` to unary.
```
^(1+),
```
Match k, then ...
```
(?!(\1{10})+$)
```
... while ensuring `10k` doesn't divide `10n` (i.e `k` does not divide `n`), ...
```
\1+$
```
... ensure `k` divides `10n`.
[Answer]
# [Vyxal v2.6.0+](https://github.com/Lyxal/Vyxal), 6 bytes
```
ġ/₀KḢc
```
Takes its input as \$k\$ followed by \$n\$.
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLEoS/igoBL4biiYyIsIiIsIjEwXG4xMjM0NTY3ODkxMjM0NTY4OTUiXQ==)
This uses the same algorithm as my [regex answer](https://codegolf.stackexchange.com/a/249412/17216), which is similar to the algorithm used by [Leo's Husk answer](https://codegolf.stackexchange.com/a/220433/17216). It asserts that $${k\over gcd(n,k)} ∈ [2,5,10]$$
It doesn't use floating point, and can thus handle arbitrarily large integers correctly.
```
ġ Push gcd(n,k)
/ Pop the above result, and push k divided by it
₀K Push the divisors of 10, i.e. [1, 2, 5, 10]
Ḣ Head remove – drop first element, yielding [2, 5, 10]
c Is the above quotient contained in the above list?
```
## [Vyxal v2.5.3ω](https://github.com/Vyxal/Vyxal/tree/old), 7 bytes
```
ġ/₀Kḣ„c
```
Takes its input as \$k\$ followed by \$n\$.
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%C4%A1%2F%E2%82%80K%E1%B8%A3%E2%80%9Ec&inputs=10%0A123456789123456895&header=&footer=) - v2.5.3ω
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLEoS/igoBL4bij4oCeYyIsIiIsIjEwXG4xMjM0NTY3ODkxMjM0NTY4OTUiXQ==) - latest
The reason I didn't use the `Ḣ` head-remove element in the first place is that I was referring to outdated documentation – my clone of the git repo was pointed at master instead of main.
```
ġ Push gcd(n,k)
/ Pop the above result, and push k divided by it
₀K Push the divisors of 10, i.e. [1, 2, 5, 10]
ḣ Head extract – split the above, yielding 1 and [2, 5, 10]
„ Rotate stack left, such that a=the above quotient, and b=[2, 5, 10]
c Is a contained in b?
```
# [Vyxal v2.5.3ω](https://github.com/Vyxal/Vyxal/tree/old), 7 bytes
```
Ḋ⁰₀*¹Ḋ<
```
Takes its input as \$k\$ followed by \$n\$.
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=%E1%B8%8A%E2%81%B0%E2%82%80*%C2%B9%E1%B8%8A%3C&inputs=10%0A123456789123456895&header=&footer=) - v2.5.3ω
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCLhuIrigbDigoAqwrnhuIo8IiwiIiwiMTBcbjEyMzQ1Njc4OTEyMzQ1Njg5NSJd) - latest
This uses the same logic as in [xnor's Python answer](https://codegolf.stackexchange.com/a/220283/17216) and many subsequent answers, which is to assert that \$n≢0\pmod k\ \land\ 10n≡0\pmod k\$.
```
Ḋ Push 1 if n is divisible by k, 0 otherwise
⁰ Push n
₀ Push 10
* Push n*10, popping both n and 10
¹ Push k
Ḋ Push 1 if n*10 is divisible by k, 0 otherwise (pop both)
< Is the top boolean less than the bottom boolean?
```
## [Vyxal v2.5.3ω](https://github.com/Vyxal/Vyxal/tree/old), 7 bytes, 6 elements
```
k≈↵*⁰Ḋ¯
```
Takes its input as \$n\$ followed by \$k\$.
[Try it Online!](https://lyxal.pythonanywhere.com?flags=&code=k%E2%89%88%E2%86%B5*%E2%81%B0%E1%B8%8A%C2%AF&inputs=123456789123456895%0A10&header=&footer=) - v2.5.3ω
[Try it Online!](https://vyxal.pythonanywhere.com/#WyIiLCIiLCJr4omI4oa1KuKBsOG4isKvIiwiIiwiMTIzNDU2Nzg5MTIzNDU2ODk1XG4xMCJd) - latest
```
k≈ Push [0, 1]
↵ Raise 10 to the power of the above: [1, 10]
* Multiply the above list by n
⁰ Push k
Ḋ Are the list items divisible by k? (Result is a list)
¯ Take deltas (consecutive differences) of the list. Iff the two
elements of the list were different, this will be truthy.
```
Oddly, the behavior of `¯` was changed. It used to give \$[a[0]-a[1], a[1]-a[2], …]\$ but now gives \$[a[1]-a[0], a[2]-a[1], …]\$. This doesn't change the truthiness of the output, just the sign of the truthy result: `⟨-1⟩` in old, `⟨1⟩` in new.
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 9 bytes
```
⁼¹⌕⮌I∕NN.
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z@gKDOvRMO1sDQxp1jDUEfBLTMvRSMotSy1qDhVwzmxuETDJbMsMyVVwzOvoLTErzQ3KbVIQ1NHAYULBDoKSnpKQNr6/38LBdP/umU5AA "Charcoal – Try It Online") Link is to verbose version of code. Outputs a Charcoal boolean, i.e. `-` for semidivisble, nothing if not. Explanation:
```
N First input
∕ Divided by
N Second input
I Cast to string
⮌ Reversed
⌕ Index of
. Literal `.`
⁼ Equal to
¹ Literal 1
Implicitly print
```
[Answer]
# [Husk](https://github.com/barbuz/Husk), 9 bytes
```
&¬%³*10¹%
```
[Try it online!](https://tio.run/##yygtzv6fq3Fo@aOmxkdtEx61TdL8r3ZojeqhzVqGBod2qv5XSq0oSE0uSU1RyC8tKSgtsVIw1DHQMQRCAwUNMx0TheiSotKSjMpYhbT8nJz8cqDCpEqFkoxUBROF9Myy1DyFktTiEt3kxOLUYs3//6OjTXTMYnWApAWQNIWSlkDSWMc8NhYA "Husk – Try It Online")
[Answer]
# [K (ngn/k)](https://bitbucket.org/ngn/k), 13 bytes
```
{>/~y!10 1*x}
```
[Try it online!](https://tio.run/##y9bNS8/7/z/NqtpOv65S0dBAwVCrovY/kAJCAzCuU0hT0FNX0LBQMLG2UDC1tgRicwVjIG1oAGSYaP4HAA "K (ngn/k) – Try It Online")
Uses [@xnor's approach](https://codegolf.stackexchange.com/a/220283/98547). `n` is `x`, and `k` is `y`.
* `10 1*x` generate list of 10 times `x`, and `x`
* `y!` mod each of those by `y`
* `~` not them, i.e. check if `y` evenly divides `10*x` and `x`
* `>/` return true iif `y` evenly divides `10*x` but not `x`
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), ~~9~~ ~~8~~ ~~8~~ 6 bytes
-2 thanks to @Kevin Cruijssen
```
/`×'.å
```
[Try it online!](https://tio.run/##yy9OTMpM/f9fP@HwdHW9w0v//zflsgAA "05AB1E – Try It Online")
[Try more cases](https://tio.run/##yy9OTMpM/V9WGZRgr65vb6@k8KhtkoKSfWXCf/2Ew9PV9Q4v/a/zPzraTMckVifaAkqaAklLMGmuYwwkDXUMIaQBlILTBrGxAA)
[Answer]
# [Vyxal 2.0.0](https://github.com/Lyxal/Vyxal), 6 bytes
```
/Ṫt\.=
```
[Try it Online!](http://lyxal.pythonanywhere.com?flags=&code=%2F%E1%B9%AAt%5C.%3D&inputs=5%0A8&header=&footer=)
Checks if the second last character is "."
[Answer]
# APL, 14 bytes
```
{0≠.=⍵|1 10×⍺}
```
Explanations. For example, ⍺ = 3 and ⍵ = 5
```
1 10×⍺ ⍝ Make two-element vector: 3 30
⍵| ⍝ Remanders of division to 5: 3 0
0≠.= ⍝ Check if they are zero: 0 1 (no yes)
⍝ Then check if answers are different
```
[Answer]
# Regex (ECMAScript), ~~35~~ 33 bytes
```
^(?=(.+)\1*,\1+$)(\1\B|\1{5})\2?,
```
Takes its input in unary, as the length of two strings of `x`s delimited by a `,` specifying (\$k,n\$).
[Try it online!](https://tio.run/##TY9BbtswEEX3OgUVNNaMxSikLTmuBdZAgBToJou2u6gFCIeRVVG0QNJNGtunKLLL6XoRl2pSIAs@Dub/j5n5IX9Kt7JN789c39wq221Mq34drTDqnnxW9dVDD/AoPpyPj99hKSBLseJjWvH0HULFq8t9xXfFAavJkh7H54@Y@c0XbxtTA2ZONysFM3qWI5ZOsPJ@3WgFoIVV8lY3RgFiLMxWa9y50agPOQ@DlZe10JnrdeMhoQmWzR3UmVam9utYTPb7xl3LazCil9apTyFV37BviP@F9q3Ag4D91jtv4eTK2o1dkJNUYxkRorRTu44IAslDklnVK@mhxTQMTd90DGLWSb9ag8WSyOA3p20sGBmNCJgxZ3jainAgeR0DcdwJIcmSJH@ef5OELIbiiSSYQjd0v9qtWpAX4aMMSywGLex0OBznNI/mtIjeh3dBp@HnLBR5NKW8iPIBfEJzFvHpwIvZwGI@cML@MXiLGeWziDMewiwKlr8 "JavaScript (SpiderMonkey) – Try It Online")
This uses a similar algorithm to [Leo's Husk answer](https://codegolf.stackexchange.com/a/220433/17216). We can't directly compute \$lcm(n,k)\$ since it can be larger than both the inputs, so instead we compute \$k/gcd(n,k)\$, which is conveniently equivalent to \$lcm(n,k)/n\$. All that remains is to assert that the result is in \$[2,5,10]\$.
```
^ # tail = K
(?=
(x+)\1*,\1+$ # \1 = greatest common factor of K and N
)
# Assert that K == \1*2, \1*5, or \1*10, i.e. that K/\1 == 2, 5, or 10
( # \2 = one of the below choices, \1 or \1*5
\1 # tail -= \1
\B # Assert tail > 0; this prevents matching on K == \1
| # or
\1{5} # tail -= \1*5
)
\2? # optionally, tail -= \2; this option must be taken if
# \2 == \1, because in that choice, the assertion was made
# that K > \1
, # Assert tail == 0
```
# Regex (ECMAScript), 33 bytes
```
^(((x+)(\3{4})?)\2?),(?!\1+$)\3+$
```
[Try it online!](https://tio.run/##TY9NbtswEIX3OgUVJNaMxSikJTuuBdarFOgmi7a7ugUIh5VZUbRA0o0Tx6cousvpchGX6g@QBT8O5r2Hmfkuf0i/droPl77Xd8p1W9uqh5MTVt2TD6q52fcAj@Lt1fj0FQD2OcKqPFRHXOJqskQKy3TF83Nclfn5aXz1iEXYfgxO2waw8EavFczoZYVYe8Hq@402CsAIp@Sd0VYBYirszhg8@NGoj7kAg5XXjTCF740OkNEMa/0NmsIo24RNKiZPT9rfyluwopfOq/cx1XxmXxD/C@1rgUcB@13wwcHZjXNbtyBnucE6IUQZrw4dEQSyfVY41SsZoMU8Ds1fdSxi0cmw3oDDmsjotxdtKhgZjQjYMWd40Yp4IPk3BtK0E0KSJclenn@SjCyG4hfJMIdu6H5yO7Ugf4V3Mi6xGLS40/F4mtMqmdNp8ia@a1rGn7NYVElJ@TSpBvAJrVjCy4HXs4HT@cAJ@8Ponc4onyWc8RhmSbT8Bg "JavaScript (SpiderMonkey) – Try It Online")
By an interesting coincidence, there's another method that has the same length. It asserts that both:
* \$k\$ does not divide \$n\$
* At least one member of \$\{k, {k\over 2}, {k\over 5}, {k\over 10}\}\$ is an integer and divides \$n\$ (of course it's redundant to try to assert that for \$k\$, as it contradicts the previous assertion, but it results in a shorter regex)
```
^ # tail = K
# Divide \3 = K, K/2, K/5, or K/10
( # \1 = tail == K
( # \2 = \3 or \3*5
(x+) # \3 = any positive number satisfying the assertions below
(\3{4})? # optionally add \3*4 to \2
) # tail -= \2
\2? # optionally, tail -= \2
)
, # Assert tail == 0;
# tail = N
(?!\1+$) # Assert N is not divisible by K
\3+$ # Assert N is divisible by \3
```
# Regex (Ruby), 31 bytes
```
^(((x+)\3{4}?)\2?),(?!\1+$)\3+$
```
[Try it online!](https://tio.run/##ZU9dS8MwFH3vr7gp25Ius7R@vFhCGUx9mzAGvhRLZamUbllJOpyIPvoD/In@kXqXVCd6IeHecw7n3Kt3D8@dBgEL@Sj3TajkE8ymy2moZbFKvKYwRq6Qjjyp9VYb25ZbDQoqBXEYxhexnetfM2AVqFTDmogIRiNgahxHwbAWIrLsBlnm7/1xDRz8iX/4cVIBiDfQVlKV6EEEELKx86GaXWtAhe02N5xOKK/7Fj7fP4BytoEU6FLvJIVLoNfF2kgaIH0Cd4vb@Q2hP079NVyAW1ei9Bjjrj6SauXhS2zT6Eq1veQ7vpWmxXgHEhEf1jB2BxvvcOrhSX0u3hUl4Kz8TPnc4X/8HPjfryyqNfq5ffL8aj7L8@6eMbbnQXb2cv6aBtlpGkxYSrKYDxDjg677Ag "Ruby – Try It Online")
This is a straight port of the above ECMAScript regex. Ruby allows multiple back-to-back quantifiers in situations where the meaning is unambiguous, so `(\3{4})?` can be done as `\3{4}?` instead. In other regex engines, the `?` in `\3{4}?` would be interpreted as modifying the quantifier to be lazy (non-greedy), even though on a constant quantifier that has no effect.
Note that `(A{N,M})?` *cannot* be changed to `A{N,M}?` in Ruby, because in that case the `?` does act as a lazy modifier to the quantifier.
### Regex (ECMAScript), ~~171~~ 151 bytes
Just for kicks, let's see if we can port the algorithm from [xnor's Python answer](https://codegolf.stackexchange.com/a/220283/17216) and many subsequent answers, which is to assert that \$n≢0\pmod k\ \land\ 10n≡0\pmod k\$. The challenge here is that we can't directly compute \$10n\$, since regex can't operate on numbers larger than any of the inputs (of course, we could if \$k\ge 10n\$, but in most cases it won't). So we need to emulate the calculation of \$10n\$ modulo \$k\$.
`^(?=(x*),\1*(x*))(?=(?=\2\B(x*))(x*(?=\3\3)|\2\2))(?=((?=\4(x*))x*(?=\3\6)|\4\2))(?=((?=\5(x*))x*(?=\3\8)|\5\2))(?=((?=\7(x*))x*(?=\3\10)|\7\2))\9{2}\b`
[Try it online!](https://tio.run/##VZBNbtswEIX3OgUdINaMrCii/uxYYA0USIFusmi7q1qAdVhZFUULpNw4sX2KoruerhdxybgBnAUfZ@Z7gxnyB//JzVI3/XBl@uZe6G6tWvF41EyJB/JB1LfbHuCJvbkOjl9hwWAbYFjRwN3o8gWrkurtKd0GLk2rFPe2mJwMrpQ98xdcWJyd4/wVnlmcn@PpK0xjy6eOVze75FB9OwbXTxgN64@DblQNGBnZLAUU4VWGWBoWlw@rRgoAybTg97JRAhBHTG2kxJ0Zj3vbN4Cz0rJmMjK9bAbwQx/L5jvUkRSqHlYjluz3jbnjd6BYz7UR721X/Tn@gvgC2nNALcB@M5hBw8Wt1ms9JxcTiaVHiJBG7DrCCPhbP9KiF3yAFid26OSsohCjjg/LFWgsCbd@ddmOWEzGYwIqsF9x2TL7QPJ/DIxGHWOcLIj/988v4pO5C34THyfQueonvRFzcgLvuF1i7pjd6XA4zsLMm4W5d2PPNEztTWMbZF4a0tzLnNAkzGKPpk6nhdN85jSJn9V68yKkhUdjaptjz1r@AQ "JavaScript (SpiderMonkey) – Try It Online")
```
^ # tail = K
(?=(x*),\1*(x*)) # \1 = K; \2 = N % K
(?=
(?=
\2 # tail -= \2
\B # Assert 0 < \2 < K
(x*) # \3 = tail == K - \2 == also a tool to make tail = \2
)
( # \4 = (\2 + \2) % K == (N * 2) % K
x*(?=\3\3) # \4 = head = \2 - \3
| # if above failed due to K - \2 > \2 then fall back on:
\2\2 # \4 = \2 + \2
)
)
(?=((?=\4(x*))x*(?=\3\6 )|\4\2)) # \5 = (\4 + \2) % K == (N * 3) % K
(?=((?=\5(x*))x*(?=\3\8 )|\5\2)) # \7 = (\5 + \2) % K == (N * 4) % K
(?=((?=\7(x*))x*(?=\3\10)|\7\2)) # \9 = (\7 + \2) % K == (N * 5) % K
\9{2} # tail = tail - \9*2 == K - \9*2
\b # Assert tail==K or tail==0, which is equivalent to
# asserting (N * 5 * 2) % K == 0
```
This could be shortened greatly in regex flavors with forward-declared backreferences, but it'd still be much longer than 33 bytes.
# [Retina 0.8.2](https://github.com/m-ender/retina/wiki/The-Language/a950ad7d925ec9316e3e2fb2cf5d49fd15d23e3d), ~~42~~ 40 bytes
```
\d+
$*
^(?=(.+)\1*,\1+$)(\1\B|\1{5})\2?,
```
[Try it online!](https://tio.run/##Hcs7DgIxDATQ3ucIUrKxUCa/DQVaiQtwAWsFEhQ0FCs64OzBofCbKcbb/fV4XvvOns16kZunPjATrXY52r13gokF3jgrkNNH8C5fJ3Hh3htnalzooDdz0kTQkikxCuUBIudASMO5DksbxvBXt6UyKiFAnwPp5Ac "Retina 0.8.2 – Try It Online")
[Answer]
# [Raku](http://raku.org/), 16 bytes
```
*/(.1&none 1)%%*
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPtfS19Dz1AtLz8vVcFQU1VV67@1QnFipYJ9mkaNSrymQlp@kYKNhYKJnQ6IMgVRlhDKXMHY7j8A "Perl 6 – Try It Online")
This is an anonymous function where the asterisks represent the two arguments. The main expression is `* / X %% *`, which checks that the first argument divided by an expression X is divisible by the second argument. `X` here is an and-junction of the number `.1`, and the none-junction of the number `1`. Raku threads the expression over the junction, producing a truthy value if the first argument divided by `.1` is divisble by the second argument, AND the first argument divided by `1` is NOT divisible by the second argument.
The return value is a junction of boolean values, which collapses into a single value in a boolean context. Fortunately, this challenge did not stipulate that the return value must be one of two distinct values, or I'd have to add a `so` to collapse the junction to a regular boolean, for two more bytes.
Note that I used division instead of multiplication because an extra space would have been required to separate the first function argument from the multiplication operator: `* *(10&none 1)%%*`. `.1` is a rational number in Raku, not a floating-point number, so there's no danger of floating-point rounding error.
[Answer]
# Java, 35 bytes
```
n->k->(n/k+"").matches(".+\\.[^0]")
```
Port of my [JavaScript answer](https://codegolf.stackexchange.com/a/220304/99986).
[Try it online!](https://tio.run/##lY1Ba8JAEIXv@RVLTruVTAUrWmxzKt4EwaNaGDcbu8lmd8lOBBF/e7rF2LO@y/DefPOmwhNmVVH3uvGuJVZFDx1pA2VnJWln4WWR@O5gtGTSYAhshdpeEhY1xIGQ4jg5XbAmLvmGWm2P2z3D9hjEjf3Tl4sHajkUf9zsulWFlkgqZ@Vnb7O8znJuX@tRmgpokOSPCjyF0W4H2@/xPhX94r9wcw6kGnAdgY8vyVheAnpvznwugFQg/ibEU/z0Qf79SX428JM7f02u/S8)
# Java, 20 bytes
```
n->k->n*10%k<1&n%k>0
```
Port of [xnor's answer](https://codegolf.stackexchange.com/a/220283/99986).
[Try it online!](https://tio.run/##lY1BC4JAEIXv/oq9FCq4KBUVmqfoFgQeo8Omq6yuu4s7ChL@dtvQOue7DO/NN29K0hGvzKqR1Uo2gErjcQuM47wVKTApsBtaqn1ylqKUE63RlTDxspDRHGsgYEYnWYZqs7QTaJgo7g9EmkI7E/vRWZoDepmLo8neGpqxlACNUX4ahRdXXizcwF9VUbAWqyr2x/DXkPQaaI1lC1iZH8CFnWOiFO/tg4OBarC3jrOI3/3JHxfy@5nffPnBGsY3)
[Answer]
# JavaScript, 22 bytes
```
n=>k=>/\..$/.test(n/k)
```
Checks that there is exactly one decimal place after division.
[Try it online!](https://tio.run/##y0osSyxOLsosKNEts/ifZvs/z9Yu29ZOP0ZPT0VfryS1uEQjTz9b839BUWZeiUaahoWmhommJhcS1xSJa4nKNdfUMNbU/A8A)
[Answer]
# Scala, 20 bytes
```
n=>k=>n%k-n*10%k*k>0
```
[Try it in Scastie](https://scastie.scala-lang.org/uFovZj1ZReWVY1LcySfBvA)
If `n` is divisible by `k` but not `n*10`, `n%k-n*10%k*k` is negative. If the both are divisible by `k`, it's 0. If only `n*10` is divisible by `k`, it's positive. If neither is divisible by `k`, it's still negative, because we're multiplying the second by `k` to make it bigger.
[Answer]
# [Templates Considered Harmful](https://github.com/feresum/tmp-lang), 51 bytes
```
Fun<If<Rem<Mul<I<10>,A<1>>,A<2>>,F,Rem<A<1>,A<2>>>>
```
[Try it online!](https://tio.run/##K0nNLchJLEkt/u9YYPPfrTTPxjPNJig118a3NMfG08bQwE7H0cbQDkQaAUk3HZAcSAQiYGf3X4eL09PG0g5Mmdpx2f0HAA "Templates Considered Harmful – Try It Online")
Implementation of [xnor's answer](https://codegolf.stackexchange.com/a/220283/66421). Anonymous function that takes 2 arguments.
```
Fun<
If<Rem<Mul<I<10>,A<1>>,A<2>>, # if 10n%k > 0
F, # false
Rem<A<1>,A<2>>>> # else n%k
```
[Answer]
## [Kustom](https://help.kustom.rocks/s1-general/knowledgebase/top/c2-functions), 30 bytes
this one is really small for a language for making android widgets O.o
```
$tc(cut,gv(n)/gv(k),-2,1)=.$
```
28+2 extra bytes for global names
] |
[Question]
[
Write a program that displays on the screen the sum of the divisors of a number (1 ≤ N ≤ 100) entered by the user in the range of 1 to N.
This is [OEIS A000203](https://oeis.org/A000203).
---
Examples:
**Input**: 7
```
7 / 1 = 7
7 / 7 = 1
7 + 1 = 8
```
**Output:** 8
---
**Input:** 15
```
15 / 1 = 15
15 / 3 = 5
15 / 5 = 3
15 / 15 = 1
15 + 5 + 3 + 1 = 24
```
**Output:** 24
---
**Input:** 20
```
20 / 1 = 20
20 / 2 = 10
20 / 4 = 5
20 / 5 = 4
20 / 10 = 2
20 / 20 = 1
20 + 10 + 5 + 4 + 2 + 1 = 42
```
**Output:** 42
---
**Input:** 1
```
1 / 1 = 1
```
**Output:** 1
---
**Input:** 5
```
5 / 1 = 5
5 / 5 = 1
5 + 1 = 6
```
**Output:** 6
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E), 2 bytes
```
ÑO
```
[Try it online!](https://tio.run/##MzBNTDJM/f//8ET///@NDAA "05AB1E – Try It Online")
### How?
```
Ñ Divisors
O Sum
```
[Answer]
# x86-64 Machine Code, 23 bytes
```
89 F9 89 FE EB 0D 89 F8 99 F7 F1 85 D2 99 0F 44 D1 01 D6 E2 F1 96 C3
```
The above bytes of code define a function that accepts a single integer, N, and returns the sum of its multiples as a result.
The single parameter is passed in the `EDI` register, consistent with the System V AMD64 ABI (as used on \*nix-style systems). The result is returned in the `EAX` register, as with all x86 calling conventions.
The algorithm is a very straightforward one, similar to many of the other submissions in other languages. We loop N times, each time computing the modulo and adding that to our running total.
**Ungolfed assembly mnemonics:**
```
; unsigned SumOfMultiples(unsigned N /* (EDI) */)
mov ecx, edi ; make copy of input N, to be used as our loop counter
mov esi, edi ; make copy of input N, to be used as our accumulator
jmp CheckEnd ; jump directly to 'CheckEnd'
AddModulo:
mov eax, edi ; make copy of input N, to be used as input to DIV instruction
cdq ; short way of setting EDX to 0, based on EAX
div ecx ; divide EDX:EAX by ECX, placing remainder in EDX
test edx, edx ; test remainder, and set ZF if it is zero
cdq ; again, set EDX to 0, without clobbering flags
cmovz edx, ecx ; set EDX to ECX only if remainder was zero (EDX = ZF ? 0 : ECX)
add esi, edx ; add EDX to accumulator
CheckEnd:
loop AddModulo ; decrement loop counter (ECX), and keep looping if it != 0
xchg eax, esi ; move result from accumulator (ESI) into EAX
ret ; return, with result in EAX
```
**[Try it online!](https://tio.run/##bY5NasMwEIXX1ikGl4Jd6kZS/YvbLBrHl4i6MLLjCBK5WDIISq9eV8UKycKLYeY9vpk3POo5n2c@SKWBn5oRTJ7uhrY7fMI7@MzkBTN14fqemf0HM7hyOmem@O@ZLWK9hJmKLh6umYljq62PbVWp3aULV9h59@qXSOlGCw6TVKKXXQvBk02vjQyDqxXaL9xH5fwgJD9PbQdvSrdieDltERJSw6URMgjRN/K@RquPgQ8Z09GW6ceWSf8ZlqsBZGFYepsN5DeSJGskSRxJ4xtK8RpKsUNjepdPVvOJQ8kduZoP1/wUecgbOz2NEnCJfuZffjw3vZqjSxr/AQ)**
It sure seems like there should be a way to make this shorter, but I can't see it. Computing modulo on x86 takes quite a bit of code, since you do it using the `DIV` (or `IDIV`) instruction, and both of those use fixed input registers (`EDX` and `EAX`), the values of which get clobbered (because they receive the results, the remainder and quotient, respectively).
The only real tricks here are pretty standard golfing ones:
* I've structured the code in a somewhat unusual way so that I can use the CISC-style `LOOP` instruction, which is basically just a combination of `DEC`+`JNZ` with the `ECX` register as the implicit operand.
* I'm using `XCHG` at the end instead of `MOV` because the former has a special 1-byte encoding when `EAX` is one of the operands.
* I use `CDQ` to zero out `EDX` in preparation for the division, even though for unsigned division you would ordinarily just zero it using a `XOR`. However, `XOR` is always 2 bytes, while `CDQ` is only 1 byte. I use `CDQ` again a second time inside of the loop to zero `EDX`, before the `CMOVZ` instruction. This works because I can be guaranteed that the quotient of the division (in `EAX`) is always unsigned, so a sign-extension into `EDX` will set `EDX` equal to 0.
[Answer]
# C (gcc), 45 bytes
```
i,s;f(n){for(s=i=n;--i;)s+=n%i?0:i;return s;}
```
[Try it online!](https://tio.run/##Xc/RCoIwGIbh4@0qhiFs5HITzWhpN@JJTFc/1IxtHonXbh0YiYcfPPDyaX7Xep4h8cpQy0bTO@orqKziHBTz@8rGcBVnUK4Lg7PEq2negdXPoe3IxYcW@sOjxhhsIK8bWMrwiNHbfbehESmbwOsmxG1jo4QYSkrGFEpTcvojWWyQLBaU5X@ViY3KxKLybBWU26BclFyhbZD8gkeMMFqeCoWn@QM "C (gcc) – Try It Online")
[Answer]
## C, C++, C#, D, Java, ~~65~~ 62 bytes
```
int d(int n){int s=0,i=1;for(;i<=n;++i)s+=n%i>0?0:i;return s;}
```
This works in all theses 5 programming languages because of similarities.
### C, C++ and D optimization : ~~62~~ 60 bytes
In C++ and D, integers convert implicitly to booleans ( Zero => false, Not Zero => true ), so you don't need to have the `!=0`
```
int d(int n){int s=0,i=1;for(;i<=n;++i)s+=n%i?0:i;return s;}
```
### D optimization : golfy template system, 55 bytes
```
T d(T)(T n){T s,i=1;for(;i<=n;++i)s+=n%i?0:i;return s;}
```
### C++ optimization by c and c-- : ~~53~~ 52 bytes
```
int f(int n,int i=0){return++i<n?f(n,i)+i*!(n%i):n;}
```
**Code to test** :
C :
```
printf("%d %d %d %d %d", d(7), d(15), d(20), d(1), d(5));
```
C++ :
```
std::cout << d(7) << ' ' << d(15) << ' ' << d(20) << ' ' << d(1) << ' ' << d(5);
```
C# :
```
class FindSum
{
int d(int n) { int s = 0, i = 1; for (; i <= n; ++i) s += n % i > 0 ? 0 : i; return s; }
static void Main(string[] args)
{
var f = new FindSum();
Console.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}", f.d(7), f.d(15), f.d(20), f.d(1), f.d(5)));
}
}
```
D :
```
writeln(d(7));
writeln(d(15));
writeln(d(20));
writeln(d(1));
writeln(d(5));
```
Java :
```
public class FindSum {
int d(int n){int s=0,i=1;for(;i<=n;++i)s+=n%i>0?0:i;return s;}
public static void main(String[] args) {
FindSum f = new FindSum();
System.out.println(String.format("%d, %d, %d, %d, %d", f.d(7), f.d(15), f.d(20), f.d(1), f.d(5)));
}
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 3 bytes
```
â)x
```
[Try it online!](https://ethproductions.github.io/japt/?v=1.4.5&code=4il4&input=MjA=)
[Answer]
# [Brachylog](https://github.com/JCumin/Brachylog), 2 bytes
```
f+
```
[Try it online!](https://tio.run/##SypKTM6ozMlPN/r/P037/38jg/9RAA "Brachylog – Try It Online")
### Explanation
```
f Factors
+ Sum
```
[Answer]
# Mathematica, 14 bytes
```
Tr@Divisors@#&
```
or an answer by @Loki
# Mathematica, 17 bytes
```
DivisorSum[#,#&]&
```
[Answer]
# [Shnap](https://github.com/ShnapLang/Shnap), ~~44~~ 43 bytes
-1 bye thanks to Mr. Xcoder (lol I was outgolfed in my own language)
```
$n return:{s=0for d:range(n+1)if n%d<1s+=d}
```
This is a function (`$` starts a function in Shnap).
[Try it online!](https://tio.run/##K87ISyz4n2b7XyVPoSi1pLQoz6q62NYgLb9IIcWqKDEvPVUjT9tQMzNNIU81xcawWNs2pfY/SDbaXMfQVMfIQMdQxzRWoaAoM68kJ08jTSOzRFPzPwA)
Explanation:
```
$ n //Start function with parameter n
return: { //Technically, we are returning a scope-block, which evaluates to the last statement run
s = 0 //Our result
for d : range(n+1) //For each value in the iterator range(n+1)
if n % d < 1 // If n is divisible by d
s += d // Add d to the sum
// Since (s += d) returns (s + d), and a scope-block returns the last run statement, this will be the last statement and equal to our result
}
```
---
# Noncompeting, 19 bytes
After many language updates, this can now be reduced to a measly 19 bytes:
```
$n=>sum(factors(n))
```
[Try it online!](https://tio.run/##K87ISyz4n2b7XyXP1q64NFcjLTG5JL@oWCNPU/N/Wn6RQrS5jqGpjpGBjqGOaaxCQVFmXklOnkaaRmYJUAEA)
[Answer]
# [Risky](https://github.com/Radvylf/risky), 3 bytes
```
+/?+??
```
[Try it online!](https://radvylf.github.io/risky?p=WyIrLz8rPz8iLCJbN10iLDBd)
[Answer]
# Python, 44 bytes
```
lambda k:sum(i*(k%i<1)for i in range(1,1+k))
```
* Thanks to Stephen, save 1 byte by removing whitespace.
* Thanks to Jonathan Frech, save another 1 byte by changing if to multiply.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 5 bytes
```
sigma
```
[Try it online!](https://tio.run/##K0gsytRNL/ifpmCr8L84Mz038X9afpFGHpBrqKNgaGCgo1BQlJlXAhRRUtC1AxJpGnmampr/AQ "Pari/GP – Try It Online")
[Answer]
# J, 23 bytes
```
[:+/](([:=&0]|[)#])1+i.
```
[Try it online!](https://tio.run/##y/r/P81WTyHaSls/VkMj2spWzSC2JlpTOVbTUDtTjys1OSNfIU3B0BTGMjKAi/3/DwA "J – Try It Online")
For J fans, there is a [clever 13 byte solution](http://code.jsoftware.com/wiki/Essays/Divisors#Sum_of_Divisors): `>:@#.~/.~&.q:` but since it wasn't my invention I'm not posting it as my official answer.
My own solution simply filters 1..n, finding divisors, then sums them. The crux of it is the dyadic fork
```
](([:=&0]|[)#])
```
Note that in this context `]` is 1..n, and `[` is n itself. Hence `]|[` are the remainders when dividing each element of 1..n into n, and `=&0` tells you if they're equal to 0.
[Answer]
# [Pyth](https://pyth.readthedocs.io), 6 bytes
```
s*M{yP
```
**[Try it here!](https://pyth.herokuapp.com/?code=s%2aM%7ByP&input=20&debug=0)**
Pyth doesn't have a built-in for divisors, so I think this is reasonable.
# Explanation
```
s*M{yP - Full program with implicit input.
P - The prime factors of the input.
y - The powerset of its prime factors.
{ - Deduplicate.
*M - Map with multiplication.
s - Sum.
- Implicitly display the result.
```
Given `20`, for instance, this is what our program does after each instruction:
* `P`: `[2, 2, 5]`.
* `y`: `[[], [2], [2], [5], [2, 2], [2, 5], [2, 5], [2, 2, 5]]`.
* `{`: `[[], [2], [5], [2, 2], [2, 5], [2, 2, 5]]`.
* `*M`: `[1, 2, 5, 4, 10, 20]`.
* `s`: `42`.
[Answer]
# [Java (OpenJDK 8)](http://openjdk.java.net/), ~~53~~ 51 bytes
```
n->{int s=0,i=0;for(;i++<n;)s+=n%i<1?i:0;return s;}
```
[Try it online!](https://tio.run/##lY5BS8NAEIXv@RVzERJil1QQwW0Ujx6sh@JJPIxpUibdzi67s4VQ8tvjVoJn847D9@Z9PZ5xZV3L/f44ufhtqIHGYAjwhsRwySAlCEq6d8RooE8NFYWM6iI3QpbVK8sHox/eXetRrIct1BOvni7EAqGubqmudGd9rqksN6yLUNZ8Q5v1Mz1W2rcSPUPQ43Qd09nv5uwyT58t7eGUjPKdeOLD5xegP4RiFrxmNwRpT8pGUS4hYjjfKnTODC8hCeYPRaH/Da/vl9B31aLfS@A/jzEbpx8 "Java (OpenJDK 8) – Try It Online")
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 2 bytes
```
Æs
```
[Try it online!](https://tio.run/##y0rNyan8//9wW/H////NAQ "Jelly – Try It Online")
Built-in that does exactly as wanted.
[Answer]
# [Haskell](https://www.haskell.org/), 30 bytes
```
f n=sum[i|i<-[1..n],n`mod`i<1]
```
[Try it online!](https://tio.run/##y0gszk7Nyfn/P00hz7a4NDc6sybTRjfaUE8vL1YnLyE3PyUh08Yw9n9uYmaegq1CQWlJcEmRT56CikJxRn45kMpNLFDQiMlT0LVT0AAL5WkqaGsrKIEElEAsiKgG0HxNTU2FaHMdBUNTHQUjAyCto2Aa@x8A "Haskell – Try It Online")
[Answer]
# [MATL](https://github.com/lmendo/MATL), 6 bytes
```
t:\~fs
```
[Try it online!](https://tio.run/##y00syfn/v8Qqpi6t@P9/IwMA "MATL – Try It Online")
-4 bytes thanks to @LuisMendo
# 10 bytes
My previous solution using a loop
```
:"G@\~@*vs
```
[Try it online!](https://tio.run/##y00syfn/30rJ3SGmzkGrrPj/fyMDAA "MATL – Try It Online")
# 3 bytes
Using built-in
```
Z\s
```
[Try it online!](https://tio.run/##y00syfn/Pyqm@P9/I4P/AA "MATL – Try It Online")
[Answer]
# Javascript, ~~54~~ 44 bytes
```
n=>[...Array(x=n)].reduce(y=>y+!(n%x)*x--,0)
```
Saved 10 bytes thanks to [Shaggy](https://codegolf.stackexchange.com/users/58974/shaggy)
### Try it online!
```
const f = n=>[...Array(x=n)].reduce(y=>y+!(n%x)*x--,0)
console.log(f(7))
console.log(f(15))
console.log(f(20))
console.log(f(1))
console.log(f(5))
```
[Answer]
# [Brain-Flak](https://github.com/DJMcMayhem/Brain-Flak), 96 bytes
```
((({})<>){<(([()]{})){<>(({})(<()>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({})){((<{}{}>))}}{}>{}})
```
[Try it online!](https://tio.run/##LYsxCoBADAS/sylsrCxCPnJYnIUgioXtkrfHPRFCyM5Otqcf97Rf/awCwDQPowMNtirpjg/DYWFq@UWj9nBEkqmR15gifw2nqF5GGVKsal5e "Brain-Flak – Try It Online")
## Explanation:
Now outdated by improvements.
The heart of the algorithm is this:
```
({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({})) turns |N, M...| into |N mod M, M...|
{((<{}{}>))} if the top of stack is not zero, replace it and the second with zero
```
That is a modification on mod that will give us `M` if it is a factor of `N` and `0` otherwise. Full code is below.
```
((({})<>) place input, N on both stacks
{ Loop to find factors
<
(([()]{})) Decrement and Duplicate; get next factor to check
{ if not zero
(<>({})<>) Copy N from other stack
({}(<>))<>{(({})){({}[()])<>}{}}{}<>([{}()]({})){((<{}{}>))} Code explained above
}
{} drop the zero
>
{} add the factor
}) push the sum
```
[Answer]
# [R](https://www.r-project.org/), ~~31~~ 26 bytes
```
function(N)(x=1:N)%*%!N%%x
```
[Try it online!](https://tio.run/##K/qfZvs/rTQvuSQzP0/DT1OjwtbQyk9TVUtV0U9VteJ/moahgeZ/AA "R – Try It Online")
Returns a `1x1` matrix.
Computes `!N%%x` maps elements `d` of `1:N` by: `d->(1 if d divides N, 0 otherwise)`
Then `x%*%x!N%%x` is the matrix product of `1:N` which results in the sum of `x` where `!N%%x` is `1`. Neat! Technically a port of Luis Mendo's [Octave answer](https://codegolf.stackexchange.com/a/142151/67312) but I only saw that after I thought of this.
# [R](https://www.r-project.org/)+ numbers, 14 bytes
```
numbers::Sigma
```
[Try it online!](https://tio.run/##K/r/P680Nym1qNjKKjgzPTfx/38A "R – Try It Online")
[Answer]
# TI-Basic, 16 bytes
```
sum(seq(Inot(fPart(Ans/I)),I,1,Ans
```
Takes input in `Ans`. Output is stored in `Ans` and displayed.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal) `s`, 1 byte
```
K
```
[Try it Online!](https://vyxal.pythonanywhere.com/#WyJzIiwiIiwiSyIsIiIsIjciXQ==)
`K∑` flagless. `K` just gets the divisors of a number.
[Answer]
# [Husk](https://github.com/barbuz/Husk), 2 bytes
```
ΣḊ
```
[Try it online!](https://tio.run/##yygtzv7//9zihzu6/v//b2QAAA "Husk – Try It Online")
[Answer]
# [Raku](https://www.raku.org/), ~~25~~ ~~23~~ 22 bytes
thanks ovs for 2 byte improvement
also JoKing for 1 byte improvement
```
{sum grep $_%%*,1..$_}
```
```
declare anonymous block ($_ implicitly declared)
filter (grep) numbers from 1 to $_ inclusive using the whatever variable (*) that are divisible by $_
get the sum of that list
```
[Try it online!](https://tio.run/##NY3NCoJAGEX331NcRMMJHRpRC8SeoqUggUMM@YejRojPPn0u2p5zOXfUU5u77otTY9bYLh1Kt4VKSr8W8jXpMfTrIDgLyWp3i9V4aDsXRK3ptZXvVXbPMYzvqEzfRKgOjI0ATobMGA3LLFDiMPIzTI0tWBsL08v/aQQeRfBmbmPj0u7RLtwVN1IZkpSSC9KEFBRlyH8 "Raku – Try It Online")
[Answer]
# Excel VBA, 41 Bytes
Anonymous VBE immediate window function that takes input from `[A1]` and outputs to the VBE immediate window
```
For i=1To[A1]:s=s-i*([A1]mod i=0):Next:?s
```
# Excel, 41 Bytes
Worksheet formula that takes input from `[A1]` and outputs to the caller
Requires MS Excel Version 16.0 or later for access to `Let(...)` function
```
=LET(a,SEQUENCE(A1),SUM((MOD(A1,a)=0)*a))
```
[Answer]
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~74~~ 73 bytes
```
(load library
(d D(q((K N)(i K(a(i(mod N K)0 K)(D(s K 1)N))0
(q((N)(D N N
```
[Try it online!](https://tio.run/##FcohEoAgEAXQ7il@/NsgeAMaMxROgEPZGRQFC6dHDK@9V69RtN9zstSUUfRoqY2NGY4P6RGECs9E5VkzAryYhY4dHlaCiPl7/PvKbpUwGWH3@QE "tinylisp – Try It Online")
-1 byte thanks to DLosc.
And without `library` just for fun:
# [tinylisp](https://github.com/dloscutoff/Esolangs/tree/master/tinylisp), ~~97~~ 90 bytes
```
(d D(q((N K)(i(l N K)N(D(s N K)K
(d F(q((K N)(i K(a(i(D N K)0 K)(F(s K 1)N))0
(q((N)(F N N
```
[Try it online!](https://tio.run/##Hcw9DoUwDAPgnVN4dDY6cIOKJVIWTlDEUqnv8btw@pJ2s@IvfvL/Lfk@auWGyJM0qDCzoAVj5N2TDg7mBhTmAMrkLPZybD@zS0UQExkbXvqa351YZdnThpLXK12vDPylAwsYnh1hEqkf "tinylisp – Try It Online")
-7 bytes thanks to DLosc.
[Answer]
# JavaScript, 31 bytes
```
f=(n,i=n)=>i&&!(n%i)*i+f(n,i-1)
```
[Answer]
# Bash + GNU utilities, 36
```
bc<<<`seq -f"n=%g;a+=n*!$1%%n;" $1`a
```
[Try it online](https://tio.run/##S0oszvj/PynZxsYmoTi1UEE3TSnPVjXdOlHbNk9LUcVQVTXPWklBxTAh8f///4amAA).
---
# Pure Bash, 41
```
for((;++i<=$1;a+=$1%i?0:i))
{
:
}
echo $a
```
[Try it online](https://tio.run/##S0oszvj/Py2/SEPDWls708ZWxdA6URtIqmbaG1hlampyVXNZcdVypSZn5CuoJP7//9/QFAA).
I first tried a fancy bash expansion answer, but it ended up being longer than the simple loop above:
```
echo $[$(eval echo +\\\(n={1..$1},$1%n?0:n\\\))]
```
[Answer]
# [Python 2](https://docs.python.org/2/), 41 bytes
```
f=lambda n,i=1:i<=n and(n%i<1)*i+f(n,i+1)
```
[Try it online!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIU8n09bQKtPGNk8hMS9FI08108ZQUytTO00DKKNtqPk/JTVNwU0jT9OKi7OgKDOvBKgDKKfJxeWmYa4JJAxNQaSRAYgEM4F6AA "Python 2 – Try It Online")
[Answer]
# VBA (Excel), 73 bytes
```
a=Cells(1,1)
x=1
While x<=a
If a Mod x = 0 Then b=b+x
x=x+1
Wend
MsgBox b
```
] |
[Question]
[
**Input:**
* A string (the wave-snippet) with a length `>= 2`.
* A positive integer *n* `>= 1`.
**Output:**
We output a single-line wave. We do this by repeating the input string *n* times.
**Challenge rules:**
* If the first and last character of the input string matches, we only output it once in the total output (i.e. `^_^` of length 2 becomes `^_^_^` and not `^_^^_^`).
* The input string won't contain any whitespaces/tabs/new-lines/etc.
* If your language doesn't support non-ASCII characters, then that's fine. As long as it still complies to the challenge with ASCII-only wave-input.
**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](http://meta.codegolf.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, full programs. Your call.
* [Default Loopholes](http://meta.codegolf.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:**
```
_.~"( length 12
_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(
'°º¤o,¸¸,o¤º°' length 3
'°º¤o,¸¸,o¤º°'°º¤o,¸¸,o¤º°'°º¤o,¸¸,o¤º°'
-__ length 1
-__
-__ length 8
-__-__-__-__-__-__-__-__
-__- length 8
-__-__-__-__-__-__-__-__-
¯`·.¸¸.·´¯ length 24
¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯
** length 6
*******
String & length of your own choice (be creative!)
```
[Answer]
## Python 3, 32 bytes
```
lambda s,n:s+s[s[0]==s[-1]:]*~-n
```
Concatenates `n` copies of the string, removing the first character from all copies but the first if the first character matches the last one.
[Answer]
# [05AB1E](http://github.com/Adriandmen/05AB1E), 13 bytes
Uses [CP-1252](http://www.cp1252.com/) encoding.
```
D¬U¤XQi¦}I<×J
```
[Try it online!](http://05ab1e.tryitonline.net/#code=RMKsVcKkWFFpwqZ9STzDl0o&input=wq9gwrcuwrjCuC7Ct8K0wq8KOA)
**Explanation**
`-___-` and `3` used as input for example.
```
D # duplicate input string
# STACK: "-___-", "-___-"
¬U¤X # push copies of the first and last element of the string
# STACK: "-___-", "-___-", "-", "-"
Q # compare for equality
# STACK: "-___-", "-___-", 1
i¦} # if true, remove the first char of the copy of the input string
# STACK: "-___-", "___-"
I< # push input number and decrease by 1
# STACK: "-___-", "___-", 2
× # repeat the top string this many times
# STACK: "-___-", "___-___-"
J # join with input string
# STACK: "-___-___-___-"
# implicitly output
```
[Answer]
## JavaScript (ES6), 47 bytes
```
f=
(s,n)=>s+s.slice(s[0]==s.slice(-1)).repeat(n-1)
;
```
```
<div oninput=o.textContent=n.value&&f(s.value,n.value)><input id=s><input id=n type=number min=1><div id=o>
```
[Answer]
## Perl, 29 bytes
**28 bytes code + 1 for `-p`.**
Thanks to [@Dada](https://codegolf.stackexchange.com/users/55508/dada) for helping me shave off a few bytes!
```
s/^((.).*?)(\2?)$/$1x<>.$3/e
```
### Usage
```
perl -pe 's/^((.).*?)(\2?)$/$1x<>.$3/e' <<< "'°º¤o,¸¸,o¤º°'
3"
'°º¤o,¸¸,o¤º°'°º¤o,¸¸,o¤º°'°º¤o,¸¸,o¤º°'
perl -pe 's/^((.).*?)(\2?)$/$1x<>.$3/e' <<< '**
6'
*******
```
[Online example.](https://ideone.com/SiWXQ0#view_edit_box)
[Answer]
## Pyke, ~~15~~ ~~14~~ 10 bytes
```
tQQhQeq>*+
```
[Try it here!](http://pyke.catbus.co.uk/?code=tQQhQeq%3E%2a%2B&input=-__-%0A3)
```
QhQeq - input_1[0] == input_1[-1]
Q > - input_1[^:]
* - ^ * V
t - input_2 - 1
+ - input_1 + ^
```
[Answer]
# Perl, 23 bytes
Includes +1 for `-p`
Give input string followed by number on separate lines on STDIN
```
wave.pl <<< "'°º¤o,¸¸,o¤º°'
3"
```
`wave.pl`:
```
#!/usr/bin/perl -p
$_ x=<>;s/(.)\K
\1?//g
```
If the first character in the word is not a regex special character this 22 bytes version works too:
```
#!/usr/bin/perl -p
$_ x=<>;/./;s/
$&?//g
```
[Answer]
## [Retina](http://github.com/mbuettner/retina), 29 bytes
Lines 2 and 5 have a trailing space.
```
.+
$*
$
$`
(.) +\1?
$1
```
[Try it online!](http://retina.tryitonline.net/#code=JShHYAogLisKJCogCiAkCgogCiAkYAooLikgK1wxPwokMQ&input=Xy5-IiggMTIKJ8KwwrrCpG8swrjCuCxvwqTCusKwJyAzCi1fXyAxCi1fXyA4Ci1fXy0gOArCr2DCty7CuMK4LsK3wrTCryAyNAoqKiA2CsKvXF8o44OEKV8vwq8gMTE) (The first line enables a linefeed-separated test suite.)
[Answer]
## Batch, 117 bytes
```
@set/ps=
@set t=%s%
@if %s:~0,1%==%s:~1% set t=%s:~1%
@for /l %%i in (2,1,%1)do @call set s=%%s%%%%t%%
@echo %s%
```
Takes the number of repetitions as a command-line parameter and reads the string from STDIN.
[Answer]
# MATL, ~~19~~ ~~17~~ 14 bytes
```
ttP=l):&)liX"h
```
This works for ASCII on the online interpreter and for both unicode and ASCII when run using MATLAB.
[**Try it Online!**](http://matl.tryitonline.net/#code=dHRQPWwpOiYpbGlYImg&input=JypfXyonCjU&debug=on)
**Explanation**
```
% Implicitly grab the input as a string
% STACK: {'abcdea'}
%
tt % Make two copies and push them to the stack
% STACK: {'abcdea' 'abcdea' 'abcdea'}
%
P % Flip the second copy around
% STACK: {'abcdea' 'abcdea' 'aedcba'}
%
= % Perform an element-wise comparison. Creates a boolean array
% STACK: {'abcdea' [1 0 0 0 1]}
%
l) % Get the first element. If the first and last char are the same this will be
% TRUE (1), otherwise FALSE (0)
% STACK: {'abcdea' 1 }
%
: % Create an array from [1...previous result]. If the first char was repeated,
% this results in the scalar 1, otherwise it results in an empty array: []
% STACK: {'abcdea' 1 }
%
&) % Break the string into pieces using this index. If there were repeated
% characters, this pops off the first char, otherwise it pops off
% an empty string
% STACK: {'a' 'bcdea'}
%
li % Push the number 1 and explicitly grab the second input argument
% STACK: {'a' 'bcdea' 1 3}
%
X" % Repeat the second string this many times
% STACK: {'a' 'bcdeabcdeabcdea'}
%
h % Horizontally concatenate the first char (in case of repeat)
% or empty string (if no repeat) with the repeated string
% STACK: {'abcdeabcdeabcdea'}
%
% Implicitly display the result
```
[Answer]
# Pyth, 13 bytes
```
+z*@tBzqhzezt
```
[Test suite!](http://pyth.herokuapp.com/?code=%2Bz%2a%40tBzqhzezt&input=5%0A%C2%AF%60%C2%B7.%C2%B8&test_suite=1&test_suite_input=12%0A_.%7E%22%28%0A3%0A%27%C2%B0%C2%BA%C2%A4o%2C%C2%B8%C2%B8%2Co%C2%A4%C2%BA%C2%B0%27%0A1%0A-__%0A8%0A-__%0A8%0A-__-%0A24%0A%C2%AF%60%C2%B7.%C2%B8%C2%B8.%C2%B7%C2%B4%C2%AF%0A6%0A%2a%2a%0A7%0AString+%26+length+of+your+own+choice+%28be+creative%21%29&debug=0&input_size=2)
Explanation to follow.
[Answer]
# Gema, 41 characters
```
* *=@subst{\? \$1=\?\; =;@repeat{$2;$1 }}
```
Sample run:
```
bash-4.3$ gema '* *=@subst{\? \$1=\?\; =;@repeat{$2;$1 }}' <<< '_.~"( 12'
_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(
bash-4.3$ gema '* *=@subst{\? \$1=\?\; =;@repeat{$2;$1 }}' <<< "'°º¤o,¸¸,o¤º°' 3"
'°º¤o,¸¸,o¤º°'°º¤o,¸¸,o¤º°'°º¤o,¸¸,o¤º°'
bash-4.3$ gema '* *=@subst{\? \$1=\?\; =;@repeat{$2;$1 }}' <<< '** 6'
*******
```
[Answer]
# PowerShell v2+, 48 bytes
```
Param($s,$n)$s+$s.Substring($s[0]-eq$s[-1])*--$n
```
Outputs the whole string once, followed by n-1 copies of the string or substring, depending on if the first and last characters match.
The `.Substring()` method outputs from the index supplied to the end of the string, so if `$s[0]-eq$s[-1]` evaluates to false (0), we get the whole string. If that statement is true (1), We get the substring starting at the second character.
[Answer]
# VBA 119 bytes
New to this game and vba wins with the highest bytes :P
PS: can't believe vba stands close to JAVA **HAHA**
```
Function l(s,x)
l=s: s=IIf(Left(s,1)=Right(s,1),Mid(s,2,Len(s)),s)
z: x=x-1: If x>0 Then l=l & s: GoTo z:
End Function
```
Explanation:
```
+------------------------------------------------------------+-----------------------------------------------------------------------------------+
| code | function |
+------------------------------------------------------------+-----------------------------------------------------------------------------------+
| l=s | input string s is saved to base |
| s = IIf(Left(s, 1) = Right(s, 1), Right(s, Len(s) - 1), s) | checks whether 1 and last char is equal, |
| | if yes removes the first char from s and that s will be used to for further joins |
| z: | z: is a label |
| x = x - 1: | decreases looping round |
| If x > 0 Then l = l & s: GoTo z: | join strings until no more rounds to do |
+------------------------------------------------------------+-----------------------------------------------------------------------------------+
```
[Answer]
## K, 12 Bytes
```
{,/[y#(,)x]}
/in action
{,/[y#(,)x]}["lollol";4]
"lollollollollollollollol"
{,/[y#(,)x]}["-_";10]
"-_-_-_-_-_-_-_-_-_-_"
/explanation (read function from right to left)
x is the string and y is the number of repetitions
(,)y --enlist x so it becomes 1 value (rather than a list)
y#x --take y many items of x
,/ --coalesce the list ,/[("-_";"-_")] --> "-_-_"
```
Thanks
[Answer]
# PHP, 72 Bytes
```
<?=($a=$argv[1]).str_repeat(substr($a,$a[0]==substr($a,-1)),$argv[2]-1);
```
with PHP 7.1 it could be reduce to 65 Bytes
```
<?=($a=$argv[1]).str_repeat(substr($a,$a[0]==$a[-1]),$argv[2]-1);
```
[Answer]
## [Pip](http://github.com/dloscutoff/pip), 18 bytes
Regex solution, taking advantage of the "no spaces in input" rule. Takes the string from stdin and the number as a command-line argument.
```
(q.s)XaR`(.) \1?`B
```
[Try it online!](http://pip.tryitonline.net/#code=KHEucylYYVJgKC4pIFwxP2BC&input=XsK3LsK4X8yy4pu1X8K4LsK3Xg&args=Mw)
Explanation:
```
q.s Read from stdin and append a space
( )Xa String-multiply by first cmdline arg
R Replace
`(.) \1?` Regex: char followed by space followed by (optional) same char again
B Callback function, short for {b}: return 1st capturing group
```
Thus, `a b` turns into `ab`, `a a` turns into `a`, and the space at the end of the string is removed. Then the result is autoprinted.
[Answer]
# CJam, ~~16~~ 15 bytes
```
l]li*{(s@)@|@}*
```
[Try it online](http://cjam.tryitonline.net/#code=bF1saSp7KHNAKUB8QH0q&input=4paBIOKWgiDiloMg4paFIOKWhiDilocg4paGIOKWhSDiloMg4paCIOKWgQoz)
Explanation:
```
l]li* Create a list of n-times the input string.
{(s@)@|@}* Fold this list by taking out the last character of the first
argument and the first character of the second argument and
replacing them by their unique set union.
e.g.: "aba" "aba" -> "ab" 'a"a"| "ba" -> "ab" "a" "ba"
"abc" "abc" -> "ab" 'c"a"| "bc" -> "ab" "ca" "bc
```
[Answer]
# Haskell, 59 bytes
```
a%b=concat$replicate a b
a@(s:z)#n|s/=last z=n%a|1<2=s:n%z
```
### Ungolfed version:
```
-- Helper: Appends str to itself n times
n % str = concat (replicate n str)
-- Wave creating function
(x:xs) # n
-- If start and end of wave differ,
| x /= last xs = n%(x:xs)
| otherwise = x:(n%xs)
```
[Answer]
# Java 11, ~~123~~ ~~111~~ ~~109~~ ~~107~~ ~~102~~ ~~100~~ ~~79~~ 58 bytes
```
s->n->s+s.substring(s.matches("(.).*\\1")?1:0).repeat(n-1)
```
[Try it online.](https://tio.run/##lY@xTsMwFEX3fIWVpXaIn0hBCFEIGxIDU0eCgpuGkuDYUexUqlD5mu7tgNSK0T8WXBqFDVLJg5/uPe/el7M5o/n0rUk4Uwo9sEy8OwgpzXSWoNyqUOuMw0stEp1JAXft53qsq0zM/D8990Kns7Ty0cEchihBN42ioaChOlGg6on6UbCCgunkNVXYxUDAi6LAJbfB1SmBKi1TprGgAWlGji1X1hNuy7Ud5zKbosL2xoeQxydG9icgNF4onRYgaw2lVTQXOAFWlnyB3Rg@Ihe7pJ2DISGjf6GB2Zgvs5K@2ZmdL83KTptBt@Sszw4ax7@pxwKXPQF6HGHWz2YL@6PAbM2nWXf48LwP73kdcNHHzyW3r2PajKWzbL4B)
I'll of course try to answer my own question. ;)
-5 bytes thanks to *@dpa97*.
**Explanation:**
```
s->n-> // Method with String & integer parameters and String return-type
s // Return the input-String as result
+ // Appended with:
s.subtring( // A substring of the input-String:
s.matches("(.).*\\1")?
// If the first and last characters are the same:
1 // Remove the first character in the substring-call
: // Else:
0) // Use the input-String as is
.repeat(n-1) // Repeated the input-integer minus 1 amount of times
```
[Answer]
# Javascript ES6, 49 chars
```
(s,n)=>s.replace(/(.).*?(?=\1?$)/,m=>m.repeat(n))
```
Test:
```
f=(s,n)=>s.replace(/(.).*?(?=\1?$)/,m=>m.repeat(n))
console.log(document.querySelector("pre").textContent.split(`
`).map(s=>s.split` `).every(([s,n,k])=>f(s,n)==k))
```
```
<pre>_.~"( 12 _.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(
'°º¤o,¸¸,o¤º°' 3 '°º¤o,¸¸,o¤º°'°º¤o,¸¸,o¤º°'°º¤o,¸¸,o¤º°'
-__ 1 -__
-__ 8 -__-__-__-__-__-__-__-__
-__- 8 -__-__-__-__-__-__-__-__-
¯`·.¸¸.·´¯ 24 ¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯`·.¸¸.·´¯
** 6 *******</pre>
```
[Answer]
## [QBIC](https://codegolf.stackexchange.com/questions/44680/showcase-your-language-one-vote-at-a-time/86385#86385), 65 bytes
```
;:~left$$|(A,1)=right$$|(A,1)|A=left$$|(A,len(A)-1)][1,a|B=B+A]?B
```
I guess I should add LEFT$ and RIGHT$ to QBIC...
Explanation:
```
; make the first cmd line parameter into A$
: make the second cmd line parameter into a (num)
~left..] Drop the last char if equal to the first char
[1,a...] FOR the given number of repetitions, concat A$ to B$ (starts out empty)
?B print B$
```
[Answer]
# C#, 79 bytes
```
(s,n)=>s+new string('x',n-1).Replace("x",s[0]==s[s.Length-1]?s.Substring(1):s);
```
A bit of an absurd method of repeating a string. Create a new string of the desired repeat length and then replace each character with the string to repeat. Other than that, looks like pretty much the same strategy as many others.
```
/*Func<string, int, string> Lambda =*/ (s, n) =>
s // Start with s to include first char at start
+ new string('x', n - 1).Replace("x", // Concatenate n-1 strings of...
s[0] == s[s.Length - 1] // if first/last char are the same
? s.Substring(1) // then skip the first char for each concat
: s // else concat whole string each time
)
;
```
[Answer]
# SpecBAS - 68 bytes
```
1 INPUT a$,n: l=LEN a$: ?IIF$(a$(1)<>a$(l),a$*n,a$( TO l-1)*n+a$(l))
```
Uses inline-`IF` to check if first and last characters are the same.
If not, print string `n` number of times.
Otherwise, splice the string to length-1, repeat that and put last character at end.
Can only accept ASCII characters (or characters built into SpecBAS IDE)
[](https://i.stack.imgur.com/df11L.png)
[Answer]
# APL, 19 bytes
```
{⍺,∊1↓⍵⍴⊂⍺↓⍨⊃⍺=⊃⌽⍺}
```
Usage:
```
'^_^' {⍺,∊1↓⍵⍴⊂⍺↓⍨⊃⍺=⊃⌽⍺} 5
^_^_^_^_^_^
```
Explanation:
* `⊃⍺=⊃⌽⍺`: see if the first character matches the last character
* `⍺↓⍨`: if this is the case, drop the first character
* `⊂`: enclose the result
* `⍵⍴`: replicate it `⍵` times
* `1↓`: drop the first one (this is shorter than `(⍵-1)⍴`)
* `∊`: get all the simple elements (undo the boxing)
* `⍺,`: add one instance of the whole string to the front
[Answer]
# Postscript, 98 bytes
```
exch/s exch def/l s length 1 sub def s 0 get s l get eq{/s s 0 l getinterval def}if{s print}repeat
```
...but you might need a ' flush' tacked onto that to get your PS interpreter to flush the comm buffer, another six bytes :(
[Answer]
# Common Lisp (LispWorks), 176 bytes
```
(defun f(s pos)(if(equal(elt s 0)(elt s #1=(1-(length s))))(let((s1(subseq s 0 1))(s2(subseq s 0 #1#)))(dotimes(j pos)(format t s2))(format t s1))(dotimes(j pos)(format t s))))
```
Usage:
```
CL-USER 130 > (f "_.~~\"(" 12)
_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(_.~"(
NIL
CL-USER 131 > (f "'°o¤o,??,o¤o°'" 3)
'°o¤o,??,o¤o°'°o¤o,??,o¤o°'°o¤o,??,o¤o°'
NIL
CL-USER 132 > (f "-__" 1)
-__
NIL
CL-USER 133 > (f "-__" 8)
-__-__-__-__-__-__-__-__
NIL
CL-USER 134 > (f "ˉ`·.??.·′ˉ" 24)
ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ`·.??.·′ˉ
NIL
CL-USER 135 > (f "**" 6)
*******
NIL
```
Explanation:
```
~~ => ~
\" => "
```
Ungolf:
```
(defun f (s pos)
(if (equal (elt s 0) (elt s (1- (length s))))
(let ((s1 (subseq s 0 1)) (s2 (subseq s 0 (1- (length s)))))
(dotimes (j pos)
(format t s2))
(format t s1))
(dotimes (i pos)
(format t s))))
```
[Answer]
# Vim, 17 bytes
The easy way to do this is to use a back-reference regex that can tell if the first and last chars match. But long regexes are long. We don't want that.
```
lDg*p^v$?<C-P>$<CR>hd@aP
```
The wave to repeat is in the buffer. I'm assuming the number to be repeated is in the register `"a` (type `qaNq` with N as the number to set it up). The idea is:
* If the first and last bytes match, delete everything up to the last character.
* If the first and last bytes *don't* match, delete all the characters.
Then `P` the deleted text `@a` times.
* `lDg*`: This maneuver creates a regex that matches any first character, regardless of whether it needs to be escaped or not, or whether it's a word or not. (`*` would be enough to make the properly escaped regex, but would add unwanted `\<\>` garbage if it was a word character, like `_`.)
* `p^`: Last step was messy. Clean up to the original position, beginning of the line.
* `v$`: In visual mode, `$` by default moves to *after* the end of the line.
* `?<C-P>$<CR>hd`: If the previous regex exists at the end of the line, this search will move to it; otherwise, stay beyond the end of the line. Move left from there and we accomplish the (tedious) delete we need.
* `@aP`: Run the number repeat as a macro to be used as an argument to `P`.
[Answer]
# Ruby, 38 bytes
```
->s,n{s[0]==s[-1]?s[0..-2]*n+s[0]:s*n}
```
I think this is pretty self-explanatory. I'm still wondering if there's a more concise way to represent the `s[0..-2]` block, but I haven't found it yet.
[Answer]
# Java (117 bytes)
```
String w(String a,int b){String c=a;for(;b>0;b--)c+=b+a.substring(a.charAt(a.length()-1)==a.charAt(0)?1:0);return c;}
```
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.